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

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

import { onMounted, ref } from 'vue';

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 {
  configList,
  deleteConfig,
  exportConfig,
  refreshConfig,
} from '#/api/system/config/config';
import { DictTag } from '#/components/dict/index';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns } from './config-data';
import ConfigDrawerComp from './config-drawer.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl: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,
    // 点击行选中
    trigger: 'default',
    checkMethod: ({ row }) => row?.roleId !== 1,
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await configList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'roleId',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-role-index',
};
const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
const [VbenConfigDrawer, configDrawerApi] = useVbenDrawer({
  connectedComponent: ConfigDrawerComp,
});
// 新增打开配置
function openDrawer() {
  configDrawerApi.setData({ isUpdate: false }).open();
}
// 编辑修改配置
function handleEdit(configModel: ConfigModel) {
  configDrawerApi.setData({ ...configModel, isUpdate: true }).open();
}
// 单个删除配置
async function confirmEvent(configModel: ConfigModel) {
  await deleteConfig([configModel.configId]);
  await basicTableApi.reload();
}
// 删除多个配置
function deleteHandle() {
  // 获取全部选中的数据
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  // 数据转换只要roleId
  const ids = checkRecords.map((item: ConfigModel) => item.configId);
  if (ids.length <= 0) {
    return;
  }
  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除配置
    await deleteConfig(ids);
    // 重置查询
    await basicTableApi.reload();
  });
}
// 导出配置
async function exportHandle() {
  await commonDownloadExcel(
    exportConfig,
    '系统参数数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
// 刷新缓存
async function refreshHandle() {
  await refreshConfig();
  await basicTableApi.reload();
}
// 获取状态字典值
const dictStatusRef = ref<DictOption[]>([]);
onMounted(() => {
  dictStatusRef.value = getDictOptions(DictEnum.SYS_YES_NO);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="参数列表">
      <template #roleKey="{ row }">
        <ElTag>
          {{ row.roleKey }}
        </ElTag>
      </template>
      <template #configType="{ row }">
        <DictTag :value="row.configType" :dicts="dictStatusRef" />
      </template>
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            @click="exportHandle"
            v-access:code="['system:config:export']"
          >
            导出
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['system:config:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="warning"
            @click="refreshHandle"
            v-access:code="['system:config:remove']"
          >
            刷新缓存
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['system:config:add']"
          >
            {{ $t('pages.common.add') }}
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace v-if="row.roleId !== 1">
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:config:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:config:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <VbenConfigDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
