<template>
  <div>
    <Navbar title="待打印" :is-go-back="true" />
    <PrintWidget
      ref="printWidget" :printer-localstorage-id="'#InventoryPrinterPrinter'"
      @selected-printer-name="getPrintName"
    />
    <a-form :colon="false">
      <a-row :gutter="[8, 0]" justify="space-start">
        <a-col>
          <a-form-item label="采购订单号" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-input v-model:value="documentNo" placeholder="输入采购订单号" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label="存货名称" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-input v-model:value="inventoryName" placeholder="输入存货档案名称" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label="存货编码" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-input v-model:value="inventoryCode" placeholder="输入存货档案编码" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item label="规格型号" :label-col="{ style: 'width: 80px' }" class="horizontal-form-item">
            <a-input v-model:value="inventoryType" placeholder="输入规格型号" class="w-full" />
          </a-form-item>
        </a-col>
        <a-col>
          <a-form-item>
            <a-button type="primary" @click="loadNeedPrintInventoryInstance">查询</a-button>
            <a-button style="margin-left: 10px;" type="primary" @click="printBarCode">打印条码</a-button>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <div>
      <CommonTable :total="pagination.total" :columns="columns" :data-source="inventoryInstances" :is-select="true" @get-selected="getSelected">
        <template #bodyCell="{ column, record, index }">
          <template v-if="column.dataIndex === 'index'">{{ index + 1 }}</template>
          <template v-if="column.dataIndex === 'printStatus'">待打印</template>
          <template v-else>{{ record[column.dataIndex] }}</template>
        </template>
      </CommonTable>
    </div>
    <Modal v-model:show="modal">
      <ProcessReportResult :process-report-result="processReportResult" />
      <template #header>执行结果</template>
    </Modal>
    <Loading v-if="loading" />
  </div>
</template>

<script>
import Common from '../common/Common.js';
import { PrintUtil } from 'pc-component-v3';
import CommonTable from '../common/CommonTable.vue';
import InventoryInstancePrintResource from '../api/wms/InventoryInstancePrintResource.js';
import { Form, Input, Button, Table, Checkbox } from 'ant-design-vue';

export default {
  components: {
    [Form.name]: Form,
    [Form.Item.name]: Form.Item,
    [Input.name]: Input,
    [Button.name]: Button,
    [Table.name]: Table,
    [Checkbox.name]: Checkbox,
    CommonTable,
  },
  data: function () {
    return {
      inventoryName: '',
      inventoryCode: '',
      inventoryType: '',
      documentNo: '',
      inventoryInstances: [],
      checkboxModel: [],
      checkAll: false,
      reportResult: {},
      processReportResult: {},
      pagination: {
        total: 0,
        pageSize: 30,
        current: 1,
      },
      loading: false,
      modal: false,
      selectedPrinterTitle: '',
      indeterminate: false,
    };
  },
  computed: {
    columns: function () {
      return [
        {
          title: '序号',
          dataIndex: 'index',
        },
        {
          title: '订单编号',
          dataIndex: 'purchaseOrderDocumentNo',
        },
        {
          title: '存货名称',
          dataIndex: 'inventoryName',
        },
        {
          title: '存货编码',
          dataIndex: 'inventoryCode',
        },
        {
          title: '规格型号',
          dataIndex: 'inventoryType',
        },
        {
          title: '创建日期',
          dataIndex: 'createDate',
        },
        {
          title: '包装内物料数量',
          dataIndex: 'printQuantity',
        },
        {
          title: '订单数量',
          dataIndex: 'quantity',
        },
        {
          title: '打印状态',
          dataIndex: 'printStatus',
        },
      ];
    },
    rowSelection() {
      return {
        selectedRowKeys: this.checkboxModel.map(item => item.id),
        onChange: (selectedRowKeys, selectedRows) => {
          this.checkboxModel = selectedRows;
        },
        getCheckboxProps: record => ({
          disabled: false, // 可根据需要设置禁用状态
        }),
      };
    },
  },
  watch: {
    checkboxModel: {
      handler(newVal) {
        this.indeterminate = !!newVal.length && newVal.length < this.inventoryInstances.length;
        this.checkAll = newVal.length === this.inventoryInstances.length;
      },
      deep: true,
    },
  },
  mounted: function () {
    this.loadNeedPrintInventoryInstance();
    this.keydown();
  },
  methods: {
    getSelected: function (selectedRows) {
      this.checkboxModel = selectedRows.selectedRows;
    },
    getPrintName: function (value) {
      this.selectedPrinterTitle = value;
    },
    loadNeedPrintInventoryInstance: function () {
      var _self = this;
      const documentNo = _self.documentNo;
      const inventoryName = _self.inventoryName;
      const inventoryCode = _self.inventoryCode;
      const inventoryType = _self.inventoryType;
      _self.loading = true;
      InventoryInstancePrintResource.queryInventoryInstancePrint(
        false,
        documentNo,
        inventoryName,
        inventoryCode,
        inventoryType,
      ).then(
        data => {
          if (data) {
            _self.inventoryInstances = data.inventoryInstancePrintDtos.map(item => ({
              ...item,
              checked: false,
            }));
            _self.pagination.total = data.totalCount;
          }
          _self.loading = false;
        },
        errorData => {
          _self.loading = false;
          Common.processException(errorData);
        },
      );
    },

    printBarCode: function () {
      if (this.checkboxModel.length === 0) {
        Notify.notice('提示', '请至少选择一项打印', false);
      } else if (!this.selectedPrinterTitle) {
        Notify.error('提示', '请先选择打印机。', false);
        return;
      }
      this.loading = true;
      const inventoryIds = this.checkboxModel.map(item => item.inventoryInstanceId);
      InventoryInstancePrintResource.print(inventoryIds).then(
        baseListResponse => {
          if (baseListResponse.errorCode === 0) {
            this.loading = false;
            const contents = [];
            baseListResponse.datas.forEach(item => {
              const printItem = {
                id: null,
                name: null,
                content: item,
              };
              if (
                !printItem.content ||
                !printItem.content.printItems ||
                printItem.content.printItems.length === 0
              ) {
                Notify.error('错误', '打印模板无数据，不能打印。');
                return;
              }
              const content = JSON.stringify(printItem.content);
              if (!content || content === '{}') {
                Notify.error('错误', '请先选择模板，再点击下载。');
                return;
              }
              contents.push(printItem.content);
            });
            PrintUtil.printPrintPages(contents, this.selectedPrinterTitle);
          }
        },
        errorData => {
          this.loading = false;
          Common.processException(errorData);
        },
      );
      setTimeout(() => {
        this.loadNeedPrintInventoryInstance();
        this.checkboxModel = [];
      }, 2000);
    },
    printPdf: function () {
      if (this.checkboxModel.length === 0) {
        Notify.notice('提示', '请至少选择一项打印', false);
        return;
      }
      this.loading = true;
    },
    keydown: function () {
      document.addEventListener('keydown', event => {
        if (event.key === 'Enter') {
          event.preventDefault();
          this.loadNeedPrintInventoryInstance();
        }
      });
    },
  },
};
</script>

<style scoped>
.ant-form-item {
  margin-bottom: 0px;
}

.horizontal-form-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.w-full {
  width: 160px;
}

:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}

:deep(.ant-form-item-label > label) {
  font-size: 14px !important;
  font-weight: 600 !important;
}
</style>