import { ElMessage } from 'element-plus';

import { getCommonWordsCates, getCommonWordsList, setCommonWordsCate, removeCommonWords, setCommonWords } from '@/api/knowledgeBase'


export default function useCommonWordsApi() {
  const corpId = sessionStorage.getItem('corpId');
  const userId = sessionStorage.getItem('userId');

  async function getCates(cateType) {
    const { success, data: { list = [] }, message } = await getCommonWordsCates(corpId, userId, cateType);
    if (!success) ElMessage.error(message);
    return Array.isArray(list) ? list : []
  }

  async function getCommonWords(page, wordsType, cateId, keyword) {
    const params = {
      page,
      corpId,
      userId,
      wordsType,
      cateId,
      pageSize: 30,
      keyword
    }
    const { success, data, message } = await getCommonWordsList(params);

    if (!success) ElMessage.error(message);
    return {
      list: Array.isArray(data.list) ? data.list : [],
      pages: data.pages > 0 ? data.pages : 0
    }
  }

  async function setWords(cateId, content, id) {
    const params = { cateId, content, corpId, userId };
    if (id) params.id = id;
    const { success, message } = await setCommonWords(params);
    if (success) ElMessage.success(message);
    else ElMessage.error(message);
    return success
  }

  async function remove(id) {
    const { success, message } = await removeCommonWords({ id, corpId, userId });
    if (!success) ElMessage.error(message);
    return success
  }

  async function setCate(name, id, cateType) {
    const params = { name, corpId, userId, cateType };
    if (id) params.id = id;
    const { success, message } = await setCommonWordsCate(params);
    if (!success) ElMessage.error(message);
    return success
  }


  return { getCates, getCommonWords, setCate, setWords, remove }

}