import { loginByUsername, loginByPhone, sendSMS, logout } from "@/api/login";
// import { removeKeyToken, setKeyToken } from "@/auth/auth";
import { omit } from "lodash-es";
import { LOGIN_BY_USERNAME, LOGIN_BY_PHONE, SEND_SMS } from "../action-types";

const user = {
  state: {
    accountType: "LOGIN_NAME",
    datasetId: null,
    loginName: "",
    name: "",
    partitionId: null,
    roleList: null,
    smsSendDate: null,
  },

  mutations: {
    SET_USER: (state, user) => {
      // state.user = user;
      if (user && user.datasetId === -1) {
        user.datasetId = null;
      }
      state = Object.assign(state, user);
    },
    SET_SMS_SEND_DATE: (state, date) => {
      state = Object.assign(state, { smsSendDate: date });
    },
  },

  actions: {
    // 用户名登录
    [LOGIN_BY_USERNAME]({ commit }, userInfo) {
      return loginByUsername(userInfo).then(response => {
        const data = response.data;
        commit("SET_USER", omit(data.accessAdminUser, ["token", "uid"]));
        // setKeyToken(response.data.accessAdminUser);
      });
    },
    [LOGIN_BY_PHONE]({ commit }, userInfo) {
      return loginByPhone(userInfo).then(response => {
        const data = response.data;
        commit("SET_USER", omit(data.accessAdminUser, ["token", "uid"]));
        // setKeyToken(response.data.accessAdminUser);
      });
    },
    [SEND_SMS]({ commit }, userInfo) {
      return sendSMS(userInfo).then(() => {
        commit("SET_SMS_SEND_DATE", Date.now());
      });
    },

    // 登出
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_USER", null);
            // removeKeyToken();
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_USER", null);
        // removeKeyToken();
        resolve();
      });
    },
  },
};

export default user;
