import { defineStore } from 'pinia'; import { safeJsonParse } from '../utils/common'; import { analysisKeyword, analysisSuggestions, analysisRival, analysisQualitative } from '../utils/api'; import { incrementCount } from '@/utils/limit'; 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 }, expanded: false, isLoadOver: false }), actions: { 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; }, // 获取定性分析 getQualitative(): Promise { const { productName, description = '' } = this.getFormData; return analysisQualitative(encodeURIComponent(productName + description)); }, // 获取竞品 getRival(website: string): Promise { 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; await incrementCount(); }); }, initData() { this.getKeywordData(); this.getSuggestions(); // this.getQualitative(); } }, getters: { 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; } } });