import {computed, nextTick, onMounted, ref, watch} from "vue";
import {ProviderEnum} from "@/views/ai/model/image/composables/consts";
import {ModelApi} from "@/api/new-ai/model";
import { ModelTypeEnum } from "../../chatModel/composables/consts";
import {ElTag, ElMessageBox as dialog, ElMessage as message} from "element-plus";

export default function () {
  const editRef = ref()
  const formData = ref({
    provider: ProviderEnum.OPENAI,
    type: ModelTypeEnum.TEXT_IMAGE
  });
  const tableData = ref([])
  const loading = ref(false)
  const baseColumns = [
    {
      label: '模型别名',
      field: 'name',
    },
    {
      label: '模型版本',
      field: 'model',
    },
  ];

  const openaiColumns = [
    ...baseColumns,
    {
      label: 'Api Key',
      field: 'apiKey',
    },
  ];

  const azureOpenaiColumns = [
    ...baseColumns,
    {
      label: 'Api Key',
      field: 'apiKey',
    },
    {
      label: 'Endpoint',
      field: 'endpoint',
    },
    {
      label: 'Deployment Name',
      field: 'azureDeploymentName',
    },
  ];

  const zhipuColumns = [...baseColumns];
  
  function getColumns(provider: string) {
    switch (provider) {
      case ProviderEnum.OPENAI: {
        return openaiColumns;
      }
      case ProviderEnum.AZURE_OPENAI: {
        return azureOpenaiColumns;
      }
      case ProviderEnum.ZHIPU: {
        return zhipuColumns;
      }
      default: {
        return baseColumns;
      }
    }
  }

  const columns = computed(() => {
    nextTick();
    return [...getColumns(formData.value.provider), {label: '操作', field: 'action', width: 150}]
  });

  // 加载数据
  const loadData = async () => {
    try {
      const res = await ModelApi.getModelList({ provider: formData.value.provider, type: ModelTypeEnum.TEXT_IMAGE }).finally(() => loading.value = false);
      tableData.value = res;
    } catch (error) {
      console.error('Failed to load image models:', error);
    }
  }

  // 监听供应商变化
  watch(() => formData.value.provider, () => {
    loadData();
  }, { immediate: true });

  const open = () => {
    editRef.value.show({provider: formData.value.provider,  type: ModelTypeEnum.TEXT_IMAGE});
  }
  function handleEdit(record: any) {
    editRef.value.show(record);
  }
  
  async function reloadTable() {
    await loadData();
  }
  
  async function handleDel(record: any) {
    dialog.confirm('确定要删除该模型吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      try {
        await ModelApi.deleteModel(record.id);
        await reloadTable();
        message.success('模型删除成功');
      } catch (error) {
        console.error('Failed to delete model:', error);
        message.error('删除模型失败');
      }
    }).catch(() => {
    });
  }
  return {
    columns,
    tableData,
    formData,
    editRef,
    open,
    loadData,
    handleDel,
    handleEdit,
    loading,
  }
}
