<template>
  <doc-alert title="调用方日志" url="https://doc.iocoder.cn/system-log/" />

  <!-- 使用 TableList 组件 -->
  <TableList
    ref="tableListRef"
    :config="tableListConfig"
    @update:data="list = $event"
    @update:loading="loading = $event"
  >
    <!-- 额外展示内容插槽 -->
    <template #actions-right v-if="capacityTotal">
      <el-divider direction="vertical" />
      <span style="font-size: 13px;font-weight: 600;">总产能：{{ capacityTotal }}</span>
    </template>
  </TableList>
</template>
<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as PurchaseOrderApi from '@/api/print/purchaseOrder'
import TableList from '@/components/TableList/index.vue'
import type { TableListConfig } from '@/components/TableList/types'
import { checkPermi } from '@/utils/permission'
const tableListRef = ref<InstanceType<typeof TableList>>() // TableList组件引用

defineOptions({ name: 'SystemLoginLog' })

const message = useMessage() // 消息弹窗

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const capacityTotal = ref<any>(null) // 存储产能汇总数据
// 定义 props
const props = defineProps<{
  callType?: number
}>()

const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  purchaseOrder: undefined,
  styleNo: undefined,
  printed: undefined,
  printedByName: undefined,
  printedTime: [],
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

// 搜索表单配置
const loginLogSearchFormConfig = {
  items: [
    {
      field: 'purchaseOrder',
      label: '订单编码',
      type: 'input' as const,
      placeholder: '请输入订单编码'
    },
    {
      field: 'styleNo',
      label: '内部款号',
      type: 'input' as const,
      placeholder: '请输入内部款号'
    },
    {
      field: 'printed',
      label: '打印状态',
      type: 'select' as const,
      placeholder: '请选择打印状态',
      options: [
        { label: '否', value: 0 },
        { label: '是', value: 1 },
      ]
    },
    {
      field: 'printedByName',
      label: '打印人',
      type: 'input' as const,
      placeholder: '请输入打印人'
    },
    {
      field: 'printedTime',
      label: '打印日期',
      type: 'date-range' as const,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      field1: 'printedStartDate',
      field2: 'printedEndDate',
      defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')],
    },
    {
      field: 'createTime',
      label: '创建日期',
      type: 'date-range' as const,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      field1: 'createStartDate',
      field2: 'createEndDate',
      defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')],
    }
  ]
}

// 表格列配置
const loginLogTableColumns = [
  {
    prop: 'purchaseOrder',
    label: '订单编码',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'purchaseOrderType',
    label: '订单类型',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'companyCode',
    label: '公司代码',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'purchasingOrganization',
    label: '采购组织',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'purchasingGroup',
    label: '采购组',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'supplier',
    label: '供应商',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'supplierName',
    label: '供应商描述',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'creationDate',
    label: '创建时间',
    width: 180,
    align: 'center' as const,
    showOverflowTooltip: true,
    // formatter: (row: any) => dateFormatter(row, {}, row.createTime)
  },
  {
    prop: 'printed',
    label: '打印状态',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true,
    formatter: (row: any) => {
      const maps = {
        0: '否',
        1: '是'
      }
      return maps[row.printed] || '未知'
    }
  },
  {
    prop: 'printedByName',
    label: '打印人',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'printedTime',
    label: '打印时间',
    width: 180,
    align: 'center' as const,
    showOverflowTooltip: true,
    formatter: (row: any) => dateFormatter(row, {}, row.printedTime)
  },
  {
    prop: 'purchaseOrderItem',
    label: '行项目',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'material',
    label: '物料号',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'materialName',
    label: '物料描述',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'orderQuantity',
    label: '订单数量',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'customerMaterialNo',
    label: '客户物料编号',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'customerMaterialName',
    label: '客户物料名称',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'styleNo',
    label: '内部款号',
    width: 120,
    align: 'center' as const,
    showOverflowTooltip: true
  },
  {
    prop: 'barcode',
    label: '条形码',
    minWidth: 200,
    align: 'center' as const,
    showOverflowTooltip: true
  }
]

// 表格操作按钮配置
const loginLogTableActions = [
  {
    label: '导出',
    type: 'default' as const,
    icon: 'ep:download',
    loading: exportLoading,
    permission: 'capctity_export',
    handler: () => handleExport()
  }
]

/** 查询列表 - 由 TableList 组件处理 */

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  tableListRef.value?.getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryParams.purchaseOrder = undefined
  queryParams.styleNo = undefined
  queryParams.printed = undefined
  queryParams.printedByName = undefined
  queryParams.printedTime = []
  queryParams.createTime = []
  tableListRef.value?.getList()
}


/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await PurchaseOrderApi.exportCapacityTotal(tableListRef.value?.queryParams)
    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(data, `产能统计导出_${timestamp}.xlsx`)
  } catch {
  } finally {
    exportLoading.value = false
  }
}
// 处理文件流下载
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('文件下载失败')
  }
}
// TableList 配置
const tableListConfig: TableListConfig = {
  searchForm: loginLogSearchFormConfig,
  actions: loginLogTableActions,
  settings: {
    refresh: true, // 显示刷新按钮
    download: false,
    // download: handleExport, // 传递导出方法
    print: true, // 不显示打印按钮
    size: true, // 显示大小设置按钮
    columns: true, // 显示列设置按钮
    fullscreen: true // 暂时不显示全屏按钮
  },
  table: {
    loading: false,
    index: true,
    data: list.value,
    selection: false, // 不显示选择框
    actionsWidth: 0, // 显示操作列宽度
    columns: [...loginLogTableColumns],
    actions: [
    ]
  },
  pagination: {
    show: true,
    pageSize: 10
  },
  api: {
    getList: async (params) => {
      const response = await PurchaseOrderApi.capacityTotalPage(params)
      return response
    }
  },
  queryParams: queryParams,
  onSearch: async () => {
    await handleQuery()
    await fetchCapacityTotal()
  },
  onReset: async () => {
    await resetQuery()
    await fetchCapacityTotal()
  }
}

/** 获取产能汇总 */
const fetchCapacityTotal = async () => {
  try {
    const data = await PurchaseOrderApi.getCapacityTotalByOrderNo(tableListRef.value?.queryParams)
    capacityTotal.value = data || '-'
  } catch (error) {
    console.error('获取产能汇总数据失败:', error)
    capacityTotal.value = '-'
  }
}

/** 初始化 **/
onMounted(async () => {
  tableListRef.value?.getList()
  await fetchCapacityTotal()
})
</script>
