import {request, api} from "@/utils/request";
import {message, Modal} from "ant-design-vue";
import qs from "qs";
import {useRoute} from "vue-router";

//登录
export const loginPort = function (data) {
  return new Promise((resolve) => {
    request.post("/login/", data).then((res) => {
      if (res.data) {
        sessionStorage.setItem("token", res.data);
        message.success("登录成功");
        resolve(true);
      } else {
        message.error(res.message);
        resolve(false);
      }
    })
  })
}

//退出
export const layout = function () {
  return request.get("/logout/")
}

//TODO 标签管理相关
export const getLabelList = function (params) {
  return request.get("/tags/", params)
}

//TODO 知识库列表相关
//1.知识库列表查询接口
export const getDataSetList = function (search, pagination) {
  const json = qs.stringify({
    page: pagination.current,
    limit: pagination.pageSize,
    keyword: search.keyword,
    tag_ids: search.tag_ids
  }, {arrayFormat: 'repeat'})
  return new Promise((resolve) => {
    request.get("/datasets/?" + json).then((res) => {
      resolve(res)
    })
  })
}

//知识库删除
export const delDatasets = function (id) {
  return new Promise((resolve) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前知识库',
      onOk() {
        request.delete("/datasets/" + id).then((res) => {
          if (res.status_code === 200) {
            message.success(res.message);
          } else {
            message.error(res.message);
          }
          resolve(res.data)
        }).catch(() => {
          resolve(false)
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  })
}

//5.知识库创建文档上传接口
export const upload = function (file, type = "datasets") {
  return request.postForm("/files/upload", {file}, {source: type})
}

//知识库新建
export const addDatasets = function (data) {
  return request.post("/datasets/init", data)
}

//空白知识库创建
export const addEmptyDatasets = function (name) {
  return request.post("/datasets/", {name})
}

//文档分页接口查询
export const getDocumentList = function (id, param) {
  return request.get("/datasets/" + id + "/documents", param)
}

//文档分段接口
export const getSegments = function (id, docId, params) {
  if (!docId) {
    return Promise.reject()
  }
  return request.get(`/datasets/${id}/documents/${docId}/segments`, params)
}

//文档详情查看接口
export const getDocumentInfo = function (id, docId) {
  return request.get(`/datasets/${id}/documents/${docId}?metadata=without`)
}

//文档切换状态
export const switchStatus = function (id, docId, action) {
  return new Promise(resolve => {
    request.patch(`/datasets/${id}/documents/${docId}/status/${action}`).then(res => {
      if (res.status_code === 200) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
      resolve(res.data)
    })
  })
}

//修改文件名称
export const editFileName = function (id, docId, name) {
  return new Promise(resolve => {
    request.post(`/datasets/${id}/documents/${docId}/rename`, {name}).then(res => {
      if (res.name) {
        message.success("重命名成功")
      }
      resolve(res)
    })
  })
}

//删除知识库文件
export const delDocument = function (id, docId) {
  return new Promise((resolve) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前文档',
      onOk() {
        request.delete("/datasets/" + id + "/documents/" + docId).then(() => {
          resolve(true)
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  })
}

//知识库内上传文档接口
export const docUpload = function (id, data) {
  return request.post(`/datasets/${id}/documents`, data)
}

//3.知识库编辑接口
export const editDataSets = function (id, data) {
  return new Promise(resolve => {
    request.patch("/datasets/" + id, data).then(res => {
      if (res.message) {
        message.error(res.message);
        resolve(false);
      } else {
        message.success("成功")
        resolve(true);
      }
    })
  })
}

//文本分段与清洗自定义策略查询接口
export const getCreateDocumentInfo = function (id) {
  return request.get("/datasets/process-rule", {document_id: id})
}

//查询文档状态接口
export const getFileStatus = function (id, batch) {
  return request.get(`/datasets/${id}/batch/${batch}/indexing-status`)
}

//应用列表查询
export const getAppList = function (params) {
  const json = qs.stringify(params, {arrayFormat: 'repeat'});
  return request.get("/apps/?" + json)
}

//应用删除
export const delApp = function (id) {
  return new Promise((resolve) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前应用',
      onOk() {
        request.delete("/apps/" + id).then((res) => {
          message.success("删除成功")
          resolve(true)
        }).catch(() => {
          resolve(false)
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  })
}

//创建应用
export const addApp = function (data) {
  return new Promise((resolve) => {
    request.post("/apps/", data).then((res) => {
      if (res.status_code !== '200') {
        message.error(res.message);
        resolve(false);
      } else {
        message.success(res.message)
        resolve({
          bool: true,
          id: res.data.id
        });
      }
    })
  })
}

//应用编辑
export const editApp = function (id, data) {
  return new Promise((resolve) => {
    request.put("/apps/" + id, data).then((res) => {
      if (res.status_code !== '200') {
        message.error(res.message);
        resolve(false);
      } else {
        message.success(res.message)
        resolve(true);
      }
    })
  })
}

//应用详情
export const getAppsInfo = function (id) {
  return request.get("/apps/" + id)
}

//查询知识库列表
export const getDatasetsAll = function () {
  return request.get("/datasets/", {page: 1, limit: 9999})
}

//查询知识库详情
export const getDatasetsInfo = function (id) {
  return request.get("/datasets/" + id)
}

//修改知识库设置
export const editDatasets = function (id, data) {
  return new Promise(resolve => {
    request.patch("/datasets/" + id, data).then(res => {
      message.success("修改成功");
      resolve(true)
    }).catch((error) => {
      message.error(error.message)
      resolve(false)
    })
  })
}

//修改文档状态
export const switchSegments = function (id, docId, status) {
  return request.patch(`/datasets/${id}/segments/${docId}/${status}`)
}

//发送消息
export const sendMessage = function (id, data) {
  return fetch(`/console/api/apps/${id}/chat-messages`,
    {
      method: "post",
      responseType: "stream",
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("token"),
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }
  );
}

//应用发布
export const appRelease = function (id, data) {
  return request.post(`/apps/${id}/model-config`, data)
}

// 获取聊天应用的接口
export const getChatPort = function () {
  const route = useRoute();
  return new Promise((resolve) => {
    api.requestConfig({
      url: "/passport",
      headers: {
        "X-App-Code": route.params.id,
      }
    }).then(res => {
      sessionStorage.setItem("console-token", res.access_token);
      setTimeout(() => {
        resolve(undefined);
      }, 1000);
    })
  })
}

//获取聊天信息
export const getSite = function () {
  return api.get("/site")
}

//获取聊天配置
export const getParameters = function () {
  return api.get("/parameters")
}

//获取聊天列表
export const getConversations = function (pageSize = 100) {
  return api.get("/conversations", {pinned: false, limit: pageSize})
}

//聊天接口
export const chatMessage = function (data) {
  return fetch(`/api/chat-messages`,
    {
      method: "post",
      responseType: "stream",
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("console-token"),
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }
  );
}

//文本聊天接口
export const completionMessage = function (data) {
  return fetch(`/api/completion-messages`,
    {
      method: "post",
      responseType: "stream",
      headers: {
        Authorization: "Bearer " + sessionStorage.getItem("console-token"),
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }
  );
}

//获取消息
export const getMessages = function (id) {
  return api.get("/messages", {conversation_id: id, limit: 100})
}

//发送消息停止
export const stepMessages = function (id) {
  return api.post(`/chat-messages/${id}/stop`)
}

//修改名称
export const editName = function (id, name) {
  return api.post(`/conversations/${id}/name`, {name})
}

//删除会话
export const delConversations = function (id) {
  return api.delete("/conversations/" + id)
}

//系统默认配置信息
export const getDefaultMode = function () {
  const url = [
    "/workspaces/current/default-model?model_type=text-embedding",
    "/workspaces/current/default-model?model_type=rerank",
    "/workspaces/current/default-model?model_type=llm",
  ]
  const requestAll = url.map((item) => {
    return request.get(item)
  })
  return new Promise(resolve => {
    Promise.all(requestAll).then(res => {
      const arr = [];
      res.forEach(item => {
        arr.push(item.data.model)
      })
      resolve(arr);
    })
  })
}

//模型设置-模型列表信息查询
export const getModelType = function () {
  const url = [
    "/workspaces/current/models/model-types/text-embedding",
    "/workspaces/current/models/model-types/rerank",
    "/workspaces/current/models/model-types/llm",
  ];
  const requestAll = url.map((item) => {
    return request.get(item)
  })
  return new Promise(resolve => {
    Promise.all(requestAll).then(res => {
      const arr = [];
      res.forEach(item => {
        if (item.data[0]?.models) {
          arr.push(item.data[0]?.models)
        }
      })
      resolve(arr);
    })
  })
}

//查询模型列表信息
export const getModelList = function () {
  const url = [
    "/workspaces/current/model-providers/ollama/models",
    "/workspaces/current/model-providers/xinference/models"
  ];
  const requestAll = url.map((item) => {
    return request.get(item)
  })
  return Promise.all(requestAll)
}

//设置系统模型
export const setModel = function (data) {
  return new Promise(resolve => {
    request.post("/workspaces/current/default-model", data).then(res => {
      if (res.message) {
        message.error(res.message);
        resolve(false);
      } else {
        message.success("设置成功")
        resolve(true);
      }
    })
  })
}

//新增，修改模型
export const addModel = function (type, data) {
  return new Promise(resolve => {
    request.post(`/workspaces/current/model-providers/${type}/models`, data).then(res => {
      if (res.message) {
        message.error(res.message);
        resolve(false);
      } else {
        message.success("成功")
        resolve(true);
      }
    })
  })
}

//删除模型
export const delModel = function (type, data) {
  return new Promise((resolve) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前模型？',
      onOk() {
        request.requestConfig({
          url: `/workspaces/current/model-providers/${type}/models`,
          data,
          method: "delete",
        }).then(res => {
          console.log(res.result)
           resolve(res.result === "success");
        }).catch(() => {
          resolve(false);
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  })
}

//模型查询详情
export const getModelInfo = function (type, param) {
  return request.get(`/workspaces/current/model-providers/${type}/models/credentials`, param)
}

//召回测试最近查询
export const getQueries = function (id) {
  return request.get(`/datasets/${id}/queries?limit=999&page=1`)
}

//召回测试
export const testing = function (id, data) {
  return request.post(`/datasets/${id}/hit-testing`, data)
}

//用户列表
export const getUserList = function (params) {
  return request.get("/user/page", params)
}

//新增用户
export const addUser = function (data) {
  return new Promise(resolve => {
    request.post("/user/", data).then(res => {
      if (!res.data) {
        message.error(res.message);
        resolve(false);
      } else {
        message.success(res.message);
        resolve(true);
      }
    })
  })
}

//删除用户
export const delUser = function (id) {
  return new Promise((resolve) => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前用户',
      onOk() {
        request.delete("/user/" + id).then((res) => {
          console.log(res)
          if (res.status_code !== 200) {
            message.success(res.message);
            resolve(true)
          } else {
            message.error(res.message);
            resolve(false);
          }
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  })
}

//启用/禁用用户
export const disabledUser = function (id, status) {
  return new Promise(resolve => {
    request.get(`/user/${id}/${status}`).then(res => {
      if (res.status_code === 200) {
        message.success(res.message);
        resolve(true)
      } else {
        message.error(res.message);
        resolve(false);
      }
    })
  })
}

//修改用户
export const editUser = function (id, data) {
  console.log(id)
  return new Promise(resolve => {
    request.patch(`/user/`, {...data, id}).then(res => {
      if (res.status_code === "200") {
        message.success(res.message);
        resolve(true)
      } else {
        message.error(res.message);
        resolve(false);
      }
    })
  })
}

//获取系统配置
export const getConfig = function () {
  return request.get("/system-config/")
}

//添加系统配置
export const setConfig = function (data) {
  return new Promise(resolve => {
    request.postForm("/system-config/", data).then(res => {
      if (res === 200) {
        message.success("配置成功")
      } else {
        message.error("配置失败")
      }
      resolve(res);
    })
  })
}

//获取系统配置
export const getConfigInfo = function (type: "LOGO" | "ICON" | "PRODUCT-NAME") {
  return new Promise<string>(resolve => {
    request.get("/system-config/" + type).then((res) => {
      if (type !== "PRODUCT-NAME") {
        resolve(res.file_binary);
      } else {
        resolve(res.name);
      }
    })
  })
}

//获取应用api key
export const getAppKeys = function (id) {
  return request.get(`/apps/${id}/api-keys`)
}

//添加api keys
export const addAppkeys = function (id) {
  return request.post(`/apps/${id}/api-keys`)
}

//删除api keys
export const delAppkeys = function (id, key) {
  return request.delete(`/apps/${id}/api-keys/${key}`)
}

//应用日志查询
export const getChatConversations = function (id, params) {
  return request.get(`/apps/${id}/chat-conversations`, params)
}

//应用日志插查询，文本生成
export const getCompletionConversations = function (id, params) {
  return request.get(`/apps/${id}/completion-conversations`, params)
}

//标注查询
export const getAnnotations = function (id, params) {
  return request.get(`/apps/${id}/annotations`, params)
}

//标注添加
export const addAnnotations = function (id, data) {
  return request.post(`/apps/${id}/annotations`, data)
}

//标注删除
export const delAnnotations = function (id, dataId) {
  return new Promise(resolve => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前段落',
      onOk() {
        request.delete(`/apps/${id}/annotations/${dataId}`).then((res) => {
          if (res.status_code === 200) {
            message.success(res.message);
          } else {
            message.error(res.message);
          }
          resolve(res.data);
        }).catch((e) => {
          resolve(false)
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  })
}

//标注修改
export const editAnnotations = function (id, dataId, data) {
  return request.post(`/apps/${id}/annotations/${dataId}`, data)
}

//获取标注设置
export const getAnnotationSetting = function (id) {
  return request.get(`/apps/${id}/annotation-setting`)
}

//标注回复初始设置
export const settingAnnotation = function (id, status, data) {
  return request.post(`/apps/${id}/annotation-reply/${status}`, data)
}

//查询标注状态是否完成
export const searchAnnotationStatus = function (id, status, jobId) {
  return request.get(`/apps/${id}/annotation-reply/${status}/status/${jobId}`)
}

//获取用户信息
export const userInfo = function () {
  return request.get("/account/profile")
}

//文档段落删除
export const delDocumentSegments = function (dataSetid, id, segmentsId) {
  return new Promise(resolve => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前段落',
      onOk() {
        request.delete(`/datasets/${dataSetid}/documents/${id}/segments/${segmentsId}`).then((res) => {
          if (res.status_code === 200) {
            message.success(res.message);
          } else {
            message.error(res.message);
          }
          resolve(res.data);
        }).catch((e) => {
          resolve(false)
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  })
}

//文档段落编辑
export const editDocumentSegments = function (dataSetid, id, segmentsId, data) {
  return request.patch(`/datasets/${dataSetid}/documents/${id}/segments/${segmentsId}`, data)
}

//文档段落添加
export const addDocumentSegments = function (dataSetid, id, data) {
  return request.post(`/datasets/${dataSetid}/documents/${id}/segment`, data)
}

//文本生成聊天
export const completionMessages = function (id, json) {
  return fetch(`/console/api/apps/${id}/completion-messages`, {
    method: "post",
    responseType: "stream",
    headers: {
      Authorization: "Bearer " + sessionStorage.getItem("token"),
      "Content-Type": "application/json",
    },
    body: JSON.stringify(json),
  })
}

//获取索引文档
export const messagesConversation = function (id, conversation_id) {
  return request.get(`/apps/${id}/chat-messages`, {conversation_id})
}

//应用概览汇总
export const getInteractions = function () {
  return request.get("/apps/statistics/basic-quantitative-analysis")
}

//应用数量变化
export const appCount = function () {
  return request.get("/apps/statistics/app-count")
}

//应用活跃用户数
export const dailyUsers = function () {
  return request.get("/apps/statistics/daily-end-users")
}

//全部消息数
export const dailyConversations = function () {
  return request.get("/apps/statistics/daily-conversations")
}

//应用平均会花数
export const averageInteractions = function () {
  return request.get("/apps/statistics/average-session-interactions")
}

//知识库，统计
export const tableCounts = function () {
  return request.get("/apps/statistics/table-counts")
}

//文档解析top5
export const topLongest = function () {
  return request.get("/apps/statistics/top-5-longest")
}

//知识库数量
export const datasetsDailyCount = function () {
  return request.get("/apps/statistics/datasets-daily-count")
}

//文档数量
export const documentsDailyCount = function () {
  return request.get("/apps/statistics/documents-daily-count")
}

//pdf解析时长分布
export const timeStatistics = function () {
  return request.get("/apps/statistics//time-statistics")
}

//历史会话
export const messagesList = function (id, conversation_id) {
  return request.get(`/apps/${id}/chat-messages?conversation_id=${conversation_id}&limit=30`)
}

//历史会话
export const completionConversationsHistory = function (id, conversation_id) {
  return request.get(`/apps/${id}/completion-conversations/${conversation_id}`)
}

//导入文件
export const batchImport = function (id, file) {
  return request.postForm(`/apps/${id}/annotations/batch-import`, { file })
}

//聊天，添加对话记录
export const addName = function (id) {
  return api.post(`/conversations/${id}/name`, { auto_generate: true })
}

//修改密码
export const editPassword = function (data) {
  return request.post("/account/password", data)
}

//文件大小接口
export const fileSize = function () {
  return request.get("/files/upload")
}

//文件类型接口
export const fileType = function () {
  return request.get("/files/support-type")
}

//文本记录保存
export const saveMessage = function (message_id) {
  return new Promise(resolve => {
    api.post("/saved-messages/", {message_id}).then(res => {
      if (res.status_code === 200) {
        message.success(res.message);
      } else {
        message.error(res.message);
      }
      resolve(res.data);
    })
  })
}

//文本记录查询
export const getMessage = function () {
  return api.get("/saved-messages/")
}

//文本记录删除
export const removeMessage = function (id) {
  return new Promise(resolve => {
    Modal.confirm({
      title: '提示',
      content: '确认删除当前结果',
      onOk() {
        api.delete(`/saved-messages/` + id).then((res) => {
          if (res.status_code === 200) {
            message.success(res.message);
          } else {
            message.error(res.message);
          }
          resolve(res.data);
        }).catch((e) => {
          resolve(false)
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  });
}

//获取知识库关联应用
export const relatedApps = function (id) {
  return request.get(`/datasets/${id}/related-apps`);
}

//文档重试
export const retry = function (id, document_ids) {
  return new Promise(resolve => {
    Modal.confirm({
      title: '提示',
      content: '确认重试该文档',
      onOk() {
        request.post(`/datasets/${id}/retry`, {document_ids}).then((res) => {
          if (res.status_code === 200) {
            message.success(res.message || "成功");
          } else {
            message.error(res.message || "失败");
          }
          resolve(res.data);
        })
      },
      onCancel() {
        resolve(false);
      }
    });
  });
}

//下一步建议
export const suggestedQuestions = function (id, messageId) {
  return request.get(`/apps/${id}/chat-messages/${messageId}/suggested-questions`)
}

//聊天。下一步开启
export const chatSuggestedQuestions = function (id) {
  return api.get(`/messages/${id}/suggested-questions`)
}

//工具类型查询接口
export const toolLabels = function () {
  return request.get("/workspaces/current/tool-labels")
}

//工具详细信息集合接口
export const builtin = function (name, labels) {
  return request.get("/workspaces/current/tools/builtin", { name, labels })
}

//自定义工具
export const toolsApi = function (name, labels) {
  return request.get("/workspaces/current/tools/api", { name, labels })
}

//发布的工作流
export const toolsWorkflow = function (name, labels) {
  return request.get("/workspaces/current/tools/workflow", { name, labels })
}

//获取工具图片
export const toolProviders = function () {
  return request.get("/workspaces/current/tool-providers")
}

//获取工具类型
export const getTools = function (type, id) {
  return request.get(`/workspaces/current/tool-provider/${type}/${id}/tools`)
}
