import pinia from '~src/store/init'
import { useAppStore } from '~src/store'
import { getButtons } from '~api/menu'
import projectApi from '~api/project'
import router from '~src/router/index'
import { getStoreValue } from '~src/utils/storage'
import { ArrToOneObj, getArrValue, getObjVal, getObjValue, isNullES } from 'js-fast-way'

const store = useAppStore(pinia)

//项目合同段初始化
export const initProjectContract = async () => {
    const value = getStoreValue('projectContract')
    if (!value || value.length <= 0) {
        const { error, data } = await getProjectContract()
        if (error) return Promise.reject('error')
        return Promise.resolve(data)
    } else {
        return Promise.resolve(value)
    }
}

//获取默认项目信息
export const getProjectContract = async () => {
    const { error, data } = await projectApi.getProjectAndContract()
    let projectList = await getProjectArr(error, data)
    if (projectList.length <= 0) {
        return { error: true, data: [] }
    }
    //获取缓存的项目合同段数据
    const isStore = await getStoreProjecInfo(projectList)
    if (!isStore) {
        const isDefault = await getDefaultProject(projectList)
        if (!isDefault) return { error: true, data: [] }
    }
    //获取按钮权限
    await initButtons()
    //返回数据
    return { error: false, data: projectList }
}

//根据缓存获取项目合同段数据
const getStoreProjecInfo = async (arr) => {
    const projectId = store.projectId //项目ID
    const contractId = store.contractId //合同段ID
    //查询缓存的选中ID是否存在
    const pid = arr.findIndex(item => Number(item.id) === Number(projectId))
    const contractList = getArrValue(arr[pid]?.contractInfoList)
    const cid = contractList.findIndex(item => Number(item.id) === Number(contractId))
    //如果缓存的选中ID不存在
    if (cid === -1) {
        return false
    }
    //获取项目合同段数据
    const projectInfo = await getProjectInfo(projectId)
    const contractInfo = await getContractInfo(contractId)
    if (isNullES(projectInfo) || isNullES(contractInfo)) {
        return false
    }
    setProjectStore(projectInfo, contractInfo)
    return true
}

//获取默认项目信息
const getDefaultProject = async (projectList) => {
    const { error, status, data } = await projectApi.getDefaultProject()
    if (!error && status === 200 && !isNullES(data)) {
        const { projectId, contractId } = getObjValue(data)
        if (!projectId || !contractId) {
            return false
        }
        const projectInfo = await getProjectInfo(projectId)
        const contractInfo = await getContractInfo(contractId)
        if (isNullES(projectInfo) || isNullES(contractInfo)) {
            return false
        }
        setProjectStore(projectInfo, contractInfo)
        return true
    }
    //获取第一个项目的第一个合同段数据
    const contractList = getArrValue(projectList[0]?.contractInfoList)
    const projectInfo = projectList[0]
    const contractInfo = contractList[0]
    //缓存数据
    setProjectStore(projectInfo, contractInfo)
    return true
}

//缓存数据
const setProjectStore = (project, contract) => {
    store.setProjectInfo(project)
    store.setProjectId(project.id)
    store.setContractInfo(contract)
    store.setContractId(contract.id)
}

const getProjectArr = async (error, data) => {
    let projectList = getArrValue(data)
    if (error || projectList.length <= 0) {
        window.$messageBox.alert('您账户下还没有任何项目，请先联系管理员给你配置相关项目', '登录失败')
        router.push({ path: '/login-main' })
        return []
    }
    //处理合同段的别名
    projectList.forEach(item => {
        item['name'] = item['projectName']
        let contractArr = item['contractInfoList'] || []
        contractArr.forEach(items => {
            items['projectAlias'] = items['name']
        })
    })
    //过滤空合同段的项目合同段数据
    const projectArr = projectList.filter(({ contractInfoList }) => {
        const contractList = getArrValue(contractInfoList)
        return contractList.length > 0
    })
    if (projectArr.length <= 0) {
        window.$messageBox.alert('您账户下还没有任何项目，请先联系管理员给你配置相关项目', '登录失败')
        router.push({ path: '/login-main' })
        return []
    }
    store.setProjectContract(projectArr)
    //返回数据
    return projectArr
}

//获取项目信息
const getProjectInfo = async (projectId) => {
    const { data } = await projectApi.getProjectInfo(projectId)
    const item = getObjValue(data)
    item['name'] = item['projectName']
    return item
}

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

//按钮初始化
export const initButtons = async () => {
    const value = getStoreValue('buttons')
    if (!getObjVal(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
}
