<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:action="{ row }">
        <el-link type="primary" :underline="false" @click="goToDetail(row)">
          详情
        </el-link>
      </template>

      <template v-slot:bizNo="{ row }">
        <el-link type="primary" @click="goToDetail(row)">{{
          row.bizNo
        }}</el-link>
      </template>
      <template v-slot:toolbar>
        <exportButton
          fileName="入库单"
          apiUrl="/wms/outintwo/exportBatchRecordPage"
          :params="params"
        ></exportButton>
        <print-selector :options="printOptions" @select="handlePrint" />
      </template>
    </ele-pro-table>

    <finished-product-warehouse ref="finishedProductWarehouse" />
  </div>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import tableColumnsMixin from '@/mixins/tableColumnsMixin';
  import { getPages } from '@/api/wms/index';
  import { sceneState } from '@/utils/dict/index';
  import { getBatchRecordPage, printInbound } from '@/api/wms/index';
  import exportButton from '@/components/upload/exportButton.vue';
  import printSelector from '../printSelector.vue';
  import finishedProductWarehouse from '../../print/electrodeBatchRecord/finishedProductWarehouse.vue';

  export default {
    mixins: [dictMixins, tableColumnsMixin],
    components: { exportButton, printSelector, finishedProductWarehouse },
    props: {
      tableQuery: {
        type: Object,
        default: () => {
          return {};
        }
      }
    },
    data() {
      return {
        sceneState,
        columns: [
          {
            width: 45,
            type: 'selection',
            columnKey: 'selection',
            align: 'center',
            fixed: 'left'
          },
          {
            width: 50,
            type: 'index',
            columnKey: 'index',
            align: 'center',
            label: '序号'
          },
          {
            prop: 'bizNo',
            label: '单号',
            align: 'center',
            minWidth: 110,
            showOverflowTooltip: true,
            slot: 'bizNo'
          },
          {
            prop: 'warehouseName',
            label: '仓库名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'bizType',
            label: '入库类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150,
            formatter: (row) => {
              for (const key in this.sceneState) {
                if (this.sceneState[key].code == row.bizType) {
                  return this.sceneState[key].label;
                }
              }
            }
          },
          {
            prop: 'sourceBizNo',
            label: '来源单据',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'createUserName',
            label: '入库人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'storageTime',
            label: '入库时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150
          },
          {
            prop: 'outInStatus',
            label: '入库状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 150,
            formatter: (row) => {
              if (row.verifyStatus == 2) {
                switch (row.outInStatus) {
                  case '1':
                    return '预入库';
                  case '2':
                    return '部分入库';
                  case '3':
                    return '已入库';
                  default:
                    return '';
                }
              }
            }
          },
          {
            label: '操作',
            columnKey: 'action',
            slot: 'action',
            showOverflowTooltip: true,
            minWidth: 110,
            align: 'center',
            fixed: 'right'
          }
        ],
        cacheKeyUrl: 'mes-259231507-mwmsoutint-table',
        params: {},
        tableData: [],
        selection: [],
        printOptions: [
          {
            key: 'finishedProductWarehouse',
            label: '产成品入库单（畅捷通）',
            code: 'TR.D-012CG'
          }
        ]
      };
    },
    computed: {
      seekList() {
        return [
          {
            label: '来源单据：',
            value: 'sourceBizNo',
            type: 'input',
            placeholder: '请输入'
          },
          {
            label: '入库时间',
            value: 'time',
            type: 'date',
            dateType: 'daterange',
            valueFormat: 'yyyy-MM-dd',
            placeholder: '请输入'
          },
          {
            label: '入库单号',
            value: 'bizNo',
            type: 'input',
            placeholder: '请输入'
          }
        ];
      }
    },
    methods: {
      // 刷新表格
      reload(where = {}) {
        this.$refs.table.reload({
          where,
          ...this.tableQuery
        });
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        // 参数
        const body = {
          ...where,
          ...order,
          pageNum: page,
          size: limit,
          ...this.tableQuery,
          // type  "1=入库 2=出库" 默认1
          type: 1
        };
        this.params = body;
        const res = getBatchRecordPage(body);
        Promise.resolve(res).then((data) => {
          this.tableData = data?.list || data?.records || [];
        });
        return res;
      },
      search(where) {
        console.log('where', where);
        if (where.time) {
          where.startTime = where.time[0];
          where.endTime = where.time[1];
        }
        // 覆盖时间
        this.reload({ ...where, time: null });
      },
      goToDetail(row) {
        const path = `/page-wms/warehouseManagement/stockManagement/details?id=${row.id}&verifyStatus=${row.verifyStatus}`;
        window.history.pushState(null, '', path);
      },
      openPrint(row) {
        this.$refs.finishedProductWarehouse.open(row);
      },
      async handlePrint(key) {
        try {
          const printRows = this.selection.length
            ? this.selection
            : this.tableData;
          const ids = printRows.map((item) => item.id).filter(Boolean);
          if (!ids.length) {
            this.$message.warning('列表暂无可打印的入库单');
            return;
          }
          const res = await printInbound(ids);
          const data = this.buildPrintData(res, printRows);
          if (!data) {
            this.$message.warning('未查询到可打印的入库单数据');
            return;
          }
          if (this.$refs[key]) {
            this.$refs[key].open(data);
          }
        } catch (error) {
          this.$message.error(error.message || '查询打印数据失败');
        }
      },
      buildPrintData(res, printRows = []) {
        const list = Array.isArray(res)
          ? res
          : Array.isArray(res?.data)
          ? res.data
          : [];
        const r = printRows[0] || {};
        const firstItem = list[0] || {};
        const today = this.$util?.toDateString
          ? this.$util.toDateString(new Date(), 'yyyy-MM-dd')
          : new Date().toISOString().slice(0, 10);
        const itemList = list.map((item) => ({
          ...item,
          itemCode: item.code || '',
          itemName: item.name || '',
          modelType: item.modelType || '',
          specification: item.specification || '',
          specificationModel: this.joinPrintValues([
            item.specification,
            item.modelType
          ]),
          batchNo: item.batchNo || '',
          productionDate: this.formatPrintDate(item.productionDate),
          expiryDate: this.formatPrintDate(item.expirationDate),
          unit: item.unit || '',
          quantity: item.quantity ?? '',
          remark: item.remark || ''
        }));
        if (!itemList.length) {
          return null;
        }
        return {
          batchNo: this.tableQuery.batchNo,
          productCode: this.tableQuery.productCode,
          productName: r.productName || firstItem.name || '',
          specification: this.joinPrintValues([
            firstItem.specification,
            firstItem.modelType
          ]),
          code: r.bizNo || '',
          date:
            this.formatPrintDate(r.storageTime || firstItem.createTime) ||
            today,
          warehouse: r.warehouseName || '',
          department: firstItem.groupName || r.groupName || '',
          processOrderCode: r.sourceBizNo || '',
          processOrderNo: r.sourceBizNo || '',
          moCode: r.sourceBizNo || '',
          handler: r.createUserName || '',
          receiver: r.createUserName || '',
          reporter: r.createUserName || '',
          creator: r.createUserName || '',
          reviewer:
            firstItem.verifyName || r.verifyName || r.reviewerName || '',
          totalQuantity: this.getTotalQuantity(itemList),
          remark: r.remark || firstItem.remark || '',
          itemList
        };
      },
      formatPrintDate(value) {
        if (!value) {
          return '';
        }
        if (typeof value === 'string') {
          return value.slice(0, 10);
        }
        return this.$util?.toDateString
          ? this.$util.toDateString(value, 'yyyy-MM-dd')
          : '';
      },
      joinPrintValues(values) {
        return values
          .filter(
            (value, index, list) => value && list.indexOf(value) === index
          )
          .join('/');
      },
      getTotalQuantity(list) {
        const total = list.reduce((sum, item) => {
          const quantity = Number(item.quantity);
          return Number.isNaN(quantity) ? sum : sum + quantity;
        }, 0);
        return total || '';
      }
    }
  };
</script>

<style></style>
