import pinia from "@/store/init"
import {useAppStore} from "@/store";
import {getStorage, setStorage} from "@/utils/storage";
import userApi from '~api/user/index';
import menuApi from '~api/menu';
import projectApi from "~api/user/project";
import {setToken, setRefreshToken} from '@/httpApi/util/auth';
import {getArrValue, getObjVal, getObjValue, isNullES, ArrToOneObj} from "js-fast-way";

const store = useAppStore(pinia)

//账号密码登录
export const userLogin = async (form) => {
    console.log(form,'form');
    const {error, status, res, response, message} = await userApi.userLogin(form);
    if (!error && status === 200) {
        //设置全局状态
        const {access_token, refresh_token, tenant_id} = res;
        setToken(access_token)
        setRefreshToken(refresh_token)
        store.setTenantId(tenant_id)
        store.setUserInfo(res)
        //设置登录信息的缓存
        setStorage('login_user_info', {
            tenantId: tenant_id,
            username: form.username,
            password: form.password,
            type: form.type
        });
        //await getProjectContract()
        return Promise.resolve(res);
    } else {
        uni.showToast({title: message, icon: 'error'});
        return Promise.reject({msg: message, res: response});
    }
}

//获取默认项目信息
export const getProjectContract = async () => {
    const { error, data } = await projectApi.getProjectAndContract()
    const projectList = getArrValue(data)
    if (error || projectList.length <= 0) {
        uni.showToast({title: '没有相关项目权限', icon: 'error'});
        return false
    }
    //获取默认项目合同段数据
    const defaultProject = await getDefaultProject()
    let projectInfo = {}, contractInfo = {}
    if (defaultProject.code === 200) {
        projectInfo = defaultProject.project
        contractInfo = defaultProject.contract
    } else {
        //过滤空合同段的项目合同段数据
        const projectArr = projectList.filter(({contractInfoList}) => {
            const contractList = getArrValue(contractInfoList)
            return contractList.length > 0
        })
        if (projectArr.length <= 0) {
            uni.showToast({title: '没有相关项目权限', icon: 'error'});
            return false
        }
        //获取第一个项目的第一个合同段数据
        const contractList = projectArr[0].contractInfoList
        projectInfo = projectList[0]
        contractInfo = contractList[0]
    }
    //获取按钮权限
    await initButtons()
    //设置项目合同段数据
    store.setProjectInfo(projectInfo)
    store.setProjectId(projectInfo.id)
    store.setContractInfo(contractInfo)
    store.setContractId(contractInfo.id)
    return true
}

//获取默认项目信息
const getDefaultProject = async () => {
    const {error, status, data} = await projectApi.getDefaultProject()
    if (!error && status === 200 && !isNullES(data)) {
        const {projectId, contractId} = getObjValue(data)
        if (!projectId || !contractId) {
            return {code: 300}
        }
        const projectInfo =  await getProjectInfo(projectId)
        const contractInfo =  await getContractInfo(contractId)
        if (isNullES(projectInfo) || isNullES(contractInfo)) {
            return {code: 300}
        }
        return {code: 200, project: projectInfo, contract: contractInfo}
    } else {
        return {code: 300}
    }
}

//获取项目信息
const getProjectInfo = async (projectId) => {
    const {data} = await projectApi.getProjectInfo(projectId)
    return getObjValue(data)
}

//获取合同段信息
const getContractInfo = async (contractId) => {
    const {data} = await projectApi.getContractInfo(contractId)
    return getObjValue(data)
}


//按钮初始化
export const initButtons = async () => {
    const value = getStorage('buttons')
    if (!value) {
        const { error, data } = await menuApi.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
}
