<script setup lang="ts">
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { DictType } from '#/api/system/dict/dict-data-model';
import type { DictOption } from '#/store/dict';

import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteDictType,
  dictTypeList,
  exportDictType,
  refreshDictType,
} from '#/api/system/dict/dict-data';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';
import { queryFormSchema, tableColumns } from '#/views/system/dict/config-data';

import DictTypeDrawerComp from './dict-type-drawer.vue';

// 定义侧拉
const [DictTypeDrawer, dictTypeDrawerApi] = useVbenDrawer({
  connectedComponent: DictTypeDrawerComp,
});

// 填充表格头部搜索表单配置
const formOptions: VbenFormProps = {
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-4',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};
// 填充表格配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  // 配置表格右上角全屏、刷新
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await dictTypeList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
};
// 定义表格
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
// 新增字典类型
function addDictTypeF() {
  dictTypeDrawerApi.setData({ isUpdate: false }).open();
}
// 编辑字典类型
function handleEdit(dictType: DictType) {
  dictTypeDrawerApi.setData({ ...dictType, isUpdate: true }).open();
}
// 单个删除
async function confirmEvent(dictType: DictType) {
  const ids: number[] = [];
  ids.push(dictType.dictId);
  await deleteDictType(ids);
  await basicTableApi.reload();
}
// 批量删除
async function allDeleteHandle() {
  const checkData = basicTableApi.grid.getCheckboxRecords();
  const dictTypeIds = checkData.map((item: DictType) => item.dictId);
  ElMessageBox.confirm(`确认删除选中的${dictTypeIds.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteDictType(dictTypeIds);
    await basicTableApi.reload();
  });
}
// 导出字典类型
async function exportHandle() {
  await commonDownloadExcel(
    exportDictType,
    '字典类型数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
// 刷新缓存
async function refreshHandle() {
  await refreshDictType();
  await basicTableApi.reload();
}
// 跳转字典数据页面
const router = useRouter();
function jumpDictData(dictType: DictType) {
  router.push(`/system/dict-data/${dictType.dictId}`);
}
// 获取状态字典值
const dictStatusRef = ref<DictOption[]>([]);
onMounted(() => {
  dictStatusRef.value = getDictOptions(DictEnum.SYS_NORMAL_DISABLE);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="字典类型列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            @click="exportHandle"
            v-access:code="['system:dict:export']"
          >
            导出
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="allDeleteHandle"
            v-access:code="['system:dict:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="warning"
            @click="refreshHandle"
            v-access:code="['system:dict:remove']"
          >
            刷新缓存
          </ElButton>
          <ElButton
            type="primary"
            @click="addDictTypeF"
            v-access:code="['system:dict:add']"
          >
            新增
          </ElButton>
        </ElSpace>
      </template>
      <template #dictType="{ row }">
        <ElButton type="primary" link @click="jumpDictData(row)">
          {{ row.dictType }}
        </ElButton>
      </template>
      <template #status="{ row }">
        <div>
          <DictTag :value="row.status" :dicts="dictStatusRef" />
        </div>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:dict:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm
            :title="$t('common.confirm-delete')"
            @confirm="confirmEvent(row)"
          >
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:dict:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <DictTypeDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>
