<template>
  <!-- 使用 TableList 组件 -->
  <TableList
    ref="tableListRef"
    :config="tableListConfig"
    @update:data="list = $event"
    @update:loading="loading = $event"
  />

  <!-- 表单弹窗：添加/修改 -->
  <DictTypeForm ref="formRef" @success="handleFormSuccess" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import * as DictTypeApi from '@/api/system/dict/dict.type'
import DictTypeForm from './DictTypeForm.vue'
import download from '@/utils/download'
import TableList from '@/components/TableList/index.vue'
import type { TableListConfig } from '@/components/TableList/types'
import { checkPermi } from '@/utils/permission'
import { useRouter } from 'vue-router'
defineOptions({ name: 'SystemDictType' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const router = useRouter()
const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 字典表格数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: '',
  type: '',
  status: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const checkedIds = ref<number[]>([]) // 选中的字典ID数组
const tableListRef = ref<InstanceType<typeof TableList>>() // TableList组件引用

// 处理表格选择变化
const handleSelectionChange = (rows: any[]) => {
  checkedIds.value = rows.map((row) => row.id)
}

// 搜索表单配置
const dictSearchFormConfig = {
  items: [
    {
      field: 'name',
      label: '字典名称',
      type: 'input' as const,
      placeholder: '请输入字典名称'
    },
    {
      field: 'type',
      label: '字典类型',
      type: 'input' as const,
      placeholder: '请输入字典类型'
    },
    {
      field: 'status',
      label: '状态',
      type: 'select' as const,
      placeholder: '请选择状态',
      options: getIntDictOptions(DICT_TYPE.COMMON_STATUS).map((dict: any) => ({
        label: dict.label,
        value: dict.value
      }))
    },
    {
      field: 'createTime',
      label: '创建时间',
      type: 'date-range' as const,
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
      defaultTime: [new Date('1 00:00:00'), new Date('1 23:59:59')]
    }
  ]
}

// 表格列配置
const dictTableColumns = [
  {
    prop: 'id',
    label: '字典编号',
    width: 120,
    align: 'center' as const
  },
  {
    prop: 'name',
    label: '字典名称',
    width: 180,
    align: 'center' as const
  },
  {
    prop: 'type',
    label: '字典类型',
    width: 200,
    align: 'center' as const
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    align: 'center' as const,
    dictType: DICT_TYPE.COMMON_STATUS
  },
  {
    prop: 'remark',
    label: '备注',
    minWidth: 220,
    align: 'center' as const
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: 180,
    align: 'center' as const,
    formatter: (row: any) => dateFormatter(row, {}, row.createTime)
  }
]

// 表格操作按钮配置
const dictTableActions = [
  {
    label: '新增',
    type: 'primary' as const,
    icon: 'ep:plus',
    permission: 'system:dict:create',
    handler: () => openForm('create')
  },
  {
    label: '导出',
    type: 'primary' as const,
    icon: 'ep:download',
    loading: exportLoading,
    permission: 'system:dict:export',
    handler: () => handleExport()
  },
  {
    label: '批量删除',
    type: 'danger' as const,
    icon: 'ep:delete',
    disabled: computed(() => checkedIds.value.length === 0),
    permission: 'system:dict:delete',
    handler: () => handleDeleteBatch()
  }
]

/** 查询字典类型列表 - 由 TableList 组件处理 */

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

/** 重置按钮操作 */
const resetQuery = () => {
  queryParams.pageNo = 1
  queryParams.name = ''
  queryParams.type = ''
  queryParams.status = undefined
  queryParams.createTime = []
  tableListRef.value?.getList()
}


/** 添加/修改操作 */
const formRef = ref<InstanceType<typeof DictTypeForm>>()
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 表单操作成功后的回调 */
const handleFormSuccess = () => {
  tableListRef.value?.getList()
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DictTypeApi.deleteDictType(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}
const handleRowCheckboxChange = (rows: DictTypeApi.DictTypeVO[]) => {
  checkedIds.value = rows.map((row) => row.id)
}

const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起批量删除
    await DictTypeApi.deleteDictTypeList(checkedIds.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DictTypeApi.exportDictType(queryParams)
    download.excel(data, '字典类型.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
// TableList 配置
const tableListConfig: TableListConfig = {
  searchForm: dictSearchFormConfig,
  actions: dictTableActions,
  settings: {
    refresh: true, // 显示刷新按钮
    download: false,
    // download: handleExport, // 传递导出方法
    print: true, // 不显示打印按钮
    size: true, // 显示大小设置按钮
    columns: true, // 显示列设置按钮
    fullscreen: true // 暂时不显示全屏按钮
  },
  table: {
    loading: false,
    data: list.value,
    selection: true,
    actionsWidth: 200, //操作列的宽度
    columns: [...dictTableColumns],
    actions: [
      {
        label: '修改',
        type: 'primary',
        link: true,
        show: (row) => checkPermi(['system:dict:update']),
        handler: (row) => openForm('update', row.id)
      },
      {
        label: '数据',
        type: 'primary',
        link: true,
        show: (row) => checkPermi(['system:dict:query']),
        handler: (row) => {
          // 跳转到字典数据页面
          router.push(`/dict/type/data/${row.type}`)
         // window.location.href = `/dict/type/data/${row.type}`
        }
      },
      {
        label: '删除',
        type: 'danger',
        link: true,
        show: (row) => checkPermi(['system:dict:delete']),
        handler: (row) => handleDelete(row.id)
      }
    ]
  },
  pagination: {
    show: true,
    pageSize: 10
  },
  api: {
    getList: async (params) => {
      const response = await DictTypeApi.getDictTypePage(params)
      return response
    }
  },
  queryParams: queryParams,
  onSearch: () => {
    handleQuery()
  },
  onReset: () => {
    resetQuery()
  },
  onSelectionChange: handleSelectionChange
}
onMounted(() => {
  // 初始化时调用 getList()
  tableListRef.value.getList()
})
</script>
