import { ref, h } from 'vue'
import { useModelHooks } from '@/views/setting/model/index/hooks/index.ts'
import { Modal, message } from 'ant-design-vue';


export const useModelServer = () => {
  const { listRequest, addRequest, updateRequest, deleteRequest, importPretrainedForModelRequest, deletePretrainedForModelRequest } = useModelHooks()

  const modelList = ref([])
  // 获取列表
  const getList = async (params?: any) => {
    const res = await listRequest.request(params)
    console.log('res', res)
    if (res?.code == 200) {
      modelList.value = res.models || []
    }
    return res
  }

  // 新增
  const addModel = async (params: any) => {
    return await addRequest.request(params)
  }

  // 更新
  const updateModel = async (params: any) => {
    return await updateRequest.request(params)
  }

  // 构造删除删除弹出层
  const createDeleteProps = () => {
    return {
      centered: true,
      title: h("div", { style: "font-size: 16px" }, "删除数据"),
      icon: h("span"),
      content: h(
        "div",
        { style: "font-size: 16px; margin-bottom: 20px" },
        "确定要删除当前数据吗?本次操作无法撤回",
      ),
      okText: "确定",
      cancelText: "取消",
      onOk: async () => {},
      onCancel() {},
    }
  };

  // 删除任务
  const onShowModelDelete = async (modelId: string) => {
    return new Promise((resolve, reject) => {
      const modalProps = createDeleteProps()
      modalProps.onOk = async () => {
        const res = await deleteModel(modelId)
        if (res?.code == 200) {
          message.success('删除成功')
          resolve(res)
        } else {
          reject(res)
        }
      }
      Modal.confirm(modalProps);
    })
  }

  // 删除
  const deleteModel = async (params: any) => {
    const res = await deleteRequest.request(params)
    return res
  }

  // 导入预训练权重
  const importPretrainedForModel = async (data: FormData) => {
    const res = await importPretrainedForModelRequest.request(data)
    return res
  }

  // 删除预训练权重
  const deletePretrainedForModel = async (data: Record<string, any>) => {
    const res = await deletePretrainedForModelRequest.request(data)
    return res
  }

  // 删除预训练权重弹出层
  const onShowPretrainedDelete = async (data: Record<string, any>) => {
    return new Promise((resolve, reject) => {
      const modalProps = createDeleteProps()
      modalProps.onOk = async () => {
        console.log('onShowPretrainedDelete', data)
        const res = await deletePretrainedForModel(data)
        if (res?.code == 200) {
          message.success('删除成功')
          resolve(res)
        } else {
          reject(res)
        }
      }
      Modal.confirm(modalProps);
    })
  }

  return {
    state: {
      modelList
    },
    api: {
      getList,
      addModel,
      updateModel,
      deleteModel,
      onShowModelDelete,
      importPretrainedForModel,
      deletePretrainedForModel,
      onShowPretrainedDelete
    },
    requestMap: {
      listRequest,
      addRequest,
      updateRequest,
      deleteRequest
    }
  }
}
