import { toRefs, shallowReadonly, ShallowRef } from 'vue'
import { queryWrPerformanceStepType, queryPermancePlanTmp } from '@/services/api/performance'
import { VueStore } from '../base'
import WebStorage from '@/utils/storage'

interface StoreState {
    loading: boolean;
    performanceStepTypes: ShallowRef<Ermcp.WrPerformanceStepTypeRsp[]>; // 履约步骤枚举
    performanceTemplates: ShallowRef<Ermcp.PermancePlanTmpRsp[]>; // 履约模板
}

const store = new (class extends VueStore<StoreState>{
    constructor() {
        const storage = new WebStorage(sessionStorage, { performanceStepTypes: [], performanceTemplates: [] })
        const state: StoreState = {
            loading: false,
            performanceStepTypes: storage.getRef('performanceStepTypes'),
            performanceTemplates: storage.getRef('performanceTemplates'),
        }
        super(state)
    }

    actions = {
        /** 获取履约模板列表 */
        getPerformanceTemplateList: () => {
            if (this.state.performanceTemplates.length) {
                return Promise.resolve()
            }
            this.state.loading = true
            return queryPermancePlanTmp({
                success: (res) => {
                    this.state.performanceTemplates = res.data
                },
                complete: () => {
                    this.state.loading = false
                }
            })
        },
        /** 获取履约步骤枚举列表 */
        getPerformanceStepTypeList: () => {
            if (this.state.performanceStepTypes.length) {
                return Promise.resolve()
            }
            this.state.loading = true
            return queryWrPerformanceStepType({
                success: (res) => {
                    this.state.performanceStepTypes = res.data
                },
                complete: () => {
                    this.state.loading = true
                }
            })
        }
    }
})

export function usePerformanceStore() {
    return shallowReadonly({
        ...toRefs(store.state),
        ...store.actions,
        ...store.methods,
    })
}