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

  <!-- 表单弹窗：添加/修改 -->
  <DictDataForm ref="formRef" @success="handleFormSuccess" />
</template>
<script lang="ts" setup>
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as DictDataApi from '@/api/system/dict/dict.data'
import * as DictTypeApi from '@/api/system/dict/dict.type'
import DictDataForm from './DictDataForm.vue'
import TableList from '@/components/TableList/index.vue'
import type { TableListConfig } from '@/components/TableList/types'
import { checkPermi } from '@/utils/permission'

defineOptions({ name: 'SystemDictData' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const route = useRoute() // 路由

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  label: '',
  status: undefined,
  dictType: route.params.dictType
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const dictTypeList = ref<DictTypeApi.DictTypeVO[]>() // 字典类型的列表
const checkedIds = ref<number[]>([]) // 选中的字典数据ID数组
const tableListRef = ref<InstanceType<typeof TableList>>() // TableList组件引用

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

// 搜索表单配置 - 使用ref动态更新
const dictDataSearchFormConfig = ref({
  items: [
    {
      field: 'dictType',
      label: '字典名称',
      type: 'select' as const,
      placeholder: '请选择字典名称',
      options: []
    },
    {
      field: 'status',
      label: '状态',
      type: 'select' as const,
      placeholder: '数据状态',
      options: getIntDictOptions(DICT_TYPE.COMMON_STATUS).map((dict: any) => ({
        label: dict.label,
        value: dict.value
      }))
    }
  ]
})

// 表格列配置
const dictDataTableColumns = [
  {
    prop: 'id',
    label: '字典编码',
    width: 120,
    align: 'center' as const
  },
  {
    prop: 'label',
    label: '字典标签',
    width: 180,
    align: 'center' as const
  },
  {
    prop: 'value',
    label: '字典键值',
    width: 180,
    align: 'center' as const
  },
  {
    prop: 'sort',
    label: '字典排序',
    width: 120,
    align: 'center' as const
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    align: 'center' as const,
    dictType: DICT_TYPE.COMMON_STATUS
  },
  {
    prop: 'colorType',
    label: '颜色类型',
    width: 120,
    align: 'center' as const
  },
  {
    prop: 'cssClass',
    label: 'CSS Class',
    width: 180,
    align: 'center' as const
  },
  {
    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 dictDataTableActions = [
  {
    label: '新增',
    type: 'primary' as const,
    icon: 'ep:plus',
    permission: 'system:dict:create',
    handler: () => openForm('create')
  },
  {
    label: '批量删除',
    type: 'danger' as const,
    icon: 'ep:delete',
    disabled: computed(() => checkedIds.value.length === 0),
    permission: 'system:dict:delete',
    handler: () => handleDeleteBatch()
  }
]

// TableList 配置
const tableListConfig: TableListConfig = {
  searchForm: dictDataSearchFormConfig.value,
  actions: dictDataTableActions,
  settings: {
    refresh: true, // 显示刷新按钮
    download: false,
    print: true, // 不显示打印按钮
    size: true, // 显示大小设置按钮
    columns: true, // 显示列设置按钮
    fullscreen: true // 暂时不显示全屏按钮
  },
  table: {
    loading: false,
    data: list.value,
    selection: true,
    actionsWidth: 150, //操作列的宽度
    columns: [...dictDataTableColumns],
    actions: [
      {
        label: '修改',
        type: 'primary',
        link: true,
        show: (row) => checkPermi(['system:dict:update']),
        handler: (row) => openForm('update', row.id)
      },
      {
        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 DictDataApi.getDictDataPage(params)
      return response
    }
  },
  queryParams: queryParams,
  onSearch: () => {
    handleQuery()
  },
  onReset: () => {
    resetQuery()
  },
  onSelectionChange: handleSelectionChange
}

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

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

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

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

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

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

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

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DictDataApi.exportDictData(queryParams)
    download.excel(data, '字典数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 初始化 **/
onMounted(async () => {
  // await getList()
  // 初始化时调用 getList()
  tableListRef.value?.getList()
  // 查询字典（精简)列表
  dictTypeList.value = await DictTypeApi.getSimpleDictTypeList()
  
  // 更新搜索表单的字典名称选项
  dictDataSearchFormConfig.value.items[0].options = dictTypeList.value.map((item: any) => ({
    label: item.name,
    value: item.type
  }))
})
</script>
