import { login, logout, getInfo, refreshToken, ddlogin, selectCompany } from "@/api/login";
import { getToken, setToken, setExpiresIn, removeToken, removeCompanyId, setCompanyId } from "@/utils/auth";

const user = {
  state: {
    userId: null,
    token: getToken(),
    account: '',
    phone: '',
    name: "",
    avatar: "",
    permissions: [],
    companyList: []
  },

  mutations: {
    LOGIN: (state, loginInfo) => {
      state.token = loginInfo.token;
      state.userId = loginInfo.userInfo.userId;
      state.account = loginInfo.userInfo.account;
      state.phone = loginInfo.userInfo.phone;
      state.name = loginInfo.userInfo.nickname;
      state.avatar = loginInfo.userInfo.avatar ? process.env.VUE_APP_BASE_API + loginInfo.userInfo.avatar : require("@/assets/image/profile.jpg")
      state.companyList = loginInfo.companyRelationInfo || []
    },
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_EXPIRES_IN: (state, time) => {
      state.expires_in = time;
    },
    SET_NAME: (state, name) => {
      state.name = name;
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles;
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions;
    },
    SET_COMPANYLIST: (state, companyList) => {
      state.companyList = companyList;
    }
  },

  actions: {
    // 登录
    Login({ commit }, userInfo) {
      const phone = userInfo.phone.trim();
      const code = userInfo.code;
      return new Promise((resolve, reject) => {
        login(phone, code).then(res => {
          let data = res.data;
          setToken(data.token);
          commit("LOGIN", data);
          setExpiresIn(7200);
          commit("SET_EXPIRES_IN", 7200);
          if(data.companyRelationInfo && data.companyRelationInfo.length === 1) {
            resolve(data.companyRelationInfo[0].companyId);
          } else {
            resolve();
          }
        }).catch(error => {
          reject(error);
        });
      });
    },
    // 钉钉登录
    DingDingLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        ddlogin(userInfo).then(res => {
          let data = res.data;
          setToken(data.token);
          commit("LOGIN", data);
          setExpiresIn(7200);
          commit("SET_EXPIRES_IN", 7200);
          if(data.companyRelationInfo && data.companyRelationInfo.length === 1) {
            resolve(data.companyRelationInfo[0].companyId);
          } else {
            resolve();
          }
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 选择公司
    SelectCom({ commit }, companyId) {
      return new Promise((resolve, reject) => {
        selectCompany(companyId).then(res => {
          let data = res.data;
          setToken(data.token);
          commit("LOGIN", data);
          setExpiresIn(7200);
          commit("SET_EXPIRES_IN", 7200);
          setCompanyId(data.onlineCompanyId)
          resolve();
        }).catch(error => {
          reject(error);
        });
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(res => {
            commit("LOGIN", res.data);
            resolve(res);
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ROLES", []);
            commit("SET_PERMISSIONS", []);
            commit("SET_COMPANYLIST", [])
            removeToken();
            removeCompanyId();
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_TOKEN", "");
        removeToken();
        removeCompanyId();
        resolve();
      });
    },

    SetToken({ commit, dispatch }, token) {
      return new Promise(resolve => {
        setToken(token)
        commit('SET_TOKEN', token)
        dispatch('GetInfo')
        resolve();
      })
    }
  }
};

export default user;