import { defineStore } from 'pinia'
import { ref } from 'vue'
import { sessionHistory, newCreateSession } from '@/servers/finyx/api/zhinengtiduihuajilu';

export type AnswerStatus = 'init' | 'pending' | 'done' | 'error'| undefined  // 自定义状态
export interface ChatMessage {
  question?: string // 问
  status?: AnswerStatus // 自定义状态
  id?: string
  sessionId?: string
  applicationId?: string
  answer: ChatMessage
  createdTime?: string
}

export interface ChatStateTypes {
  agentId?: string;  // 智能体id
  historyId?: string; // 选中的历史对话id默认 新建对话无id
  pageLoading?: boolean; // 页面加载中
}


const useChatStore = defineStore('chat',  () =>{

  const info = ref<ChatStateTypes>({
    historyId: '', // 选中的历史对话id默认 新建对话无id
    agentId: '', // 智能体id
    pageLoading: false, // 页面加载中
  })

  const agentInfo = ref<any>(null) //智能体详情

  const historyList = ref<Array<any>>([]) // 历史对话列表

  const questionList = ref<Array<ChatMessage>>([]) // 聊天记录

  /* Actions */

  async function addInfo(data: ChatStateTypes) {
    const { historyId, agentId } = data;
    info.value = {
      historyId, 
      agentId, 
    }
  }

  async function addAgentInfo(data: any) {
    agentInfo.value = data
  }

  async function addHistoryList(data: any) {
    historyList.value = data
  }

  async function addQuestionList(data: any) {
    // 此处分页可能追加数据
    questionList.value.push(...data)
  }

  /** 获取历史会话列表 */
  async function getHistoryList(id?: any) {
    sessionHistory({ applicationId: id || agentInfo.value.id })
    .then((res: any) => {
      const data = [
        { id: '', applicationId: info.value.agentId, sessionId:'', question: '新建对话' }, 
        ...res
      ]
      historyList.value = data;
    })
  }

  /** 新建会话 */
  async function createSession() {
    return new Promise((resolve, reject) => {
      const params: any = {
        applicationId: info.value.agentId,
      }
      newCreateSession(params)
        .then((res: any) => {
          info.value.historyId = res
          resolve(true)
        }).catch(error => {
          reject(error)
        })
    })    
  }



  return {
    info,
    agentInfo,
    questionList,
    historyList,
    addInfo,
    addAgentInfo,
    addHistoryList,
    addQuestionList,
    getHistoryList,
    createSession
  }
})

export default useChatStore
