<template>
  <div class="material-setting-page">
    <!-- 表格组件 -->
    <TableList ref="tableListRef" :config="tableConfig" />
    <!-- 物料导入弹窗 -->
    <MaterialImportForm ref="importFormRef" @success="handleImportSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElTag, ElLoading } from 'element-plus'
import TableList from '@/components/TableList/index.vue'
import MaterialImportForm from './MaterialImportForm.vue'
import { Dialog } from '@/components/Dialog'
import { fontList } from '@/api/print/font'
import { getApiSettingList, tagTemplateConfigList } from '@/api/print/apiSetting'
import { checkPermi } from '@/utils/permission'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import { DICT_TYPE, getDictOptions, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import download from '@/utils/download'
// 引入字体加载工具
import { loadAllFonts } from '@/utils/fontLoader'
// 路由
const router = useRouter()
// 表格引用
const tableListRef = ref()

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

// 物料导入弹窗相关
const importFormRef = ref()

// 物料编辑弹窗相关
const editFormRef = ref()

// 同步SAP弹窗相关
const syncDialogVisible = ref(false)
const syncFormData = ref({
  syncDate: ''
})
const syncLoading = ref(false)

// 条码生成弹窗相关
const barcodeDialogVisible = ref(false)
const barcodeFormRef = ref()
const currentPrintRow = ref(null)
const dialogPreviewRef = ref<any>(null)

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

// 条码模板数据
const barcodeTemplates = ref([])

// 条码表单数据
const barcodeFormData = reactive({
  barcodeRule: '',
  barcodeTemplate: '',
  printNumber: 1
})

// 条码表单验证规则
const barcodeFormRules = {
  barcodeRule: [{ required: true, message: '请选择条码规则', trigger: 'change' }],
  barcodeTemplate: [{ required: true, message: '请选择条码模板', trigger: 'change' }],
  printNumber: [
    {
      required: true,
      message: '请输入数量',
      trigger: 'blur',
      validator: (rule, value, callback) => {
        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()
      }
    }
  ]
}

// 打开同步SAP弹窗
const handleSyncSAP = async () => {
  const selectedRows = tableListRef.value.selectedRows
  syncDialogVisible.value = true
  syncFormData.value.syncDate = ''
}

// 确认同步SAP
const confirmSyncSAP = async () => {
  if (!syncFormData.value.syncDate) {
    ElMessage.warning('请选择同步日期')
    return
  }

  try {
    await ElMessageBox.confirm(`确定同步操作吗？`, '提示', {
      type: 'warning'
    })

    syncLoading.value = true

    const requestData = {
      syncDate: syncFormData.value.syncDate
    }

    console.log('SAP同步请求数据：', requestData)

    await materialBaseInfoSapCreate(requestData)

    ElMessage.success('同步SAP成功')
    syncDialogVisible.value = false
    tableListRef.value.getList()
  } catch (error) {
    console.error('同步SAP失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('同步失败')
    }
  } finally {
    syncLoading.value = false
  }
}

// 打印
const handlePrint = () => {
  ElMessage.info('打印功能开发中...')
}

// 详情
const handleDetail = (row: any) => {
  if (row && row.id) {
    editFormRef.value.open('view', row.id)
  }
}

// 获取条码规则数据
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 tagTemplateConfigList({ dataSource })
    barcodeTemplates.value =
      templateResponse.map((item: any) => ({
        label: item.templateName,
        value: item.templateCode,
        contentText: item.contentText
      })) || []
  } catch (error) {
    console.error('获取条码模板失败:', error)
    barcodeTemplates.value = []
  }
}

// 条码规则变更处理
const handleBarcodeRuleChange = async (value: string) => {
  if (value) {
    await fetchBarcodeTemplates(value)
    barcodeFormData.barcodeTemplate = ''
  } else {
    barcodeTemplates.value = []
    barcodeFormData.barcodeTemplate = ''
  }
}

// 数量输入处理
const handlePrintNumberInput = (value: string) => {
  // 使用正则过滤，只保留数字
  const filteredValue = value.replace(/[^\d]/g, '')
  // 更新表单数据
  barcodeFormData.printNumber = filteredValue ? Number(filteredValue) : 1
}

// 重置条码表单
const resetBarcodeForm = () => {
  barcodeFormData.barcodeRule = ''
  barcodeFormData.barcodeTemplate = ''
  barcodeFormData.printNumber = 1
  barcodeTemplates.value = []
  currentPrintRow.value = null
}

// 条码表单提交处理
const handlePrintSubmit = async () => {
  if (!barcodeFormRef.value) return
  try {
    await barcodeFormRef.value.validate()
    // 验证通过，处理打印逻辑
    const templateJson = barcodeTemplates.value.find(
      (item: any) => item.value === barcodeFormData.barcodeTemplate
    )?.contentText
    let printData = []

    // 处理打印数据，根据数量生成多个打印数据
    const printNumber = barcodeFormData.printNumber || 1
    for (let i = 0; i < printNumber; i++) {
      printData.push(currentPrintRow.value)
    }

    dialogPreviewRef.value?.open({
      template: JSON.parse(templateJson || '{}'),
      printData
    })

    // 关闭条码生成弹窗
    barcodeDialogVisible.value = false
  } catch (error) {
    console.error('表单验证失败', error)
  }
}

// 单行打印
const handlePrintRow = async (row: any) => {
  if (!row || !row.id) {
    ElMessage.warning('请选择有效的物料')
    return
  }

  currentPrintRow.value = row

  // 获取条码规则数据
  await fetchBarcodeData()
  // 清空条码模板数据
  barcodeTemplates.value = []

  // 打开条码生成弹窗
  barcodeDialogVisible.value = true

  // 设置默认值
  barcodeFormData.barcodeRule = ''
  barcodeFormData.barcodeTemplate = ''
  barcodeFormData.printNumber = 1

  // 延迟设置默认条码规则，避免触发watch
  setTimeout(async () => {
    barcodeFormData.barcodeRule = barcodeRules.value[0]?.value || ''
    await fetchBarcodeTemplates(barcodeFormData.barcodeRule)
  }, 0)
}

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

// 导入处理
const handleImport = () => {
  importFormRef.value.open()
}

// 导入成功回调
const handleImportSuccess = () => {
  // 加载所有字体
  loadAllFonts()
    .then(() => {
      console.log('字体加载完成')
    })
    .catch((error) => {
      console.error('字体加载失败:', error)
    })
  ElMessage.success('导入成功')
  tableListRef.value.getList()
}

// 高级搜索相关
const advancedSearchDrawerVisible = ref(false)
const advancedSearchForm = reactive({
  customerMaterialNoList: ''
})
const advancedSearchLoading = ref(false)

// 显示高级搜索抽屉
const showAdvancedSearchDrawer = () => {
  advancedSearchDrawerVisible.value = true
}

// 重置高级搜索
const resetAdvancedSearch = () => {
  advancedSearchForm.customerMaterialNoList = ''
  tableListRef.value.updateQueryParams({
    customerMaterialNoList: []
  })
  tableListRef.value.getList()
  advancedSearchDrawerVisible.value = false
}

// 高级搜索处理
const handleAdvancedSearch = async () => {
  if (!advancedSearchForm.customerMaterialNoList) {
    ElMessage.warning('请输入客户物料编号')
    return
  }

  advancedSearchLoading.value = true
  try {
    // 将文本域内容按换行符分割成数组
    const customerMaterialNoList = advancedSearchForm.customerMaterialNoList
      .split('\n')
      .map((item: string) => item.trim())
      .filter((item: string) => item)

    // 更新查询参数
    tableListRef.value.updateQueryParams({
      customerMaterialNoList
    })

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

    // 关闭抽屉
    advancedSearchDrawerVisible.value = false

    ElMessage.success('搜索成功')
  } catch (error) {
    console.error('高级搜索失败:', error)
    ElMessage.error('搜索失败')
  } finally {
    advancedSearchLoading.value = false
  }
}

// 编辑处理
const handleEdit = (row: any) => {
  if (row && row.id) {
    editFormRef.value.open('update', row.id)
  } else {
    editFormRef.value.open('create')
  }
}

// 编辑成功回调
const handleEditSuccess = () => {
  tableListRef.value.getList()
}

// 处理文件流下载
const handleFileDownload = (blob: Blob, filename?: string) => {
  try {
    console.log('handleFileDownload', blob)

    // 检查blob对象是否存在
    if (!blob) {
      throw new Error('文件数据为空')
    }

    // 使用封装好的下载工具
    const downloadFilename = filename || '物料基本信息.xlsx'
    download.excel(blob, downloadFilename)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('文件下载处理失败:', error)
    ElMessage.error('文件下载失败')
  }
}

// 自定义下载处理函数
const handleDownload = () => {
  // 获取查询条件参数
  const queryParams = tableListRef.value.queryParams
  exportLoading.value = true
  // 调用导出API（使用查询条件而不是传入的数据）
  materialBaseInfoExportExcel(queryParams)
    .then((blob) => {
      // 直接使用返回的blob对象
      const now = new Date()
      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0')
      const day = String(now.getDate()).padStart(2, '0')
      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')
      const timestamp = `${year}${month}${day}${hours}${minutes}${seconds}`
      handleFileDownload(blob, `物料基本信息_${timestamp}.xlsx`)
      exportLoading.value = false
    })
    .catch((error) => {
      console.error('导出失败:', error)
      exportLoading.value = false
      ElMessage.error('导出失败')
    })
}
const exportLoading = ref(false) // 导出的加载中
// 表格配置
const tableConfig: any = reactive({
  // 查询参数
  queryParams: {
  },
  // 搜索表单配置
  searchForm: {
  },
  // 操作按钮配置
  actions: [
    {
      label: '导入',
      type: 'default',
      plain: true,
      icon: 'ep:upload',
      handler: handleImport,
      permission: 'print:font:import'
    }
  ],

  // 表格配置
  table: {
    actionsWidth: 0,
    selection: false,
    index: true,
    columns: [
      {
        prop: 'fileName',
        label: '字体名称',
        minWidth: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'fileUrl',
        label: '字体地址',
        minWidth: 280,
        showOverflowTooltip: true
      },
    ],
    actions: [
      // {
      //   label: '打印',
      //   type: 'primary',
      //   link: true,
      //   handler: handlePrintRow
      // }
    ]
  },
  // 分页配置
  pagination: {
    pageSize: 10,
    show: false
  },

  // 设置
  settings: {
    refresh: true,
    download: false,
    // download: {
    //   handler: handleDownload, // 自定义下载处理函数
    //   showColumnSelector: false // 不显示列选择器
    // },
    print: true,
    size: true,
    columns: true,
    fullscreen: true
  },

  // API配置（模拟）
  api: {
    getList: async (params: any) => {
      try {
        const response = await fontList() || []
        return {
          list: response,
          total: response.length
        }
      } catch (error) {
        console.error('获取模板列表失败:', error)
        ElMessage.error('获取数据失败')
        throw error
      }
    }
  }
})
onMounted(() => {
  // 初始化时调用 getList()
  tableListRef.value.getList()
})
</script>

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

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

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

/* 高级搜索悬浮按钮 */
.advanced-search-float-btn {
  position: fixed;
  bottom: 80px;
  right: 30px;
  width: 50px;
  height: 50px;
  border-radius: 50%;
  background-color: #409eff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 100;

  &:hover {
    background-color: #66b1ff;
    transform: scale(1.1);
  }

  .icon {
    font-size: 24px;
  }
}

/* 高级搜索抽屉 */
.advanced-search-form {
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
