<template>
  <div>
    <seek-page :seekList="seekList" @search="search"></seek-page>
    <ele-pro-table
      ref="table"
      row-key="id"
      :columns="columns"
      :datasource="datasource"
      :cache-key="cacheKeyUrl"
      :selection.sync="selection"
      autoAmendPage
      height="var(--batch-record-table-height)"
    >
      <template v-slot:toolbar>
        <print-selector
          v-if="printOptions.length"
          :options="printOptions"
          @select="handlePrint"
        />
      </template>
    </ele-pro-table>

    <unqualified-product-review ref="unqualifiedProductReviewRef" />
    <product-release-approval ref="productReleaseApproval" />
    <sampling-form ref="samplingForm" />
  </div>
</template>

<script>
  import printSelector from '../printSelector.vue';
  import unqualifiedProductReview from '../../print/electrodeBatchRecord/unqualifiedProductReview.vue';
  import productReleaseApproval from '../../print/electrodeBatchRecord/productReleaseApproval.vue';
  import samplingForm from '../../print/electrodeBatchRecord/samplingForm.vue';
  import {
    checklistrecordBatchRecordPage,
    checklistrecordQueryPrint
  } from '@/api/checklistrecord/index';
  import {
    samplingRecordsBatchRecordPage,
    querySamplingPrint
  } from '@/api/samplingRecords';
  import {
    batchRecordPage as unacceptedProductPage,
    queryPrint as queryUnacceptedProductPrint
  } from '@/api/unacceptedProduct/index';
  import { getByCode } from '@/api/system/dictionary-data';
  import { reviewStatus } from '@/enum/dict';
  import { recordingMethodList } from '@/utils/util.js';
  import dictMixins from '@/mixins/dictMixins';
  import { buildReleaseOrderPrintData } from '../../utils/releaseOrderPrint';
  import {
    buildSamplingFormPrintData,
    getSamplingPrintIds
  } from '../../utils/samplingFormPrint';

  export default {
    name: 'pendingBatchRecordTable',
    mixins: [dictMixins],
    components: {
      printSelector,
      unqualifiedProductReview,
      productReleaseApproval,
      samplingForm
    },
    props: {
      tableQuery: {
        type: Object,
        default: () => {
          return {};
        }
      },
      tableType: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        selection: [],
        tableData: [],
        unacceptedProductPrintOptions: [
          {
            key: 'unqualifiedProductReview',
            label: '不合格品通知及评审处置表',
            code: 'TR.D-060/ZL'
          }
        ],
        releaseOrderPrintOptions: [
          {
            key: 'productReleaseApproval',
            label: '成品放行审批单',
            code: 'ZL-065'
          }
        ],
        samplePrintOptions: [
          {
            key: 'samplingForm',
            label: '取样单',
            code: 'ZL-041'
          }
        ],
        disposeList: []
      };
    },
    computed: {
      isSample() {
        return this.tableType === 'sample';
      },
      isUnacceptedProduct() {
        return this.tableType === 'unacceptedProduct';
      },
      isReleaseOrder() {
        return this.tableType === 'releaseOrder';
      },
      cacheKeyUrl() {
        return `batchRecord-${this.tableType || 'pending'}-table`;
      },
      printOptions() {
        if (this.isSample) {
          return this.samplePrintOptions;
        }
        if (this.isReleaseOrder) {
          return this.releaseOrderPrintOptions;
        }
        if (this.isUnacceptedProduct) {
          return this.unacceptedProductPrintOptions;
        }
        return [];
      },
      seekList() {
        if (this.isReleaseOrder) {
          return [
            {
              label: '放行单编码:',
              value: 'code',
              type: 'input',
              placeholder: '请输入'
            },
            {
              label: '放行单名称:',
              value: 'name',
              type: 'input',
              placeholder: '请输入'
            },
            {
              label: '审核状态:',
              value: 'approvalStatus',
              type: 'select',
              placeholder: '请选择',
              planList: [
                { value: 0, label: '未提交' },
                { value: 1, label: '审核中' },
                { value: 2, label: '审核通过' },
                { value: 3, label: '审核不通过' }
              ]
            }
          ];
        }

        if (this.isSample) {
          return [
            {
              label: '检测工单编码:',
              value: 'qualityWorkOrderCode',
              type: 'input',
              placeholder: '请输入',
              labelWidth: 120
            },
            {
              label: '取样记录编码:',
              value: 'code',
              type: 'input',
              placeholder: '请输入',
              labelWidth: 120
            },
            {
              label: '类型:',
              value: 'qualityType',
              type: 'DictSelection',
              dictName: '质检计划类型',
              placeholder: '请选择'
            },
            {
              label: '记录方法:',
              value: 'recordingMethod',
              type: 'select',
              placeholder: '请选择',
              planList: recordingMethodList
            }
          ];
        }

        return [
          {
            label: '编码:',
            value: 'unqualifiedProductsCode',
            type: 'input',
            placeholder: '请输入'
          },
          {
            label: '来源编码:',
            value: 'sourceCode',
            type: 'input',
            placeholder: '请输入'
          },
          {
            label: '物品编码:',
            value: 'categoryCode',
            type: 'input',
            placeholder: '请输入'
          },
          {
            label: '状态:',
            value: 'status',
            type: 'select',
            placeholder: '请选择',
            planList: [
              { value: 0, label: '待处置' },
              { value: 1, label: '部分处置' },
              { value: 2, label: '处置完成' }
            ]
          }
        ];
      },
      columns() {
        if (this.isReleaseOrder) {
          return [
            {
              width: 45,
              type: 'selection',
              columnKey: 'selection',
              align: 'center',
              fixed: 'left'
            },
            {
              width: 50,
              type: 'index',
              columnKey: 'index',
              label: '序号',
              align: 'center'
            },
            {
              prop: 'code',
              label: '放行单编码',
              align: 'center',
              minWidth: 130,
              showOverflowTooltip: true
            },
            {
              prop: 'name',
              label: '放行单名称',
              align: 'center',
              minWidth: 150,
              showOverflowTooltip: true
            },
            {
              prop: 'checklistType',
              label: '放行类型',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true,
              formatter: (row) =>
                this.getDictValue('放行类型', row.checklistType + '')
            },
            {
              prop: 'productCode',
              label: '产品编码',
              align: 'center',
              minWidth: 140,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'productCode')
            },
            {
              prop: 'productName',
              label: '产品名称',
              align: 'center',
              minWidth: 150,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'productName')
            },
            {
              prop: 'batchNo',
              label: '批次号',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'batchNo')
            },
            {
              prop: 'workOrderCode',
              label: '生产工单号',
              align: 'center',
              minWidth: 150,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'workOrderCode')
            },
            {
              prop: 'formingNum',
              label: '要求生产数量',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'formingNum')
            },
            {
              prop: 'formedNum',
              label: '实际生产数量',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'formedNum')
            },
            {
              prop: 'specification',
              label: '规格',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'specification')
            },
            {
              prop: 'productModel',
              label: '型号',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true,
              formatter: (row) => this.getOrderField(row, 'productModel')
            },
            {
              prop: 'approvalStatus',
              label: '审核',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true,
              formatter: (row) =>
                this.getApprovalStatusLabel(row.approvalStatus)
            },
            {
              prop: 'createTime',
              label: '创建时间',
              align: 'center',
              minWidth: 160,
              showOverflowTooltip: true
            },
            {
              columnKey: 'action',
              label: '操作',
              align: 'center',
              minWidth: 110,
              fixed: 'right'
            }
          ];
        }

        if (this.isSample) {
          return [
            {
              width: 45,
              type: 'selection',
              columnKey: 'selection',
              align: 'center',
              fixed: 'left'
            },
            {
              width: 50,
              type: 'index',
              columnKey: 'index',
              label: '序号',
              align: 'center'
            },
            {
              prop: 'code',
              label: '取样记录编码',
              align: 'center',
              minWidth: 150,
              showOverflowTooltip: true
            },
            {
              prop: 'qualityWorkOrderCode',
              label: '检测工单编码',
              align: 'center',
              minWidth: 150,
              showOverflowTooltip: true
            },
            {
              prop: 'qualityWorkOrderName',
              label: '检测工单名称',
              align: 'center',
              minWidth: 140,
              showOverflowTooltip: true
            },
            {
              prop: 'sourceCode',
              label: '来源单号',
              align: 'center',
              minWidth: 150,
              showOverflowTooltip: true
            },
            {
              prop: 'qualityType',
              label: '类型',
              align: 'center',
              minWidth: 100,
              showOverflowTooltip: true,
              formatter: (row) =>
                this.getDictValue('质检计划类型', row.qualityType)
            },
            {
              prop: 'qualityMode',
              label: '检测方式',
              align: 'center',
              minWidth: 100,
              showOverflowTooltip: true,
              formatter: (row) => (row.qualityMode == 1 ? '全检' : '抽检')
            },
            {
              prop: 'productCode',
              label: '编码',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'productName',
              label: '名称',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true
            },
            {
              prop: 'batchNo',
              label: '批次号',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'specification',
              label: '规格',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'modelType',
              label: '型号',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'brandNo',
              label: '牌号',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'produceTaskName',
              label: '工序名称',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true
            },
            {
              prop: 'conditionType',
              label: '取样类型',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true,
              formatter: (row) => (row.conditionType == 1 ? '整样' : '小样')
            },
            {
              prop: 'recordingMethod',
              label: '记录方法',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true,
              formatter: (row) =>
                recordingMethodList.find(
                  (item) => item.value == row.recordingMethod
                )?.label || ''
            },
            {
              prop: 'pleasePurpose',
              label: '取样目的',
              align: 'center',
              minWidth: 120,
              showOverflowTooltip: true
            },
            {
              prop: 'sampleQuantity',
              label: '取样数量',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'measureUnit',
              label: '单位',
              align: 'center',
              minWidth: 90,
              showOverflowTooltip: true
            },
            {
              prop: 'status',
              label: '状态',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true,
              formatter: (row) => this.getSampleStatusLabel(row.status)
            },
            {
              prop: 'approvalStatus',
              label: '审核状态',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true,
              formatter: (row) => reviewStatus[row.approvalStatus] || ''
            },
            {
              prop: 'createUserName',
              label: '创建人',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'createTime',
              label: '创建时间',
              align: 'center',
              minWidth: 160,
              showOverflowTooltip: true
            },
            {
              prop: 'approvalUserName',
              label: '审批人',
              align: 'center',
              minWidth: 110,
              showOverflowTooltip: true
            },
            {
              prop: 'approvalTime',
              label: '审批时间',
              align: 'center',
              minWidth: 160,
              showOverflowTooltip: true
            },
            {
              columnKey: 'action',
              label: '操作',
              align: 'center',
              minWidth: 110,
              fixed: 'right'
            }
          ];
        }

        const codeColumn = {
          prop: 'unqualifiedProductsCode',
          label: '不良品编码',
          align: 'center',
          minWidth: 150,
          showOverflowTooltip: true
        };

        return [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            fixed: 'left'
          },
          {
            width: 50,
            type: 'index',
            columnKey: 'index',
            label: '序号',
            align: 'center'
          },
          codeColumn,
          {
            prop: 'sourceCode',
            label: '来源编码',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'categoryCode',
            label: '物品编码',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'categoryName',
            label: '物品名称',
            align: 'center',
            minWidth: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'batchNo',
            label: '批次号',
            align: 'center',
            minWidth: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'specification',
            label: '规格',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'brandNum',
            label: '牌号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true
          },
          {
            prop: 'modelType',
            label: '型号',
            align: 'center',
            minWidth: 130,
            showOverflowTooltip: true
          },
          {
            prop: 'quantity',
            label: '数量',
            align: 'center',
            minWidth: 100,
            showOverflowTooltip: true
          },
          {
            prop: 'workOrderCode',
            label: '工单编码',
            align: 'center',
            minWidth: 140,
            showOverflowTooltip: true
          },
          {
            prop: 'disposeTime',
            label: '处置时间',
            align: 'center',
            minWidth: 160,
            showOverflowTooltip: true
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            minWidth: 90,
            showOverflowTooltip: true,
            formatter: (row) => this.getDisposeStatusLabel(row.status)
          },
          {
            columnKey: 'action',
            label: '操作',
            align: 'center',
            minWidth: 110,
            fixed: 'right'
          }
        ];
      }
    },
    created() {
      this.requestDict('放行类型');
      this.requestDict('质检计划类型');
      this.requestDict('处置状态');
      this.getDisposeList('dispose_status');
    },
    methods: {
      reload(where = {}) {
        this.$refs.table.reload({
          where,
          ...this.tableQuery
        });
      },
      search(where) {
        this.reload(where);
      },
      async handlePrint(key) {
        if (
          ![
            'productReleaseApproval',
            'samplingForm',
            'unqualifiedProductReview'
          ].includes(key) &&
          !this.selection.length
        ) {
          this.$message.warning('请先勾选要打印的数据');
          return;
        }

        if (key === 'unqualifiedProductReview') {
          await this.openUnqualifiedProductPrint();
          return;
        }
        if (key === 'productReleaseApproval') {
          await this.openReleaseOrderPrint();
          return;
        }
        if (key === 'samplingForm') {
          await this.openSamplingFormPrint();
        }
      },
      async openSamplingFormPrint() {
        try {
          const rows = this.selection.length ? this.selection : this.tableData;
          const ids = getSamplingPrintIds(rows);
          if (!ids.length) {
            this.$message.warning('未获取到可打印数据的ID');
            return;
          }
          const res = await querySamplingPrint(ids);
          const data = buildSamplingFormPrintData(res, rows);
          if (!data) {
            this.$message.warning('未查询到可打印的取样单数据');
            return;
          }
          this.$refs.samplingForm.open(data);
        } catch (error) {
          this.$message.error(error.message || '查询打印数据失败');
        }
      },
      async openReleaseOrderPrint() {
        try {
          const rows = this.selection.length ? this.selection : this.tableData;
          const ids = rows.map((item) => item.id).filter(Boolean);
          if (!ids.length) {
            this.$message.warning('未获取到可打印数据的ID');
            return;
          }
          const res = await checklistrecordQueryPrint(ids);
          const data = buildReleaseOrderPrintData(res, rows);
          if (!data) {
            this.$message.warning('未查询到可打印的放行单数据');
            return;
          }
          this.$refs.productReleaseApproval.open(data);
        } catch (error) {
          this.$message.error(error.message || '查询打印数据失败');
        }
      },
      async openUnqualifiedProductPrint() {
        try {
          const rows = this.selection.length ? this.selection : this.tableData;
          const ids = rows.map((item) => item.id).filter(Boolean);
          if (!ids.length) {
            this.$message.warning('未获取到可打印数据的ID');
            return;
          }
          const res = await queryUnacceptedProductPrint({ ids });
          const data = this.buildUnqualifiedProductPrintData(res, rows);
          if (!data) {
            this.$message.warning('未查询到可打印的不良品数据');
            return;
          }
          this.$refs.unqualifiedProductReviewRef.open(data);
        } catch (error) {
          this.$message.error(error.message || '查询打印数据失败');
        }
      },
      buildUnqualifiedProductPrintData(res, rows = this.selection) {
        const list = Array.isArray(res) ? res : [];
        if (!list.length) {
          return null;
        }
        return list.map((item, index) =>
          this.buildUnqualifiedProductPrintItem(
            item,
            this.getSelectedUnqualifiedProduct(item, index, rows)
          )
        );
      },
      getSelectedUnqualifiedProduct(item = {}, index, rows = this.selection) {
        return (
          rows.find(
            (row) =>
              (item.id && row.id == item.id) ||
              (item.unqualifiedProductsCode &&
                row.unqualifiedProductsCode == item.unqualifiedProductsCode)
          ) ||
          rows[index] ||
          rows[0] ||
          {}
        );
      },
      buildUnqualifiedProductPrintItem(item, selected) {
        const first = item || {};
        const specification = this.joinText([
          this.getValue(first.specification, selected.specification),
          this.getValue(first.modelType, selected.modelType)
        ]);

        return {
          ...selected,
          ...first,
          disposeNo: this.getValue(
            first.disposeNo,
            selected.disposeNo,
            first.unqualifiedProductsCode,
            selected.unqualifiedProductsCode
          ),
          categoryName: this.getValue(
            first.categoryName,
            selected.categoryName
          ),
          specification,
          modelType: this.getValue(first.modelType, selected.modelType),
          batchNo: this.getValue(first.batchNo, selected.batchNo),
          quantity: this.getValue(first.quantity, selected.quantity),
          measureUnit: this.getValue(first.measureUnit, selected.measureUnit),
          unqualifiedProductsCode: this.getValue(
            first.unqualifiedProductsCode,
            selected.unqualifiedProductsCode
          ),
          unqualifiedDescription: this.getValue(
            first.unqualifiedReason,
            selected.unqualifiedDescription,
            selected.unqualifiedReason
          ),
          unqualifiedReason: this.getValue(
            first.unqualifiedReason,
            selected.unqualifiedReason
          ),
          brandNum: this.getValue(first.brandNum, selected.brandNum)
        };
      },
      joinText(list) {
        return [
          ...new Set(
            (list || []).filter(
              (item) => item !== undefined && item !== null && item !== ''
            )
          )
        ].join('/');
      },
      getValue(...values) {
        const value = values.find(
          (item) => item !== undefined && item !== null && item !== ''
        );
        return value === undefined ? '' : value;
      },
      getFirstOrder(row) {
        return Array.isArray(row.orders) && row.orders.length
          ? row.orders[0]
          : {};
      },
      getOrderField(row, key) {
        if (row[key] !== undefined && row[key] !== null && row[key] !== '') {
          return row[key];
        }
        if (!Array.isArray(row.orders)) {
          return '';
        }
        return row.orders
          .map((item) => item[key])
          .filter(Boolean)
          .join(', ');
      },
      getApprovalStatusLabel(status) {
        switch (status) {
          case 0:
            return '未提交';
          case 1:
            return '审核中';
          case 2:
            return '审核通过';
          case 3:
            return '审核不通过';
          default:
            return '';
        }
      },
      getSampleStatusLabel(status) {
        switch (status) {
          case 1:
            return '审核中';
          case 2:
            return '已取样';
          case 3:
            return '已作废';
          case 4:
            return '不通过';
          default:
            return '未提交';
        }
      },
      getDisposeStatusLabel(status) {
        const data = this.disposeList.find((item) => item.value == status);
        return data ? data.label : '';
      },
      async getDisposeList(code) {
        const res = await getByCode(code);
        if (res?.code == 0) {
          this.disposeList = res.data.map((item) => {
            const key = Object.keys(item)[0];
            return { value: Number(key), label: item[key] };
          });
        }
      },
      datasource({ page, limit, where, order }) {
        if (this.isReleaseOrder) {
          const body = {
            ...where,
            ...order,
            pageNum: page,
            size: limit,
            ...this.tableQuery
          };
          const res = checklistrecordBatchRecordPage(body);
          Promise.resolve(res).then((data) => {
            this.tableData = data?.list || data?.records || [];
          });
          return res;
        }

        if (this.isSample) {
          const body = {
            ...where,
            ...order,
            pageNum: page,
            size: limit,
            ...this.tableQuery
          };
          const res = samplingRecordsBatchRecordPage(body);
          Promise.resolve(res).then((data) => {
            this.tableData = data?.list || data?.records || [];
          });
          return res;
        }

        if (this.isUnacceptedProduct) {
          const body = {
            ...where,
            ...order,
            pageNum: page,
            size: limit,
            ...this.tableQuery
          };
          const res = unacceptedProductPage(body);
          Promise.resolve(res).then((data) => {
            this.tableData = data?.list || data?.records || [];
          });
          return res;
        }

        return Promise.resolve({
          list: [],
          count: 0
        });
      }
    }
  };
</script>
