<template>
  <Dialog
    :model-value="visible"
    @update:model-value="handleVisibleChange"
    title="选择打印模板"
    width="80%"
    :fullscreen="true"
  >
    <!-- 表格组件 -->
    <TableList ref="tableListRef" :config="tableConfig" />

    <!-- 底部按钮 -->
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button
        type="primary"
        :disabled="selectedTemplate.length == 0"
        @click="handlePreviewPrint"
      >
        预览打印
      </el-button>
    </template>
  </Dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, watch, h } from 'vue'
import { ElMessage, ElTag } from 'element-plus'
import { Dialog } from '@/components/Dialog'
import TableList from '@/components/TableList/index.vue'
import { template } from 'lodash-es'

// Props
const props = defineProps<{
  visible: boolean
}>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'preview-print': [material: any, template: any]
}>()

// 表格引用
const tableListRef = ref()

// 选中的模板
const selectedTemplate = ref<any>([])

// 模拟数据（参照template页面）
const mockTemplateData = [
  {
    id: 1,
    moduleName: '销售订单模板',
    templateCode: 'SALES_ORDER_001',
    dataSource: 'MySQL',
    docStatus: 'draft', // 草稿
    designStatus: 'not_designed', // 未设计
    data: {
      id: '1',
      logo: 'COZY EARTH',
      name: '物料1',
      code: '12345678',
      size: '120',
      color: '红色'
    },
    templateJSON:
      '{"panels":[{"index":0,"name":1,"height":297,"width":210,"paperHeader":49.5,"paperFooter":780.0000000000001,"printElements":[{"options":{"left":1.5,"top":1.5,"height":11.34,"width":68,"title":"COZY EARTH","right":119.25,"bottom":11.25,"vCenter":59.25,"hCenter":6.375,"field":"logo","testData":"COZY EARTH","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":11.25,"qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":15,"height":14,"width":100,"title":"客户物料","field":"name","testData":"客户物料","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1,"top":31,"height":14,"width":100,"title":"标签颜色","field":"color","testData":"标签颜色","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":2,"top":47,"height":14,"width":100,"title":"物料编码","field":"code","testData":"物料编码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":63,"height":14,"width":100,"title":"标签尺码","field":"size","testData":"标签尺码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"code_1","right":112.75,"bottom":71.00000429153442,"vCenter":62.75,"hCenter":64.00000429153442},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":79.5,"height":42.52,"width":100,"title":"客户物料编码","barcodeType":"code128","testData":"barcode","right":103,"bottom":122.02000429153443,"vCenter":53,"hCenter":100.76000429153443,"field":"code","coordinateSync":false,"widthHeightSync":false,"hideTitle":true},"printElementType":{"title":"条形码","type":"barcode"}},{"options":{"left":108,"top":1.5,"height":11.34,"width":68,"title":"COZY EARTH","right":182.25000762939453,"bottom":8.589996185302734,"vCenter":148.25000762939453,"hCenter":2.9199961853027343,"field":"logo","testData":"COZY EARTH","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":11.25,"qrCodeLevel":0,"qid":"logo_1"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":15,"height":14,"width":100,"title":"客户物料","field":"name","testData":"客户物料","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"name_1","right":209.00000762939453,"bottom":27.749996185302734,"vCenter":159.00000762939453,"hCenter":20.749996185302734},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":31.5,"height":14,"width":100,"title":"标签颜色","field":"color","testData":"标签颜色","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"color_1","right":207.74999237060547,"bottom":42.24999237060547,"vCenter":157.74999237060547,"hCenter":35.24999237060547},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":46.5,"height":14,"width":100,"title":"物料编码","field":"code","testData":"物料编码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"code_2","right":209.5,"bottom":54.5,"vCenter":159.5,"hCenter":47.5},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":63,"height":14,"width":100,"title":"标签尺码","field":"size","testData":"标签尺码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"size_1","right":207.25,"bottom":72.5,"vCenter":157.25,"hCenter":65.5},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":79.5,"height":42.52,"width":100,"title":"客户物料编码","barcodeType":"code128","testData":"barcode","right":209.75000762939453,"bottom":122.27000762939454,"vCenter":159.75000762939453,"hCenter":101.01000762939454,"field":"code","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"qid":"code_3"},"printElementType":{"title":"条形码","type":"barcode"}}],"paperNumberLeft":565.5,"paperNumberTop":573,"paperNumberContinue":true,"watermarkOptions":{"content":"vue-plugin-hiprint","rotate":25,"timestamp":true,"format":"YYYY-MM-DD HH:mm"},"panelLayoutOptions":{}}]}'
  },
  {
    id: 2,
    moduleName: '采购订单模板',
    templateCode: 'PURCHASE_ORDER_001',
    dataSource: 'PostgreSQL',
    docStatus: 'active', // 生效
    designStatus: 'designing', // 设计中
    data: {
      id: '1',
      logo: 'COZY EARTH',
      name: '物料1',
      code: '12345678',
      size: '120',
      color: '红色'
    },
    templateJSON:
      '{"panels":[{"index":0,"name":1,"height":297,"width":210,"paperHeader":49.5,"paperFooter":780.0000000000001,"printElements":[{"options":{"left":1.5,"top":1.5,"height":11.34,"width":68,"title":"COZY EARTH","right":119.25,"bottom":11.25,"vCenter":59.25,"hCenter":6.375,"field":"logo","testData":"COZY EARTH","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":11.25,"qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":15,"height":14,"width":100,"title":"客户物料","field":"name","testData":"客户物料","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1,"top":31,"height":14,"width":100,"title":"标签颜色","field":"color","testData":"标签颜色","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":2,"top":47,"height":14,"width":100,"title":"物料编码","field":"code","testData":"物料编码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":63,"height":14,"width":100,"title":"标签尺码","field":"size","testData":"标签尺码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"code_1","right":112.75,"bottom":71.00000429153442,"vCenter":62.75,"hCenter":64.00000429153442},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":79.5,"height":42.52,"width":100,"title":"客户物料编码","barcodeType":"code128","testData":"barcode","right":103,"bottom":122.02000429153443,"vCenter":53,"hCenter":100.76000429153443,"field":"code","coordinateSync":false,"widthHeightSync":false,"hideTitle":true},"printElementType":{"title":"条形码","type":"barcode"}},{"options":{"left":108,"top":1.5,"height":11.34,"width":68,"title":"COZY EARTH","right":182.25000762939453,"bottom":8.589996185302734,"vCenter":148.25000762939453,"hCenter":2.9199961853027343,"field":"logo","testData":"COZY EARTH","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":11.25,"qrCodeLevel":0,"qid":"logo_1"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":15,"height":14,"width":100,"title":"客户物料","field":"name","testData":"客户物料","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"name_1","right":209.00000762939453,"bottom":27.749996185302734,"vCenter":159.00000762939453,"hCenter":20.749996185302734},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":31.5,"height":14,"width":100,"title":"标签颜色","field":"color","testData":"标签颜色","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"color_1","right":207.74999237060547,"bottom":42.24999237060547,"vCenter":157.74999237060547,"hCenter":35.24999237060547},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":46.5,"height":14,"width":100,"title":"物料编码","field":"code","testData":"物料编码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"code_2","right":209.5,"bottom":54.5,"vCenter":159.5,"hCenter":47.5},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":63,"height":14,"width":100,"title":"标签尺码","field":"size","testData":"标签尺码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"size_1","right":207.25,"bottom":72.5,"vCenter":157.25,"hCenter":65.5},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":79.5,"height":42.52,"width":100,"title":"客户物料编码","barcodeType":"code128","testData":"barcode","right":209.75000762939453,"bottom":122.27000762939454,"vCenter":159.75000762939453,"hCenter":101.01000762939454,"field":"code","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"qid":"code_3"},"printElementType":{"title":"条形码","type":"barcode"}}],"paperNumberLeft":565.5,"paperNumberTop":573,"paperNumberContinue":true,"watermarkOptions":{"content":"vue-plugin-hiprint","rotate":25,"timestamp":true,"format":"YYYY-MM-DD HH:mm"},"panelLayoutOptions":{}}]}'
  },
  {
    id: 3,
    moduleName: '入库单模板',
    templateCode: 'WAREHOUSE_IN_001',
    dataSource: 'Oracle',
    docStatus: 'active', // 生效
    designStatus: 'designed', // 设计完成
    data: {
      id: '1',
      logo: 'COZY EARTH',
      name: '物料1',
      code: '12345678',
      size: '120',
      color: '红色'
    },
    templateJSON:
      '{"panels":[{"index":0,"name":1,"height":297,"width":210,"paperHeader":49.5,"paperFooter":780.0000000000001,"printElements":[{"options":{"left":1.5,"top":1.5,"height":11.34,"width":68,"title":"COZY EARTH","right":119.25,"bottom":11.25,"vCenter":59.25,"hCenter":6.375,"field":"logo","testData":"COZY EARTH","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":11.25,"qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":15,"height":14,"width":100,"title":"客户物料","field":"name","testData":"客户物料","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1,"top":31,"height":14,"width":100,"title":"标签颜色","field":"color","testData":"标签颜色","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":2,"top":47,"height":14,"width":100,"title":"物料编码","field":"code","testData":"物料编码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":63,"height":14,"width":100,"title":"标签尺码","field":"size","testData":"标签尺码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"code_1","right":112.75,"bottom":71.00000429153442,"vCenter":62.75,"hCenter":64.00000429153442},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":1.5,"top":79.5,"height":42.52,"width":100,"title":"客户物料编码","barcodeType":"code128","testData":"barcode","right":103,"bottom":122.02000429153443,"vCenter":53,"hCenter":100.76000429153443,"field":"code","coordinateSync":false,"widthHeightSync":false,"hideTitle":true},"printElementType":{"title":"条形码","type":"barcode"}},{"options":{"left":108,"top":1.5,"height":11.34,"width":68,"title":"COZY EARTH","right":182.25000762939453,"bottom":8.589996185302734,"vCenter":148.25000762939453,"hCenter":2.9199961853027343,"field":"logo","testData":"COZY EARTH","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":11.25,"qrCodeLevel":0,"qid":"logo_1"},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":15,"height":14,"width":100,"title":"客户物料","field":"name","testData":"客户物料","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"name_1","right":209.00000762939453,"bottom":27.749996185302734,"vCenter":159.00000762939453,"hCenter":20.749996185302734},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":31.5,"height":14,"width":100,"title":"标签颜色","field":"color","testData":"标签颜色","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"color_1","right":207.74999237060547,"bottom":42.24999237060547,"vCenter":157.74999237060547,"hCenter":35.24999237060547},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":46.5,"height":14,"width":100,"title":"物料编码","field":"code","testData":"物料编码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"code_2","right":209.5,"bottom":54.5,"vCenter":159.5,"hCenter":47.5},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":63,"height":14,"width":100,"title":"标签尺码","field":"size","testData":"标签尺码","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"fontSize":8.25,"textContentVerticalAlign":"middle","qrCodeLevel":0,"qid":"size_1","right":207.25,"bottom":72.5,"vCenter":157.25,"hCenter":65.5},"printElementType":{"title":"文本","type":"text"}},{"options":{"left":108,"top":79.5,"height":42.52,"width":100,"title":"客户物料编码","barcodeType":"code128","testData":"barcode","right":209.75000762939453,"bottom":122.27000762939454,"vCenter":159.75000762939453,"hCenter":101.01000762939454,"field":"code","coordinateSync":false,"widthHeightSync":false,"hideTitle":true,"qid":"code_3"},"printElementType":{"title":"条形码","type":"barcode"}}],"paperNumberLeft":565.5,"paperNumberTop":573,"paperNumberContinue":true,"watermarkOptions":{"content":"vue-plugin-hiprint","rotate":25,"timestamp":true,"format":"YYYY-MM-DD HH:mm"},"panelLayoutOptions":{}}]}'
  }
]

// 表格配置（参照template页面配置）
const tableConfig: any = reactive({
  // 查询参数
  queryParams: {
    moduleName: '',
    templateCode: '',
    dataSource: ''
  },

  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'moduleName',
        label: '模块名称',
        type: 'input',
        placeholder: '请输入模块名称',
        width: '200px'
      },
      {
        field: 'templateCode',
        label: '模板code',
        type: 'input',
        placeholder: '请输入模板code',
        width: '200px'
      },
      {
        field: 'dataSource',
        label: '数据源',
        type: 'input',
        placeholder: '请输入数据源',
        width: '200px'
      }
    ]
  },

  // 表格配置
  table: {
    selection: 'single', // 单选
    index: true,
    columns: [
      {
        prop: 'moduleName',
        label: '模块名称',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'templateCode',
        label: '模板code',
        width: 180,
        showOverflowTooltip: true
      },
      {
        prop: 'dataSource',
        label: '数据源',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'docStatus',
        label: '单据状态',
        width: 100,
        align: 'center',
        render: (_: any, { row }: { row: any }) => {
          const statusConfig: Record<string, { type: string; text: string; effect: string }> = {
            draft: { type: 'info', text: '草稿', effect: 'light' },
            active: { type: 'success', text: '生效', effect: 'light' },
            inactive: { type: 'warning', text: '失效', effect: 'light' }
          }
          const config = statusConfig[row.docStatus] || {
            type: 'info',
            text: '未知',
            effect: 'light'
          }
          return h(
            ElTag,
            {
              type: config.type,
              effect: config.effect,
              size: 'small',
              'disable-transitions': true
            },
            () => config.text
          )
        }
      },
      {
        prop: 'designStatus',
        label: '设计状态',
        width: 120,
        align: 'center',
        render: (_: any, { row }: { row: any }) => {
          const designStatusConfig: Record<string, { type: string; text: string; effect: string }> =
            {
              not_designed: { type: 'info', text: '未设计', effect: 'light' },
              designing: { type: 'warning', text: '设计中', effect: 'light' },
              designed: { type: 'success', text: '设计完成', effect: 'light' }
            }
          const config = designStatusConfig[row.designStatus] || {
            type: 'info',
            text: '未知',
            effect: 'light'
          }
          return h(
            ElTag,
            {
              type: config.type,
              effect: config.effect,
              size: 'small',
              'disable-transitions': true
            },
            () => config.text
          )
        }
      }
    ]
  },

  // 分页配置
  pagination: {
    pageSize: 10,
    show: true
  },

  // 设置
  settings: {
    refresh: true,
    size: true,
    columns: true,
    fullscreen: true
  },

  // API配置（模拟）
  api: {
    getList: async (params: any) => {
      // 模拟API调用
      return new Promise((resolve) => {
        setTimeout(() => {
          let filteredData = [...mockTemplateData]

          // 模拟搜索过滤
          if (params.moduleName) {
            filteredData = filteredData.filter((item) =>
              item.moduleName.includes(params.moduleName)
            )
          }
          if (params.templateCode) {
            filteredData = filteredData.filter((item) =>
              item.templateCode.includes(params.templateCode)
            )
          }
          if (params.dataSource) {
            filteredData = filteredData.filter((item) =>
              item.dataSource.includes(params.dataSource)
            )
          }

          resolve({
            list: filteredData,
            total: filteredData.length
          })
        }, 500)
      })
    }
  },

  // 单选配置
  onSelectionChange: (selection: any[]) => {
    selectedTemplate.value = selection
  }
})

// 监听visible变化，重置选中状态
watch(
  () => props.visible,
  (newVal) => {
    if (newVal) {
      selectedTemplate.value = []
      // 重置表格选择
      if (tableListRef.value) {
        tableListRef.value.clearSelection()
      }
    }
  }
)

// 处理弹窗显示状态变化
const handleVisibleChange = (value: boolean) => {
  emit('update:visible', value)
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
}

// 预览打印
const handlePreviewPrint = () => {
  console.log('selectedTemplate', selectedTemplate.value)
  if (selectedTemplate.value.length != 1) {
    ElMessage.warning('请选择一个模板')
    return
  }

  // 触发预览打印事件
  // emit('preview-print', currentMaterial.value, selectedTemplate.value)
}

// 当前要打印的物料（需要从父组件传入）
const currentMaterial = ref<any>(null)

// 暴露方法给父组件
defineExpose({
  setMaterial: (material: any) => {
    currentMaterial.value = material
  }
})
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding: 20px;
}
</style>
