<template>
  <div class="print-form-page">
    <div class="dialog-title-with-tags">
      <span>{{ dialogTitle }}</span>
      <el-tag
        v-if="formData.printed !== undefined"
        size="small"
        :type="yesOrNoMapClass[formData.printed]"
        class="ml-2"
        >{{ printMap[formData.printed] }}</el-tag
      >
      <el-tag
        v-if="formData.processed !== undefined"
        size="small"
        :type="yesOrNoMapClass[formData.processed]"
        class="ml-2"
        >{{ processedMap[formData.processed] }}</el-tag
      >
    </div>
    <!-- 主弹窗内容：Tab页和TableList组件 -->
    <!-- 采购订单详情Tab页 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange" class="noContent print-tabs">
      <!-- 源单明细 -->
      <el-tab-pane label="源单明细" name="sourceDetail" />

      <!-- 标签明细 -->
      <el-tab-pane label="标签明细" name="labelDetail" />

      <!-- 标签生成记录 -->
      <el-tab-pane label="标签生成记录" name="labelGenerateDetail" />

      <!-- 订单变更记录 -->
      <el-tab-pane label="订单变更记录" name="orderChangeRecord" />

      <!-- 单据信息 -->
      <el-tab-pane label="单据信息" name="billInfo" />
    </el-tabs>

    <!-- 单个TableList组件 -->
    <TableList
      v-if="activeTab != 'billInfo'"
      ref="tableListRef"
      :config="currentTableConfig.value"
      :key="tableListKey"
      :isPopup="true"
      :autoLoad="false"
      :tableHeight="tableHeight"
    />
    <div v-if="activeTab == 'billInfo'" class="material-basic-info">
      <div class="info-field" v-for="(field, index) in basicInfoFields" :key="index">
        <div class="info-item">
          <div class="info-label">{{ field.label }}</div>
          <div class="info-value">{{ formData[field.field] || '-' }}</div>
        </div>
      </div>
    </div>
  </div>


  <!-- 条码生成表单弹窗 -->
  <Dialog
    v-model="formDialogVisible"
    :title="formDialogTitle"
    width="600px"
    :close-on-click-modal="false"
    @closed="resetLabelForm"
  >
    <el-form
      ref="labelFormRef"
      :model="labelFormData"
      :rules="labelFormRules"
      label-position="top"
      label-width="100px"
    >
      <el-form-item label="条码规则" prop="barcodeRule">
        <el-select
          v-model="labelFormData.barcodeRule"
          placeholder="请选择条码规则"
          style="width: 100%"
        >
          <el-option
            v-for="rule in barcodeRules"
            :key="rule.value"
            :label="rule.label"
            :value="rule.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="条码模板" prop="barcodeTemplate">
        <el-select
          v-model="labelFormData.barcodeTemplate"
          placeholder="请选择条码模板"
          style="width: 100%"
          filterable
          remote
          :remote-method="(q) => { remoteMethodBarcodeTemplate(q, labelFormData.barcodeRule) }"
          :loading="barcodeTemplateLoading"
        >
          <el-option
            v-for="template in barcodeTemplates"
            :key="template.value"
            :label="template.label"
            :value="template.value"
          />
        </el-select>
      </el-form-item>

      <!-- 倍数字段：只在逐行生成标签、编辑时显示 -->
      <el-form-item
        v-if="formDialogTitle === '逐行生成标签' || formDialogTitle === '编辑标签'"
        label="倍数"
        prop="multiple"
      >
        <el-input
          v-model="labelFormData.multiple"
          placeholder="请输入倍数"
          @input="handlemultipleInput"
          style="width: 100%"
        />
        <p class="error-text" v-if="formDialogTitle === '逐行生成标签'">
          若不填写，按照行明细默认倍数生成标签
        </p>
      </el-form-item>

      <!-- 数量字段：只在合并生成条码时显示 -->
      <el-form-item v-if="formDialogTitle === '合并生成条码'" label="数量" prop="printNumber">
        <el-input
          v-model="labelFormData.printNumber"
          placeholder="请输入数量"
          @blur="handlePrintNumberBlur"
          @keydown="handlePrintNumberKeydown"
          style="width: 100%"
        />
        <p class="error-text" v-if="formDialogTitle === '合并生成条码'">
          倍数=数量，输入即为实际生成数量
        </p>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="formDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleFormSubmit">保存</el-button>
    </template>
  </Dialog>

  <!-- 标签预览弹窗 -->
  <Dialog
    v-model="previewDialogVisible"
    :title="previewDialogTitle"
    width="600px"
    :close-on-click-modal="false"
    @closed="resetPreviewForm"
  >
    <el-form
      ref="previewFormRef"
      :model="previewFormData"
      :rules="previewFormRules"
      label-position="top"
      label-width="100px"
    >
      <el-form-item label="条码规则" prop="barcodeRule">
        <el-select
          v-model="previewFormData.barcodeRule"
          placeholder="请选择条码规则"
          style="width: 100%"
        >
          <el-option
            v-for="rule in barcodeRules"
            :key="rule.value"
            :label="rule.label"
            :value="rule.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="条码模板" prop="barcodeTemplate">
        <el-select
          v-model="previewFormData.barcodeTemplate"
          placeholder="请选择条码模板"
          style="width: 100%"
          filterable
          remote
          :remote-method="(q) => { remoteMethodBarcodeTemplate(q, previewFormData.barcodeRule) }"
          :loading="barcodeTemplateLoading"
        >
          <el-option
            v-for="template in barcodeTemplates"
            :key="template.value"
            :label="template.label"
            :value="template.value"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="previewDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handlePrint">打印</el-button>
    </template>
  </Dialog>

  <!-- 补打标签弹窗 -->
  <Dialog
    v-model="reprintDialogVisible"
    :title="reprintDialogTitle"
    width="80%"
    :close-on-click-modal="false"
    @closed="resetReprintForm"
  >
    <el-form
      ref="reprintFormRef"
      :model="reprintForm"
      :rules="reprintFormRules"
      label-width="100px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="条码规则" prop="barcodeRule">
            <el-select
              v-model="reprintForm.barcodeRule"
              placeholder="请选择条码规则"
              style="width: 100%"
            >
              <el-option
                v-for="rule in barcodeRules"
                :key="rule.value"
                :label="rule.label"
                :value="rule.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="条码模板" prop="barcodeTemplate">
            <el-select
              v-model="reprintForm.barcodeTemplate"
              placeholder="请选择条码模板"
              style="width: 100%"
              filterable
              remote
              :remote-method="(q) => { remoteMethodBarcodeTemplate(q, reprintForm.barcodeRule) }"
              :loading="barcodeTemplateLoading"
              @change="handleBarcodeTemplateChange"
            >
              <el-option
                v-for="template in barcodeTemplates"
                :key="template.value"
                :label="template.label"
                :value="template.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 打印详情列表 -->
    <div style="margin-top: 15px">
      <EditTable
        v-if="reprintDialogTitle == '箱贴打印'"
        v-model="reprintForm.printDetails"
        :config="reprintDetailTableConfig2"
        title="打印清单"
        :addButtonShow="false"
      />
      <EditTable
        v-else
        v-model="reprintForm.printDetails"
        :config="reprintDetailTableConfig"
        title="打印清单"
        :addButtonShow="false"
      />
    </div>

    <template #footer>
      <el-button @click="reprintDialogVisible = false">取消</el-button>
      <template v-if="reprintDialogTitle == '补打标签'">
        <el-button type="primary" @click="handleReprintSubmit" :loading="silentPrintLoading">打印</el-button>
      </template>
      <template v-else>
        <el-button type="primary" @click="handleReprintSubmit" :loading="silentPrintLoading">打印</el-button>
      </template>
    </template>
  </Dialog>

  <!-- 处理弹窗 -->
  <Dialog v-model="processDialogVisible" title="处理" width="600px" :close-on-click-modal="false">
    <el-form
      ref="processFormRef"
      :model="processFormData"
      :rules="processFormRules"
      label-position="top"
      label-width="100px"
    >
      <el-form-item label="处理记录" prop="remark">
        <el-input
          v-model="processFormData.remark"
          type="textarea"
          :rows="4"
          placeholder="请输入处理记录"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="processDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleProcessSubmit">确定</el-button>
    </template>
  </Dialog>
  <!--打印预览组件-->
  <DialogPreview ref="dialogPreviewRef" :show-line-info="true" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, h, toRaw, onMounted, watch, nextTick } from 'vue'
import { useMessage } from '@/hooks/web/useMessage'
import { ElMessageBox, ElButton } from 'element-plus'
import { formatDate, dateFormatter } from '@/utils/formatTime'
import { useRoute } from 'vue-router'
import { browserPrint, silentPrint, mut_silentPrint, printFun } from '@/utils/print'
import EditTable from '@/components/EditTable/index.vue'
import DialogPreview from '@/components/PrintDesginer/dialogPreview2.vue'
import {
  getPurchaseOrderHeader,
  getPurchaseOrderDetailsPage,
  createPurchaseOrderTagDetail,
  getPurchaseOrderTagDetailPage,
  getPurchaseOrderTagRecordPage,
  getPurchaseOrderChangeRecordPage,
  updatePurchaseOrderTagDetail,
  updatePurchaseOrderTagDetailCompleteStatus,
  deletePurchaseOrderTagDetailList,
  updatePurchaseOrderChangeRecord,
  getTagTemplateConfigList
} from '@/api/print/purchaseOrder'
import { getApiSettingList, tagTemplateConfigList, tagTemplateConfigPageList } from '@/api/print/apiSetting'
import TableList from '@/components/TableList/index.vue'
defineOptions({ name: 'PrintForm' })

const message = useMessage() // 消息弹窗
const route = useRoute()
// 主弹窗相关
const dialogVisible = ref(false)
const formLoading = ref(false)
const type = ref('') // 操作类型：create-新增；update-修改
const tableHeight = ref(500) // 表格高度
const dialogPreviewRef = ref<any>(null)
const isViewMode = ref(false) // 是否为查看模式
// Tab相关
const activeTab = ref('sourceDetail') // 当前激活的tab

// TableList组件引用 - 单个组件用于所有tab
const tableListRef = ref() // 单个TableList组件引用
const printLoading = ref(false)
const previewPrintLoading = ref(false)
const silentPrintLoading = ref(false)
/** 打开弹窗 */
const open = async (typeStr: string, id?: number | string, activeTabValue?: string) => {
  dialogVisible.value = true
  type.value = typeStr
  isViewMode.value = typeStr === 'view' // 设置是否为查看模式
  if ((typeStr === 'print' || typeStr === 'view') && id) {
    await fetchPurchaseOrderDetail(id, activeTabValue)
  } else if (typeStr === 'create') {
    // 新增时清空基础信息
    Object.keys(formData).forEach((key) => {
      formData[key as keyof typeof formData] = ''
    })
    purchaseOrderNo.value = ''
  }
}
// 页面加载时设置表格高度
onMounted(() => {
  if (typeof window !== 'undefined') {
    tableHeight.value = window.innerHeight - 360
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      tableHeight.value = window.innerHeight - 360
    })
  }
  open('print', route.query.id)
})

// 表单数据对象，用于存储基础信息字段的值
const formData = reactive({
  purchaseOrder: 'PO-20260101-001',
  purchaseOrderType: '标准采购订单',
  companyCode: '0001',
  purchasingOrganization: '1000',
  purchasingGroup: '001',
  supplier: 'SUP-001',
  supplierName: '上海供应商有限公司',
  creatorName: '王五',
  createTime: '2026-01-01 10:00:00',
  remark: '这是打印备注',
  printedByName: '张三',
  printedTime: '2026-01-10 14:30:00',
  processedByName: '李四',
  processedTime: '2026-01-16 09:20:00'
})

// 条码规则数据
const barcodeRules = ref([])

// 条码模板数据
const barcodeTemplates = ref([])
const barcodeTemplateLoading = ref(false)
const printMap = {
  0: '未打印',
  1: '已打印'
}
const yesOrNoMapClass = {
  0: 'info',
  1: 'success'
}
const processedMap = {
  0: '未处理',
  1: '已处理'
}
const yesOrNoMap = {
  0: '否',
  1: '是'
}
const watchBarcode = ref(true)

// 选中的行数据
const selectedRows = ref([])

// 表单弹窗可见性
const formDialogVisible = ref(false)

// 弹窗标题
const formDialogTitle = ref('生成标签')

// 预览弹窗可见性
const previewDialogVisible = ref(false)

// 预览弹窗标题
const previewDialogTitle = ref('标签预览')

// 预览表单数据
const previewFormData = reactive({
  barcodeRule: '',
  barcodeTemplate: ''
})

// 预览表单验证规则
const previewFormRules = {
  barcodeRule: [{ required: true, message: '请选择条码规则', trigger: 'change' }],
  barcodeTemplate: [{ required: true, message: '请选择条码模板', trigger: 'change' }]
}

// 预览表单引用
const previewFormRef = ref()

// 补打标签弹窗可见性
const reprintDialogVisible = ref(false)
const reprintDialogTitle = ref('补打标签')
// 补打标签表单数据
const reprintForm = reactive({
  barcodeRule: '',
  barcodeTemplate: '',
  printDetails: [],
  contentText: ''
})

// 补打标签表单引用
const reprintFormRef = ref()

// 补打标签表单验证规则
const reprintFormRules = {
  barcodeRule: [{ required: true, message: '请选择条码规则', trigger: 'change' }],
  barcodeTemplate: [{ required: true, message: '请选择条码模板', trigger: 'change' }]
}

// 处理弹窗可见性
const processDialogVisible = ref(false)

// 处理表单数据
const processFormData = reactive({
  remark: ''
})

// 处理表单验证规则
const processFormRules = {
  remark: [{ required: true, message: '请输入处理记录', trigger: 'blur' }]
}

// 处理表单引用
const processFormRef = ref()

// 当前处理的行数据
const currentProcessRow = ref<any>(null)


// 补打标签表配置
const reprintDetailTableConfig = reactive({
  showIndex: true,
  border: true,
  fields: [
    { prop: 'purchaseOrderItem', label: '行号', disabled: true, width: 80 },
    { prop: 'material', label: '物料号', disabled: true, width: 180, showOverflowTooltip: true },
    {
      prop: 'sapMaterialDescription',
      label: '物料长描述',
      disabled: true,
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      prop: 'addPrintNumber',
      label: '打印数量',
      type: 'number',
      required: true,
      width: 180,
      min: 1
    }
  ],
  importExport: {
    showImport: false,
    showExport: false
  }
})
const reprintDetailTableConfig2 = reactive({
  showIndex: true,
  border: true,
  fields: [
    { prop: 'purchaseOrderItem', label: '行号', disabled: true, width: 80 },
    { prop: 'material', label: '物料号', disabled: true, width: 180, showOverflowTooltip: true },
    {
      prop: 'sapMaterialDescription',
      label: '物料长描述',
      disabled: true,
      minWidth: 200,
      showOverflowTooltip: true
    },
    {
      prop: 'orderQuantity',
      label: '订单数量',
      disabled: true,
      minWidth: 100,
      showOverflowTooltip: true
    },
    {
      prop: 'addPrintNumber',
      label: '打印数量',
      type: 'number',
      required: true,
      width: 180,
      min: 1
    }
  ],
  importExport: {
    showImport: false,
    showExport: false
  }
})
// 表单数据
const labelFormData = reactive({
  barcodeRule: '',
  barcodeTemplate: '',
  multiple: '',
  printNumber: 1
})

/** 表格选择事件处理 */
const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection
}
// 【源单明细】表格配置
const sourceDetailConfig = reactive({
  queryParams: {}, // 无查询条件
  searchForm: { items: [] }, // 无搜索表单
  onSelectionChange: handleSelectionChange,
  actions: computed(() => {
    if (isViewMode.value) {
      return [] // 查看模式下不显示操作按钮
    }
    return [
      {
        label: '逐行生成标签',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        handler: async () => {
          // 获取条码规则数据
          await fetchBarcodeData()
          // 清空条码模板数据
          barcodeTemplates.value = []
          // 打开表单弹窗
          formDialogTitle.value = '逐行生成标签'
          formDialogVisible.value = true
          // 设置默认值
          labelFormData.barcodeRule = ''
          labelFormData.barcodeTemplate = ''
          labelFormData.multiple = ''
          labelFormData.printNumber = 1
          if (selectedRows.value.length == 1) {
            labelFormData.multiple = selectedRows.value[0].defaultMultiple
          }
          // 延迟设置默认条码规则，避免触发watch
          setTimeout(async () => {
            labelFormData.barcodeRule = barcodeRules.value[0]?.value || ''
            await fetchBarcodeTemplates(barcodeRules.value[0]?.value)
          }, 0)
        }
      },
      {
        label: '合并生成标签',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        handler: async () => {
          // 获取条码规则数据
          await fetchBarcodeData()
          // 清空条码模板数据
          barcodeTemplates.value = []
          // 打开表单弹窗
          formDialogTitle.value = '合并生成条码'
          formDialogVisible.value = true
          // 设置默认值
          labelFormData.barcodeRule = ''
          labelFormData.barcodeTemplate = ''
          labelFormData.multiple = ''
          labelFormData.printNumber = 1
          // 延迟设置默认条码规则，避免触发watch
          setTimeout(async () => {
            labelFormData.barcodeRule = barcodeRules.value[0]?.value || ''
            await fetchBarcodeTemplates(barcodeRules.value[0]?.value)
          }, 0)
        }
      },
      {
        label: '补打标签',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        handler: async () => {
          await printActionCommonFun('补打标签')
        }
      },
      {
        label: '样贴打印',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        handler: async () => {
          await printActionCommonFun('样贴打印')
        }
      },
      {
        label: '箱贴打印',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        handler: async () => {
          await printActionCommonFun('箱贴打印')
        }
      }
    ]
  }),
  settings: computed(() => ({
    refresh: false, // 查看模式下不显示刷新按钮
    download: false,
    resetRefresh: true
  })),
  table: {
    selection: true,
    index: true,
    rowKey: 'purchaseOrderItem', // 使用行号作为唯一标识
    columns: [
      { prop: 'purchaseOrderItem', label: '行号', width: 80 },
      {
        prop: 'material',
        label: '物料号',
        width: 140,
        showOverflowTooltip: true,
        filterable: true,
        filterType: 'text'
      },
      {
        prop: 'sapMaterialDescription',
        label: '物料长描述',
        minWidth: 200,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'internalStyleNo',
        label: '内部款号',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      },
      { prop: 'orderQuantity', label: '订单数量', width: 100, filterable: true },
      { prop: 'purchaseOrderQuantityUnit', label: '基本单位', width: 100, filterable: true },
      { prop: 'defaultMultiple', label: '默认倍数', width: 100, filterable: true },
      { prop: 'expectTagNumber', label: '预计标签数', width: 120, filterable: true },
      {
        prop: 'soldToParty',
        label: '客户编码',
        width: 140,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'customerMaterialNo',
        label: '客户物料号',
        width: 140,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'styleNo',
        label: '客户款号',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      },
      { prop: 'barcode', label: '条形码', width: 150, showOverflowTooltip: true, filterable: true },
      { prop: 'name', label: '名称', width: 120, showOverflowTooltip: true, filterable: true },
      { prop: 'color', label: '颜色', width: 100, showOverflowTooltip: true, filterable: true },
      { prop: 'size', label: '尺码', width: 100, showOverflowTooltip: true, filterable: true },
      {
        prop: 'specificationModel',
        label: '规格型号',
        width: 140,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'composition',
        label: '成分',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      }
    ]
  },
  pagination: {
    pageSize: 500,
    show: true,
    pageSizes: [200, 500, 1000, 2000]
  },
  api: {
    getList: async (params: any) => {
      try {
        const response = await getPurchaseOrderDetailsPage(params)
        return response
      } catch (error) {
        console.error('获取源单明细失败:', error)
        return { total: 0, list: [] }
      }
    }
  }
})
// 【标签明细】表格配置
const labelDetailConfig = reactive({
  queryParams: {}, // 无查询条件
  searchForm: { items: [] }, // 无搜索表单
  onSelectionChange: handleSelectionChange,
  table: {
    selection: computed(() => !isViewMode.value), // 查看模式下不显示选择框
    index: true,
    rowKey: 'id', // 使用id作为唯一标识
    columns: [
      { prop: 'purchaseOrderItem', label: '行号', width: 80, showOverflowTooltip: true },
      {
        prop: 'material',
        label: '物料号',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'materialName',
        label: '物料长描述',
        minWidth: 150,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'orderQuantity',
        label: '订单数量',
        width: 100,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'barcodeRulesName',
        label: '条码规则',
        width: 150,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'barcodeTemplateName',
        label: '条码模板',
        width: 150,
        showOverflowTooltip: true,
        filterable: true
      },
      { prop: 'multiple', label: '倍数', width: 100, showOverflowTooltip: true, filterable: true },
      {
        prop: 'tagNumber',
        label: '标签数',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'customerMaterialNo',
        label: '客户物料号',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'styleNo',
        label: '客户款号',
        width: 100,
        showOverflowTooltip: true,
        filterable: true
      },
      { prop: 'barcode', label: '条形码', width: 150, showOverflowTooltip: true, filterable: true },
      { prop: 'name', label: '名称', width: 120, showOverflowTooltip: true, filterable: true },
      { prop: 'color', label: '颜色', width: 100, showOverflowTooltip: true, filterable: true },
      { prop: 'size', label: '尺码', width: 100, showOverflowTooltip: true, filterable: true },
      {
        prop: 'specificationModel',
        label: '规格型号',
        width: 150,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'composition',
        label: '成分',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      }
    ]
  },
  actions: computed(() => {
    if (isViewMode.value) {
      return [] // 查看模式下不显示操作按钮
    }
    return [
      {
        label: '打印',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        loading: computed(() => printLoading.value),
        handler: async () => {
          printLoading.value = true
          try {
            previewDialogTitle.value = '打印'
            await handlePrint()
          } catch (error) {
            console.error('打印失败:', error)
            message.error('打印失败')
          } finally {
            setTimeout(() => {
              printLoading.value = false
            }, 5000)
          }
        }
      },
      {
        label: '预览',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        handler: async () => {
          previewDialogTitle.value = '预览'
          handlePrint()
        }
      },
      {
        label: '编辑',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length !== 1),
        handler: async () => {
          watchBarcode.value = false
          barcodeTemplates.value = []
          await fetchBarcodeData()
          await fetchBarcodeTemplates(selectedRows.value[0].barcodeRulesCode)
          labelFormData.barcodeRule = selectedRows.value[0].barcodeRulesCode || ''
          labelFormData.barcodeTemplate = selectedRows.value[0].barcodeTemplateCode || ''
          labelFormData.multiple = selectedRows.value[0].multiple || ''
          formDialogTitle.value = '编辑标签'
          formDialogVisible.value = true
        }
      },
      {
        label: '删除',
        type: 'default' as const,
        disabled: computed(() => selectedRows.value.length === 0),
        handler: async () => {
          try {
            await ElMessageBox.confirm('确定删除已选择的条码标签？此操作无法恢复', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              confirmButtonType: 'danger'
            })
            await deletePurchaseOrderTagDetailList(selectedRows.value.map((item) => item.id))
            selectedRows.value = []
            if (tableListRef.value) {
              await tableListRef.value.getList()
            }
            ElMessage.success('删除成功')
          } catch (error) {
            // 取消操作
          }
        }
      },
      {
        label: '确认完成',
        type: 'default' as const,
        disabled: computed(() => formData.printed == 1),
        position: 'right',
        handler: async () => {
          try {
            await ElMessageBox.confirm('确认当前单据已打印完毕？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消'
            })
            await updatePurchaseOrderTagDetailCompleteStatus({
              id: formData.id
            })
            ElMessage.success('确认完成成功')
            open('print', formData.id, activeTab.value)
          } catch (error) {
            // 取消操作
          }
        }
      }
    ]
  }),
  settings: computed(() => ({
    refresh: false,
    download: false,
    resetRefresh: true
  })),
  pagination: {
    pageSize: 500,
    show: true,
    pageSizes: [200, 500, 1000, 2000]
  },
  api: {
    getList: async (params: any) => {
      try {
        // 调用API获取标签明细，传递purchaseOrder参数
        const response = await getPurchaseOrderTagDetailPage({
          ...params,
          purchaseOrder: formData.purchaseOrder
        })
        return response
      } catch (error) {
        console.error('获取标签明细失败:', error)
        return { total: 0, list: [] }
      }
    }
  }
})

// 【标签生成记录】表格配置
const labelGenerateDetailConfig = reactive({
  queryParams: {}, // 无查询条件
  searchForm: { items: [] }, // 无搜索表单
  table: {
    selection: false,
    index: true,
    rowKey: 'id',
    columns: [
      { prop: 'purchaseOrderItem', label: '行号', width: 80, showOverflowTooltip: true },
      { prop: 'material', label: '物料号', width: 120, showOverflowTooltip: true },
      {
        prop: 'materialName',
        label: '物料长描述',
        minWidth: 150,
        showOverflowTooltip: true
      },
      { prop: 'orderQuantity', label: '订单数量', width: 100, showOverflowTooltip: true },
      { prop: 'multiple', label: '倍数', width: 100, showOverflowTooltip: true },
      { prop: 'tagNumber', label: '标签数', width: 120, showOverflowTooltip: true },
      { prop: 'barcodeRulesName', label: '条码规则', width: 150, showOverflowTooltip: true },
      { prop: 'barcodeTemplateName', label: '条码模版', width: 150, showOverflowTooltip: true },
      { prop: 'creatorName', label: '操作人', width: 120, showOverflowTooltip: true },
      {
        prop: 'createTime',
        label: '操作时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.createTime)
      },
      { prop: 'content', label: '内容', minWidth: 200, showOverflowTooltip: true }
    ]
  },
  pagination: { show: true },
  settings: { refresh: false, download: false, resetRefresh: false },
  api: {
    getList: async (params: any) => {
      try {
        const response = await getPurchaseOrderTagRecordPage({
          ...params,
          purchaseOrder: formData.purchaseOrder
        })
        return response
      } catch (error) {
        console.error('获取标签生成记录失败:', error)
        return { total: 0, list: [] }
      }
    }
  }
})

// 【订单变更记录】表格配置
const orderChangeRecordConfig = reactive({
  queryParams: {}, // 无查询条件
  searchForm: { items: [] }, // 无搜索表单
  table: {
    selection: false,
    rowKey: 'id',
    columns: computed(() => {
      const baseColumns = [
        { prop: 'purchaseOrder', label: '单据编号', width: 180, showOverflowTooltip: true },
        {
          prop: 'createTime',
          label: '更新时间',
          width: 180,
          showOverflowTooltip: true,
          formatter: (row: any) => dateFormatter(row, {}, row.createTime)
        },
        { prop: 'orderPrintRemark', label: '打印备注', minWidth: 200, showOverflowTooltip: true },
        {
          prop: 'processed',
          label: '已处理',
          width: 100,
          formatter: (row: any) => yesOrNoMap[row.processed]
        },
        { prop: 'updaterName', label: '处理人', width: 120, showOverflowTooltip: true },
        {
          prop: 'createTime',
          label: '处理时间',
          width: 180,
          showOverflowTooltip: true,
          formatter: (row: any) => dateFormatter(row, {}, row.handleTime)
        },
        { prop: 'remark', label: '处理备注', minWidth: 200, showOverflowTooltip: true }
      ]
      if (!isViewMode.value) {
        baseColumns.push({
          prop: 'action',
          label: '操作',
          width: 100,
          fixed: 'right',
          render: (h: any, { row }: { row: any }) => {
            if (row.processed == 1) {
              return h('span', {}, '')
            } else {
              return h(
                'span',
                {
                  type: 'primary',
                  link: true,
                  style: 'color: #1677ff',
                  onClick: () => handleProcessClick(row)
                },
                '处理'
              )
            }
          }
        })
      }
      return baseColumns
    })
  },
  settings: computed(() => ({
    refresh: false,
    download: false,
    resetRefresh: false
  })),
  pagination: { show: true },
  api: {
    getList: async (params: any) => {
      try {
        const response = await getPurchaseOrderChangeRecordPage({
          ...params,
          purchaseOrder: formData.purchaseOrder
        })
        return response
      } catch (error) {
        console.error('获取订单变更记录失败:', error)
        return { total: 0, list: [] }
      }
    }
  }
})
// 当前表格配置 - 动态切换
const currentTableConfig = reactive({ value: sourceDetailConfig })
// 表单验证规则
const labelFormRules = {
  barcodeRule: [{ required: true, message: '请选择条码规则', trigger: 'change' }],
  barcodeTemplate: [{ required: true, message: '请选择条码模板', trigger: 'change' }],
  multiple: [
    {
      required: false,
      message: '请输入倍数',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // 只有当标题为逐行生成标签时才验证
        if (formDialogTitle.value === '逐行生成标签') {
          // if (!value) {
          //   callback(new Error('请输入倍数'))
          //   return
          // }
          const num = Number(value)
          if (value && (isNaN(num) || num <= 0)) {
            callback(new Error('倍数必须大于0'))
            return
          }
        }
        callback()
      }
    }
  ],
  printNumber: [
    {
      required: false,
      message: '请输入数量',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        // 只有当标题为合并生成条码时才验证
        if (formDialogTitle.value === '合并生成条码') {
          if (!value) {
            callback(new Error('请输入数量'))
            return
          }
          const num = Number(value)
          if (isNaN(num)) {
            callback(new Error('请输入数字'))
            return
          }
          if (!Number.isInteger(num)) {
            callback(new Error('请输入整数'))
            return
          }
          if (num <= 0) {
            callback(new Error('数量必须大于0'))
            return
          }
        }
        callback()
      }
    }
  ]
}

// 表单引用
const labelFormRef = ref()

/** 获取条码规则数据 */
const fetchBarcodeData = async () => {
  try {
    // 获取条码规则
    const ruleResponse = await getApiSettingList({
      dictType: 'barcode_rules'
    })
    barcodeRules.value =
      ruleResponse.map((item: any) => ({
        label: `${item.label}`,
        value: item.value
      })) || []
  } catch (error) {
    console.error('获取条码规则失败:', error)
    barcodeRules.value = []
  }
}

/** 获取条码模板数据 */
const fetchBarcodeTemplates = async (dataSource: string) => {
  try {
    // 获取条码模板，传入条码规则作为dataSource参数
    const templateResponse = await tagTemplateConfigPageList({ 
      pageNo: 1,
      pageSize: 20,
      status: 1,
      dataSource
    })
    barcodeTemplates.value =
      templateResponse.list.map((item: any) => ({
        label: item.templateName,
        value: item.templateCode,
        contentText: item.contentText
      })) || []
  } catch (error) {
    console.error('获取条码模板失败:', error)
    barcodeTemplates.value = []
  }
}

/** 远程搜索条码模板 */
const remoteMethodBarcodeTemplate = async (query: string, dataSource) => {
  barcodeTemplateLoading.value = true
  try {
    const paramBody: any = {
      pageNo: 1,
      pageSize: 20,
      status: 1,
      dataSource
    }
    
    if (query) {
      paramBody.templateName = query
    }
    
    const templateResponse = await tagTemplateConfigPageList(paramBody)
    barcodeTemplates.value =
      templateResponse.list.map((item: any) => ({
        label: item.templateName,
        value: item.templateCode,
        contentText: item.contentText
      })) || []
  } catch (error) {
    console.error('获取条码模板失败:', error)
    barcodeTemplates.value = []
  } finally {
    barcodeTemplateLoading.value = false
  }
}

/** 倍数输入处理 */
const handlemultipleInput = (value: string) => {
  // 使用正则过滤，只保留数字和小数点
  let filteredValue = value.replace(/[^\d.]/g, '')
  // 确保只有一个小数点
  const decimalPoints = (filteredValue.match(/\./g) || []).length
  if (decimalPoints > 1) {
    filteredValue = filteredValue.replace(/\.(?=.*\.)/g, '')
  }
  // 限制小数点后只能有一位
  const match = filteredValue.match(/^(\d+)\.(\d)?/)
  if (match) {
    filteredValue = `${match[1]}.${match[2] || ''}`
  }
  // 更新表单数据
  labelFormData.multiple = filteredValue
}

/** 数量输入框按键按下处理，只允许输入数字 */
const handlePrintNumberKeydown = (event: KeyboardEvent) => {
  const allowedKeys = [
    'Backspace',
    'Tab',
    'ArrowLeft',
    'ArrowRight',
    'Delete',
    'Enter'
  ]
  if (allowedKeys.includes(event.key)) {
    return
  }
  if (!/[\d]/.test(event.key)) {
    event.preventDefault()
  }
}

/** 数量输入失去焦点处理 */
const handlePrintNumberBlur = () => {
  const num = Number(labelFormData.printNumber)
  if (isNaN(num)) {
    labelFormData.printNumber = ''
  } else {
    labelFormData.printNumber = num.toString()
  }
}

/** 补打标签条码模板变化处理 */
const handleBarcodeTemplateChange = (value: string) => {
  const selectedTemplate = barcodeTemplates.value.find((item: any) => item.value === value)
  if (selectedTemplate) {
    reprintForm.contentText = selectedTemplate.contentText
  }
}

/** 打开条码生成弹窗 */
const openLabelFormDialog = (title: string) => {
  formDialogTitle.value = title
  formDialogVisible.value = true
}

/** 打开标签预览弹窗 */
const openPreviewDialog = () => {
  previewDialogVisible.value = true
}

/** 打开补打标签弹窗 */
const openReprintDialog = (title: string) => {
  reprintDialogTitle.value = title
  reprintDialogVisible.value = true
}

/** 打开处理弹窗 */
const openProcessDialog = (row: any) => {
  currentProcessRow.value = row
  processDialogVisible.value = true
}

/** 重置条码生成表单 */
const resetLabelForm = () => {
  // 重置表单数据
  labelFormData.barcodeRule = ''
  labelFormData.barcodeTemplate = ''
  labelFormData.multiple = ''
  labelFormData.printNumber = 1
  // 重置条码模板列表
  barcodeTemplates.value = []
  // 重置表单验证
  labelFormRef.value?.clearValidate()
}

/** 重置预览表单 */
const resetPreviewForm = () => {
  // 重置表单数据
  previewFormData.barcodeRule = ''
  previewFormData.barcodeTemplate = ''
  // 重置条码模板列表
  barcodeTemplates.value = []
  // 重置表单验证
  previewFormRef.value?.clearValidate()
}

/** 重置补打标签表单 */
const resetReprintForm = () => {
  // 重置表单数据
  reprintForm.barcodeRule = ''
  reprintForm.barcodeTemplate = ''
  reprintForm.printDetails = []
  reprintForm.contentText = ''
  // 重置条码模板列表
  barcodeTemplates.value = []
  // 重置表单验证
  reprintFormRef.value?.clearValidate()
}

/** 重置处理表单 */
const resetProcessForm = () => {
  // 重置表单数据
  processFormData.remark = ''
  // 重置表单验证
  processFormRef.value?.clearValidate()
}

/** 打印处理 */
const handlePrint = async () => {
  previewPrintLoading.value = true
  // if (!previewFormRef.value) return
  try {
    const arr = []
    for (const item of selectedRows.value) {
      console.log('-----item----', item)
      const obj = {
        printData: [],
        extraData: toRaw(item)
      }
      const paramBody = {
        template_code: item.barcodeTemplateCode
      }
      if (previewDialogTitle.value == '标签预览') {
        paramBody.template_code = previewFormData.barcodeTemplate
      }
      const r = await getTagTemplateConfigList(paramBody)
      const templateJson = r.find((jsonItem) => {
        return jsonItem.templateCode == paramBody.template_code
      })
      obj.templateJson = JSON.parse(templateJson.contentText || '{}')
      const tagNumber = item.tagNumber || 1
      if (previewDialogTitle.value === '预览') {
        obj.printData.push(toRaw(item))
      } else {
        for (let i = 0; i < tagNumber; i++) {
          obj.printData.push(toRaw(item))
        }
      }

      // if (previewDialogTitle.value === '打印') {
      //   // 打印的时候要把每行数量算上
      //   const tagNumber = item.tagNumber || 1
      //   for (let i = 0; i < tagNumber; i++) {
      //     obj.printData.push(toRaw(item))
      //   }
      // } else {
      //   obj.printData = [toRaw(item)]
      // }
      arr.push(obj)
    }
    if (previewDialogTitle.value === '打印') {
      printFun(
        {
          templateList: arr
        },
        null,
        'pdf',
        true
      )
      // mut_silentPrint({
      //   templateList: arr
      // })
      return
    }
    dialogPreviewRef.value?.mutOpen({
      templates: arr
    })
    // await previewFormRef.value.validate()
    // 验证通过，处理打印逻辑
    // const barcodeTemplate = selectedRows.value[0]?.barcodeTemplateCode || ''
    // const templateJson = barcodeTemplates.value.find((item: any) => item.value === barcodeTemplate)?.contentText
    // console.log('条码模板', templateJson)
    // let printData = []
    // if (previewDialogTitle.value === '打印') {
    //   // 处理打印数据，根据每项数据的tagNumber计算数据
    //   selectedRows.value.forEach((item: any) => {
    //     const tagNumber = item.tagNumber || 1
    //     for (let i = 0; i < tagNumber; i++) {
    //       printData.push(item)
    //     }
    //   })
    // } else {
    //   printData = selectedRows.value
    // }
    // dialogPreviewRef.value?.open({
    //   template: JSON.parse(templateJson || '{}'),
    //   printData
    // });
    // previewDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败', error)
  } finally {
    setTimeout(() => {
      previewPrintLoading.value = false
    }, 5000)
  }
}

const handleReprintSubmit = async () => {
  if (!reprintFormRef.value) return
  try {
    silentPrintLoading.value = true
    await reprintFormRef.value.validate()
    if (reprintDialogTitle.value === '补打标签' || reprintDialogTitle.value === '箱贴打印') {
      // 验证通过，处理表单数据
      const barcodeRulesName =
        barcodeRules.value.find((item: any) => item.value === reprintForm.barcodeRule)?.label || ''
      const barcodeTemplateName =
        barcodeTemplates.value.find((item: any) => item.value === reprintForm.barcodeTemplate)
          ?.label || ''
      let formData = {
        barcodeRulesCode: reprintForm.barcodeRule,
        barcodeTemplateCode: reprintForm.barcodeTemplate,
        barcodeRulesName,
        barcodeTemplateName,
        addPrintNumberList: reprintForm.printDetails.map((item: any) => ({
          id: item.id,
          addPrintNumber: item.addPrintNumber
        })),
        printType: reprintDialogTitle.value === '补打标签' ? 3 : 4
      }
      console.log('表单数据', formData)

      // 这里可以添加实际的提交逻辑
      // 例如调用API生成标签
      await createPurchaseOrderTagDetail(formData)
    }
    // 关闭弹窗
    await handleSilentPrint()
    // reprintDialogVisible.value = false
    // ElMessage.success('操作成功')
  } catch (error) {
    console.error('表单验证失败', error)
    silentPrintLoading.value = false
  }
}
// 静默打印
const handleSilentPrint = async () => {
  try {
    if (!reprintFormRef.value) return
    const dataForm = JSON.parse(JSON.stringify(reprintForm))
    // 表单验证
    await reprintFormRef.value.validate()
    silentPrintLoading.value = true
    // 处理打印数据，根据addPrintNumber字段复制数据
    const processedPrintData = []
    dataForm.printDetails.forEach((item: any) => {
      const quantity = item.addPrintNumber || 0
      for (let i = 0; i < quantity; i++) {
        processedPrintData.push(item)
      }
    })
    console.log(dataForm)
    console.log(processedPrintData)
    printFun(
      {
        template: JSON.parse(dataForm.contentText || '{}'),
        printData: processedPrintData
      },
      null,
      null,
      false
    )
    // if (reprintDialogTitle.value == '补打标签') {
    //   ElMessage.success('操作成功')
    // }
  } catch (error: any) {
    silentPrintLoading.value = false
    if (error?.name === 'Error') {
      // 表单验证失败
      return
    }
    console.error('静默打印失败:', error)
  } finally {
    setTimeout(() => {
      silentPrintLoading.value = false
    }, 5000)
    // if (reprintDialogTitle.value == '补打标签' || reprintDialogTitle.value == '箱贴打印') {
    //   setTimeout(() => {
    //     silentPrintLoading.value = false
    //     reprintDialogVisible.value = false
    //   }, 200)
    // } else {
    //   reprintDialogVisible.value = false
    //   setTimeout(() => {
    //     silentPrintLoading.value = false
    //   }, 5000)
    // }
  }
}
/** 表单提交处理 */
const handleFormSubmit = async () => {
  if (!labelFormRef.value) return
  try {
    await labelFormRef.value.validate()
    // 验证通过，处理表单数据
    const barcodeRulesName =
      barcodeRules.value.find((item: any) => item.value === labelFormData.barcodeRule)?.label || ''
    const barcodeTemplateName =
      barcodeTemplates.value.find((item: any) => item.value === labelFormData.barcodeTemplate)
        ?.label || ''
    let formData = {
      barcodeRulesCode: labelFormData.barcodeRule,
      barcodeTemplateCode: labelFormData.barcodeTemplate,
      barcodeRulesName,
      barcodeTemplateName,
      ids: selectedRows.value.map((item: any) => item.id)
    }
    if (formDialogTitle.value === '逐行生成标签') {
      formData.printType = 1
      formData.multiple = labelFormData.multiple
      formData.addPrintNumberList = selectedRows.value.map((item: any) => ({
        id: item.id,
        defaultMultiple: item.defaultMultiple,
        expectTagNumber: item.expectTagNumber
      }))
    }
    if (formDialogTitle.value === '合并生成条码') {
      formData.printType = 2
      formData.printNumber = labelFormData.printNumber
      formData.addPrintNumberList = selectedRows.value.map((item: any) => ({
        id: item.id
      }))
    }
    if (formDialogTitle.value === '编辑标签') {
      formData.printType = 1
      formData.multiple = labelFormData.multiple
      formData.id = selectedRows.value[0].id
      delete formData.ids
    }
    console.log('表单数据', formData)
    if (formDialogTitle.value === '逐行生成标签' || formDialogTitle.value === '合并生成条码') {
      await createPurchaseOrderTagDetail(formData)
    }
    if (formDialogTitle.value === '编辑标签') {
      await updatePurchaseOrderTagDetail(formData)
    }
    // 关闭弹窗
    formDialogVisible.value = false
    ElMessage.success('操作成功')
    if (tableListRef.value && formDialogTitle.value === '编辑标签') {
      await tableListRef.value.getList()
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}


/** Tab切换事件处理 */
const handleTabChange = async () => {
  // 切换tab时清空选中的行数据
  selectedRows.value = []

  // 根据当前激活的tab设置对应的表格配置
  switch (activeTab.value) {
    case 'sourceDetail':
      currentTableConfig.value = sourceDetailConfig
      break
    case 'labelDetail':
      currentTableConfig.value = labelDetailConfig
      break
    case 'labelGenerateDetail':
      currentTableConfig.value = labelGenerateDetailConfig
      break
    case 'orderChangeRecord':
      currentTableConfig.value = orderChangeRecordConfig
      break
    default:
      currentTableConfig.value = sourceDetailConfig
  }

  // 更新TableList的key值，强制刷新组件
  tableListKey.value++

  // 等待下一个 tick，确保响应式更新完成
  await nextTick()

  // 再次等待，确保 TableList 组件的 watch 完成
  await nextTick()

  // 重新加载表格数据
  if (tableListRef.value) {
    await tableListRef.value.getList()
  }
}

/** 处理按钮点击事件 */
const handleProcessClick = (row: any) => {
  currentProcessRow.value = row
  processFormData.remark = ''
  processDialogVisible.value = true
  console.log('---当前行--', row)
}

// 基础信息字段（采购订单相关）
const basicInfoFields = ref([
  { label: '单据编码', field: 'purchaseOrder' },
  { label: '采购订单类型', field: 'purchaseOrderType' },
  { label: '公司代码', field: 'companyCode' },
  { label: '采购组织', field: 'purchasingOrganization' },
  { label: '采购组', field: 'purchasingGroup' },
  { label: '供应商', field: 'supplier' },
  { label: '供应商描述', field: 'supplierName' },
  { label: '创建时间', field: 'creationDate' },
  { label: '打印备注', field: 'printRemark' },
  { label: '打印人', field: 'printedByName' },
  { label: '打印时间', field: 'printedTime' },
  { label: '处理人', field: 'processedByName' },
  { label: '处理时间', field: 'processedTime' }
])

// TableList组件的key值，用于强制刷新组件
const tableListKey = ref(0)

const dialogTitle = ref('采购订单')

// 打印公共方法
const printActionCommonFun = async (printTitle: string) => {
  await fetchBarcodeData()
  barcodeTemplates.value = []
  reprintForm.printDetails = selectedRows.value.map((row) => ({
    ...row,
    addPrintNumber: 1
  }))
  reprintDialogTitle.value = printTitle
  reprintDialogVisible.value = true
  reprintForm.barcodeRule = ''
  reprintForm.barcodeTemplate = ''
  setTimeout(async () => {
    reprintForm.barcodeRule = barcodeRules.value[0]?.value || ''
    await fetchBarcodeTemplates(barcodeRules.value[0]?.value)
  }, 0)
}

/** 获取采购订单详情 */
const fetchPurchaseOrderDetail = async (id: number | string, activeTabValue?: string) => {
  formLoading.value = true
  try {
    const data = await getPurchaseOrderHeader(id)
    data.creationDate = formatDate(data.creationDate)
    data.printedTime = formatDate(data.printedTime)
    data.processedTime = formatDate(data.processedTime)
    Object.assign(formData, data)
    dialogTitle.value = `采购订单-${formData.purchaseOrder || '未知'}`
    sourceDetailConfig.queryParams.id = id
    activeTab.value = activeTabValue || 'sourceDetail'
    await handleTabChange()
  } catch (error) {
    message.error('获取采购订单详情失败')
    console.log(error)
  } finally {
    formLoading.value = false
  }
}
/** 预览处理 */
const handlePreview = async () => {
  if (!previewFormRef.value) return
  try {
    await previewFormRef.value.validate()
    // 验证通过，处理预览逻辑
    const formData = {
      ...previewFormData
    }

    console.log('预览数据', formData)
    console.log('选中的行数据', selectedRows.value)

    // 这里可以添加实际的预览逻辑
    message.success('预览成功')
  } catch (error) {
    console.error('表单验证失败', error)
  }
}
/** 处理表单提交 */
const handleProcessSubmit = async () => {
  if (!processFormRef.value) return
  try {
    await processFormRef.value.validate()

    console.log('处理记录', processFormData.remark)
    console.log('处理的行数据', currentProcessRow.value)

    // 这里可以添加实际的处理逻辑
    // 例如调用API更新订单变更记录状态
    await updatePurchaseOrderChangeRecord({
      id: currentProcessRow.value.id,
      remark: processFormData.remark
    })
    // 关闭弹窗
    processDialogVisible.value = false
    ElMessage.success('处理成功')
    // 重新获取采购订单详情
    if (formData.id) {
      await fetchPurchaseOrderDetail(formData.id, activeTab.value)
    }
    // 刷新标签明细表格
    if (tableListRef.value) {
      await tableListRef.value.getList()
    }
  } catch (error) {
    console.error('表单验证失败', error)
  }
}
// 暴露方法给父组件
defineExpose({
  openLabelFormDialog,
  openPreviewDialog,
  openReprintDialog,
  openProcessDialog,
  resetLabelForm,
  resetPreviewForm,
  resetReprintForm,
  resetProcessForm,
  handleFormSubmit,
  handlePrint,
  handleReprintSubmit,
  handleProcessSubmit,
  fetchPurchaseOrderDetail
})
</script>

<style lang="scss" scoped>
// 样式可以在这里添加
.print-form-page {
  background: #fff;
  border-radius: 6px;
  padding: 15px 18px;
  padding-bottom: 5px;
  min-height: calc(100vh - 135px)
}
.dialog-title-with-tags {
  display: flex;
  align-items: center;
}

.dialog-title-with-tags .el-tag {
  margin-left: 8px;
}
.print-tabs {
  margin-top: 10px;
}
.material-basic-info {
  padding: 6px;
  margin-bottom: 20px;
  display: flex;
  width: 100%;
  gap: 15px;
  flex-wrap: wrap;
}
.info-field {
  width: calc(20% - 15px);
}

.info-item {
  display: flex;
  flex-direction: column;
}

.info-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.88);
  margin-bottom: 4px;
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: #6c6c6c;
  word-break: break-all;
  line-height: 1.4;
  min-height: 20px;
}
</style>
