<template>
  <div class="gi_table_page">
    <GiTable
      title="整箱领取记录管理"
      row-key="id"
      :data="dataList"
      :columns="columns"
      :loading="loading"
      :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
      :pagination="pagination"
      :disabled-tools="['size']"
      :disabled-column-keys="['name']"
      @refresh="search"
    >
      <template #toolbar-left>
	    <a-input-search v-model="queryForm.orderNo" placeholder="请输入任务工单号" allow-clear @search="search" />
	    <a-input-search v-model="queryForm.materialCode" placeholder="请输入物料编码" allow-clear @search="search" />
	    <a-input-search v-model="queryForm.materialName" placeholder="请输入物料名称" allow-clear @search="search" />
	    <a-input-search v-model="queryForm.batch" placeholder="请输入批次号" allow-clear @search="search" />
        <a-range-picker
            v-model="queryForm.createTime"
            :show-time="true"
            format="YYYY-MM-DD HH:mm:ss"
            style="height: 32px"
            :allow-clear="true"
            @change="search"
        />
        <a-button @click="reset">
          <template #icon><icon-refresh /></template>
          <template #default>重置</template>
        </a-button>
      </template>
      <template #toolbar-right>
        <a-button v-permission="['fullWorkOrder:fullWorkOrder:add']" type="primary" @click="onAdd">
          <template #icon><icon-plus /></template>
          <template #default>新增</template>
        </a-button>
        <a-button v-permission="['fullWorkOrder:fullWorkOrder:export']" @click="onExport">
          <template #icon><icon-download /></template>
          <template #default>导出</template>
        </a-button>
      </template>

      <template #imgUrl="{ record }">
        <a-image
            width="60"
            :src="record.imgUrl"
        />
      </template>

      <template #action="{ record }">
        <a-space>
          <a-link
            @click="onAddDetail(record.id)"
          >
            新增
          </a-link>
          <a-link
            @click="onViewDetail(record)"
          >
            详情
          </a-link>
          <a-link
            @click="onPrint(record)"
          >
            打印
          </a-link>
          <a-link
            v-permission="['fullWorkOrder:fullWorkOrder:delete']"
            status="danger"
            :disabled="record.disabled"
            :title="record.disabled ? '不可删除' : '删除'"
            @click="onDelete(record)"
          >
            删除
          </a-link>
        </a-space>
      </template>
    </GiTable>

    <FullWorkOrderAddModal ref="FullWorkOrderAddModalRef" @save-success="search" />
    <FullWorkOrderDetailModal ref="FullWorkOrderDetailModalRef" @save-success="search" />
    <FullWorkOrderDetailListModal ref="FullWorkOrderDetailListModalRef" />
  </div>
</template>

<script setup lang="ts">
import FullWorkOrderAddModal from './FullWorkOrderAddModal.vue'
import FullWorkOrderDetailModal from './FullWorkOrderDetailModal.vue'
import FullWorkOrderDetailListModal from './FullWorkOrderDetailListModal.vue'
import { type FullWorkOrderResp, type FullWorkOrderQuery, deleteFullWorkOrder, exportFullWorkOrder, listFullWorkOrder } from '@/apis/fullWorkOrder/fullWorkOrder'
import type { TableInstanceColumns } from '@/components/GiTable/type'
import { useDownload, useTable } from '@/hooks'
import { isMobile } from '@/utils'
import has from '@/utils/has'
import type {WorkOrderResp} from "@/apis/workOrder/workOrder";
import QRCode from 'qrcode';

defineOptions({ name: 'FullWorkOrder' })


const queryForm = reactive<FullWorkOrderQuery>({
  orderNo: undefined,
  materialCode: undefined,
  materialName: undefined,
  batch: undefined,
  createTime: undefined,
  sort: ['f.id,desc']
})

const {
  tableData: dataList,
  loading,
  pagination,
  search,
  handleDelete
} = useTable((page) => listFullWorkOrder({ ...queryForm, ...page }), { immediate: true })
const columns = ref<TableInstanceColumns[]>([
  { title: '标题', dataIndex: 'title', slotName: 'title' },
  { title: '任务工单号', dataIndex: 'orderNo', slotName: 'orderNo' },
  { title: '物料名称', dataIndex: 'materialName', slotName: 'materialName' },
  { title: '物料编码', dataIndex: 'materialCode', slotName: 'materialCode' },
  { title: '批次号', dataIndex: 'batch', slotName: 'batch' },
  { title: '数量', dataIndex: 'count', slotName: 'count' },
  { title: '标记号', dataIndex: 'mark', slotName: 'mark' },
  { title: '抓拍图', dataIndex: 'imgUrl', slotName: 'imgUrl' },
  { title: '创建人', dataIndex: 'createUserString', slotName: 'createUser' },
  { title: '创建时间', dataIndex: 'createTime', slotName: 'createTime' },
  { title: '修改人', dataIndex: 'updateUserString', slotName: 'updateUser', show: false },
  { title: '修改时间', dataIndex: 'updateTime', slotName: 'updateTime', show: false },
  {
    title: '操作',
    dataIndex: 'action',
    slotName: 'action',
    width: 220,
    align: 'center',
    fixed: !isMobile() ? 'right' : undefined,
    show: has.hasPermOr(['fullWorkOrder:fullWorkOrder:detail', 'fullWorkOrder:fullWorkOrder:update', 'fullWorkOrder:fullWorkOrder:delete'])
  }
]);

// 重置
const reset = () => {
  queryForm.orderNo = undefined
  queryForm.materialCode = undefined
  queryForm.materialName = undefined
  queryForm.batch = undefined
  queryForm.createTime = undefined
  search()
}

// 删除
const onDelete = (record: FullWorkOrderResp) => {
  return handleDelete(() => deleteFullWorkOrder(record.id), {
    content: `是否确定删除该条数据？`,
    showModal: true
  })
}

// 生成二维码
const generateQRCode = async (data: string) => {
  try {
    return await QRCode.toDataURL(data, {
      width: 120,
      margin: 1,
      color: {
        dark: '#000000',
        light: '#FFFFFF'
      }
    })
  } catch (error) {
    console.error('生成二维码失败:', error)
    return ''
  }
}

const onPrint = async (record: FullWorkOrderResp) => {
  try {
    // 格式化生产日期为 yyyyMMddHHmm 格式
    const now = new Date()
    const formattedDate = now.getFullYear().toString() + 
      String(now.getMonth() + 1).padStart(2, '0') + 
      String(now.getDate()).padStart(2, '0') + 
      String(now.getHours()).padStart(2, '0') + 
      String(now.getMinutes()).padStart(2, '0')

    const formattedDate2 = now.getFullYear().toString() +
        String(now.getMonth() + 1).padStart(2, '0') +
        String(now.getDate()).padStart(2, '0')
    
    // 计算二维码数据
    const qrCodeData = `10#${record.materialCode || ''}$11#9DP$12#${record.batch || ''}$17#${record.count || ''}$20#${formattedDate2}$31#${record.orderNo || ''}$DY`
    
    // 生成二维码图片
    const qrCodeImage = await generateQRCode(qrCodeData)
    
    // 直接生成打印标签
    const printWindow = window.open('', '_blank');
    if (!printWindow) return;
    
    // 构建打印内容
    const printContent = `
      <!DOCTYPE html>
      <html>
      <head>
        <title>标签打印</title>
        <style>
          body { margin: 0; padding: 10mm; font-family: Arial, sans-serif; }
          .label-container { display: flex; flex-wrap: wrap; gap: 10mm; justify-content: center; }
          .label { width: 90mm; height: 38.5mm; border: 1px solid #000; padding: 0; box-sizing: border-box; page-break-inside: avoid; }
          .label-table { width: 100%; height: 100%; border-collapse: collapse; }
          .label-cell { border: 1px solid #000; padding: 1mm; vertical-align: top; }
          .qr-cell { width: 24mm; text-align: center; vertical-align: middle; border: 1px solid #000; }
          .label-row { display: flex; align-items: center; }
          .label-field { font-size: 8pt; font-weight: bold; margin-right: 2mm; min-width: 25pt; }
          .label-value { font-size: 8pt; font-weight: bold; flex: 1; }
          .qr-code img { width: 20mm; height: 20mm; margin: 1mm 0; }
          .mark-number { font-size: 8pt; font-weight: bold; margin-top: 1mm; text-align: center; }
          .serial-number { font-size: 8pt; font-weight: bold; margin-top: 1mm; }
        </style>
      </head>
      <body>
        <div class="label-container">
          <div class="label">
            <table class="label-table">
              <tr>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">零件名称</div>
                    <div class="label-value">${record.materialName || ''}</div>
                  </div>
                </td>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">生产日期</div>
                    <div class="label-value">${formattedDate}</div>
                  </div>
                </td>
                <td class="label-cell qr-cell" rowspan="4">
                  <div class="qr-code">
                    <img src="${qrCodeImage}" alt="QR Code" />
                    <div class="mark-number">${record.mark || ''}</div>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">零件号</div>
                    <div class="label-value">${record.materialCode || ''}</div>
                  </div>
                </td>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">数量</div>
                    <div class="label-value">${record.count || ''}</div>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">标重(g)</div>
                    <div class="label-value"></div>
                  </div>
                </td>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">包装签字</div>
                    <div class="label-value"></div>
                  </div>
                </td>
              </tr>
              <tr>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">实重(g)</div>
                    <div class="label-value"></div>
                  </div>
                </td>
                <td class="label-cell">
                  <div class="label-row">
                    <div class="label-field">检验签字</div>
                    <div class="label-value"></div>
                  </div>
                </td>
              </tr>
            </table>
          </div>
        </div>
      </body>
      </html>
    `;
    
    printWindow.document.write(printContent);
    printWindow.document.close();
    
    // 等待页面加载完成后打印
    printWindow.onload = function() {
      setTimeout(() => {
        printWindow.focus();
        printWindow.print();
        printWindow.close();
      }, 500);
    };
  } catch (error) {
    console.error('打印标签失败:', error);
  }
}

// 导出
const onExport = () => {
  useDownload(() => exportFullWorkOrder(queryForm))
}

const FullWorkOrderAddModalRef = ref<InstanceType<typeof FullWorkOrderAddModal>>()
const FullWorkOrderDetailModalRef = ref<InstanceType<typeof FullWorkOrderDetailModal>>()
const FullWorkOrderDetailListModalRef = ref<InstanceType<typeof FullWorkOrderDetailListModal>>()

// 新增
const onAdd = () => {
  FullWorkOrderAddModalRef.value?.onAdd()
}

// 新增原材料详情
const onAddDetail = (id: string) => {
  FullWorkOrderDetailModalRef.value?.onAdd(id)
}

// 查看原材料详情
const onViewDetail = (record: FullWorkOrderResp) => {
  FullWorkOrderDetailListModalRef.value?.onOpen(record.id)
}

</script>

<style scoped lang="scss"></style>