import Vue from 'vue'
import Vuex from 'vuex'
import login from '@/apis/login'
import user from '@/apis/user'
import common from '@/apis/common'
import tools from '@/common/tools'

Vue.use(Vuex);

export default new Vuex.Store({
  //所有的数据都放在state中
  state: {
    msgCount:0,
    cartCount:0,
    applyData: {}, //预约考试数据存放
    currentRouter:{},
    token: '',
    user_account: '',
    userInfo: null,
    examResult:{},
    header: {
      serviceTel: {}
    },//页头配置
    footer: [],//页尾配置
    links: null,//友情链接
  },

  getters: {
    userInfo: state => state.userInfo,
    token: state => state.token,
    header: state => state.header,
    footer: state => state.footer,
    links: state => state.links,
    getApplyData: state => state.applyData,
    examResult: state => state.examResult,
    currentRouter: state => state.currentRouter,
    cartCount: state => state.cartCount,
    msgCount: state => state.msgCount
  },

  //操作数据，唯一的通道是mutations
  mutations: {
    setCurrentRouter(state,data) {
      state.currentRouter = data;
    },
    setExamResult(state,data) {
      state.examResult = data;
    },
    updateApplyData(state, data) {
      state.applyData = data;
    },
    setUserInfo(state, data) {
      state.userInfo = data;
    },
    setHomeSetList(state, data) {
      data.forEach(item => {
        if (item.configKey === 'home.header') {
          state.header = JSON.parse(item.configValue)
          console.log(state.header)
        }
        if (item.configKey === 'home.footer') {
          state.footer = JSON.parse(item.configValue)
          console.log(state.footer)
        }
        if (item.configKey === 'home.links') {
          state.links = JSON.parse(item.configValue)
          console.log(state.links)
        }
      })
    },
    getCartCount(state) {
      user.cartList().then((res) => {
        state.cartCount = res.total;
      });
    },

    getMsgCount(state) {
      user.getappinformUserlist({
        systemStatusList:'1,2',
        receiptStatus: 0,
      }).then(res => {
        state.msgCount = res.total
      })
    }
  },

  //actions,可以来做异步操作，然后提交给mutations，而后再对state(数据)进行操作
  actions: {
    /**
     * 
     * @param {*} context 
     * @returns 
     * 获取用户信息
     */
    getUserInfo(context) {
      return new Promise(resolve => {
        login.getInfo().then(res => {
          context.commit('setUserInfo', res.data)
          if(!tools.getUuid()) {
            tools.setUuid(new Date().valueOf() + "")
          }
          resolve()
        }).catch(err => {})
      })
    },
    /**
     * 
     * @param {*} context 
     * @returns 
     * 获取首页配置
     */
    getCommonBaseHomeList(context) {
      return new Promise(resolve => {
        common.getCommonBaseHomeList().then(res => {
          context.commit('setHomeSetList', res.rows)
          resolve()
        })
      })
    }
  }
})