import { defineStore } from 'pinia'

import { defaultModelName, modelMappingList } from '@/components/MarkdownPreview/models'

export interface BusinessState {
  systemModelName: string
}

export const useBusinessStore = defineStore('business-store', {
  state: (): BusinessState => {
    return {
      systemModelName: defaultModelName
    }
  },
  getters: {
    currentModelItem (state) {
      return modelMappingList.find(v => v.modelName === state.systemModelName)
    }
  },
  actions: {
    /**
     * Event Stream 调用大模型接口
     */
    async createAssistantWriterStylized(data): Promise<{error: number
      content: string | null}> {

      // 调用当前模型的接口
      return new Promise((resolve) => {
        if (!this.currentModelItem?.chatFetch) {
          return {
            error: 1,
            content: null
          }
        }
        this.currentModelItem.chatFetch(data.text)
          .then(async (res) => {
            const json = await res.json()
            if (json.code === 200) {
              if (json.notes) {
                const storageData = localStorage.getItem('chatNotes')
                if (storageData) {
                  const merged = {
                    ...JSON.parse(storageData),
                    ...json.notes
                  }
                  localStorage.setItem('chatNotes', JSON.stringify(merged))
                } else {
                  localStorage.setItem('chatNotes', JSON.stringify(json.notes))
                }
              }
              resolve({
                error: 0,
                content: json.content
              })
            } else {
              window.$ModalMessage.error(json.message)
              resolve({
                error: 0,
                content: json.message
              })
            }
          })
          .catch((err) => {
            resolve({
              error: 2,
              content: null
            })
          })
      })
    }
  }
})
