import {getPermissionsMenu} from '@/api/system';

export default {
    namespaced: true,
    state: {
        patiensInfo: sessionStorage.getItem('patiensInfo') ? JSON.parse(sessionStorage.getItem('patiensInfo')) : null, // 病人信息
        // userInfo: sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')) : {}, // 当前登录用户信息
        userInfo: sessionStorage.getItem('userinfo') ? JSON.parse(sessionStorage.getItem('userinfo')) : {}, // 当前登录用户信息
        permissions: sessionStorage.getItem('permissions') ? JSON.parse(sessionStorage.getItem('permissions')) : [], // 权限标识
        isSeeDoctor: sessionStorage.getItem('isSeeDoctor') ? sessionStorage.getItem('isSeeDoctor') : true, // 当前状态是就诊还是查看 
        preNo: sessionStorage.getItem('edit_preNo') ? sessionStorage.getItem('edit_preNo') : '', // 当前(进入)状态是修改处方还是创建处方
        outpatientDiagnosis: sessionStorage.getItem('outpatientDiagnosis') ? sessionStorage.getItem('outpatientDiagnosis') : null, // 转病例到中医诊断
        emr: sessionStorage.getItem('emrDiagnosis') ? sessionStorage.getItem('emrDiagnosis') : null // 转病历到电子病历
    },
    mutations: {
        setPatiensInfo(state, data) {
            this.commit('user/setPreNo', '')
            sessionStorage.setItem('patiensInfo', JSON.stringify(data))
            state.patiensInfo = data
        },
        setUserinfo(state, data) {
            sessionStorage.setItem('userinfo', JSON.stringify(data))
            state.userInfo = data
        },
        setPermissions(state, data) {
            sessionStorage.setItem('permissions', JSON.stringify(data));
            state.permissions = data;
        },
        setIsSee(state, data) {
            sessionStorage.setItem('isSeeDoctor', data)
            state.isSeeDoctor = data
        },
        setPreNo(state, value) {
            sessionStorage.setItem('edit_preNo', value)
            state.preNo = value
        },

        // 患者转病历
        setOutpatientDiagnosis(state, data) {
            sessionStorage.setItem('outpatientDiagnosis', data)
            state.outpatientDiagnosis = data
        },
        setEmrDiagnosis(state, data) {
            sessionStorage.setItem('emrDiagnosis', data)
            state.emr = data
        }
    },
    getters: {
        user(state) {
            return state
        }
    },
    actions: {
        async setUserinfoAndPermissions(state, data) {
            state.commit('setUserinfo', data);
            let permissions = [];
            try {
                const roles = data.roles.map(item => getPermissionsMenu({RoleID: item.roleid}).then(res => res.Data.RoleRight.split(',')).catch(() => []));
                const results = await Promise.all(roles);
                permissions = [...new Set(results.flat(1))];
            } catch (e) {}
            state.commit('setPermissions', permissions);
        },
    }
};