import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    isLogin: false,
    isSetPwd: 0, // 0 未设置 1 已设置
    userInfo: {
      phone: '',
      icon: '',
      email: '',
      auth_type: 0,
    },
    authInfo: {}, // 个人认证信息
    companyAuthInfo: {}, // 企业认证信息
    proofCount: 0,
    sysTemplateList: [],
  },
  getters: {
    isPhone( { userInfo }) {
      return userInfo.phone;
    },
    isPhoneStr( { userInfo }) {
      return userInfo.phone ? '手机号' : '邮箱';
    },
    userIcon( {userInfo} ) {
      if (userInfo.icon) {
        return userInfo.icon;
      }
      return require('@/assets/defaultusericon.png');
    },
  },
  mutations: {
    updateIsLogin(state: any, payLoad: any) {
      state.isLogin = payLoad;
    },
    updateUserInfo(state: any, payLoad: any) {
      state.userInfo  = {...state.userInfo, ...payLoad};
    },
    updateIsSetPwd(state: any, payLoad: any) {
      state.isSetPwd = payLoad;
    },
    updateAuthInfo(state: any, payload: any) {
      state.authInfo = payload;
    },
    updateCompanyAuthInfo(state: any, payload: any) {
      state.companyAuthInfo = payload;
    },
    updateProofCount(state: any, payload: any) {
      state.proofCount = payload;
    },
    updateSysTemplateList(state: any, payload: any) {
      state.sysTemplateList = payload || [];
    },
  },
  actions: {
    getUserInfo({ commit }) {
        Vue.prototype.$api.user.getUserInfo().then((res: any) => {
          commit('updateUserInfo', res);
          commit('updateIsLogin', true);
        }).catch((err: any) => {
          commit('updateUserInfo', {});
          commit('updateIsLogin', false);
        });
    },
    getProofCount( { commit } ) {
      Vue.prototype.$api.proof.count().then((res: any) => {
        commit('updateProofCount', res.total);
      }).catch((err: any) => {
        commit('updateProofCount', 0);
      });
    },
    isSetPwd({ commit , state}) {
      const { phone, email } = state.userInfo;
      Vue.prototype.$api.user.isSetPwd({phone , email}).then((res: any) => {
        commit('updateIsSetPwd', res.is_set_pwd);
      }).catch((err: any) => {
        commit('updateIsSetPwd', 0);
      });
    },
    setPwd(context: any) {
      Vue.prototype.$api.user.setPwd();
    },
    getAuthInfo({ commit }) {
      Vue.prototype.$api.auth.get().then((res: any) => {
        commit('updateAuthInfo', res);
      });
    },
    getCompanyAuthInfo({ commit }) {
      Vue.prototype.$api.auth.info().then((res: any) => {
        commit('updateCompanyAuthInfo', res);
      });
    },
    getSysTemplateList({ commit, state }) {
      if (state.sysTemplateList.length <= 0) {
        Vue.prototype.$api.template.systemList().then(({results = []}) => {
          commit('updateSysTemplateList', results);
        });
      }
    },
  },
  modules: {
  },
});
