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

    <!-- 表单弹窗组件 -->
    <ApiForm
      v-model:visible="formDialogVisible"
      :mode="formMode"
      :data="formData"
      @success="handleFormSuccess"
      @table-list-refresh="tableListRefresh"
    />

    <!-- 设计器弹窗组件 -->
    <DesignerDialog
      ref="designerDialogRef"
      v-model:visible="designerDialogVisible"
      :title="designerDialogTitle"
      :designerTemplateColumns="designerTemplateColumns"
      :template-id="designerTemplateId"
      :font-list="fontList"
      @table-list-refresh="tableListRefresh"
    />
    <!--打印预览组件-->
    <DialogPreview ref="dialogPreviewRef" :has-print-button="false"/>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
import TableList from '@/components/TableList/index.vue'
import ApiForm from './form.vue'
import DesignerDialog from './DesignerDialog.vue'
import download from '@/utils/download'
import { dateFormatter } from '@/utils/formatTime'
import { checkPermi } from '@/utils/permission'
import { hiprint } from 'sv-print'
import { fontStyleAdv } from './fontStyleAdv.js'
import fontSize from './fontSize.js'
import { fieldAdv } from './fieldAdv.js'
import DialogPreview from '@/components/PrintDesginer/dialogPreview.vue'
import { useFontStore } from '@/store/modules/font'
import {
  getTemplatePage,
  createTemplate,
  updateTemplate,
  deleteTemplate,
  deleteTemplateList,
  updateTemplateStatus,
  exportTemplate,
  getTemplateColumnInfo,
  copyTemplate
} from '@/api/print/template'
// import templateJson from "./testTemplate.json";
// 表格引用
const tableListRef = ref()
const designerDialogRef = ref()
const dialogPreviewRef = ref<any>(null)
// 弹窗相关
const formDialogVisible = ref(false)
const formMode = ref<'add' | 'edit' | 'detail'>('add')
const formData = ref<any>(null)

// 设计器弹窗相关
const designerDialogVisible = ref(false)
const designerDialogTitle = ref('模板设计器')
const designerTemplate = ref<any>({})
const designerTemplateColumns = ref<any[]>([])
const designerTemplateId = ref<number | undefined>(undefined)
// 路由
const router = useRouter()
const fontStore = useFontStore()
const loadedFonts = computed(() => fontStore.getLoadedFonts || [])
const initFontList = ref([
  { title: '微软雅黑', value: 'Microsoft YaHei' },
  { title: '苹方', value: 'PingFang SC' },
  { title: '冬青黑体', value: 'Hiragino Sans GB' },
  { title: '思源黑体', value: 'Noto Sans SC' },
  { title: '黑体', value: 'SimHei' },
  { title: 'Arial', value: 'Arial' }, // Arial，Noto Sans SC
  { title: 'Helvetica', value: 'Helvetica' },
  { title: '宋体', value: 'SimSun' },
  { title: '新宋体', value: 'NSimSun' },
  { title: '思源宋体', value: 'Noto Serif SC' },
  { title: 'Times New Roman', value: 'Times New Roman' },
  { title: 'Georgia', value: 'Georgia' },
  { title: '楷体', value: 'KaiTi' },
  { title: '隶书', value: 'LiSu' },
  { title: 'Consolas', value: 'Consolas' },
  { title: 'Monaco', value: 'Monaco' },
  { title: 'Menlo', value: 'Menlo' }
])
const fontList = computed(() => [...initFontList.value, ...loadedFonts.value])
// 新增接口
const handleAdd = () => {
  formMode.value = 'add'
  formData.value = null
  formDialogVisible.value = true
  console.log('------新增模板-------', formData.value)
}

// 编辑接口
const handleEdit = (row: any) => {
  formMode.value = 'edit'
  formData.value = row
  formDialogVisible.value = true
}

// 查看详情
const handleDetail = (row: any) => {
  formMode.value = 'detail'
  formData.value = row
  formDialogVisible.value = true
}
let template = ref({})
const handleTemplateMockData = (template: any) => {
  const mockData = []
  if (!template.panels) {
    return mockData
  }
  template.panels.forEach((item: any) => {
    let obj = {}
    item.printElements.forEach((element: any) => {
      obj[element.options.field] = element.options.testData
    })
    mockData.push(obj)
  })
  console.log('------模板打印模拟数据-------', mockData)
  return mockData
}
// 预览
const handlePreview = (row: any) => {
  template.value = JSON.parse(row.contentText || '{}')
  console.log('------模板数据-------', template.value)
  const mockData = handleTemplateMockData(template.value)
  dialogPreviewRef.value?.open({
    template: template.value,
    printData: mockData,
    title: row.templateName
  })
}
// 设计跳转
const handleDesign = async (row: any) => {
  try {
    // 调用getTemplateColumnInfo方法获取列信息
    const res = await getTemplateColumnInfo({ tableName: row.dataSource })
    console.log('获取模板列信息成功:', res)
    console.log('------字体列表-------', fontList.value)
    designerTemplateColumns.value = res || []
    designerTemplateId.value = row.id || null // 传递模板id
    designerDialogVisible.value = true
    // desingnerSetConfig(designerTemplateColumns.value || [])
    setTimeout(() => {
      designerDialogRef.value?.getTemplateDetail(row)
    }, 100)
  } catch (error) {
    console.error('获取模板列信息失败:', error)
    ElMessage.error('获取模板列信息失败')
  }
}
const desingnerSetConfig = (fieldList) => {
  const fontStyleList = [{
    fontStyle: 'normal',
    fontStyleName: '正常',
  }, {
    fontStyle: 'italic',
    fontStyleName: '斜体',
  }, {
    fontStyle: '强斜体',
    fontStyleName: 'oblique',
  }]
  hiprint.setConfig({
    optionItems: [
      fontStyleAdv({isInput: false, fontStyleList}), // 使用选择框，并传递字体字形列表
      fieldAdv({ isInput: false, fieldList }), // 使用选择框，并传递字段列表
      fontSize
    ],
    // 文本元素
    text: {
      tabs: [
        {
          name: '基础'
        },
        // 当修改第二个 tabs 时,必须把他之前的 tabs 都列举出来.
        {
          name: '样式', options: [
            {
              name:'fontStyle',
              before: 'letterSpacing', // 自定义参数，插入在 letterSpacing字间距 之前
              hidden: false
            },
          ]
        },
      ],
    }
  })
}
// 删除模板
const handleDelete = async (row: any) => {
  // 只能删除草稿状态的数据
  if (row.status !== 0) {
    ElMessage.warning('只能删除草稿状态的数据')
    return
  }

  try {
    await ElMessageBox.confirm('确定要删除该模板吗？', '提示', {
      type: 'warning'
    })

    // 调用删除API
    await deleteTemplate(row.id)
    ElMessage.success('删除成功')
    tableListRef.value.getList()
  } catch (error) {
    console.error('删除模板失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}
// 批量删除
const handleBatchDelete = async () => {
  const selectedRows = tableListRef.value.selectedRows
  if (selectedRows.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  // 检查是否有非草稿状态的数据
  const nonDraftRows = selectedRows.filter((row) => row.status !== 0)
  if (nonDraftRows.length > 0) {
    ElMessage.warning('只能删除草稿状态的数据，请重新选择')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.length} 条数据吗？`, '提示', {
      type: 'warning'
    })

    // 调用批量删除API
    const ids = selectedRows.map((row) => row.id)
    await deleteTemplateList(ids)
    ElMessage.success('批量删除成功')
    tableListRef.value.getList()
  } catch (error) {
    console.error('批量删除模板失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
    }
  }
}

// 复制按钮处理函数
const handleBatchCopy = async (selectedRow) => {
  const content = `生成当前所选数据"${selectedRow.templateName}(复制)"的草稿数据`
  try {
    await ElMessageBox.confirm(content, '复制', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    await copyTemplate(selectedRow.id)
    ElMessage.success('复制成功')
    tableListRef.value?.getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('复制失败:', error)
      ElMessage.error('复制失败')
    }
  }
}

// 表格配置
const tableConfig: any = reactive({
  // 查询参数
  queryParams: {
    templateName: '',
    status: undefined,
    designStatus: undefined
  },

  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'templateName',
        label: '模版名称',
        type: 'input',
        placeholder: '请输入模版名称',
        width: '200px'
      },
      {
        field: 'status',
        label: '模版状态',
        type: 'select',
        placeholder: '请选择模版状态',
        width: '200px',
        options: [
          { label: '草稿', value: 0 },
          { label: '生效', value: 1 },
          { label: '失效', value: 2 }
        ]
      },
      {
        field: 'designStatus',
        label: '设计状态',
        type: 'select',
        placeholder: '请选择设计状态',
        width: '200px',
        options: [
          { label: '未设计', value: 0 },
          { label: '设计中', value: 1 },
          { label: '设计完成', value: 2 }
        ]
      }
    ]
  },

  // 操作按钮配置
  actions: [
    {
      label: '新增模板',
      type: 'primary',
      icon: 'ep:plus',
      handler: handleAdd,
      permission: 'print:tag-template-config:create'
    },
    {
      label: '批量删除',
      type: 'danger',
      icon: 'ep:delete',
      handler: handleBatchDelete,
      permission: 'print:tag-template-config:delete'
    }
    // {
    //   label: '复制',
    //   type: 'default',
    //   icon: 'ep:copy-document',
    //   handler: handleBatchCopy
    // }
  ],

  // 表格配置
  table: {
    selection: true,
    index: true,
    columns: [
      {
        prop: 'templateCode',
        label: '模版编码',
        width: 180,
        showOverflowTooltip: true
      },
      {
        prop: 'templateName',
        label: '模版名称',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'status',
        label: '模版状态',
        width: 100,
        align: 'center',
        render: (_: any, { row }: { row: any }) => {
          const statusConfig: Record<
            number,
            {
              type: 'primary' | 'success' | 'warning' | 'danger' | 'info'
              text: string
              effect: 'light' | 'dark' | 'plain'
            }
          > = {
            0: { type: 'info', text: '草稿', effect: 'light' },
            1: { type: 'success', text: '生效', effect: 'light' },
            2: { type: 'warning', text: '失效', effect: 'light' }
          }
          const config = statusConfig[row.status] || {
            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<
            number,
            {
              type: 'primary' | 'success' | 'warning' | 'danger' | 'info'
              text: string
              effect: 'light' | 'dark' | 'plain'
            }
          > = {
            0: { type: 'info', text: '未设计', effect: 'light' },
            1: { type: 'warning', text: '设计中', effect: 'light' },
            2: { 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
          )
        }
      },
      {
        prop: 'dataSourceName',
        label: '数据源',
        minWidth: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'creatorName',
        label: '创建人',
        minWidth: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'createTime',
        label: '创建时间',
        minWidth: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.createTime)
      },
      {
        prop: 'updaterName',
        label: '修改人',
        minWidth: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'updateTime',
        label: '修改时间',
        minWidth: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.updateTime)
      }
    ],
    showActionsMoreNum: 5,
    actionsWidth: 240,
    actions: [
      {
        label: '设计',
        type: 'primary',
        link: true,
        handler: (row: any) => handleDesign(row),
        show: () => checkPermi(['print:tag-template-config:design'])
      },
      {
        label: '编辑',
        type: 'primary',
        link: true,
        // show: (row: any) => row.status == 0, // 只有草稿状态可以编辑
        handler: handleEdit,
        show: () => checkPermi(['print:tag-template-config:update'])
      },
      {
        label: '复制',
        type: 'primary',
        link: true,
        handler: (row: any) => handleBatchCopy(row),
        show: () => checkPermi(['print:tag-template-config:cooy'])
      },
      // {
      //   label: '删除',
      //   type: 'danger',
      //   link: true,
      //   show: (row: any) => row.status == 0, // 只有草稿状态可以删除
      //   handler: handleDelete
      // },
      {
        label: '生效',
        type: 'primary',
        link: true,
        show: (row: any) =>
          checkPermi(['print:tag-template-config:open']) &&
          row.designStatus == 2 &&
          row.status !== 1, // 只有设计完成状态可以生效
        handler: (row: any) => handleStatusChange(row, 1)
      },
      {
        label: '失效',
        type: 'danger',
        link: true,
        show: (row: any) => checkPermi(['print:tag-template-config:close']) && row.status == 1, // 只有生效状态可以失效
        handler: (row: any) => handleStatusChange(row, 2)
      },
      {
        label: '预览',
        type: 'primary',
        link: true,
        show: (row: any) => row.designStatus != 0,
        handler: handlePreview
      },
    ]
  },

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

  // 设置
  settings: {
    refresh: true,
    download: false,
    // download: async () => {
    //   try {
    //     const queryParams = tableConfig.queryParams
    //     const data = await exportTemplate(queryParams)
    //     download.excel(data, '标签模板.xls')
    //     ElMessage.success('导出成功')
    //   } catch (error) {
    //     console.error('导出模板失败:', error)
    //     ElMessage.error('导出失败')
    //   }
    // },
    print: true,
    size: true,
    columns: true,
    fullscreen: true
  },

  // API配置
  api: {
    getList: async (params: any) => {
      try {
        const response = await getTemplatePage(params)
        return response
      } catch (error) {
        console.error('获取模板列表失败:', error)
        ElMessage.error('获取数据失败')
        throw error
      }
    }
  }
})

// 表单提交成功处理
const handleFormSuccess = async (type: 'save' | 'saveAndDesign', data: any) => {
  try {
    let response = null
    delete data.contentText // 新增模板、编辑模板不要传设计数据
    if (type === 'saveAndDesign') {
      // 保存并设计操作，会自动跳转到设计器，不需要关闭弹窗
      formDialogVisible.value = false
      // tableListRef.value.getList()
      handleDesign(data)
    } else {
      if (data.id) {
        // 编辑
        const updateData = {
          id: data.id,
          templateName: data.templateName
        }
        response = await updateTemplate(updateData)
        ElMessage.success('更新成功')
      } else {
        // 新增
        response = await createTemplate(data)
        ElMessage.success('新增成功')
      }
      formDialogVisible.value = false
      tableListRef.value.getList()
    }
  } catch (error) {
    console.error('保存模板失败:', error)
    ElMessage.error('保存失败')
  }
}

// 状态切换
const handleStatusChange = async (row: any, newStatus: 1 | 2) => {
  try {
    const statusText = newStatus === 1 ? '生效' : '失效'
    await ElMessageBox.confirm(`确定要将该模板状态更改为${statusText}吗？`, '提示', {
      type: 'warning'
    })

    // 调用状态更新API
    await updateTemplateStatus(row.id, newStatus)
    ElMessage.success(`${statusText}成功`)
    tableListRef.value.getList()
  } catch (error) {
    console.error('更新模板状态失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('状态更新失败')
    }
  }
}
const tableListRefresh = () => {
  tableListRef.value.getList()
}
onMounted(() => {
  // 初始化时调用 getList()
  tableListRefresh()
})
</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;
}
</style>
