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

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

import { onMounted, ref } from 'vue';
import { useRoute } 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 {
  deleteDictData,
  dictDataExport,
  dictDataList,
  dictTypeDetail,
} from '#/api/system/dict/dict-data';
import { DictTag } from '#/components/dict';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { columns, querySchema } from './config-data';
import DictDataDrawerComp from './dict-data-drawer.vue';

const route = useRoute();
const dictId = route.params.dictId as string;
// 初始化刚进来的字典类型对象，用于重置还原为刚进来的这个字典类型
let initDictType: DictType = { dictId: -1 };
// 获取状态字典值
const dictStatusRef = ref<DictOption[]>([]);
onMounted(async () => {
  dictStatusRef.value = getDictOptions(DictEnum.SYS_NORMAL_DISABLE);
  const dictTypeData = await dictTypeDetail(dictId);
  initDictType = dictTypeData;
  await basicTableApi.formApi.setValues({ dictType: dictTypeData.dictType });
  await basicTableApi.query({ dictType: dictTypeData.dictType });
});

const [DictDataDrawer, dictDrawerApi] = useVbenDrawer({
  connectedComponent: DictDataDrawerComp,
});
const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema(),
  handleReset: queryHandleReset,
  wrapperClass: 'grid-cols-4',
};
async function queryHandleReset() {
  await basicTableApi.formApi.resetForm();
  await basicTableApi.formApi.setValues({ dictType: initDictType.dictType });
  const formValues = await basicTableApi.formApi.getValues();
  // 必须加这句不然重置看着标签是空的，但是接口传参数据没有重置！！！
  basicTableApi.formApi.setLatestSubmissionValues({
    ...formValues,
    dictType: initDictType.dictType,
  });
  await basicTableApi.query();
}
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await dictDataList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
async function handelAdd() {
  const values = await basicTableApi.formApi.getValues();
  dictDrawerApi.setData({ ...values, isUpdate: false }).open();
}
async function handleEdit(dictData: DictData) {
  const values = await basicTableApi.formApi.getValues();
  dictDrawerApi.setData({ ...values, ...dictData, isUpdate: true }).open();
}
// 批量删除
async function allDeleteHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const dictCodes = checkRecords.map((item: DictData) => item.dictCode);
  if (dictCodes.length <= 0) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的${dictCodes.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    await deleteDictData(dictCodes);
    await callTableReload();
  });
}
// 单个删除
async function confirmEvent(dictData: DictData) {
  const dictCodes: number[] = [];
  dictCodes.push(dictData.dictCode);
  await deleteDictData(dictCodes);
  await callTableReload();
}
// 导出
async function exportHandle() {
  await commonDownloadExcel(
    dictDataExport,
    '字典数据',
    basicTableApi.formApi.form.values,
  );
}
// 重新刷新页面
async function callTableReload() {
  const param = await basicTableApi.formApi.getValues();
  await basicTableApi.query(param);
}
</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="primary"
            @click="handelAdd"
            v-access:code="['system:dict:add']"
          >
            新增
          </ElButton>
        </ElSpace>
      </template>
      <template #dictLabel="{ row }">
        <ElTag :class="row.cssClass" :type="row.listClass">
          {{ row.dictLabel }}
        </ElTag>
      </template>
      <template #status="{ row }">
        <DictTag :value="row.status" :dicts="dictStatusRef" />
      </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>
    <DictDataDrawer @reload="callTableReload" />
  </Page>
</template>
