import pinia from "~src/store/init"
import {useAppStore} from "~src/store";
import {getButtons} from '~api/menu';
import {getProjectAndContract} from '~api/user';
import {getStoreValue} from '~src/utils/storage'
import {ArrToOneObj, getArrValue} from "js-fast-way"

const store = useAppStore(pinia)

//项目合同段初始化
export const initProjectContract = async () => {
    const value = getStoreValue('projectContract')
    if (!value) {
        const {error, data} = await getProjectAndContract();
        if (error) return Promise.reject('error');
        const datas = getArrValue(data)
        store.setProjectContract(datas)
        return Promise.resolve(data);
    } else {
        return Promise.resolve(value);
    }
}

//按钮初始化
export const initButtons = async () => {
    const value = getStoreValue('buttons')
    if (!value) {
        const {error, data} = await getButtons();
        if (error) return Promise.reject('error');
        const buttons = getArrValue(data)
        const buttonsArr = await setButtonsData(buttons)
        store.setButtons(buttonsArr)
        return Promise.resolve(true);
    } else {
        return Promise.resolve(true);
    }
}

//设置按钮
const setButtonsData = async (data) => {
    let buttonsArr = {};
    await ArrToOneObj(data, 'code', buttonsArr)
    return buttonsArr;
}
