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

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

    <!-- 打印弹窗组件 -->
    <PrintDialog
      ref="printDialogRef"
      v-model:visible="printDialogVisible"
      :purchase-order="selectedPurchaseOrder"
      @print="handlePrintEvent"
    />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, h } from 'vue'
import { ElMessage, ElMessageBox, ElTag } from 'element-plus'
import TableList from '@/components/TableList/index.vue'
import ApiForm from './form.vue'
import PrintDialog from './PrintDialog.vue'
import download from '@/utils/download'
import {
  getPurchaseOrderHeaderPage,
  getPurchaseOrderHeader,
  updatePurchaseOrderHeader,
  createPurchaseOrderHeader,
  deletePurchaseOrderHeader,
  deletePurchaseOrderHeaderList
} from '@/api/print/purchaseOrder'
import { dateFormatter } from '@/utils/formatTime'
import { checkPermi } from '@/utils/permission'
// 表格引用
const tableListRef = ref()

// 弹窗相关
const formDialogVisible = ref(false)
const formMode = ref<'add' | 'edit' | 'detail'>('add')
const formData = ref<any>(null)

// 打印弹窗相关
const printDialogVisible = ref(false)
const printDialogRef = ref()
const selectedPurchaseOrder = ref<any>(null)
// 新增采购订单
const handleAdd = () => {
  formMode.value = 'add'
  formData.value = null
  formDialogVisible.value = true
}

// 编辑采购订单
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
}

// 删除采购订单
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该采购订单吗？', '提示', {
      type: 'warning'
    })

    // 调用删除API
    await deletePurchaseOrder(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
  }

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

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

// 打印采购订单
const handlePrint = async (row: any) => {
  try {
    // 调用getPurchaseOrderHeader接口获取数据
    const purchaseOrderData = await getPurchaseOrderHeader(row.id)
    // 设置当前选中的采购订单
    selectedPurchaseOrder.value = purchaseOrderData
    // 打开打印弹窗
    printDialogVisible.value = true
    setTimeout(() => {
      printDialogRef.value.getList()
    }, 200)
  } catch (error) {
    console.error('打印采购订单失败:', error)
    // ElMessage.error('打印失败')
  }
}

// 处理打印事件
const handlePrintEvent = (data: any) => {
  console.log('打印事件触发:', data)
  // 这里可以添加实际的打印逻辑
}
const yesOrNoMap = {
  0: '否',
  1: '是'
}
// 表格配置
const tableConfig: any = reactive({
  // 查询参数
  queryParams: {},

  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'purchaseOrder',
        label: '采购订单号',
        type: 'input',
        placeholder: '请输入采购订单号',
        span: 8
      },
      {
        field: 'salesOrder',
        label: '销售订单号',
        type: 'input',
        placeholder: '请输入销售订单号',
        span: 8
      },
      {
        field: 'styleNo',
        label: '内部款号',
        type: 'input',
        placeholder: '请输入内部款号',
        span: 8
      },
      {
        field: 'interPurchaseOrderNumber',
        label: '公司间订单号',
        type: 'input',
        placeholder: '请输入公司间订单号',
        span: 8
      },
      {
        field: 'createTimeRange',
        label: '订单创建时间',
        type: 'date-range',
        placeholder: ['开始时间', '结束时间'],
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        field1: 'startCreateDate',
        field2: 'endCreateDate',
        span: 8
      },
      {
        field: 'updateTimeRange',
        label: '订单更新时间',
        type: 'date-range',
        placeholder: ['开始时间', '结束时间'],
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        field1: 'startUpdateDate',
        field2: 'endUpdateDate',
        span: 8
      }
    ]
  },

  // 操作按钮配置
  actions: [
    // {
    //   label: '新增采购订单',
    //   type: 'primary',
    //   icon: 'ep:plus',
    //   handler: handleAdd
    // },
    // {
    //   label: '批量删除',
    //   type: 'danger',
    //   icon: 'ep:delete',
    //   handler: handleBatchDelete
    // }
  ],

  // 表格配置
  table: {
    selection: false,
    index: true,
    columns: [
      {
        prop: 'purchaseOrder',
        label: '单据编码',
        width: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'purchaseOrderType',
        label: '采购订单类型',
        width: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'documentType',
        label: '单据类型',
        width: 100,
        render: (_: any, { row }: { row: any }) => {
          return '采购订单'
        }
      },
      {
        prop: 'interPurchaseOrderNumber',
        label: '公司间订单号',
        width: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'salesOrder',
        label: '销售订单号',
        width: 150,
        showOverflowTooltip: true
      },
      {
        prop: 'printed',
        label: '已打印',
        width: 80,
        align: 'center',
        render: (_: any, { row }: { row: any }) => {
          const type = yesOrNoMap[row.printed] === '是' ? 'success' : 'info'
          return h(
            ElTag,
            { type, effect: 'light', size: 'small', 'disable-transitions': true },
            () => yesOrNoMap[row.printed]
          )
        }
      },
      {
        prop: 'printedByName',
        label: '打印人',
        width: 100,
        showOverflowTooltip: true
      },
      {
        prop: 'printedTime',
        label: '打印时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.printedTime)
      },
      {
        prop: 'updatedTime',
        label: '订单更新时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.updatedTime)
      },
      {
        prop: 'processed',
        label: '已处理',
        width: 80,
        align: 'center',
        render: (_: any, { row }: { row: any }) => {
          const type = yesOrNoMap[row.processed] === '是' ? 'success' : 'info'
          return h(
            ElTag,
            { type, effect: 'light', size: 'small', 'disable-transitions': true },
            () => yesOrNoMap[row.processed]
          )
        }
      },
      {
        prop: 'processedByName',
        label: '处理人',
        width: 100,
        showOverflowTooltip: true
      },
      {
        prop: 'processedTime',
        label: '处理时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.processedTime)
      },
      {
        prop: 'companyCode',
        label: '公司代码',
        width: 100,
        showOverflowTooltip: true
      },
      {
        prop: 'purchasingOrganization',
        label: '采购组织',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'purchasingGroup',
        label: '采购组',
        width: 100,
        showOverflowTooltip: true
      },
      {
        prop: 'supplier',
        label: '供应商',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'supplierName',
        label: '供应商描述',
        minWidth: 150,
        showOverflowTooltip: true
      },
      // {
      //   prop: 'creatorName',
      //   label: '创建人',
      //   width: 100,
      //   showOverflowTooltip: true
      // },
      {
        prop: 'creationDate',
        label: '创建时间',
        width: 180,
        showOverflowTooltip: true
        // formatter: (row: any) => dateFormatter(row, {}, row.creationDate)
      }
    ],
    actionsWidth: 100,
    actions: [
      // {
      //   label: '详情',
      //   type: 'primary',
      //   link: true,
      //   handler: handleDetail
      // },
      // {
      //   label: '编辑',
      //   type: 'primary',
      //   link: true,
      //   handler: handleEdit
      // },
      {
        label: '打印',
        type: 'primary',
        link: true,
        handler: handlePrint,
        show: () => checkPermi(['print:stm:print'])
      }
      // {
      //   label: '删除',
      //   type: 'danger',
      //   link: true,
      //   handler: handleDelete
      // }
    ]
  },

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

  // 设置
  settings: {
    refresh: true,
    download: false,
    // download: async () => {
    //   try {
    //     const queryParams = tableConfig.queryParams
    //     const data = await exportPurchaseOrder(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 getPurchaseOrderHeaderPage(params)
        return response
      } catch (error) {
        console.error('获取模板列表失败:', error)
        ElMessage.error('获取数据失败')
        throw error
      }
    }
  }
})

// 表单提交成功处理
const handleFormSuccess = async (data: any) => {
  try {
    let response = null
    if (data.id) {
      // 编辑
      response = await updatePurchaseOrder(data)
      ElMessage.success('更新成功')
    } else {
      // 新增
      response = await createPurchaseOrder(data)
      ElMessage.success('新增成功')
    }

    formDialogVisible.value = false
    tableListRef.value.getList()
  } catch (error) {
    console.error('保存采购订单失败:', error)
    ElMessage.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;
}
</style>
