<!-- 采购需求处理 -->
<script>
import useColumns from "./columns";
import { dicts } from "./dicts";
import {
  getSummaryList,
  auditSummary,
  cancelAudits,
  editSummaryList,
  exportList,
  exportItems,
} from "@/api/purchase/DemandSummary.js";
export default {
  name: "DemandSummary",
  dicts: [...dicts],
  components: {
    CgxqDetails: () => import("./add/index.vue"),
    ConfirmBtn: () => import("./confirm/index.vue"),
    CloseLineBtn: () => import("./closeLine/index.vue"),
    ElSuperSearch: () => import("@/components/super-search/index.vue"),
    ElSuperUxTable: () => import("@/components/super-ux-table/index.vue"),
    ElPopoverSelectV2: () => import("@/components/popover-select-v2/index.vue"),
    ElPopoverMultipleSelectV2: () =>
      import("@/components/popover-select-v2/multiple.vue"),
  },
  data() {
    const { SearchColumns, TableColumns } = useColumns();
    const params = this.$init.params(SearchColumns);
    const page = this.$init.page();
    return {
      page,
      params: {
        ...params,
        rowStatus: ["1"],
      },
      TableColumns,
      SearchColumns,
      size: "mini",
      isEdit: false,
      loading: false,
      tableData: [],
      selectData: [],
      recordData: [],
      rowDetail: {},
      // 物料参照
      materialReference: {
        name: "",
      },
    };
  },
  computed: {
    materialNum: {
      get() {
        const { materialCodeList } = this.params;
        return materialCodeList ? materialCodeList.split(/,|，|\s+/).length : 0;
      },
      set() {},
    },
  },
  methods: {
    async useQuery(params, page) {
      try {
        this.loading = true;
        let data = {
          ...params,
          ...page,
          materialCodeList: params.materialCodeList
            ? params.materialCodeList.split(/,|，|\s+/)
            : null,
        };
        let { code, rows, total } = await getSummaryList(data);
        this.selectData = [];
        if (code == 200) {
          this.tableData = rows;
          this.page.total = total;
          this.isEdit = false;
        }
      } catch (error) {
      } finally {
        this.loading = false;
      }
    },
    // 重置
    useReset() {
      this.params = {
        ...this.$init.params(this.SearchColumns),
        rowStatus: ["1"],
      };
      this.page = this.$init.page();
      this.useQuery(this.params, this.page);
    },
    // 查看
    useSee(row) {
      const { setVisible } = this.$refs.DemandSummaryAdd;
      setVisible(true);
      this.rowDetail = row;
    },
    // 选 择
    useSelect(prop) {
      this.selectData = prop;
    },
    // 编辑
    useEdit() {
      this.isEdit = true;
    },
    // 保存
    async useSave() {
      try {
        // this.loading = true;
        let newRecord = Array.from(new Set(this.recordData));
        let changeList = newRecord.map((i) => {
          return this.tableData[i];
        });
        let { code, msg } = await editSummaryList(changeList);
        if (code == 200) {
          this.$modal.notifySuccess(msg);
          this.useQuery(this.params, this.page);
        }
      } catch (error) {
      } finally {
        // this.loading = false;
      }
    },

    // 取消
    useCancel() {
      this.isEdit = false;
      this.useQuery(this.params, this.page);
    },
    // 审核
    async useAudits() {
      try {
        this.$modal.loading("正在处理，请稍后...");
        let ids = this.selectData.map((item) => item.demandItemId).join();
        let { code, msg } = await auditSummary(ids);
        if (code == 200) {
          this.$modal.notifySuccess(msg);
          this.useQuery(this.params, this.page);
        }
      } catch (error) {
      } finally {
        this.$modal.closeLoading();
      }
    },
    // 导出
    useExport(params, page) {
      this.$modal.loading("正在导出数据，请稍后...");
      exportItems({ ...params, ...page, pageSize: page.total }).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); // 创建下载的链接
        // var temp = res.headers["content-disposition"];
        // var fileName = decodeURIComponent(temp.split("filename=")[1]); // 中文需要转码 (前端乱码）
        // var name = fileName.split(";")[0]; //切割成文件名
        downloadElement.href = href; //下载地址
        downloadElement.download =
          "采购需求处理导出" + new Date().getTime() + ".xlsx"; // 下载后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); // 点击下载
        document.body.removeChild(downloadElement); // 下载完成移除元素
        window.URL.revokeObjectURL(href); // 释放blob对象
      });
    },
    // 单元格标红
    cellClassName({ row, column, rowIndex, columnIndex }) {
      if (column.title == "需求可用周期" && Number(row.demandCycle) > 1.5) {
        return "success-row";
      }
    },
    // 最终采购量
    changeFinalBuyQty({ $rowIndex }) {
      this.recordData.push($rowIndex);
      // this.$refs.DemandSummaryTable.updateFooter();
    },
    // 采购员
    changeBuyerName({ $rowIndex }) {
      this.recordData.push($rowIndex);
    },
    changeMaterial(val) {
      this.params.materialCodeList = val;
      this.useQuery(this.params, this.page);
    },
    openMaterial() {
      let { open } = this.$refs.materialPopoverSelect;
      open();
    },
    // 物料参照
    materialReferenceChange(prop, { source }) {
      this.params.materialCodeList = prop.map((item) => item.code).join();
      this.useQuery(this.params, this.page);
    },
  },
  created() {
    this.useQuery(this.params, this.page);
  },
};
</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)"
    >
      <!-- 物料 -->
      <template slot="materialCodeList" slot-scope="scope">
        <el-popover
          placement="top-start"
          width="500"
          trigger="hover"
          :title="'数量:' + materialNum"
          :disabled="!params.materialCodeList"
        >
          <p style="height: 50vh; overflow-y: auto">
            {{ params.materialCodeList }}
          </p>
          <component
            slot="reference"
            v-bind="scope.attr"
            v-model="scope.row[scope.item.key]"
            :size="size"
            :source.sync="scope.row"
            @change="changeMaterial"
          >
            <el-button :size="size" slot="append" @click="openMaterial">
              数量: {{ materialNum }}
              <el-popover-multiple-select-v2
                ref="materialPopoverSelect"
                v-show="false"
                title="物料"
                v-model="materialReference.name"
                :source.sync="materialReference"
                valueKey="code"
                referName="MATERIAL_PARAM"
                style="width: 100%"
                @change="materialReferenceChange"
              >
              </el-popover-multiple-select-v2>
            </el-button>
          </component>
        </el-popover>
      </template>
    </el-super-search>

    <el-row class="my-4" style="text-align: right">
      <el-col v-if="isEdit">
        <el-button-group>
          <el-button :size="size" @click="useCancel">取 消</el-button>
          <el-button type="primary" :size="size" @click="useSave"
            >保 存</el-button
          >
        </el-button-group>
      </el-col>

      <el-col v-else>
        <el-button-group>
          <el-button type="primary" :size="size" @click="useEdit"
            >编 辑</el-button
          >
        </el-button-group>

        <!-- 确认、取消确认 -->
        <confirm-btn
          :size="size"
          :select-data="selectData"
          @refresh="useQuery(params, page)"
        ></confirm-btn>

        <el-button-group>
          <el-button
            :size="size"
            :disabled="!selectData.length"
            @click="useAudits"
            >审 核</el-button
          >
        </el-button-group>

        <el-button-group>
          <close-line-btn
            :size="size"
            :select-data="selectData"
            @refresh="useQuery(params, page)"
          ></close-line-btn>
        </el-button-group>

        <el-button-group>
          <el-button :size="size" @click="useExport(params, page)"
            >导 出</el-button
          >
        </el-button-group>
      </el-col>
    </el-row>

    <el-super-ux-table
      v-model="tableData"
      :size="size"
      :dict="dict"
      :page="page"
      :columns="TableColumns"
      index
      checkbox
      pagination
      showSummary
      convenitentOperation
      ref="DemandSummaryTable"
      storage-key="DemandSummarySuperTable"
      @row-select="useSelect"
      @pagination="useQuery(params, page)"
      :cell-class-name="cellClassName"
      :checkbox-config="{ trigger: 'row', highlight: true }"
    >
      <!-- @row-dblclick="useSee" -->
      <!-- 最终采购量 -->
      <template slot="finalBuyQty" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="size"
          :source.sync="scope.row"
          :disabled="scope.row.status !== '1' || !isEdit"
          @change="changeFinalBuyQty(scope)"
        >
        </component>
      </template>
      <!-- 采购员 -->
      <template slot="buyerName" slot-scope="scope">
        <component
          v-bind="scope.attr"
          v-model="scope.row[scope.item.key]"
          :size="size"
          :source.sync="scope.row"
          :disabled="scope.row.status !== '1' ||!isEdit"
          @clear="changeBuyerName(scope)"
          @change="changeBuyerName(scope)"
        >
        </component>
      </template>
      <ux-table-column fixed="right" title="操作" align="center" width="80">
        <template slot-scope="scope">
          <el-button type="text" :size="size" @click="useSee(scope.row)"
            >查看</el-button
          >
        </template>
      </ux-table-column>
    </el-super-ux-table>

    <cgxq-details
      ref="DemandSummaryAdd"
      :dict="dict"
      :size="size"
      :data="rowDetail"
      @refresh="useQuery(params, page)"
    ></cgxq-details>
  </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;
}

::v-deep .elx-body--row .success-row {
  background-color: #ff8a8a !important;
}
</style>
