import { shallowRef } from 'vue'
import { queryWrPerformanceStepType, queryPermancePlanTmp } from '@/services/api/performance'
import { defineStore } from '../store'
import { sessionData } from '../storage'

export const usePerformanceStore = defineStore(() => {
    const loading = shallowRef(false)
    const performanceStepTypes = sessionData.getRef('performanceStepTypes') // 履约步骤枚举
    const performanceTemplates = sessionData.getRef('performanceTemplates') // 履约模板

    // 获取履约模板列表
    const getPerformanceTemplateList = async () => {
        try {
            if (performanceTemplates.value.length) {
                return Promise.resolve()
            }
            loading.value = true
            const res = await queryPermancePlanTmp({ marketid: 67201 })
            performanceTemplates.value = res.data
        } finally {
            loading.value = false
        }
    }

    // 根据 id 查找对应的履约模板
    const getPerformanceTemplateById = (id: number) => {
        return performanceTemplates.value.find((e) => e.autoid.toString() === id.toString())
    }

    // 获取履约步骤枚举列表
    const getPerformanceStepTypeList = async () => {
        try {
            if (performanceStepTypes.value.length) {
                return Promise.resolve()
            }
            loading.value = true
            const res = await queryWrPerformanceStepType()
            performanceStepTypes.value = res.data
        } finally {
            loading.value = true
        }
    }

    return {
        loading,
        performanceStepTypes,
        performanceTemplates,
        getPerformanceTemplateList,
        getPerformanceTemplateById,
        getPerformanceStepTypeList,
    }
})