<template>
  <div class="material-setting-page">
    <!-- 表格组件 -->
    <TableList ref="tableListRef" :config="tableConfig" />
    <!-- 客户组表单弹窗 -->
    <CustomerForm
      v-model:visible="formDialogVisible"
      :mode="formMode"
      :data="formData"
      @success="handleFormSuccess"
    />
    
    <!-- 修改记录弹窗 -->
    <Dialog
      v-model="updateLogDialogVisible"
      title="修改记录"
      width="80%"
      :close-on-click-modal="false"
    >
      <TableList ref="updateLogTableRef" :config="updateLogTableConfig" />
    </Dialog>
  </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 { dateFormatter } from '@/utils/formatTime'
import TableList from '@/components/TableList/index.vue'
import CustomerForm from './form.vue'
import { customerGroupPage, createCustomerGroup, updateCustomerGroup, deleteCustomerGroup, customerGroupOperationLogPage } from '@/api/print/customerGroup'
import { checkPermi } from '@/utils/permission'
// 路由
const router = useRouter()
// 表格引用
const tableListRef = ref()

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

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

// 客户组表单弹窗相关
const formDialogVisible = ref(false)
const formMode = ref('add')
const formData = ref({})

// 修改记录弹窗相关
const updateLogDialogVisible = ref(false)
const updateLogTableRef = ref()

// 修改记录表格配置
const updateLogTableConfig = reactive({
  // 查询参数
  queryParams: {
    customerGroup: '',
    customerSapCode: ''
  },
  
  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'customerGroup',
        label: '客户组',
        type: 'input',
        placeholder: '请输入客户组',
        width: '200px'
      },
      {
        field: 'customerSapCode',
        label: '客户SAP编码',
        type: 'input',
        placeholder: '请输入客户SAP编码',
        width: '200px'
      }
    ]
  },
  
  // 表格配置
  table: {
    selection: false,
    index: true,
    columns: [
      {
        label: '修改前',
        align: 'center',
        children: [
          {
            prop: 'oldCustomerGroup',
            label: '客户组',
            width: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'oldCustomerSapCode',
            label: '客户SAP编码',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'oldCustomerName',
            label: '客户备注',
            minWidth: 150,
            showOverflowTooltip: true
          }
        ]
      },
      {
        label: '修改后',
        align: 'center',
        children: [
          {
            prop: 'customerGroup',
            label: '客户组',
            width: 120,
            showOverflowTooltip: true
          },
          {
            prop: 'customerSapCode',
            label: '客户SAP编码',
            width: 150,
            showOverflowTooltip: true
          },
          {
            prop: 'customerName',
            label: '客户备注',
            minWidth: 150,
            showOverflowTooltip: true
          }
        ]
      },
      {
        prop: 'operationName',
        label: '操作类型',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'creatorName',
        label: '操作人',
        width: 120,
        showOverflowTooltip: true,
      },
      {
        prop: 'createTime',
        label: '操作时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: dateFormatter
      }
    ]
  },
  
  // 分页配置
  pagination: {
    pageSize: 10,
    show: true
  },
  
  // 设置
  settings: {
    refresh: false,
    download: false,
    print: false,
    size: false,
    columns: false,
    fullscreen: false
  },
  
  // API配置
  api: {
    getList: async (params: any) => {
      const response = await customerGroupOperationLogPage(params)
      return response
    }
  }
})

// 打开新增客户组表单
const handleAddCustomerGroup = () => {
  formMode.value = 'add'
  formData.value = {}
  formDialogVisible.value = true
}

// 表单成功回调
const handleFormSuccess = async (type: string, data: any) => {
  try {
    if (formMode.value === 'add') {
      // 创建客户组
      await createCustomerGroup(data)
    } else if (formMode.value === 'edit') {
      // 更新客户组
      await updateCustomerGroup(data)
    }
    
    formDialogVisible.value = false
    ElMessage.success('保存成功')
    tableListRef.value.getList()
  } catch (error) {
    console.error('保存失败:', error)
    // ElMessage.error('保存失败')
  }
}

// 打开编辑客户组表单
const handleEdit = (row: any) => {
  formMode.value = 'edit'
  formData.value = { ...row }
  formDialogVisible.value = true
}

// 打开修改记录弹窗
const handleShowUpdateLog = () => {
  updateLogDialogVisible.value = true
  // 刷新修改记录表格数据
  if (updateLogTableRef.value) {
    updateLogTableRef.value.getList()
  }
}

// 删除客户组
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定删除数据？此操作不可逆', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    // 调用删除接口
    await deleteCustomerGroup(row.id)
    
    ElMessage.success('删除成功')
    tableListRef.value.getList()
  } catch (error) {
    // 用户取消操作或删除失败
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 模拟数据
const mockData = [
  {
    id: 1,
    customerGroup: 'A组',
    customerSapCode: 'SAP001',
    customerName: '客户一',
    createUser: '张三',
    createTime: '2024-01-01 10:00:00',
    updateUser: '李四',
    updateTime: '2024-01-02 14:30:00'
  },
  {
    id: 2,
    customerGroup: 'B组',
    customerSapCode: 'SAP002',
    customerName: '客户二',
    createUser: '王五',
    createTime: '2024-01-03 09:00:00',
    updateUser: '赵六',
    updateTime: '2024-01-04 11:00:00'
  },
  {
    id: 3,
    customerGroup: 'C组',
    customerSapCode: 'SAP003',
    customerName: '客户三',
    createUser: '钱七',
    createTime: '2024-01-05 16:00:00',
    updateUser: '孙八',
    updateTime: '2024-01-06 10:30:00'
  }
]
// 同步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: {
    customerGroup: '',
    customerSapCode: ''
  },

  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'customerGroup',
        label: '客户组',
        type: 'input',
        placeholder: '请输入客户组',
        width: '200px'
      },
      {
        field: 'customerSapCode',
        label: '客户SAP编码',
        type: 'input',
        placeholder: '请输入客户SAP编码',
        width: '200px'
      }
    ]
  },

  // 操作按钮配置
  actions: [
    {
      label: '新增',
      type: 'primary',
      icon: 'ep:plus',
      handler: handleAddCustomerGroup,
      permission: 'print:customer:add'
    },
    {
      label: '修改记录',
      type: 'default',
      handler: handleShowUpdateLog,
      permission: 'print:customer:updateLog'
    }
  ],

  // 表格配置
  table: {
    selection: true,
    index: true,
    columns: [
      {
        prop: 'customerGroup',
        label: '客户组',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'customerSapCode',
        label: '客户SAP编码',
        width: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'customerName',
        label: '客户备注',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'creatorName',
        label: '创建人',
        width: 100,
        showOverflowTooltip: true
      },
      {
        prop: 'createTime',
        label: '创建时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.createTime)
      },
      {
        prop: 'updaterName',
        label: '修改人',
        width: 100,
        showOverflowTooltip: true
      },
      {
        prop: 'updateTime',
        label: '修改时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.updateTime)
      }
    ],
    actions: [
      {
        label: '编辑',
        type: 'primary',
        link: true,
        handler: handleEdit,
        show: () => checkPermi(['print:customer:edit']),
      },
      {
        label: '删除',
        type: 'danger',
        link: true,
        handler: handleDelete,
        show: () => checkPermi(['print:customer:delete']),
      }
    ],
    actionsWidth: 100
  },

  // 分页配置
  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调用
      const response = await customerGroupPage(params)
      return response
    }
  }
})
onMounted(() => {
  // 初始化时调用 getList()
  tableListRef.value.getList()
})
</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>
