<template>
  <!-- 列表 -->
  <div>
    <!-- 操作按钮 -->
    <!-- <el-row :gutter="10" class="mb10">
      <el-col class="text-right">
        <el-button
          v-hasPermi="['wms:incoming-produce-detail:query']"
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleCase()"
        >入库方案</el-button>
      </el-col>
    </el-row> -->
    <AutoResizer :given-height="230">
      <template #default="{ height }">
        <el-table
          ref="table"
          v-if="columnsList.length > 0"
          v-loading="loading"
          :data="list"
          :height="height"
          border
          :summary-method="getSummaries"
          show-summary
          @selection-change="tableSelected"
        >
          <!-- <el-table-column
            type="selection"
            width="55"
            fixed="left"
            align="center"
          /> -->
          <el-table-column
            prop="inOrderNo"
            label="入库单号"
            width="140"
            align="center"
          >
            <template #default="{ row }">
              <el-button type="text" @click="findDetail(row)">{{
                row.inOrderNo
              }}</el-button>
            </template>
          </el-table-column>
          <el-table-column
            prop="productCode"
            label="产品编码"
            min-width="90"
            align="center"
          />
          <el-table-column
            prop="productName"
            label="产品名称"
            min-width="120"
            align="center"
          />
          <el-table-column
            prop="erpWorkOrderNo"
            label="生产订单编号"
            width="120"
            align="center"
          />
          <el-table-column
            prop="inQty"
            label="入库箱数"
            width="80"
            align="center"
          />
          <el-table-column
            prop="applyer"
            label="申请人员"
            width="80"
            align="center"
          />
          <el-table-column
            prop="applyTime"
            label="申请入库时间"
            align="center"
            min-width="160"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.applyTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="inStorager"
            min-width="80"
            label="入库人员"
            align="center"
          />
          <el-table-column
            prop="realTime"
            min-width="160"
            label="实际入库时间"
            align="center"
          >
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.realTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="sumDetailQty"
            min-width="100"
            label="箱内产品总数"
            align="center"
          />
          <el-table-column
            :key="Math.random()"
            prop="storageStatus"
            label="状态"
            min-width="80"
            align="center"
          >
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.MES_IMPLEMENT_STORAGE_STATE"
                :value="scope.row.storageStatus"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="countOrderNo"
            label="关联订单数"
            min-width="90"
            align="center"
          />
        </el-table>
      </template>
    </AutoResizer>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNo"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 入库方案 -->
    <ProductWareHousingPlan
      ref="productWareHousingPlan"
      :current-rows="currentRows"
      @complete="complete"
      storageStatus="0"
    />
    <!-- 查看明细 -->
    <AwaitProductDetal ref="awaitProductDetail" />
  </div>
</template>

<script>
import { countProductInStoragePage } from "@/api/wms/incoming/production";
import AwaitProductDetal from "./AwaitProductDetal.vue";
import ProductWareHousingPlan from "./ProductWareHousingPlan.vue";
import { getFormColumnsList } from "@/api/system/saveColumns/index";
import { mapGetters } from "vuex";
import { isArray } from "min-dash";

export default {
  name: "AwaitWare",
  components: {
    AwaitProductDetal,
    ProductWareHousingPlan,
  },
  props: {
    activeName: {
      type: String,
      default: "",
    },
    queryParamspro: {
      type: Object,
      default: () => {},
    },
  },
  inject: ["paramsQuery"],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // 领料单列表
      list: [],
      // 是否显示弹出层
      open: false,
      // 高级查询参数
      advParams: {},
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      //   表单参数
      form: {},
      // 表单校验
      rules: {},
      currentRows: [],
      // 显示隐藏列默认参数
      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: "BOM版本", 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 },
        { key: 19, label: "入库时间", visible: true },
      ],
      // 显示隐藏持久化参数
      columnsList: [],
    };
  },
  // 获取当前登录用户id
  computed: {
    ...mapGetters(["userId"]),
  },
  beforeUpdate() {
    this.$nextTick(() => {
      if (this.$refs.table) {
        this.$refs.table.doLayout();
      }
    });
  },
  created() {
    this.getColumnsList();
    this.getList();
  },
  methods: {
    findDetail(data) {
      const { inOrderNo, productCode } = data;
      this.$refs.productWareHousingPlan.queryParams.warehousingOrderNo =
        inOrderNo;
      this.$refs.productWareHousingPlan.queryParams.materialNo = productCode;
      this.$refs.productWareHousingPlan.open = true;
    },
    // 表格选中
    tableSelected(val) {
      this.currentRows = val;
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      const params = {
        ...this.paramsQuery,
        ...this.queryParams,
        ...this.advParams,
        storageStatus: 0,
      };
      countProductInStoragePage(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();
    },
    // 入库方案
    handleCase() {
      if (this.currentRows.length <= 0) {
        this.$modal.msgWarning("请选择您要入库的数据!");
        return;
      }
      this.$refs.productWareHousingPlan.open = true;
    },
    // 查看明细
    handleView(row) {
      const { warehousingOrderNo } = row;
      this.$refs.awaitProductDetail.queryParams.warehousingOrderNo =
        warehousingOrderNo;
      this.$refs.awaitProductDetail.open = true;
    },
    complete() {
      this.getList();
      this.$emit("productComplete");
    },
    // 获取显示隐藏列
    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);
        });
    },
    // 小数点问题处理
    getHandleTotalNumber(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 === "inQty" || column.property === "sumDetailQty") {
          sums[index] = values.reduce((acc, cur) => {
            const value = Number(cur);
            if (!isNaN(value)) {
              return this.getHandleTotalNumber(acc + cur);
            } else {
              return this.getHandleTotalNumber(acc);
            }
          }, 0);
          sums[index];
        }
      });
      return sums;
    },
  },
};
</script>

<style></style>
