<script setup lang="tsx">
import { NButton, NPopconfirm, NTag } from 'naive-ui';
import { useTable, useTableOperate } from '@/hooks/common/table';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import {
  createModelConfig,
  deleteModelConfig,
  fetchModelConfigDetail,
  fetchModelConfigList,
  updateModelConfig
} from '@/service/api/modelConfig';
import ModelConfigSearch from '@/views/foreground-setting/modules/model-config/modules/model-config-search.vue';
import ModelConfigOperateModel from '@/views/foreground-setting/modules/model-config/modules/model-config-operate-model.vue';
import type { ModelCallback } from '@/hooks/common/form';

const appStore = useAppStore();

defineOptions({
  name: 'ModelConfig'
});

type PageType = Api.ModelConfig.ContractModelConfigVo;
type PageTypeId = Api.ModelConfig.ContractModelConfigVo['id'];

const modelTypeOptions = [
  { label: 'openai', value: 'openai' },
  { label: 'deepseek', value: 'deepseek' }
];

const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useTable({
  apiFn: fetchModelConfigList,
  apiParams: {
    pageNum: 1,
    pageSize: 10,
    modelName: null,
    modelKey: null,
    modelType: null
  },
  columns: () => [
    {
      type: 'selection',
      align: 'center',
      width: 48
    },
    {
      key: 'id',
      title: '配置ID',
      align: 'center'
    },
    {
      key: 'modelName',
      title: '模型名称',
      align: 'center'
    },
    {
      key: 'modelType',
      title: '模型类型',
      align: 'center',
      render: row => {
        const model = modelTypeOptions.find(item => item.value === row.modelType);
        return <NTag type="primary">{model?.label}</NTag>;
      }
    },
    {
      key: 'modelUrl',
      title: '模型地址',
      align: 'center'
    },
    {
      key: 'modelKey',
      title: '参数键值',
      align: 'center'
    },
    {
      key: 'modelVersion',
      title: '模型版本',
      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.id)}>
            {$t('common.edit')}
          </NButton>
          <NPopconfirm onPositiveClick={() => handleDelete(row.id)}>
            {{
              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: PageTypeId) {
  deleteModelConfig([id]).then(res => {
    if (!res.error) {
      onDeleted();
    }
  });
}

// 批量删除
function handleBatchDelete() {
  deleteModelConfig(checkedRowKeys.value as PageTypeId[]).then(res => {
    if (!res.error) {
      onBatchDeleted();
    }
  });
}

// 编辑
async function edit(id: PageTypeId) {
  fetchModelConfigDetail(id).then(res => {
    if (!res.error) {
      editingData.value = res.data;
      handleEdit();
    }
  });
}

// 提交
function handleSubmit(callback: (params: ModelCallback<PageType>) => void) {
  callback({
    add: createModelConfig,
    edit: updateModelConfig,
    getData
  });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <ModelConfigSearch
      v-model:model="searchParams"
      :model-type-options="modelTypeOptions"
      @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>
      <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="({id}) => id"
        :pagination="mobilePagination"
        class="sm:h-full"
      />
      <ModelConfigOperateModel
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        :model-type-options="modelTypeOptions"
        @submit="handleSubmit"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
