<script>
import useColumns from "./columns";
import {
  getReqList,
  delReq,
  importData,
  fileImport,
  betchSubmit,
  toOA,
  oaBack,
} from "@/api/requisition/basic";
import { saveAs } from "file-saver";
import { blobValidate } from "@/utils/ruoyi";
import { dicts } from "./dicts";
export default {
  name: "requisition",
  dicts: [...dicts, "oa_templete_id"],
  components: {
    DetailsRequsition: () => import("./details/index.vue"),
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
    BatchImport: () => import("@/components/BatchImport/index.vue"),
    plscButton: () => import("./fun-button/pi-liang-shan-chu/index.vue"),
  },
  data() {
    const { SearchColumns, TableColumns } = useColumns();
    const page = this.$init.page();
    const params = this.$init.params(SearchColumns);
    return {
      loading: false,
      size: "mini",
      page: page,
      params: params,
      tableData: [],
      selectData: [],
      SearchColumns: SearchColumns,
      TableColumns: TableColumns,
      addType: "add",
    };
  },
  created() {},
  mounted() {
    this.params.billCode = this.$route.query.billCode;
    this.useQuery(this.params, this.page);
  },
  methods: {
    async useQuery(prop, page) {
      try {
        this.loading = true;

        let { code, rows, total } = await getReqList({ ...prop, ...page });

        if (code == 200) {
          this.tableData = rows;
          this.page.total = total;
        }
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    // 打开详细
    openDetails(option, prop) {
      this.addType = option;

      let { setVisible, fetchItem } = this.$refs.detailsRequsition;

      setVisible(true);

      prop && fetchItem(prop);
    },
    //
    handleDbclick(prop) {
      this.openDetails("see", prop);
    },

    handleSelectionChange(selection) {
      this.selectData = selection;
    },
    // 流程跳转
    async jumpFlow(row) {
      const { name } = this.$store.state.user;

      try {
        let { code, msg, oaUrl } = await toOA(name, row.oaId);

        if (code == 200) {
          window.open(oaUrl);
        }
      } catch (error) {
      } finally {
      }
    },
    //流程收回
    async handleBack(row) {
      try {
        const { msg, code } = await oaBack({
          fdTemplateId: this.dict.type.oa_templete_id.find((item) => {
            return item.label == "物料申请单";
          }).value,
          fdId: row.oaId,
          billCode: row.billCode,
          billMaker: row.createBy,
        });
        if (code === 200) {
          this.$emit("success");
          this.$notify.success(msg);
        }
      } catch (err) {
        console.error(err);
      } finally {
        this.getList(this.queryParams);
      }
    },
    // 删行
    deleteRow(row) {
      this.handleConfirmTips(async () => {
        try {
          let { code, msg } = await delReq(row.id);

          if (code === 200) {
            this.useQuery(this.params, this.page);
            this.$notify.success(msg);
          }
        } catch (error) {}
      });
    },
    reset() {
      this.page = this.$init.page();
      this.params = this.$init.params(this.SearchColumns);
      this.useQuery(this.params, this.page);
    },
    // 批量提交
    batchSubmit() {
      let filterList = this.selectData.filter(
        (item) => !(item.status === "0" || item.status === "3")
      );

      if (!filterList.length && this.selectData.length) {
        this.handleConfirmTips(async () => {
          try {
            this.loading = true;
            let ids = this.selectData.map((item) => Number(item.id));
            let { code, msg } = await betchSubmit({ ids });
            if (code == 200) {
              this.$notify.success({
                message: msg,
              });
              this.reset();
            } else {
              this.$notify.error({
                message: msg,
              });
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        });
      } else {
        this.$notify.warning({
          message: "存在不符合提交条件数据或未选择数据！",
        });
      }
    },
    // 导入
    async handelImport(fileList) {
      let formData = new FormData();

      formData.append("file", fileList[0].raw);

      let { setVisible } = this.$refs.batchImport;

      setVisible(false);

      try {
        this.loading = true;
        let { code, msg, data } = await importData(formData);

        if (code == 200) {
          // 存在导入失败的数据
          data.flag && (await this.exportfail(data.datas));

          this.$notify({
            message: data.msg,
            type: data.flag ? "warning" : "success",
          });
        } else {
          this.$notify({
            message: msg,
            type: code == 200 ? "success" : "warning",
          });
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 导出失败数据
    async exportfail(prop) {
      try {
        this.loading = true;

        let res = await fileImport({ failDatas: prop });

        const isBlob = blobValidate(res);

        if (isBlob) {
          const blob = new Blob([res]);

          await saveAs(blob, "导入失败的物料申请单数据.xlsx");

          this.reset();
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 模板下载,
    handleTemDownload() {
      this.download("/system/apply/material/download", {}, "申请单模板.xlsx");
    },
    // 操作提示弹窗
    handleConfirmTips(success) {
      this.$confirm("是否继续此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          success();
        })
        .catch(() => {});
    },
  },
};
</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="reset"
      @submit="useQuery(params, page)"
    ></el-super-search>

    <el-row :gutter="24" type="flex" justify="end" style="margin: 16px 0 12px">
      <el-col :span="24" style="text-align: right">
        <el-button-group style="margin-left: 10px">
          <el-button :size="size" type="primary" @click="openDetails('add')"
            >新增</el-button
          >
          <el-button
            :size="size"
            :disabled="selectData.length !== 1"
            @click="openDetails('add', selectData[0])"
            >复制</el-button
          >
        </el-button-group>
        <el-button-group style="margin: 0 10px">
          <el-button :size="size" @click="batchSubmit">批量提交</el-button>
        </el-button-group>
        <BatchImport
          ref="batchImport"
          @import="handelImport"
          @temDownload="handleTemDownload"
          :fileSize="2"
        ></BatchImport>
        <plsc-button
          :size="size"
          :select-data="selectData"
          @success="useQuery(params, page)"
        ></plsc-button>
      </el-col>
    </el-row>

    <el-super-ux-table
      v-model="tableData"
      :dict="dict"
      :columns="TableColumns"
      :size="size"
      pagination
      index
      checkbox
      convenitentOperation
      :page="page"
      storage-key="MaterialRequisitionSuperTable"
      @pagination="useQuery(params, page)"
      @row-dblclick="handleDbclick"
      @selection-change="handleSelectionChange"
    >
      <ux-table-column fixed="right" title="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            type="text"
            :size="size"
            @click.stop="openDetails('see', scope.row)"
            >查看</el-button
          >
          <el-button
            @click.stop="openDetails('edit', scope.row)"
            v-if="scope.row.status == 0 || scope.row.status == 3"
            type="text"
            :size="size"
            >编辑</el-button
          >
          <el-button
            @click.stop="jumpFlow(scope.row)"
            v-if="scope.row.oaId && scope.row.oaId != ''"
            type="text"
            :size="size"
            >流程跳转</el-button
          >
          <el-button
            type="text"
            :size="size"
            @click.stop="deleteRow(scope.row)"
            v-if="scope.row.status == 0 || scope.row.status == 3"
            >删除</el-button
          >
          <el-button
            v-if="
              scope.row.status == '1' && scope.row.oaId && scope.row.oaId != ''
            "
            type="text"
            :size="size"
            @click.stop="handleBack(scope.row)"
            >流程收回</el-button
          >
        </template>
      </ux-table-column>
    </el-super-ux-table>

    <details-requsition
      ref="detailsRequsition"
      :addType="addType"
      :dict="dict"
      :size="size"
      @success="useQuery(params, page)"
    ></details-requsition>
  </el-card>
</template>

<style scoped lang="scss">
.el-card {
  width: calc(100% - 32px);
  height: calc(100vh - 32px);
  margin: 16px;
  padding: 16px;
  border-radius: 8px;
}
</style>
