<template>
  <!-- 打印弹窗 -->
  <Dialog
    v-model="localVisible"
    :title="`采购订单-${purchaseOrder?.purchaseOrder || '打印'}`"
    width="80%"
    :fullscreen="true"
    :default-fullscreen="true"
    :scroll="true"
    @closed="handleClose"
  >
    <template #title>
      <div class="dialog-title-with-tags">
        <span>采购订单-{{ purchaseOrder?.purchaseOrder || '打印' }}</span>
        <el-tag
          v-if="props.purchaseOrder.printed !== undefined"
          size="small"
          :type="yesOrNoMapClass[props.purchaseOrder.printed]"
          class="ml-2"
          >{{ printMap[props.purchaseOrder.printed] }}</el-tag
        >
        <el-tag
          v-if="props.purchaseOrder.processed !== undefined"
          size="small"
          :type="yesOrNoMapClass[props.purchaseOrder.processed]"
          class="ml-2"
          >{{ processedMap[props.purchaseOrder.processed] }}</el-tag
        >
      </div>
    </template>
    <!-- Tab页签 -->
    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <!-- 打印数据信息Tab -->
      <el-tab-pane label="打印数据信息" name="printData">
        <TableList ref="detailTableRef" :config="detailTableConfig" :isPopup="true" :tableHeight="tableHeight"/>
      </el-tab-pane>
      <!-- 单据信息Tab -->
      <el-tab-pane label="单据信息" name="bill">
        <div 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">{{ field.value || '-' }}</div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </Dialog>
  <!-- 标签打印弹窗 -->
  <Dialog
    v-model="labelPrintDialogVisible"
    title="标签打印"
    width="80%"
    :fullscreen="true"
    :scroll="true"
    @closed="handleLabelPrintClose"
  >
    <el-form ref="labelFormRef" :model="printForm" :rules="rules" label-width="100px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="条码规则" prop="barcodeRule" required>
            <el-select
              v-model="printForm.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" required>
            <el-select
              v-model="printForm.barcodeTemplate"
              placeholder="请选择条码模板"
              style="width: 100%"
              filterable
              remote
              :remote-method="(q) => { remoteMethodBarcodeTemplate(q, printForm.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-col>
      </el-row>
    </el-form>

    <!-- 打印详情列表 -->
    <div style="margin-top: 15px">
      <EditTable
        v-model="printForm.printDetails"
        :config="printDetailTableConfig"
        title="打印清单"
        :addButtonShow="false"
      />
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleLabelPrintClose">取消</el-button>
        <el-button type="primary" @click="handleSilentPrint" :loading="printLoading"
          >打印</el-button
        >
        <!-- <el-popover placement="bottom" width="120" trigger="click">
          <template #reference>
            <el-button type="primary">打印</el-button>
          </template>
          <el-button type="text" @click="handleBrowserPrint">浏览器打印</el-button>
          <el-button type="text" @click="handleSilentPrint" style="margin-left: 0;">静默打印</el-button>
        </el-popover> -->
      </span>
    </template>
  </Dialog>
  <!--打印预览组件-->
  <DialogPreview ref="dialogPreviewRef" />
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElForm } from 'element-plus'
import EditTable from '@/components/EditTable/index.vue'
import TableList from '@/components/TableList/index.vue'
import Dialog from '@/components/Dialog/src/Dialog.vue'
import { getPurchaseOrderDetailsPage } from '@/api/print/purchaseOrder'
import { getApiSettingList, tagTemplateConfigList, tagTemplateConfigPageList } from '@/api/print/apiSetting'
import DialogPreview from '@/components/PrintDesginer/dialogPreview.vue'
import { formatDate } from '@/utils/formatTime'
import { printFun } from '@/utils/print'
// 响应式变量
const activeTab = ref('printData') // 默认显示打印数据信息Tab
const printLoading = ref(false)
const tableHeight = ref(500) // 表格高度
// Props
const props = defineProps<{
  visible: boolean
  purchaseOrder: any
}>()

// Emits
const emit = defineEmits<{
  (e: 'update:visible', value: boolean): void
  (e: 'close'): void
  (e: 'print', data: any): void
}>()

// 响应式变量
const detailTableRef = ref()
const labelFormRef = ref<InstanceType<typeof ElForm> | null>(null)
const selectedDetailRows = ref<any[]>([])
const labelPrintDialogVisible = ref(false)
const dialogPreviewRef = ref<any>(null)
// 本地可见性变量，用于控制弹窗显示/隐藏
const localVisible = ref(props.visible)
const printMap = {
  0: '未打印',
  1: '已打印'
}
const yesOrNoMapClass = {
  0: 'info',
  1: 'success'
}
const processedMap = {
  0: '未处理',
  1: '已处理'
}
// 监听props.visible变化，更新本地变量
watch(
  () => props.visible,
  async (newVal) => {
    localVisible.value = newVal
    if (localVisible.value) {
      activeTab.value = 'printData'
      // 如果条码规则为空，先获取条码规则
      if (barcodeRules.value.length === 0) {
        await getBarcodeRules()
      }
      // 设置条码规则默认值为第一条数据
      if (barcodeRules.value.length > 0) {
        printForm.barcodeRule = barcodeRules.value[0].value
      }
    }
  }
)

// 监听本地可见性变化，通知父组件
watch(localVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 表单数据
const printForm = reactive({
  barcodeRule: '',
  barcodeTemplate: '',
  printDetails: []
})

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

// 条码规则和模板选项
const barcodeRules = ref<any[]>([])
const barcodeTemplates = ref<any[]>([])
const barcodeTemplateLoading = ref(false)

// 获取条码模板
const getBarcodeTemplates = async (dataSource: string) => {
  try {
    const response = await tagTemplateConfigPageList({ 
      pageNo: 1,
      pageSize: 20,
      status: 1,
      dataSource
    })
    // 假设返回的数据结构中包含模板列表，需要根据实际API返回结构调整
    // 这里假设返回的数据是一个数组，每个元素有name和value属性
    barcodeTemplates.value =
      response.list.map((item: any) => ({
        label: item.templateName,
        value: item.contentText
      })) || []
  } catch (error) {
    console.error('获取条码模板失败:', error)
    ElMessage.error('获取条码模板失败')
  }
}

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

// 监听条码规则变化，更新条码模板
watch(
  () => printForm.barcodeRule,
  async (newVal) => {
    // 清空条码模板值
    printForm.barcodeTemplate = ''
    // 清空条码模板列表
    // barcodeTemplates.value = []
    // 如果条码规则有值，获取对应的模板
    if (newVal) {
      await getBarcodeTemplates(newVal)
    }
  }
)

const getBarcodeRules = async () => {
  try {
    const response = await getApiSettingList({
      dictType: 'barcode_rules'
    })
    // 假设返回的数据结构中包含规则列表，需要根据实际API返回结构调整
    // 这里假设返回的数据是一个数组，每个元素有name和value属性
    barcodeRules.value =
      response.map((item: any) => ({
        label: `${item.label}`,
        value: item.value
      })) || []
  } catch (error) {
    console.error('获取条码规则失败:', error)
    ElMessage.error('获取条码规则失败')
  }
}
// 主表字段配置
const basicInfoFields = computed(() => [
  { label: '单据编码', value: props.purchaseOrder?.purchaseOrder || '-' },
  { label: '采购订单类型', value: props.purchaseOrder?.purchaseOrderType || '-' },
  { label: '公司代码', value: props.purchaseOrder?.companyCode || '-' },
  { label: '采购组织', value: props.purchaseOrder?.purchasingOrganization || '-' },
  { label: '采购组', value: props.purchaseOrder?.purchasingGroup || '-' },
  { label: '供应商', value: props.purchaseOrder?.supplier || '-' },
  { label: '供应商描述', value: props.purchaseOrder?.supplierName || '-' },
  // { label: '创建人', value: props.purchaseOrder?.creatorName || '-' },
  // { label: '创建时间', value: formatDate( props.purchaseOrder?.createTime) || '-' },
  { label: '创建时间', value: formatDate(props.purchaseOrder?.creationDate) || '-' },
  { label: '打印备注', value: props.purchaseOrder?.remark || '-' },
  { label: '打印人', value: props.purchaseOrder?.printedByName || '-' },
  { label: '打印时间', value: formatDate(props.purchaseOrder?.printedTime) || '-' },
  { label: '处理人', value: props.purchaseOrder?.processedByName || '-' },
  { label: '处理时间', value: formatDate(props.purchaseOrder?.processedTime) || '-' }
])

// 关闭弹窗
const handleClose = () => {
  localVisible.value = false
  emit('close')
}

// 标签打印
const handleLabelPrint = async () => {
  if (selectedDetailRows.value.length === 0) {
    ElMessage.warning('请先选择明细行数据')
    return
  }

  // 获取条码规则
  await getBarcodeRules()

  // 准备打印标签数据
  printForm.printDetails = selectedDetailRows.value.map((row) => ({
    ...row,
    printQuantity: 1 // 默认打印数量为1
  }))

  // 打开标签打印弹窗
  labelPrintDialogVisible.value = true
  await getBarcodeTemplates(barcodeRules.value[0].value)
}

// 关闭标签打印弹窗
const handleLabelPrintClose = () => {
  // 清空表单数据
  printForm.barcodeRule = ''
  printForm.barcodeTemplate = ''
  printForm.printDetails = []

  // 清空条码规则和模板列表
  barcodeRules.value = []
  barcodeTemplates.value = []

  // 重置表单校验
  if (labelFormRef.value) {
    labelFormRef.value.resetFields()
  }

  // 关闭弹窗
  labelPrintDialogVisible.value = false
}

// 浏览器打印
const handleBrowserPrint = async () => {
  try {
    if (!labelFormRef.value) return

    // 表单验证
    await labelFormRef.value.validate()

    // 处理打印数据，根据printQuantity字段复制数据
    const processedPrintData = []
    printForm.printDetails.forEach((item: any) => {
      const quantity = item.printQuantity || 0
      for (let i = 0; i < quantity; i++) {
        processedPrintData.push(item)
      }
    })

    // dialogPreviewRef.value?.open({
    //   template: JSON.parse(printForm.barcodeTemplate || '{}'),
    //   printData: processedPrintData
    // });
    printFun(
      {
        template: JSON.parse(printForm.barcodeTemplate || '{}'),
        printData: processedPrintData
      },
      null,
      null,
      false,
      'browser'
    )
  } catch (error: any) {
    if (error?.name === 'Error') {
      // 表单验证失败
      return
    }
    console.error('浏览器打印失败:', error)
  }
}

// 静默打印
const handleSilentPrint = async () => {
  try {
    if (!labelFormRef.value) return

    // 表单验证
    await labelFormRef.value.validate()
    printLoading.value = true
    // 处理打印数据，根据printQuantity字段复制数据
    const processedPrintData = []
    printForm.printDetails.forEach((item: any) => {
      const quantity = item.printQuantity || 0
      for (let i = 0; i < quantity; i++) {
        processedPrintData.push(item)
      }
    })
    printFun(
      {
        template: JSON.parse(printForm.barcodeTemplate || '{}'),
        printData: processedPrintData
      },
      null,
      null,
      false
    )
    setTimeout(() => {
      printLoading.value = false
    }, 5000)
  } catch (error: any) {
    printLoading.value = false
    if (error?.name === 'Error') {
      // 表单验证失败
      return
    }
    console.error('静默打印失败:', error)
  }
}
// 明细表配置
const detailTableConfig = reactive({
  // 查询参数
  queryParams: {
    id: props.purchaseOrder?.id || '',
    pageNo: 1,
    pageSize: 500
  },
  // 操作按钮配置
  actions: [
    {
      label: '标签打印',
      type: 'primary',
      icon: 'ep:printer',
      handler: handleLabelPrint
    }
  ],
  // 表格配置
  table: {
    selection: true,
    index: true,
    columns: [
      { prop: 'purchaseOrderItem', label: '行号', width: 80, showOverflowTooltip: true },
      {
        prop: 'material',
        label: '物料号',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'sapMaterialDescription',
        label: '物料长描述',
        minWidth: 150,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'orderQuantity',
        label: '订单数量',
        width: 100,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'purchaseOrderQuantityUnit',
        label: '基本单位',
        width: 100,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'defaultMultiple',
        label: '默认倍数',
        width: 100,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'expectTagNumber',
        label: '预计标签数',
        width: 120,
        showOverflowTooltip: true,
        filterable: true
      },
      {
        prop: 'soldToParty',
        label: '客户编码',
        width: 120,
        showOverflowTooltip: true,
        // render: (_: any, { row }: { row: any }) => {
        //   return row.distributionChannel === 10 ? row.salesOrder : row.purchaseOrder
        // },
        filterable: true
      },
      {
        prop: 'customerName',
        label: '客户名称',
        minWidth: 150,
        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
      }
      // {
      //   prop: 'price',
      //   label: '价格',
      //   width: 100,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'poNo',
      //   label: 'PO号',
      //   width: 140,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'topBarcode',
      //   label: '上衣条形码',
      //   width: 150,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'topName',
      //   label: '上衣名称',
      //   width: 120,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'topSku',
      //   label: '上衣SKU',
      //   width: 120,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'pantsBarcode',
      //   label: '裤子条形码',
      //   width: 150,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'customField1',
      //   label: '自定义字段1',
      //   width: 120,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'customField2',
      //   label: '自定义字段2',
      //   width: 120,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'customField3',
      //   label: '自定义字段3',
      //   width: 120,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'customField4',
      //   label: '自定义字段4',
      //   width: 120,
      //   showOverflowTooltip: true,
      //   filterable: true
      // },
      // {
      //   prop: 'customField5',
      //   label: '自定义字段5',
      //   width: 120,
      //   showOverflowTooltip: true,
      //   filterable: true
      // }
    ]
  },
  // 分页配置
  pagination: {
    pageSize: 500,
    show: true,
    pageSizes: [200, 500, 1000, 2000]
  },
  // 设置
  settings: {
    resetRefresh: true,
    refresh: false,
    download: false,
    print: false,
    size: false,
    columns: false,
    fullscreen: false
  },
  // API配置
  api: {
    getList: async (params: any) => {
      try {
        // 确保id参数存在
        params.id = props.purchaseOrder?.id || ''
        const response = await getPurchaseOrderDetailsPage(params)
        return {
          list: response?.list || [],
          total: response?.total || 0
        }
      } catch (error) {
        console.error('获取采购订单明细失败:', error)
        ElMessage.error('获取采购订单明细失败')
        return { list: [], total: 0 }
      }
    }
  },
  // 选择变化事件
  onSelectionChange: (selection: any[]) => {
    selectedDetailRows.value = selection
  }
})

// 打印标签表配置
const printDetailTableConfig = reactive({
  showIndex: true,
  border: true,
  fields: [
    { prop: 'purchaseOrderItem', label: '行号', disabled: true, width: 80 },
    { prop: 'material', label: '物料号', disabled: true, width: 200, showOverflowTooltip: true },
    {
      prop: 'sapMaterialDescription',
      label: '物料长描述',
      disabled: true,
      minWidth: 200,
      showOverflowTooltip: true
    },
    { prop: 'printQuantity', label: '打印数量', type: 'number', required: true, width: 180, min: 1 }
  ],
  importExport: {
    showImport: false,
    showExport: false
  }
})
// 标记打印状态
const isPrinting = ref(false)

// 打印弹窗出现处理
const handlePrintShow = () => {
  if (isPrinting.value) return
  isPrinting.value = true
  console.log('Vue中监听到第三方插件触发打印弹窗')
  // 你的业务逻辑：比如禁用按钮、修改打印样式等
}

// 打印弹窗关闭处理
const handlePrintClose = () => {
  if (!isPrinting.value) return
  isPrinting.value = false
  console.log('Vue中监听到打印弹窗关闭')
}

let printTimer = null
const lastPrintState = ref(false)

// 轮询检测打印状态
const checkPrintState = () => {
  const current = window.matchMedia('print').matches
  // 弹窗出现
  if (current && !lastPrintState.value) {
    console.log('Vue轮询：打印弹窗出现')
    alert('打印弹窗出现（Vue验证）')
  }
  // 弹窗关闭
  if (!current && lastPrintState.value) {
    console.log('Vue轮询：打印弹窗关闭')
  }
  lastPrintState.value = current
}
const getList = () => {
  // 如果默认标签页是 printData，调用 getList()
  if (activeTab.value === 'printData' && detailTableRef.value) {
    detailTableRef.value.getList()
  }
}
onMounted(() => {
  // 启动轮询（100ms一次，几乎无性能消耗）
  printTimer = setInterval(checkPrintState, 100)
  
})

onUnmounted(() => {
  if (typeof window !== 'undefined') {
    tableHeight.value = window.innerHeight - 360
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      tableHeight.value = window.innerHeight - 360
    })
  }
  // 停止轮询
  clearInterval(printTimer)
})

// 处理标签页切换
const handleTabChange = (name: string) => {
  // if (name === 'printData' && detailTableRef.value) {
  //   detailTableRef.value.getList()
  // }
}

// 监听purchaseOrder变化，更新明细表数据
watch(
  () => props.purchaseOrder,
  (newVal) => {
    if (newVal?.id) {
      // 更新查询参数中的id
      detailTableConfig.queryParams.id = newVal.id
      // 重新获取数据
      if (detailTableRef.value) {
        detailTableRef.value.getList()
      }
    }
  },
  { immediate: true, deep: true }
)

// 监听visible变化，重置状态
watch(
  () => props.visible,
  (newVal) => {
    if (!newVal) {
      selectedDetailRows.value = []
      labelPrintDialogVisible.value = false
      // 重置表单
      printForm.barcodeRule = ''
      printForm.barcodeTemplate = ''
      printForm.printDetails = []
    }
  }
)
defineExpose({
  getList
})
</script>

<style scoped>
/* 物料基础信息显示区域样式 */
.material-basic-info {
  padding: 6px;
  margin-bottom: 30px;
  display: flex;
  width: 100%;
  gap: 15px;
  flex-wrap: wrap;
}
.info-field {
  width: calc(20% - 15px);
}
.info-item {
}

.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;
}

/* 明细表操作区样式 */
.detail-actions {
  text-align: right;
}

/* 标签打印弹窗样式 */
.label-print-dialog {
  padding: 20px;
}
.dialog-title-with-tags {
  display: flex;
  align-items: center;
}

.dialog-title-with-tags .el-tag {
  margin-left: 8px;
}
</style>
