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

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

    <!-- 物料导入弹窗 -->
    <MaterialImportForm ref="importFormRef" @success="handleImportSuccess" />

    <!-- 物料编辑弹窗 -->
    <MaterialEditForm ref="editFormRef" @success="handleEditSuccess" />

    <!-- 同步SAP弹窗 -->
    <el-dialog
      v-model="syncDialogVisible"
      title="同步SAP"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="syncFormData" label-width="100px">
        <el-form-item label="同步日期" required>
          <el-date-picker
            v-model="syncFormData.syncDate"
            type="date"
            placeholder="请选择同步日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDate"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="syncDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="syncLoading"
            @click="confirmSyncSAP"
          >
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </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 TemplateSelectDialog from './TemplateSelectDialog.vue'
import MaterialImportForm from './MaterialImportForm.vue'
import MaterialEditForm from './MaterialEditForm.vue'
import {
  getPurchaseOrderHeaderPage,
  getPurchaseOrderHeader,
  updatePurchaseOrderHeader,
  createPurchaseOrderHeader,
  deletePurchaseOrderHeader,
  deletePurchaseOrderHeaderList
} from '@/api/print/purchaseOrder'
// 假设采购订单的API接口
import {
  purchaseOrderPage,
  purchaseOrderSapCreate,
  purchaseOrderExportExcel
} from '@/api/print/purchaseOrder'
import { dateFormatter, dateFormatter2 } from '@/utils/formatTime'
import { checkPermi } from '@/utils/permission'
import { DICT_TYPE, getDictOptions, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import download from '@/utils/download'
import { List } from 'echarts'
import { id } from 'element-plus/es/locale'
// 路由
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 disabledDate = (time) => {
  // 获取今天的日期，设置时间为23:59:59
  const today = new Date()
  today.setHours(23, 59, 59, 999)

  // 返回true表示禁用该日期，即禁用今天之后的日期
  return time.getTime() > today.getTime()
}

// 打开同步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
  }

  // 验证日期不能大于今天
  const selectedDate = new Date(syncFormData.value.syncDate)
  const today = new Date()
  // 设置今天的时间为23:59:59，确保当天的日期也能通过验证
  today.setHours(23, 59, 59, 999)

  if (selectedDate > today) {
    ElMessage.warning('同步日期不能大于今天')
    return
  }

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

    // 显示全局 loading 遮罩
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '同步中...',
      background: 'rgba(0, 0, 0, 0.7)',
      zIndex: 2000
    })

    syncLoading.value = true

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

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

    try {
      await createPurchaseOrderHeader(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
      loadingInstance.close()
    }
  } catch (error) {
    console.error('同步SAP失败:', error)
    if (error !== 'cancel') {
      ElMessage.error('同步失败')
    }
  }
}

// 打印
const handlePrint = (row: any) => {
  // if (row) {
  //   editFormRef.value.open('print', row.id)
  // }
  router.push({
    name: 'purchaseOrderPrint',
    query: {
      id: row.id,
      customTagTitle: `采购订单打印-${row.purchaseOrder}`,
    }
  })
}

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

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

// 预览打印处理
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 = () => {
  ElMessage.success('导入成功')
  tableListRef.value.getList()
}

// 编辑处理
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

  // 调用导出API（使用查询条件而不是传入的数据）
  materialBaseInfoExportExcel(queryParams)
    .then((blob) => {
      // 直接使用返回的blob对象
      handleFileDownload(blob, '采购订单信息.xlsx')
    })
    .catch((error) => {
      console.error('导出失败:', error)
      ElMessage.error('导出失败')
    })
}
const yesOrNoMap = {
  0: '否',
  1: '是'
}
// 表格配置
const tableConfig: any = reactive({
  // 查询参数
  queryParams: {},

  // 搜索表单配置
  searchForm: {
    maxItemsPerRow: 3,
    items: [
      {
        field: 'purchaseOrder',
        label: '采购订单号',
        type: 'input',
        placeholder: '请输入采购订单号'
      },
      {
        field: 'salesOrder',
        label: '销售订单号',
        type: 'input',
        placeholder: '请输入销售订单号',
        labelWidth: '100px'
      },
      {
        field: 'printed',
        label: ' 是否已打印',
        type: 'select',
        placeholder: '请选择是否已打印',
        labelWidth: '100px',
        options: [
          { label: '是', value: '1' },
          { label: '否', value: '0' }
        ]
      },
      {
        field: 'processed',
        label: '更新是否处理',
        type: 'select',
        placeholder: '请选择更新是否处理',
        labelWidth: '100px',
        options: [
          { label: '是', value: '1' },
          { label: '否', value: '0' }
        ]
      },
      {
        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
      },
      {
        field: 'styleNo',
        label: '内部款号',
        type: 'input',
        placeholder: '请输入内部款号'
      },
      {
        field: 'materialNo',
        label: '内部物料号',
        type: 'input',
        placeholder: '请输入内部物料号'
      },
      {
        field: 'interPurchaseOrderNumber',
        label: '公司间订单号',
        type: 'input',
        placeholder: '请输入公司间订单号'
      }
    ]
  },

  // 操作按钮配置
  actions: [
    {
      label: '同步SAP',
      type: 'default',
      icon: 'ep:refresh',
      handler: handleSyncSAP,
      permission: 'print:purchase-order:syncSap'
    },
    {
      label: '导入',
      type: 'default',
      plain: true,
      icon: 'ep:upload',
      handler: handleImport,
      permission: 'print:purchase-order:import'
    }
  ],

  // 表格配置
  table: {
    actionsWidth: 120,
    selection: true,
    index: true,
    columns: [
      {
        prop: 'purchaseOrder',
        label: '单据编码',
        width: 140,
        showOverflowTooltip: true
      },
      {
        prop: 'totalQuantity',
        label: '订单总数量',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'purchaseOrderType',
        label: '采购订单类型',
        width: 140,
        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: 'salesName',
        label: '销售员',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'supplierName',
        label: '供应商描述',
        minWidth: 200,
        showOverflowTooltip: true
      },
      {
        prop: 'printRemark',
        label: '打印备注',
        minWidth: 200,
        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: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'printedTime',
        label: '打印时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.printedTime)
      },
      {
        prop: 'updateTime',
        label: '订单更新时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.updateTime)
      },
      {
        prop: 'updatedContent',
        label: '更新内容',
        minWidth: 200,
        showOverflowTooltip: true
      },
      {
        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: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'processedTime',
        label: '处理时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.processedTime)
      },
      {
        prop: 'companyCode',
        label: '公司代码',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'purchasingOrganization',
        label: '采购组织',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'purchasingGroup',
        label: '采购组',
        width: 100,
        showOverflowTooltip: true
      },
      {
        prop: 'supplier',
        label: '供应商',
        width: 140,
        showOverflowTooltip: true
      },
      // {
      //   prop: 'creatorName',
      //   label: '创建人',
      //   width: 120,
      //   showOverflowTooltip: true
      // },
      {
        prop: 'creatorName',
        label: '创建人',
        width: 120,
        showOverflowTooltip: true
      },
      {
        prop: 'createTime',
        label: '创建时间',
        width: 180,
        showOverflowTooltip: true,
        formatter: (row: any) => dateFormatter(row, {}, row.createTime)
      },
    ],
    actions: [
      {
        label: '打印',
        type: 'primary',
        link: true,
        handler: handlePrint,
        show: () => checkPermi(['print:purchase-order:print'])
      },
      {
        label: '查看',
        type: 'primary',
        link: true,
        handler: handleDetail,
        show: () => checkPermi(['print:purchase-order:detail'])
      }
    ]
  },
  // 分页配置
  pagination: {
    pageSize: 10,
    show: true
  },

  // 设置
  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 getPurchaseOrderHeaderPage(params)
        return response
      } 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;
}
</style>
