// eslint-disable-next-line no-unused-vars
import { login, logout, getInfo } from "@/api/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";

const state = {
  token: getToken(),
  name: "",
  rolename: "",
  avatar: "",
  introduction: "",
  roles: [],
  role: 0,
  userInfo: {},
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_ROLE: (state, role) => {
    state.role = role;
  },
  SET_ROLENAME: (state, name) => {
    state.rolename = name;
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo;
  },
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    console.log(123);
    const { account_name: username, password } = userInfo;
    console.log(223, userInfo);
    return new Promise((resolve, reject) => {
      console.log(323, login);
      login({ username: username.trim(), password: password })
        .then((response) => {
          console.log(423);
          const { d } = response;
          // console.log(d)
          commit("SET_TOKEN", d);
          setToken(d);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    let tmp = {
      c: 200,
      m: null,
      d: {
        id: "1460521822741229570",
        createDate: null,
        lastUpdateDate: null,
        version: 0,
        username: "root",
        name: "管理员",
        email: "string",
        type: 0,
        status: "1",
        remark: null,
        serviceAgreementUrl: null,
      },
    };
    return new Promise((resolve, reject) => {
      // getInfo(state.token)
      //   .then((response) => {
      const { d } = tmp;

      // if (!data) {
      //   reject('Verification failed, please Login again.')
      // }

      // const { roles, name, avatar, introduction } = data
      const { avatar, name, username, type } = d;
      // d.roles = [username === 'root' ? 'root' : type]
      d.roles = [type];
      // let { role_type } = data
      // if (from_id === 7 && role_type === 2) {
      //   role_type = 1
      // }
      // const { role_name } = role
      // data.roles = [role_type]
      // const { roles } = data

      // roles must be a non-empty array
      // if (!roles || roles.length <= 0) {
      //   reject('getInfo: roles must be a non-null array!')
      // }

      // commit('SET_ROLES', roles)
      commit("SET_ROLES", d.roles);
      // commit('SET_ROLE', role_type)
      commit("SET_NAME", name);
      // commit('SET_ROLENAME', role_name)
      commit("SET_AVATAR", avatar);
      commit("SET_USERINFO", d);
      resolve(d);
    });
    // .catch((error) => {
    //   reject(error);
    //     });
    // });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // logout(state.token).then(() => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resetRouter();

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch("tagsView/delAllViews", null, { root: true });

      resolve();
      // }).catch(error => {
      //   reject(error)
      // })
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + "-token";

    commit("SET_TOKEN", token);
    setToken(token);

    const { roles } = await dispatch("getInfo");

    resetRouter();

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch("permission/generateRoutes", roles, {
      root: true,
    });
    // dynamically add accessible routes
    router.addRoutes(accessRoutes);

    // reset visited views and cached views
    dispatch("tagsView/delAllViews", null, { root: true });
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
