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

const store = useAppStore(pinia)

//账号密码登录
export const userLogin = async (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 {
        return Promise.reject({
            msg: message,
            res: response
        });
    }
}

//获取默认项目信息
export const getProjectContract = async () => {
    const {error, status, data} = await projectApi.getDefaultProject()
    if (!error && status === 200) {
        store.setProjectId(data.projectId)
        store.setContractId(data.contractId)
        //获取项目详情
        await getProjectInfo(data.projectId)
        await getContractInfo(data.contractId)
    }
}

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

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