<!-- 采购订单修订—— 列表 -->
<script>
import { judgeColumns, SearchColumns } from "./column";
import orderApi from "@/api/business/purchase/purchase-order";
import {
  initPage,
  initParams,
  // initDicts,
} from "@/utils/init/index.js";
import { initDicts } from "@/utils/init.js";

const { Columns, TabColumns } = judgeColumns();

const allColumns = [...Columns, ...SearchColumns];

TabColumns.forEach((column) => {
  allColumns.push(...column.tableColumns);
});

export default {
  name: "PuchaseOrder",
  dicts: [...initDicts(allColumns), "oa_templete_id"],
  components: {
    AddDrawer: () => import("./add/index.vue"),
    SeeDrawer: () => import("./see/index.vue"),
    EditDrawer: () => import("./edit/index.vue"),
    PurchaseReturnDrawer: () => import("./purchaseReturn/index.vue"),
    ElSuperTable: () => import("@/components/super-table/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
    Retrieve: () => import("@/components/Retrieve/index.vue"),
    ZpButton: () => import("./zhuan-pai/index.vue"),
    ZpjlButton: () => import("./zhuan-pai/record.vue"),
    ZdgbButton: () => import("./close/allClose.vue"),
    HgbButton: () => import("./close/itemClose.vue"),
    HdkButton: () => import("./close/itemOpen.vue"),
    CounterApprove: () => import("./fan-shen/index.vue"),
    QueryScheme: () => import("@/components/query-scheme/index.vue"),
    thButton: () => import("./tui-hui/index.vue"),
    HdButton: () => import("./he-dan/index.vue"),
  },
  data() {
    const initTabColumns = () => TabColumns;
    const page = this.$init.page();
    return {
      loading: false,
      tabLoading: false,
      page: page,
      searchColumns: SearchColumns,
      params: initParams(SearchColumns),
      tableColumns: Columns,
      tableData: [],
      tabColumns: initTabColumns(),
      tabName: "puOrderItemList",
      tabTableDatas: {
        puOrderItemList: [],
        puOrderExecuteList: [],
      },
      checkedList: [],
      // 子表Select
      checkedTabList: [],
      // 主表点击信息
      primaryResource: {},
      timer: 300,
      timeOut: null,
      size: "mini",
    };
  },

  computed: {
    $dicts: {
      get: function () {
        return this.dict.type;
      },
    },
    tabHeight: {
      get() {
        return `${
          this.tabTableDatas["puOrderItemList"].length
            ? this.tabTableDatas["puOrderItemList"].length > 8
              ? 500
              : this.tabTableDatas["puOrderItemList"].length * 36 + 120
            : 120
        }px`;
      },
      set() {},
    },
  },
  created() {
    if (this.$route.query.billCode)
      this.params.orderCode = this.$route.query.billCode;
    this.fetchList(this.params, this.page);
  },
  methods: {
    async fetchList(data, params) {
      try {
        this.loading = true;

        let { date } = data;

        data.startDate = date ? date[0] : "";

        data.endDate = date ? date[1] : "";

        params["isAsc"] = "desc";

        params["orderByColumn"] = "updateTime";

        const { code, msg, rows, total } = await orderApi.list(data, params);

        if (code === 200) {
          this.page.total = total;

          this.tableData = rows;
        }
      } catch (err) {
        //
      } finally {
        this.loading = false;

        for (const key in this.tabTableDatas) {
          this.tabTableDatas[key] = [];
        }
      }
    },

    queryScheme(prop) {
      console.log(prop, "查询");
    },

    async handleDownload() {
      console.log(this.params, "条件");
      this.download(
        "/pu/order/export",
        { ...this.params },
        `采购订单维护${new Date().getTime()}.xlsx`
      );
      // try {
      //   this.loading = true;

      //   orderApi.orderExport({...this.params}).then(res=>{

      //     const isBlob = blobValidate(res);
      //     if (isBlob) {
      //       const blob = new Blob([res]);
      //       saveAs(blob, `采购订单维护${new Date().getTime()}.xlsx`);
      //     }

      //   })

      // } catch (error) {

      // }finally{
      //   this.loading = false;
      // }
    },
    async jumpFlow(row) {
      const { name } = this.$store.state.user;

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

        if (code == 200) {
          window.open(oaUrl);
        }
      } catch (error) {
      } finally {
      }
    },
    setSelectable() {
      return true;
    },
    setTabSelectable() {
      if (this.tabName === "puOrderItemList") {
        return true;
      }

      return false;
    },

    // 刷新操作
    handleRefreshList() {
      this.page = this.$init.page();
      this.$refs.purchaseTable.$refs.superTable &&
        this.$refs.purchaseTable.$refs.superTable.clearSelection();

      for (const key in this.tabTableDatas) {
        this.tabTableDatas[key] = [];
      }
      this.$refs.puOrderItemList[0].$refs.superTable &&
        this.$refs.puOrderItemList[0].$refs.superTable.clearSelection();

      // this.checkedList = [];

      // this.checkedTabList = [];

      this.primaryResource = {};

      this.fetchList(this.params, this.page);
    },
    // 重置操作
    handleResetList() {
      this.page = this.$init.page();

      this.params = initParams(SearchColumns);

      this.fetchList(this.params, this.page);
    },
    handleTabClick() {},
    // 新增
    handleOpenAddDrawer(copyVal) {
      const { setVisible, setCopyParams } = this.$refs.addDrawerFef;

      setVisible(true, copyVal.id && copyVal.id != "" ? true : false);

      copyVal.id && copyVal.id != "" && setCopyParams(copyVal.id);
    },
    // 查看
    async handleOpenSeeDrawer(row) {
      window.clearInterval(this.timeOut);

      const { id } = row;

      const { setVisible, fetchItem } = this.$refs.seeDrawerRef;

      await setVisible(true);

      await fetchItem(id);
    },
    // 编辑、修订
    async handleOpenEditDrawer(row) {
      const { id } = row;

      const { setVisible, fetchItem } = this.$refs.editDrawerRef;

      await setVisible(true);

      await fetchItem(id);
    },

    // 获取子表信息
    handleDetailsData(row) {
      window.clearTimeout(this.timeOut);

      this.timeOut = setTimeout(async () => {
        try {
          this.tabLoading = true;

          this.primaryResource = row;

          this.checkedTabList = [];

          const { code, msg, data } = await orderApi.details(row.id);

          if (code === 200) {
            // 物料信息:puOrderItemList   执行结果:puOrderExecuteList
            for (const key in this.tabTableDatas) {
              this.tabTableDatas[key] = data[key];
            }
          }
        } catch (err) {
        } finally {
          this.tabLoading = false;
        }
      }, this.timer);
    },

    // 操作提示弹窗
    handleConfirmTips(success) {
      this.$confirm("是否继续此操作?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          success();
        })
        .catch(() => {});
    },

    // 删除操作
    handleDeleteList(row) {
      try {
        this.loading = true;

        this.handleConfirmTips(async () => {
          const { id } = row;

          const { code } = await orderApi.remove(id);

          if (code === 200) {
            this.handleRefreshList();
          }
        });
      } catch (err) {
        //
      } finally {
        this.loading = false;
      }
    },
    // 批量提交
    handleBatchSubmit() {
      let inconformity = this.checkedList.filter(
        (row) =>
          !(
            (row.status == "0" || row.status == "3" || row.status == "9") &&
            row.isEnd === "N"
          )
      );

      if (!inconformity.length && this.checkedList.length) {
        let puOrderIds = this.checkedList.map((item) => Number(item.id));

        this.fetchSubmit(puOrderIds);
      } else {
        this.$notify({
          title: "警告",
          message: "当前选中存在不满足提交条件的数据！",
          type: "warning",
        });
      }
    },
    // 提交
    handleSubmit(row) {
      let puOrderIds = [Number(row.id)];

      this.fetchSubmit(puOrderIds);
    },
    fetchSubmit(puOrderIds) {
      let _this = this;

      this.handleConfirmTips(async () => {
        try {
          _this.loading = true;

          let { code, msg } = await orderApi.submit({
            puOrderIds,
            checkAmount: true,
          });

          if (code == 200) {
            _this.handleRefreshList();
          } else if (code == 10000) {
            _this.$alert(
              "<div style='overflow: auto;overflow-x: hidden;max-height: 65vh;padding: 10px 20px 0;'>" +
                msg +
                "</div>",
              "提示",
              {
                showCancelButton: true,
                dangerouslyUseHTMLString: true,
                confirmButtonText: "继续提交",
                cancelButtonText: "取消",
                beforeClose: async (action, instance, done) => {
                  if (action === "confirm") {
                    instance.confirmButtonLoading = true;
                    instance.confirmButtonText = "执行中...";
                    try {
                      let { code, msg } = await orderApi.submit({
                        puOrderIds,
                        checkAmount: false,
                      });
                      if (code == 200) {
                        done();
                        _this.handleRefreshList();
                      }
                    } catch (error) {
                      instance.confirmButtonText = "确认";
                    } finally {
                      instance.confirmButtonLoading = false;
                    }
                  } else {
                    done();
                  }
                },
              }
            );
          }
        } catch (error) {
        } finally {
          this.loading = false;
        }
      });
    },
    //流程收回
    async handleBack(row) {
      try {
        const { msg, code } = await orderApi.oaBack({
          fdTemplateId: this.dict.type.oa_templete_id.find((item) => {
            return item.label == "采购订单";
          }).value,
          fdId: row.flowId,
          billCode: row.code,
          billMaker: row.createBy,
        });
        if (code === 200) {
          this.$emit("success");
          this.$notify.success(msg);
        }
      } catch (err) {
        console.error(err);
      } finally {
        this.fetchList(this.params, this.page);
      }
    },

    // 付款协议
    async handlePaymentRequest() {
      // name:工号
      try {
        let { code, msg } = await orderApi.payRequest();

        if (code == 200) {
          msg.replace(/\/n/g, "");

          let url = `uclient://start/http://172.16.100.2:8081?ssoKey=${msg}&uiloader=nc.uap.lfw.applet.PortalUILoader&nodeId=40040407`;

          window.location.href = url;
        }
      } catch (error) {}
    },
    // 主表Select框
    handleSelect(selection, row) {
      this.checkedList = selection;
    },
    handleSelectionChange(selection) {
      this.checkedList = selection;
    },
    // 子表Select框
    handleTabSelect(selection, row) {
      this.checkedTabList = selection;
    },
    handleTabSelectionChange(selection) {
      this.checkedTabList = selection;
    },
    // 保留两位小数，补位
    keepTwoDecimalStr(num) {
      if (num) {
        const result = Number(num.toString().match(/^\d+(?:\.\d{0,2})?/));

        let s = result.toString();

        let rs = s.indexOf(".");

        if (rs < 0) {
          rs = s.length;

          s += ".";
        }
        while (s.length <= rs + 2) {
          s += "0";
        }

        return s;
      } else {
        return "";
      }
    },
    judgeIsOption(type, source) {
      // status: 0=自由态，1=审批中，2=已审核，3=已驳回 4=提交中 9=已回退
      // source: 1=自动协议直采，2=协议直采，3=手工
      // isEnd:整单关闭标识
      switch (type) {
        case "edit":
          return (
            (source.status == "0" ||
              source.status == "3" ||
              source.status == "9") &&
            source.isEnd === "N"
          );
        case "revise":
          return source.status == "2" && source.isEnd === "N";
        case "del":
          return (
            (source.status == "0" ||
              source.status == "3" ||
              source.status == "9") &&
            source.source != "1" &&
            source.source != "2" &&
            source.isEnd === "N"
          );
        case "submit":
          return (
            (source.status == "0" ||
              source.status == "3" ||
              source.status == "9") &&
            source.isEnd === "N"
          );
        // case "allClose":
        //   return source.status == 2 && source.isEnd === "N";
        case "return":
          return (
            source.source != 3 &&
            source.isEnd === "N" &&
            (source.status == 0 || source.status == 3 || source.status == "9")
          );
        default:
          return false;
      }
    },
    handelRetrieve(row) {
      let { status, flowId, code, createBy } = row;
      return {
        status,
        fdId: flowId,
        fdTemplateId: this.dict.type.oa_templete_id.find((item) => {
          return item.label == "采购订单";
        }).value,
        billCode: code,
        billMaker: createBy,
      };
    },
  },
};
</script>

<template>
  <el-card
    v-loading="loading"
    style="width: calc(100% - 24px); height: 100%; margin: 10px; padding: 10px"
    :body-style="{ padding: 0 }"
  >
    <SeeDrawer ref="seeDrawerRef"></SeeDrawer>
    <AddDrawer ref="addDrawerFef" @close="handleRefreshList"></AddDrawer>
    <EditDrawer ref="editDrawerRef" @close="handleRefreshList"></EditDrawer>
    <PurchaseReturnDrawer
      ref="PurchaseReturnDrawerRef"
      @close="handleRefreshList"
    ></PurchaseReturnDrawer>

    <el-super-search
      v-model="params"
      :size="size"
      :dict="dict"
      :columns="searchColumns"
      @reset="handleResetList"
      @submit="fetchList(params, page)"
    ></el-super-search>

    <!-- 操作 -->
    <el-row :gutter="24" type="flex" justify="end" style="margin: 20px 0 12px">
      <el-col :span="24" style="text-align: right">
        <!-- <query-scheme
          :candidate="candidate"
          @submit="queryScheme"
        ></query-scheme> -->
        <el-button
          :size="size"
          type="primary"
          @click="handleOpenAddDrawer"
          v-hasPermi="['material:order:add']"
          >新增</el-button
        >

        <el-button-group style="margin-left: 10px">
          <el-button
            :size="size"
            :disabled="checkedList.length != 1"
            @click="handleOpenAddDrawer(checkedList[0])"
            >复制</el-button
          >
          <el-button :size="size" @click="handleBatchSubmit"
            >批量提交</el-button
          >
        </el-button-group>

        <el-button-group
          style="margin-left: 10px"
          :key="checkedList.length + 1"
        >
          <th-button
            :size="size"
            :main-data="checkedList"
            @success="handleRefreshList"
          ></th-button>
          <zdgb-button
            :select-data="checkedList"
            :size="size"
            @submit="handleRefreshList"
          ></zdgb-button>
        </el-button-group>

        <el-button-group style="margin: 0 10px">
          <el-button :size="size" @click="handlePaymentRequest"
            >付款申请</el-button
          >
          <el-button :size="size" @click="handleDownload">批量导出</el-button>
        </el-button-group>
        <el-button-group style="margin: 0 10px">
          <zp-button
            :size="size"
            :select-data="checkedList"
            @success="fetchList(params, page)"
          >
          </zp-button>
          <zpjl-button :size="size" :select-data="checkedList"> </zpjl-button>
          <counter-approve
            :size="size"
            :select-data="checkedList"
            @success="fetchList(params, page)"
          ></counter-approve>
        </el-button-group>

        <el-button-group>
          <hd-button
            :size="size"
            :select-data="checkedList"
            @success="fetchList(params, page)"
          >
          </hd-button>
        </el-button-group>
      </el-col>
    </el-row>

    <el-super-ux-table
      class="purchaseTable"
      v-model="tableData"
      ref="purchaseTable"
      index
      checkbox
      pagination
      showSummary
      :page="page"
      :size="size"
      :dict="dict"
      :height="400"
      convenitentOperation
      :columns="tableColumns"
      :selectable="setSelectable"
      storage-key="PuchaseOrderSuperTable"
      @select="handleSelect"
      @row-click="handleDetailsData"
      @row-dblclick="handleOpenSeeDrawer"
      @pagination="fetchList(params, page)"
      @selection-change="handleSelectionChange"
    >
      <ux-table-column fixed="right" title="操作" width="180">
        <template slot-scope="scope">
          <el-button
            v-if="judgeIsOption('revise', scope.row)"
            type="text"
            :size="size"
            @click.stop="handleOpenEditDrawer(scope.row)"
            v-hasPermi="['material:order:edit']"
          >
            修订
          </el-button>
          <el-button
            v-if="judgeIsOption('edit', scope.row)"
            type="text"
            :size="size"
            @click.stop="handleOpenEditDrawer(scope.row)"
            v-hasPermi="['material:order:edit']"
          >
            编辑
          </el-button>
          <!-- 0=自由态，1=审批中，2=已审核，3=已驳回 4=提交中-->
          <el-button
            v-if="judgeIsOption('del', scope.row)"
            type="text"
            :size="size"
            @click.stop="handleDeleteList(scope.row)"
            v-hasPermi="['material:order:remove']"
            >删除</el-button
          >
          <el-button
            v-if="judgeIsOption('submit', scope.row)"
            type="text"
            size="mini"
            v-hasPermi="['material:order:toOa']"
            @click.stop="handleSubmit(scope.row)"
            >提交</el-button
          >
          <el-button
            v-if="scope.row.status == '1'"
            type="text"
            size="mini"
            @click.stop="handleBack(scope.row)"
            >收回</el-button
          >
          <el-button
            v-if="
              scope.row.flowId &&
              scope.row.flowId !== '' &&
              scope.row.status !== '9'
            "
            type="text"
            size="mini"
            @click.stop="jumpFlow(scope.row)"
            >流程跳转</el-button
          >
          <!-- <Retrieve :data="handelRetrieve(scope.row)" @success="fetchList(params, page)"></Retrieve> -->
        </template>
      </ux-table-column>
    </el-super-ux-table>

    <div style="position: relative" v-loading="tabLoading">
      <el-row style="position: absolute; top: 5px; right: 20px; z-index: 10">
        <th-button
          :size="size"
          type="line"
          :main-data="[...primaryResource]"
          :subtabulation="checkedTabList"
          @success="handleRefreshList"
        ></th-button>
        <hgb-button
          :select-data="checkedTabList"
          :size="size"
          @submit="handleRefreshList"
        ></hgb-button>
        <hdk-button
          :select-data="checkedTabList"
          :size="size"
          @submit="handleRefreshList"
        ></hdk-button>
      </el-row>
      <el-tabs
        v-model="tabName"
        @tab-click="handleTabClick"
        style="width: 100%; padding: 0px 10px"
      >
        <el-tab-pane
          v-for="(column, index) in tabColumns"
          :key="index"
          :label="column.title"
          :name="column.key"
        >
          <el-super-ux-table
            v-model="tabTableDatas[column.key]"
            showSummary
            convenitentOperation
            :dict="dict"
            :ref="column.key"
            :height="tabHeight"
            :columns="column.tableColumns"
            :selectable="setTabSelectable"
            :checkbox="setTabSelectable()"
            :size="size"
            :storage-key="'PuchaseOrder' + column.key"
            @select="handleTabSelect"
            @selection-change="handleTabSelectionChange"
          >
          </el-super-ux-table>
        </el-tab-pane>
      </el-tabs>
    </div>
  </el-card>
</template>
