<template>
  <!-- 列表 -->
  <div>
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      label-width="68px"
      @submit.native.prevent
    >
      <el-row :gutter="24">
        <el-col :span="6">
          <el-form-item label="箱号" prop="splitBoxNo">
            <el-input
              v-model="queryParams.splitBoxNo"
              placeholder="请输入箱号"
              clearable
              @keyup.enter.native="handleCase"
            />
          </el-form-item>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-s-release"
            size="mini"
            style="height: 30px"
            @click="handleUnpacking"
          >
            拆箱
          </el-button>
          <el-button
            type="primary"
            plain
            icon="el-icon-refresh-right"
            size="mini"
            style="height: 30px"
            @click="handleRebox"
          >
            重新装箱/打印外箱标签
          </el-button>
        </el-col>
      </el-row>
    </el-form>
    <AutoResizer :given-height="265">
      <template #default="{ height }">
        <el-table
          v-if="columnsList.length > 0"
          v-loading="loading"
          :data="list"
          :height="height"
          :row-key="getOnlyRowKey"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column
            type="selection"
            width="55"
            :selectable="selected"
            fixed="left"
          />
          <el-table-column
            v-if="columnsList[0].visible"
            :key="Math.random()"
            label="产品编码"
            align="center"
            prop="productCode"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[1].visible"
            :key="Math.random()"
            label="产品名称"
            align="center"
            prop="productName"
            width="150"
            show-overflow-tooltip
          />
          <el-table-column
            v-if="columnsList[2].visible"
            :key="Math.random()"
            label="成品SN码"
            align="center"
            show-overflow-tooltip
            prop="materialSerinalNo"
          />
          <el-table-column
            v-if="columnsList[3].visible"
            :key="Math.random()"
            label="原箱号"
            align="center"
            prop="oldBoxNo"
          />
          <el-table-column
            v-if="columnsList[4].visible"
            :key="Math.random()"
            label="生产订单"
            align="center"
            prop="workOrderNo"
          />
          <el-table-column
            v-if="columnsList[5].visible"
            :key="Math.random()"
            label="状态"
            align="center"
            prop="mesReBoxStatus"
          >
            <template slot-scope="scope">
              <dict-tag
                :type="DICT_TYPE.WMS_UNPACKING_STATUS"
                :value="scope.row.mesReBoxStatus"
              />
            </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"
    />

    <CommonPrintDialog ref="commonPrintDialog" @success="handleReboxAndPrint" />
  </div>
</template>

<script>
import {
  getReBoxDetailPage,
  createSplit,
} from "@/api/wms/inLibrary/productsReBox";
import { reCreateBox, getPrintData } from "@/api/wms/inLibrary/productsReBox";
import CommonPrintDialog from "./CommonPrintDialog.vue";
import { getFormColumnsList } from "@/api/system/saveColumns/index";
import { mapGetters } from "vuex";
import { printLabel } from "@/api/common";
import { isArray } from "min-dash";

export default {
  name: "DismantledList",
  components: {
    CommonPrintDialog,
  },
  props: {
    activeName: {
      type: String,
      default: "",
    },
    queryParamspro: {
      type: Object,
      default: () => {},
    },
  },
  inject: ["paramsQuery"],
  data() {
    return {
      printData: [],
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 成品列表
      list: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        splitBoxNo: null,
      },
      // 选中的数据
      currentRows: [],
      //   表单参数
      form: {},
      // 显示隐藏列参数
      columns: [
        { key: 0, label: "产品编码", visible: true },
        { key: 1, label: "产品名称", visible: true },
        { key: 2, label: "成品SN码", 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: "半成品SN", visible: true },
      ],
      // 显示隐藏持久化参数
      columnsList: [],
    };
  },
  computed: {
    ...mapGetters(["userId"]),
  },
  created() {
    // 获取显隐列列表
    this.getColumnsList();
    this.getList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      const params = {
        ...this.paramsQuery,
        ...this.queryParams,
      };
      getReBoxDetailPage(params)
        .then((response) => {
          this.list = response.data.list;
          this.total = response.data.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 表单重置 */
    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() {
      this.handleUnpacking();
    },
    // 拆箱
    handleUnpacking() {
      const params = {
        boxNo: this.queryParams.splitBoxNo,
      };
      if (
        this.queryParams.splitBoxNo === null ||
        this.queryParams.splitBoxNo === ""
      ) {
        this.$modal.msgWarning("箱号不能为空，请输入箱号拆箱");
        return;
      }
      const isExits = this.list.some(
        (item) => item.oldBoxNo === this.queryParams.boxNo
      );
      if (isExits) {
        this.$modal.msgWarning("该箱号已拆箱完成，请勿重复拆箱~");
        this.queryParams.splitBoxNo = null;
        return;
      }
      createSplit(params).then((res) => {
        this.$modal.msgSuccess("拆箱成功");
        this.getList();
        this.queryParams.splitBoxNo = null;
      });
    },
    getOnlyRowKey(row) {
      return row.id;
    },
    // 选中的
    handleSelectionChange(val) {
      this.currentRows = val;
    },
    // 重新装箱/打印外箱标签
    async handleRebox() {
      if (this.currentRows.length === 0) {
        return this.$modal.msgWarning("请先选择要重新装箱的数据~");
      }
      this.$refs.commonPrintDialog.visible = true;
    },

    // 选完模板打印
    async handleReboxAndPrint(templateData) {
      this.loading = true;
      try {
        const result = await reCreateBox(this.currentRows);
        this.list = [];
        this.$emit("complete");
        this.queryParams.caseNum = null;
        this.queryParams.materialSerinalNo = null;
        this.$modal.msgSuccess("重新装箱完成,正在打印...");
        this.getList();
        const { data } = result;

        const params = {
          id: data,
        };
        const reBoxDetailsResult = await getPrintData(params);
        this.printData.push(reBoxDetailsResult.data);

        // 打印参数
        const printParams = {
          printJson: JSON.stringify(this.printData),
          fileUrl: templateData?.BtReportUrl,
        };

        await printLabel(printParams); // 打印
        this.printData.length = 0;
      } catch (error) {
      } finally {
        this.loading = false;
        this.$refs.commonPrintDialog.visible = false;
      }
    },
    // mesReBoxStatus为1时，勾选框禁用
    selected(row) {
      const { mesReBoxStatus } = row;
      if (mesReBoxStatus === 1) {
        return false;
      } else {
        return true;
      }
    },
    // 获取显示隐藏列
    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);
        });
    },
  },
};
</script>

<style></style>
