<template>
  <!-- 列表 -->
  <div>
    <el-col :span="1.5" class="mb5">
      <el-button
        type="warning"
        plain
        icon="el-icon-download"
        size="mini"
        :loading="exportLoading"
        @click="handleExport"
        >导出</el-button
      >
    </el-col>
    <AutoResizer :given-height="220">
      <template #default="{ height }">
        <el-table
          v-if="columnsList.length > 0"
          ref="multipleTable"
          v-loading="loading"
          show-summary
          :summary-method="getSummaries"
          :data="list"
          :height="height"
          border
        >
          <!-- <el-table-column
        type="selection"
        width="55"
        fixed="left"
        align="center"
      /> -->
          <el-table-column
            label="erp单号"
            align="center"
            prop="erpWriteNo"
            width="140"
            fixed="left"
          />
          <el-table-column
            v-if="columnsList[15].visible"
            :key="Math.random()"
            label="来料入库单号"
            align="center"
            prop="incomingStockNo"
            width="160"
            fixed="left"
          />
          <el-table-column
            v-if="columnsList[16].visible"
            :key="Math.random()"
            label="入库时间"
            align="center"
            prop="createTime"
            width="150"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[17].visible"
            :key="Math.random()"
            label="操作人"
            align="center"
            prop="creator"
            width="120"
          />
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="检验单号"
            align="center"
            prop="inspectionNo"
            width="170"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="物料批次"
            align="center"
            prop="materialLots"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="采购订单"
            align="center"
            prop="purchaseOrderNo"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="物料编码"
            align="center"
            prop="materialNo"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="物料名称"
            align="center"
            prop="materialName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="到货数量"
            sortable
            width="100"
            align="center"
            prop="receiptQty"
          />
          <el-table-column
            v-if="columnsList[18].visible"
            :key="Math.random()"
            label="入库数量"
            width="100"
            sortable
            align="center"
            prop="inQty"
          />
          <el-table-column
            v-if="columnsList[8].visible"
            :key="Math.random()"
            label="单位"
            align="center"
            prop="unitCode"
          />
          <el-table-column
            v-if="columnsList[9].visible"
            :key="Math.random()"
            label="供应商"
            align="center"
            prop="supplierName"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[10].visible"
            :key="Math.random()"
            label="存储条件"
            align="center"
            prop="storageEnvironment"
            width="120"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[11].visible"
            :key="Math.random()"
            label="登记时间"
            align="center"
            prop="receiptTime"
            width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.receiptTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="columnsList[12].visible"
            :key="Math.random()"
            label="登记人"
            align="center"
            prop="receiptPerson"
            width="100"
          />
          <el-table-column
            v-if="columnsList[14].visible"
            :key="Math.random()"
            label="检验结果"
            align="center"
            prop="testResult"
          >
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.WMS_TEST_RESULT"
                :value="scope.row.testResult"
              />
            </template>
          </el-table-column>
          <el-table-column
            v-if="operateShow"
            label="操作"
            align="center"
            class-name="small-padding fixed-width"
            width="80"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['wms:incoming-stock:delete']"
                size="mini"
                type="text"
                icon="el-icon-delete"
                class="text-danger"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
    </AutoResizer>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 物流需求清单查看对话框 -->
    <AlreadyWareDetail ref="wareDetail" />
    <!-- 单据打印 -->
    <IssuePrinit ref="issuePrinit" />
  </div>
</template>

<script>
import {
  getIncomingStockPage,
  deleteIncomingStock,
  exportIncomingStock,
} from "@/api/wms/incoming/wareHousing";
import AlreadyWareDetail from "./AlreadyWareDetail.vue";
import IssuePrinit from "@/views/wms/output/productionIssue/issueDetails/IssuePrinit.vue";
const AccessTokenKey = "ACCESS_TOKEN";
import { getFormColumnsList } from "@/api/system/saveColumns/index";
import { mapGetters } from "vuex";
import { isArray } from "min-dash";

export default {
  name: "AlreadyWare",
  components: {
    AlreadyWareDetail,
    IssuePrinit,
  },
  props: {
    activeName: {
      type: String,
      default: "",
    },
    queryParamspro: {
      type: Object,
      default: () => {},
    },
  },
  inject: ["paramsQuery"],
  data() {
    return {
      // 是否显示操作列
      operateShow: true,
      // 遮罩层
      loading: false,
      // 导出遮罩层
      exportLoading: false,
      // 总条数
      total: 0,
      // 领料单列表
      list: [],
      // 是否显示弹出层
      open: false,
      currentRows: [],
      // 高级查询
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      //   表单参数
      form: {},
      // 表单校验
      rules: {},
      tokens: "",
      baseUrl: "",
      reportId: "",
      // 显示隐藏列参数
      columns: [
        { key: 0, label: "检验单号", visible: true },
        { key: 1, label: "物料批次", visible: true },
        { key: 2, label: "采购订单", visible: true },
        { key: 3, label: "物料编码", visible: true },
        { key: 4, label: "物料名称", visible: true },
        { key: 5, label: "到货数量", visible: true },
        { key: 6, label: "合格数量", visible: true },
        { key: 7, label: "检验状态", visible: true },
        { key: 8, label: "单位", visible: true },
        { key: 9, label: "供应商", visible: true },
        { key: 10, label: "存储条件", visible: true },
        { key: 11, label: "登记时间", visible: true },
        { key: 12, label: "登记人", visible: true },
        { key: 13, label: "处理结果", visible: true },
        { key: 14, label: "检验结果", visible: true },
        { key: 15, label: "来料入库单号", visible: true },
        { key: 16, label: "入库时间", visible: true },
        { key: 17, label: "操作人", visible: true },
        { key: 18, label: "入库数量", visible: true },
      ],
      // 显示隐藏持久化参数
      columnsList: [],
    };
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters(["userId"]),
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList();
    this.getList();
    // console.log(this.paramsQuery)
    this.tokens = localStorage.getItem(AccessTokenKey);
    this.baseUrl = process.env.VUE_APP_REPORT_API;
    this.reportId = this.$route.meta.reportId;
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      const params = {
        ...this.paramsQuery,
        ...this.queryParams,
        ...this.advParams,
      };
      // 执行查询
      getIncomingStockPage(params)
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        wmsIncomingReceiptId: undefined,
        orderType: undefined,
        erpStockId: undefined,
        wmsStoreAreaId: undefined,
        wmsStoreId: undefined,
        inQty: undefined,
        funitId: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    // 入库明细
    handleView(row) {
      const { incomingStockNo } = row;
      this.$refs.wareDetail.queryParams.incomingStockNo = incomingStockNo;
      this.$refs.wareDetail.open = true;
      this.$refs.wareDetail.title = "入库明细";
    },
    // 删除明细
    handleDelete(row) {
      const { id, materialName } = row;
      this.$modal
        .confirm('是否确认删除物料编码为"' + materialName + '"的数据项?')
        .then(function () {
          return deleteIncomingStock(id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val;
      const list = this.currentRows.map((item) => item.materialLots);
      this.ids = list.join(",");
    },
    select(selection, row) {
      if (selection.length > 1) {
        const del_row = selection.shift();
        this.$refs.multipleTable.toggleRowSelection(del_row, false);
      }
    },
    selectAll(selection) {
      if (selection.length > 1) {
        selection.length = 1;
      }
    },
    // 标签打印
    handlePrint() {
      const src = `${this.baseUrl}/jmreport/view/${this.reportId}?token=${this.tokens}&materialLots=${this.ids}`;
      this.$refs.issuePrinit.dialogVisible = true;
      this.$refs.issuePrinit.title = "单据打印";
      this.$refs.issuePrinit.src = src;
    },
    // 获取显示隐藏列
    getColumnsList() {
      const { componentName } = this.$route.meta || null;
      const params = {
        userId: this.userId,
        vueForm: componentName,
      };
      getFormColumnsList(params)
        .then((res) => {
          if (isArray(res.data)) {
            this.columnsList = res.data.length === 0 ? this.columns : res.data;
            // 对比默认数据和接口数据，将缺失的列添加到接口数据中
            this.columnsList = this.columns.reduce((acc, defaultColumn) => {
              const found = res.data.find(
                (apiColumn) => apiColumn.key === defaultColumn.key
              );
              if (!found) {
                acc.push({
                  ...defaultColumn,
                  vueForm: componentName,
                  userId: this.userId,
                  id: null,
                });
              }
              return acc;
            }, res.data);
          } else {
            this.columnsList = this.columns;
          }
        })
        .catch((err) => {
          if (err) {
            this.columnsList = this.columns;
          }
        })
        .finally(() => {
          this.$emit("columns", this.columnsList);
        });
    },
    // 小数点问题处理
    getHandleNumber(val) {
      return Math.round(parseFloat(val) * 100000000) / 100000000;
    },
    // 总计
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }

        const values = data.map((item) => Number(item[column.property]));
        if (column.property === "receiptQty" || column.property === "inQty") {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur);
            if (!isNaN(value)) {
              return this.getHandleNumber(acc + cur);
            } else {
              return acc;
            }
          }, 0);
          sums[index];
        }
      });
      return sums;
    },
    // 导出
    handleExport() {
      // 处理查询参数
      const params = { ...this.queryParams };
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal
        .confirm("是否确认导出所有WMS 来料入库数据项?")
        .then(() => {
          this.exportLoading = true;
          return exportIncomingStock(params);
        })
        .then((response) => {
          this.$download.excel(
            response,
            `WMS 来料入库-${new Date().toLocaleString()}.xls`
          );
          this.exportLoading = false;
        })
        .catch(() => {});
    },
  },
};
</script>
<style></style>
