import { defineStore } from 'pinia';
import { safeJsonParse } from '../utils/common';
import {
  analysisKeyword,
  analysisSuggestions,
  analysisRival,
  analysisQualitative
} from '../utils/api';
import type { FormDataInfo, KeywordInfo, RelatedInfoBOItem, CompetitorBOSItem } from '@/types';

export const useMainStore = defineStore('main', {
  state: () => ({
    currentStep: 1,
    clearCache: false,
    formData: {} as FormDataInfo,
    keywordInfo: {
      loading: true,
      data: {} as KeywordInfo
    },
    suggestionsInfo: {
      loading: true,
      autoFinish: false,
      data: [] as RelatedInfoBOItem[],
      fail: false
    },
    aiAnalysisData: {
      loading: true,
      autoFinish: false,
      data: '',
      fail: false
    },
    expanded: false,
    isLoadOver: false,
    isShowCompetitor: false,
    phone: '',
    id: '',
    cacheViews: ['Record'],
  }),
  actions: {
    setCacheViews(val: string[]) {
      this.cacheViews = val;
    },
    setPhone(val: string) {
      this.phone = val;
    },
    setRecordId(val: string) {
      this.id = val;
    },
    setClearCache(val: boolean) {
      this.clearCache = val;
    },
    setIsLoadOver(val: boolean) {
      this.isLoadOver = val;
    },
    setExpanded(val: boolean) {
      this.expanded = val;
    },
    setCurrentStep(val: number) {
      this.currentStep = val;
    },
    setFormData(data: FormDataInfo) {
      sessionStorage.setItem('formData', JSON.stringify(data));
      this.formData = data;
    },
    // 获取定性分析
    async getQualitative() {
      this.aiAnalysisData.loading = true;
      this.aiAnalysisData.fail = false;
      const { productName, description = '' } = this.getFormData;
      return analysisQualitative(encodeURIComponent(productName + description)).then((res: any) => {
        const rawText = res.msg.replace(/^```[a-zA-Z]*\n?/, '').replace(/```$/, '');
        this.aiAnalysisData.autoFinish = true;
        this.aiAnalysisData.data = rawText;
        setTimeout(() => {
          this.aiAnalysisData.loading = false;
          this.aiAnalysisData.autoFinish = false;
        }, 300);
      }).catch(() => {
        this.aiAnalysisData.fail = true;
      }).finally(() => {
        this.isLoadOver = true;
      })
    },
    // 获取竞品
    getRival(website: string): Promise<any> {
      const { locationName } = this.getFormData;
      return analysisRival({ competitorWebsite: website, locationName });
    },
    // 获取推荐
    async getSuggestions() {
      this.suggestionsInfo.loading = true;
      const { productName, locationName } = this.getFormData;
      return analysisSuggestions({ productName, locationName })
        .then((res) => {
          this.suggestionsInfo.data = res.data.relatedInfoBOList;
          this.suggestionsInfo.autoFinish = true;
          setTimeout(() => {
            this.suggestionsInfo.loading = false;
            this.suggestionsInfo.autoFinish = false;
          }, 300);
        })
        .catch(() => (this.suggestionsInfo.fail = true));
    },
    // 获取关键词
    async getKeywordData() {
      this.keywordInfo.loading = true;
      const { productName, locationName } = this.getFormData;
      return analysisKeyword({ productName, locationName })
        .then((res) => {
          this.keywordInfo.data = res.data;
        })
        .finally(async () => {
          this.keywordInfo.loading = false;
        });
    },
    initData() {
      this.isLoadOver = false;
      this.getKeywordData();
      this.getSuggestions();
      // 判断是否输入合法的竞品网站地址
      const { competitorWebsite } = this.getFormData;
      const isShowCompetitor = !!(competitorWebsite?.split(',') || []).filter(
        (item) => item.trim() !== ''
      ).length;
      this.isShowCompetitor = isShowCompetitor;
      this.getQualitative();
    }
  },
  getters: {
    getCacheViews(): string[] {
      return this.cacheViews;
    },
    getPhone(): string {
      return this.phone;
    },
    getRecordId(): string {
      return this.id;
    },
    getClearCache(): boolean {
      return this.clearCache;
    },
    getExpanded(): boolean {
      return this.expanded;
    },
    getCurrentStep(): number {
      return this.currentStep;
    },
    getFormData(): FormDataInfo {
      if (Object.keys(this.formData).length === 0) {
        const data = sessionStorage.getItem('formData') ?? '';
        return safeJsonParse(data);
      }
      return this.formData;
    },
    getKeywordInfo(): { data: KeywordInfo } & { loading: boolean } {
      return this.keywordInfo;
    },
    getSuggestionsInfo(): { data: RelatedInfoBOItem[] } & {
      autoFinish: boolean;
      loading: boolean;
    } {
      return this.suggestionsInfo;
    },
    getIsLoadOver(): boolean {
      return this.isLoadOver;
    },
    getIsShowCompetitor(): boolean {
      return this.isShowCompetitor;
    },
    getAiAnalysisData(): { loading: boolean; autoFinish: boolean; data: string; fail: boolean} {
      return this.aiAnalysisData;
    }
  }
});
