<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { useDownLoadFile } from '@/hooks/common/download';
import { $t } from '@/locales';
import { addConfig, delConfig, getConfig, listConfig, refreshCache, updateConfig } from '@/service/api/system/config';
import { getDicts } from '@/service/api/system/dict';
import { useAppStore } from '@/store/modules/app';
import ConfigSearch from '@/views/system/config/modules/config-search.vue';
import ConfigOperateModel from '@/views/system/config/modules/config-operate-model.vue';
import type { ModelCallback } from '@/hooks/common/form';

const appStore = useAppStore();
const { loading: exportLoading, downLoadExcelPost } = useDownLoadFile();

const typeOptions = ref<Api.SystemManage.DictInfo[]>([]);
getDicts('sys_yes_no').then(response => {
  if (!response.error) {
    typeOptions.value = response.data as Api.SystemManage.DictInfo[];
  }
});

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: listConfig,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    configName: null,
    configKey: null,
    configType: null,
    params: []
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'configId',
      title: '参数主键',
      width: 200,
      align: 'center'
    },
    {
      key: 'configName',
      title: '参数名称',
      minWidth: 120
    },
    {
      key: 'configKey',
      title: '参数键名',
      minWidth: 120
    },
    {
      key: 'configValue',
      title: '参数键值',
      align: 'center',
      minWidth: 60
    },
    {
      key: 'configType',
      title: '系统内置',
      align: 'center',
      width: 150,
      render: row => {
        if (row.configType === null) {
          return null;
        }
        return typeOptions.value.find(item => item.dictValue === row.configType)?.dictLabel;
      }
    },
    {
      key: 'remark',
      title: '备注',
      minWidth: 120,
      align: 'center',
      ellipsis: {
        tooltip: true
      }
    },
    {
      key: 'createTime',
      title: '创建时间',
      minWidth: 120,
      align: 'center'
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 200,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.configId)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.configId)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);

// 单个删除
function handleDelete(id: Api.SystemManage.Config['configId']) {
  delConfig([id]).then(res => {
    if (!res.error) {
      onDeleted();
    }
  });
}

// 批量删除
function handleBatchDelete() {
  delConfig(checkedRowKeys.value).then(res => {
    if (!res.error) {
      onBatchDeleted();
    }
  });
}

// 编辑
async function edit(id: Api.SystemManage.Config['configId']) {
  getConfig(id).then(res => {
    if (!res.error) {
      editingData.value = res.data;
      handleEdit();
    }
  });
}

// 提交
function handleSubmit(callback: (params: ModelCallback<Api.SystemManage.Config>) => void) {
  callback({
    add: addConfig,
    edit: updateConfig,
    getData
  });
}

// 导出
function handleExport() {
  downLoadExcelPost('/system/config/export', searchParams);
}

function handleRefresh() {
  refreshCache().then(res => {
    if (!res.error) {
      window.$message?.success('刷新成功');
    }
  });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <ConfigSearch
      v-model:model="searchParams"
      :type-options="typeOptions"
      @reset="resetSearchParams"
      @search="getDataByPage"
    />
    <NCard title="参数列表" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="getData"
        >
          <template #middle>
            <NButton :loading="exportLoading" type="success" ghost size="small" @click="handleExport">
              <template #icon>
                <SvgIcon icon="mdi:file-export-outline"></SvgIcon>
              </template>
              导出
            </NButton>
            <NButton type="error" ghost size="small" @click="handleRefresh">
              <template #icon>
                <SvgIcon icon="ep:refresh"></SvgIcon>
              </template>
              刷新缓存
            </NButton>
          </template>
        </TableHeaderOperation>
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="702"
        :loading="loading"
        remote
        :row-key="(row: Api.SystemManage.Config) => row.configId"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <ConfigOperateModel
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :type-options="typeOptions"
        @submit="handleSubmit"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
