<template>
  <div class="material-setting-page">
    <!-- 表格组件 -->
    <TableList ref="tableListRef" :config="tableConfig" />

    <!-- 模板选择弹窗 -->
    <TemplateSelectDialog
      v-model:visible="templateDialogVisible"
      ref="templateDialogRef"
      @preview-print="handlePreviewPrint"
    />
    <!-- <printDemo
      v-model:visible="templateDialogVisible"
      ref="templateDialogRef"
      @preview-print="handlePreviewPrint"
    /> -->

    <!-- 设计器全屏弹窗 -->
    <el-dialog
      v-model="designDialogVisible"
      title="打印设计"
      fullscreen
      :show-close="true"
      @close="handleDesignDialogClose"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
import TableList from '@/components/TableList/index.vue'
import TemplateSelectDialog from './TemplateSelectDialog.vue'
import printDemo from './printDemo.vue'
// 路由
const router = useRouter()
// 表格引用
const tableListRef = ref()

// 模板选择弹窗相关
const templateDialogVisible = ref(false)
const templateDialogRef = ref()

// 设计器弹窗相关
const designDialogVisible = ref(false)

// 模拟数据
const mockData = [
  {
    id: 1,
    materialName: '钢材A型',
    materialCode: 'MAT001',
    materialSpec: '10mm*1000mm*2000mm',
    sapSyncStatus: 'not_synced', // 未同步
    syncTime: ''
  },
  {
    id: 2,
    materialName: '钢材B型',
    materialCode: 'MAT002',
    materialSpec: '15mm*1500mm*3000mm',
    sapSyncStatus: 'synced', // 已同步
    syncTime: '2024-01-15 10:30:00'
  },
  {
    id: 3,
    materialName: '铝合金板',
    materialCode: 'MAT003',
    materialSpec: '5mm*800mm*1200mm',
    sapSyncStatus: 'not_synced', // 未同步
    syncTime: ''
  }
]
// 同步SAP
const handleSyncSAP = async () => {
  const selectedRows = tableListRef.value.selectedRows
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要同步的物料')
    return
  }

  // 检查是否有已同步的数据
  const syncedRows = selectedRows.filter((row) => row.sapSyncStatus === 'synced')
  if (syncedRows.length > 0) {
    ElMessage.warning('只能同步未同步的物料，请重新选择')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要同步选中的 ${selectedRows.length} 条物料到SAP吗？`, '提示', {
      type: 'warning'
    })

    // 模拟同步操作
    for (const row of selectedRows) {
      const index = mockData.findIndex((item) => item.id === row.id)
      if (index > -1) {
        mockData[index].sapSyncStatus = 'synced'
        mockData[index].syncTime = new Date().toLocaleString('zh-CN')
      }
    }

    ElMessage.success('同步SAP成功')
    tableListRef.value.getList()
  } catch {
    // 用户取消操作
  }
}

// 获取当前实例
const { proxy } = getCurrentInstance() as any

// 打印
const handlePrint = () => {
  const templateData = {
    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: {}
      }
    ]
  }
  console.log('$hiprint', proxy.$hiprint)
  // 使用Vue 3的方式访问全局插件
  const hiprintTemplate = new proxy.$hiprint.PrintTemplate({
    template: templateData // 模板json [对象]
  })
  console.log('hiprintTemplate', hiprintTemplate)
  hiprintTemplate.print({
    id: '1',
    logo: 'COZY EARTH',
    name: '物料1',
    code: '12345678',
    size: '120',
    color: '红色'
  })
}

// 单行同步SAP
const handleSyncSAPRow = async (row: any) => {
  try {
    await ElMessageBox.confirm(`确定要将物料【${row.materialName}】同步到SAP吗？`, '提示', {
      type: 'warning'
    })

    // 模拟同步操作
    const index = mockData.findIndex((item) => item.id === row.id)
    if (index > -1) {
      mockData[index].sapSyncStatus = 'synced'
      mockData[index].syncTime = new Date().toLocaleString('zh-CN')
    }

    ElMessage.success('同步SAP成功')
    tableListRef.value.getList()
  } catch {
    // 用户取消操作
  }
}

// 单行打印
const handlePrintRow = (row: any) => {
  templateDialogVisible.value = true
  // 设置当前物料到弹窗组件
  if (templateDialogRef.value) {
    templateDialogRef.value.setMaterial(row)
  }
}

// 单行设计
const handleDesignRow = (row: any) => {
  designDialogVisible.value = true
}

// 设计弹窗关闭处理
const handleDesignDialogClose = () => {
  designDialogVisible.value = false
}

// 预览打印处理
const handlePreviewPrint = (material: any, template: any) => {
  console.log('预览打印处理', material, template)
  // 这里可以调用实际的打印预览功能
  templateDialogVisible.value = false
  router.push('/print/print/designer')
}

// 表格配置
const tableConfig: any = reactive({
  // 查询参数
  queryParams: {
    materialName: '',
    materialCode: '',
    materialSpec: ''
  },

  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'materialName',
        label: '物料名称',
        type: 'input',
        placeholder: '请输入物料名称',
        width: '200px'
      },
      {
        field: 'materialCode',
        label: '物料编码',
        type: 'input',
        placeholder: '请输入物料编码',
        width: '200px'
      },
      {
        field: 'materialSpec',
        label: '物料规格',
        type: 'input',
        placeholder: '请输入物料规格',
        width: '200px'
      }
    ]
  },

  // 操作按钮配置
  actions: [
    {
      label: '同步SAP',
      type: 'primary',
      icon: 'ep:refresh',
      handler: handleSyncSAP
    }
  ],

  // 表格配置
  table: {
    selection: true,
    index: true,
    columns: [
      {
        prop: 'materialName',
        label: '物料名称',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'materialCode',
        label: '物料编码',
        width: 180,
        showOverflowTooltip: true
      },
      {
        prop: 'materialSpec',
        label: '物料规格',
        minWidth: 200,
        showOverflowTooltip: true
      },
      {
        prop: 'sapSyncStatus',
        label: 'SAP同步状态',
        width: 120,
        align: 'center',
        render: (_: any, { row }: { row: any }) => {
          const statusConfig: Record<string, { type: string; text: string; effect: string }> = {
            not_synced: { type: 'warning', text: '未同步', effect: 'light' },
            synced: { type: 'success', text: '已同步', effect: 'light' }
          }
          const config = statusConfig[row.sapSyncStatus] || {
            type: 'info',
            text: '未知',
            effect: 'light'
          }
          return h(
            ElTag,
            {
              type: config.type,
              effect: config.effect,
              size: 'small',
              'disable-transitions': true
            },
            () => config.text
          )
        }
      },
      {
        prop: 'syncTime',
        label: '同步时间',
        width: 180,
        showOverflowTooltip: true
      }
    ],
    actions: [
      {
        label: '同步SAP',
        type: 'primary',
        link: true,
        show: (row: any) => row.sapSyncStatus === 'not_synced', // 只有未同步的可以同步
        handler: handleSyncSAPRow
      },
      {
        label: '打印',
        type: 'primary',
        link: true,
        // handler: handlePrint
        handler: handlePrintRow
      }
      // {
      //   label: '设计',
      //   type: 'primary',
      //   link: true,
      //   handler: handleDesignRow
      // }
    ]
  },

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

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

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

          // 模拟搜索过滤
          if (params.materialName) {
            filteredData = filteredData.filter((item) =>
              item.materialName.includes(params.materialName)
            )
          }
          if (params.materialCode) {
            filteredData = filteredData.filter((item) =>
              item.materialCode.includes(params.materialCode)
            )
          }
          if (params.materialSpec) {
            filteredData = filteredData.filter((item) =>
              item.materialSpec.includes(params.materialSpec)
            )
          }

          resolve({
            list: filteredData,
            total: filteredData.length
          })
        }, 500)
      })
    }
  }
})
</script>

<style scoped>
.page-header {
  padding-bottom: 20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.page-header h2 {
  margin: 0 0 8px;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  font-size: 14px;
  color: #909399;
}
</style>
