import { getAircraftNumbersApi, getBasicParamsListApi, getTerminalListApi } from 'mocp/api/base'
import { defineStore } from 'pinia'

const useBaseStore = defineStore('base', {
    state: () => {
        return {
            selectList: {
                deviceNumSelect: [], //机号
                terminalSelect: [] //航站下拉数据
            },
            allBasicParams: {} //系统基础参数
        }
    },
    getters: {
        getTerminalSelect(state) {
            return state.selectList.terminalSelect?.reduce((q, w) => {
                if (!q[w.terminalCode]) {
                    q[w.terminalCode] = []
                }
                q[w.terminalCode] = w.terminalCity + '-' + w.terminalName + '-' + w.terminalCode
                return q
            }, {})
        }
    },
    actions: {
        async initSysData() {
            uni.showLoading({
                title: '正在加载系统所有基本参数中，请稍后！',
                mask: true
            })
            try {
                await Promise.all(this.getAircraftNumbers(), this.getBasicParamsList(), this.getTerminalList())
                uni.hideLoading()
            } catch (error) {
                uni.hideLoading()
            }
        },
        async getAircraftNumbers() {
            const res = await getAircraftNumbersApi({})
            if (res.code == 200) {
                this.selectList.deviceNumSelect = res.data
            }
        },
        async getTerminalList() {
            const res = await getTerminalListApi({ pageSize: 100, pageIndex: 1 })
            if (res.code == 200) {
                this.selectList.terminalSelect = res.data.list
            }
        },
        async getBasicParamsList() {
            const res = await getBasicParamsListApi({})
            if (res.code == 200) {
                this.allBasicParams = res.data.reduce((q, w) => {
                    if (!q[w.paramType]) {
                        q[w.paramType] = []
                    }
                    q[w.paramType].push(w)
                    return q
                }, {})
            }
        },
        getParamsByType(paramType) {
            return this.allBasicParams[paramType]
                ?.filter((item) => item.isDel == 0)
                ?.map((item) => {
                    return { label: item.paramName, value: item.paramCode }
                })
        },
        getParamNameByValue(paramType, paramName) {
            return this.getParamsByType(paramType).find((item) => item.value == paramName)?.label || ''
        }
    },
    // 配置持久化
    persist: {
        // 调整为兼容多端的API
        storage: {
            setItem(key, value) {
                uni.setStorageSync(key, value)
            },
            getItem(key) {
                return uni.getStorageSync(key)
            }
        }
    }
})
export default useBaseStore
