import {readItems,readMe} from '@directus/sdk';

const sessionStorageUser = sessionStorage.getItem('user')?JSON.parse(sessionStorage.getItem('user')):{}
export default {
    namespaced: true,
    state: {
        isLogin: sessionStorageUser.isLogin || false,
        module:sessionStorageUser.module || {},
        corporate_customer:sessionStorageUser.corporate_customer || null,
        user_info:sessionStorageUser.user_info || null,
        role:sessionStorageUser.role || null,
        current_corporate_customer:sessionStorageUser.current_corporate_customer || null,
        current_corporate_customer_name:sessionStorageUser.current_corporate_customer_name || null,

    },
    actions: {
        async login({rootState, commit, dispatch}, {email,password}){
            const client = rootState.directus.client
            await client.login(email, password);
            commit("isLogin",true)
        },
        async logout({rootState, commit, dispatch}, ){
            const client = rootState.directus.client
            await client.logout()
            commit('isLogin',false)
        },
        async getUserInfo({rootState, commit, dispatch}){
            const client = rootState.directus.client
            const result = await client.request(readMe({
                fields:["*","corporate_customer.*"]
            }))
            commit("user_info",result)
            commit("current_corporate_customer",result.corporate_customer?result.corporate_customer.id:null)
            commit("current_corporate_customer_name",result.corporate_customer?result.corporate_customer.name:'請選擇公司')
            commit("role",result.role)
        },
        async getCorporateList({state,rootState, commit, dispatch}){
            const client = rootState.directus.client
            const result = await client.request(readItems('corporate_customer'))
            commit('corporate_customer',result)
        },
        async setCorporateCustomerName({rootState, commit, dispatch},id){
            commit("current_corporate_customer",id)
            rootState.user.corporate_customer.forEach((item)=>{
                if(item.id == id)
                    commit("current_corporate_customer_name",item.name)
            })
        }

    },
    mutations: {
        user_info(state,val){
            state.user_info = val
        },
        isLogin(state,val){
            state.isLogin = val
        },
        corporate_customer(state,val){
            state.corporate_customer = val
        },
        current_corporate_customer(state,val){
            state.current_corporate_customer = val
        },
        current_corporate_customer_name(state,val){
            state.current_corporate_customer_name = val
        },
        role(state,val){
            state.role = val
        }
    },
    getters: {}
}
