import tool from '../../utils/tool' import api from '@/api' export default{ state: { familyId: tool.data.get('familyId') || '', familyInfo: tool.data.get('familyInfo') || {}, isOwner: tool.data.get('isOwner') || false }, mutations:{ setFamilyInfo(state, data){ if(data && data.id){ tool.data.set('familyId', data.id) state.familyId = data.id tool.data.set('familyInfo', data) state.familyInfo = data }else{ tool.data.set('familyId', '') state.familyId = '' tool.data.set('familyInfo', {}) state.familyInfo = {} } }, setIsOwner(state, isOwner){ tool.data.set('isOwner', isOwner) state.isOwner = isOwner }, clearFamily(state){ tool.data.set('familyId', '') state.familyId = '' tool.data.set('familyInfo', {}) state.familyInfo = {} tool.data.set('isOwner', false) state.isOwner = false } }, getters:{ hasFamily(state){ return !!state.familyId } }, actions:{ async getFamilyInfo({commit}){ try { const res = await api.family.info.get() if(res.data){ commit('setFamilyInfo', res.data) commit('setIsOwner', res.data.is_owner || false) } return res }catch(e){ console.error('获取家庭信息失败', e) throw e } }, async createFamily({commit}, familyName){ try { const res = await api.family.create.post({name: familyName}) if(res.data){ commit('setFamilyInfo', res.data) commit('setIsOwner', true) } return res }catch(e){ console.error('创建家庭失败', e) throw e } }, async joinFamily({commit}, inviteCode){ try { const res = await api.family.join.post({invite_code: inviteCode}) if(res.data){ commit('setFamilyInfo', res.data) commit('setIsOwner', res.data.is_owner || false) } return res }catch(e){ console.error('加入家庭失败', e) throw e } }, async leaveFamily({commit}){ try { const res = await api.family.leave.post() if(res.code === 200){ commit('clearFamily') } return res }catch(e){ console.error('退出家庭失败', e) throw e } } } }