<script setup lang="tsx">
import { ref } from 'vue';
import { NButton, NPopconfirm, NTag, type SelectOption } from 'naive-ui';
import { useRoute } from 'vue-router';
import {
  addData,
  delData,
  fetchGetDict,
  fetchGetDictDataList,
  fetchGetDictList,
  updateData
} from '@/service/api/system/dict';
import { useAppStore } from '@/store/modules/app';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { specialEnableStatusRecord } from '@/constants/business';
import type { ModelCallback } from '@/hooks/common/form';
import DataOperateModel from './modules/data-operate-model.vue';
import DataSearch from './modules/data-search.vue';

const appStore = useAppStore();
const route = useRoute();
const dictId = route.params.dictId;
const dictOptions = ref<SelectOption[]>([]);

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchGetDictDataList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    status: null,
    dictLabel: null,
    dictType: null
  },
  immediate: false,
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'dictCode',
      title: '字典编码',
      align: 'center'
    },
    {
      key: 'dictLabel',
      title: '字典标签',
      align: 'center',
      render: row => {
        if (!row.listClass || row.listClass === 'default') {
          return row?.dictLabel;
        }
        return <NTag type={row.listClass === 'danger' ? 'error' : row.listClass}>{row.dictLabel}</NTag>;
      }
    },
    {
      key: 'dictValue',
      title: '字典健值',
      align: 'center'
    },
    {
      key: 'status',
      title: '状态',
      align: 'center',
      width: 120,
      render: row => {
        if (row.status === null) {
          return null;
        }
        const tagMap: Record<Api.Common.SpecialEnableStatus, NaiveUI.ThemeColor> = {
          '0': 'success',
          '1': 'warning'
        };
        const label = $t(specialEnableStatusRecord[row.status]);
        return <NTag type={tagMap[row.status]}>{label}</NTag>;
      }
    },
    {
      key: 'remark',
      title: '备注',
      align: 'center'
    },
    {
      key: 'createTime',
      title: '创建时间',
      minWidth: 120
    },
    {
      key: 'operate',
      title: $t('common.operate'),
      align: 'center',
      width: 130,
      render: row => (
        <div class="flex-center gap-8px">
          <NButton type="primary" ghost size="small" onClick={() => edit(row.dictCode as string)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.dictCode as string)}>
            {{
              default: () => $t('common.confirmDelete'),
              trigger: () => (
                <NButton type="error" ghost size="small">
                  {$t('common.delete')}
                </NButton>
              )
            }}
          </NPopconfirm>
        </div>
      )
    }
  ]
});

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

// 查询字典列表
function getDictList() {
  fetchGetDictList<Api.SystemManage.DictList>().then(res => {
    if (res.error) return;

    dictOptions.value = res.data.data.map(item => {
      return {
        label: item.dictName,
        value: item.dictType
      };
    });
  });
}

// 查询字典详情
function getDictInfo() {
  fetchGetDict(dictId as string).then(res => {
    if (res.error) return;
    searchParams.dictType = res.data?.dictType;
    getData();
  });
}

// 批量删除
async function handleBatchDelete() {
  const { error } = await delData(checkedRowKeys.value as string[]);
  if (!error) {
    await onBatchDeleted();
  }
}

async function handleDelete(id: string) {
  const { error } = await delData([id]);
  if (!error) {
    await onDeleted();
  }
}

async function edit(dictCode: string) {
  handleSimpleEdit(dictCode);
}

function reset() {
  resetSearchParams();
  getDictInfo();
}

function handleSubmit(callback: (params: ModelCallback<Api.SystemManage.DictInfo>) => void) {
  callback({
    add: addData,
    edit: updateData,
    getData
  });
}

function init() {
  getDictInfo();
  getDictList();
}

init();
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <DataSearch v-model:model="searchParams" :dict-options="dictOptions" @reset="reset" @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>
      <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.Dict) => row.dictCode"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <DataOperateModel
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :dict-type="searchParams.dictType"
        @submit="handleSubmit"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
