import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import { proof } from './modules/proof';
import { template } from './modules/template';
export default new Vuex.Store({
  state: {
    isLogin: false,
    isLogin2: null,
    isSetPwd: 0, // 0 未设置 1 已设置
    userInfo: {
      phone: '',
      icon: '',
      email: '',
      auth_type: 0,
    },
    authInfo: {}, // 个人认证信息
    companyAuthInfo: {}, // 企业认证信息
  },
  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;
      state.isLogin2 = 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;
    },
    save(state: any, payload) {
      Object.assign(state, payload);
    },
    clearAuthInfo(state: any) {
      state.authInfo = {};
    },
  },
  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);
        });
    },
    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 }) {
      return Vue.prototype.$api.auth.get().then((res: any) => {
        commit('updateAuthInfo', res);
      });
    },
    getCompanyAuthInfo({ commit }) {
      Vue.prototype.$api.auth.info().then((res: any) => {
        commit('updateCompanyAuthInfo', res);
      });
    },
  },
  modules: {
    proof,
    template,
  },
});
