<script>
import { dicts } from "./dicts";
import useColumns from "./columns";
import {
  LIST,
  mbDownload,
  failDownload,
  oaBack,
} from "@/api/business/purchase/apply";
// 导入的token
import { getToken } from "@/utils/auth";

export default {
  name: "PuchaseApply",
  dicts: dicts,
  components: {
    SeeButton: () => import("./see/index.vue"),
    AddButton: () => import("./add/index.vue"),
    CopyButton: () => import("./copy/index.vue"),
    EditButton: () => import("./edit/index.vue"),
    DeleButton: () => import("./delete/index.vue"),
    SubmButton: () => import("./submit/index.vue"),
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
  },
  data() {
    const { TableColumns, SearchColumns } = useColumns();
    const page = this.$init.page();
    const params = this.$init.params(SearchColumns);
    return {
      // 导入参数
      upload: {
        // 是否显示弹出层（导入）
        open: false,
        // 弹出层标题（导入）
        title: "数据导入",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 1,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pu/priceApply/import",
      },
      size: "mini",
      loading: false,
      params: params,
      page: page,
      tableData: [],
      selectData: [],
      SearchColumns: SearchColumns,
      TableColumns: TableColumns,
    };
  },
  computed: {
    tableHeight: {
      get() {
        return window.innerHeight - 220;
      },
      set() {},
    },
  },
  created() {
    this.params.priceCode = this.$route.query.billCode;
    this.useQuery(this.params, this.page);
  },
  methods: {
    //
    async fetchList(prop, page) {
      try {
        this.loading = true;
        const { pageNum, pageSize } = page;
        const { code, rows, total } = await LIST(
          { ...prop },
          { pageNum, pageSize }
        );
        if (code === 200) {
          this.tableData = rows.map((item, index) => ({
            ...item,
            $index: (pageNum - 1) * pageSize + index + 1,
          }));
          this.page.total = total;
        }
      } catch (err) {
        // catch
        console.error(err);
      } finally {
        // finally
        this.loading = false;
      }
    },
    // 查 询
    useQuery(prop, page) {
      const { billDates } = prop;
      const [startTime, endTime] = billDates || [];
      this.fetchList(
        {
          ...prop,
          startTime,
          endTime,
        },
        page
      );
    },
    // 重 置
    useReset() {
      this.page = this.$init.page();
      this.params = this.$init.params(this.SearchColumns);
      this.useQuery(this.params, this.page);
    },
    // 选 择
    useSelect(prop) {
      this.selectData = prop;
    },
    // 明 细
    async useSee(prop) {
      const { open } = this.$refs.SeeButton;
      await open([prop]);
    },
    // 下载模板
    downLoadMb() {
      this.$modal.loading("正在下载模板，请稍后...");
      mbDownload()
        .then((res) => {
          this.$modal.closeLoading();
          const blob = new Blob([res], {
            type: "application/vnd.ms-excel;charset=UTF-8",
          }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
          const downloadElement = document.createElement("a"); //创建a标签
          const href = window.URL.createObjectURL(blob); // 创建下载的链接
          downloadElement.href = href; //下载地址
          downloadElement.download =
            "价格申报单导入模板" +
            this.parseTime(new Date().getTime()) +
            ".xlsx"; // 下载后文件名
          document.body.appendChild(downloadElement);
          downloadElement.click(); // 点击下载
          document.body.removeChild(downloadElement); // 下载完成移除元素
          window.URL.revokeObjectURL(href); // 释放blob对象
        })
        .catch((err) => {
          this.$modal.closeLoading();
        });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
      this.$modal.loading("正在导入数据，请稍后...");
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.$modal.closeLoading();
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      if (response.code == 200) {
        this.$alert(response.data.msg, "导入结果", {
          dangerouslyUseHTMLString: true,
        });
        // 有失败的再次下载下来
        if (response.data.flag) {
          this.$modal.loading("正在下载导入失败数据，请稍后...");
          failDownload({ failDatas: response.data.datas })
            .then((res) => {
              this.$modal.closeLoading();
              const blob = new Blob([res], {
                type: "application/vnd.ms-excel;charset=UTF-8",
              }); // 创建一个类文件对象：Blob对象表示一个不可变的、原始数据的类文件对象
              const downloadElement = document.createElement("a"); //创建a标签
              const href = window.URL.createObjectURL(blob); // 创建下载的链接
              downloadElement.href = href; //下载地址
              downloadElement.download =
                "价格申报单导入失败数据" +
                this.parseTime(new Date().getTime()) +
                ".xlsx"; // 下载后文件名
              document.body.appendChild(downloadElement);
              downloadElement.click(); // 点击下载
              document.body.removeChild(downloadElement); // 下载完成移除元素
              window.URL.revokeObjectURL(href); // 释放blob对象
            })
            .catch((err) => {
              this.$modal.closeLoading();
            });
        }
      } else {
        this.$notify({
          message: response.msg,
          type: response.code == 200 ? "success" : "warning",
        });
      }
      this.useQuery(this.params, this.page);
    },
    errorFile(err) {
      this.$modal.closeLoading();
      this.$modal.notifyError("文件已变动，请重新上传");
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 导入数据
    importMb() {
      this.upload.title = "文件导入";
      this.upload.open = true;
    },
    // 收回
    async reback(row) {
      console.log("xxxx", this.dict.type);
      try {
        const { msg, code } = await oaBack({
          fdTemplateId: this.dict.type.oa_templete_id.find((item) => {
            return item.label == "价格申报单";
          }).value,
          fdId: row.flowId,
          billCode: row.priceCode,
          billMaker: row.createBy,
        });
        if (code === 200) {
          this.$emit("success");
          this.$notify.success(msg);
        }
      } catch (err) {
        console.error(err);
      } finally {
      }
    },
  },
};
</script>

<template>
  <el-card
    v-loading="loading"
    :body-style="{
      height: '100%',
      padding: 0,
      display: 'flex',
      'flex-direction': 'column',
    }"
  >
    <el-super-search
      v-model="params"
      :size="size"
      :dict="dict"
      :columns="SearchColumns"
      @reset="useReset"
      @submit="useQuery(params, page)"
    ></el-super-search>
    <el-row class="my-4" style="text-align: right">
      <el-button-group>
        <add-button
          :size="size"
          :dict="dict"
          type="primary"
          @success="useQuery(params, page)"
        ></add-button>
        <copy-button
          :size="size"
          :dict="dict"
          :select-data="selectData"
          @success="useQuery(params, page)"
        >
        </copy-button>
      </el-button-group>
      <el-button-group>
        <see-button
          v-show="false"
          :size="size"
          :dict="dict"
          :model="params"
          :select-data="selectData"
          ref="SeeButton"
          @success="useQuery(params, page)"
        ></see-button>
        <edit-button
          :size="size"
          :dict="dict"
          :select-data="selectData"
          @success="useQuery(params, page)"
        ></edit-button>
        <dele-button
          :size="size"
          :select-data="selectData"
          @success="useQuery(params, page)"
        ></dele-button>
      </el-button-group>
      <el-button-group>
        <subm-button
          :size="size"
          :select-data="selectData"
          @success="useQuery(params, page)"
        ></subm-button>
      </el-button-group>
      <el-button-group>
        <el-button :size="size" @click="downLoadMb">模 板</el-button>
        <el-button :size="size" type="primary" @click="importMb">导 入</el-button>
      </el-button-group>
    </el-row>
    <el-super-ux-table
      v-model="tableData"
      :size="size"
      :dict="dict"
      :page="page"
      :columns="TableColumns"
      index
      checkbox
      pagination
      convenitentOperation
      storage-key="PuchaseApplySuperTable1"
      @row-dblclick="useSee"
      @row-select="useSelect"
      @pagination="useQuery(params, page)"
    >
      <ux-table-column fixed="right" title="操作" align="center" width="100">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            v-if="scope.row.status == '1' && scope.row.flowId"
            @click="reback(scope.row)"
            >收回</el-button
          >
        </template>
      </ux-table-column>
    </el-super-ux-table>
    <!-- 文件导入对话框 -->
    <el-dialog title="文件导入" :visible.sync="upload.open" width="400px">
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="errorFile"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!-- <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
        </div> -->
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer">
        <el-button size="mini" type="primary" @click="submitFileForm"
          >确 定</el-button
        >
        <el-button size="mini" @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<style scoped lang="scss">
.el-card {
  width: calc(100% - 32px);
  height: calc(100vh - 32px);
  margin: 16px;
  padding: 16px;
  border-radius: 8px;
}

.el-button-group + .el-button-group {
  margin: 0 0 0 8px;
}
</style>
