import { login, logout, getInfo } from "@/api/acl/user";
import { getToken, setToken, removeToken } from "@/utils/auth";
import { resetRouter } from "@/router";
import router from "@/router";
import api from "@/api/api";
import Layout from "@/layout";
const getDefaultState = () => {
  return {
    token: "",
    userName: "",
    headImage: "",
    userType: "",
    telPhone: "",
    time: new Date(),
    avatar: "",
    roles: [],
    statRoutes: [
      {
        path: "/",
        name: "Layout",
        redirect: "/login",
        alwaysShow: true,
        component: Layout,
        children: [
          // {
          //     path: 'home',
          //     name: 'Home',
          //     meta: {
          //         isAuth: true,
          //         title: '主页',
          //         keepAlive: true //缓存组件
          //     },
          //     component: () => import('@/views/home'),
          // },
          {
            path: "inform",
            name: "Inform",
            meta: { isAuth: true, title: "系统通知" },
            component: () => import("@/views/inform")
          },
          {
            path: "home/ICcard",
            name: "icCard",
            meta: { isAuth: true, title: "IC卡管理" },
            component: () => import("@/views/icCard")
          },
          {
            path: "home/fingerprint",
            name: "fingerprint",
            meta: { isAuth: true, title: "指纹管理" },
            component: () => import("@/views/fingerprint")
          }
        ]
      }
    ],
    buttons: []
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: state => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },

  SET_USERINFO: (state, userInfo) => {
    state.userName = userInfo.userName;
    state.headImage = userInfo.headImage;
    state.userType = userInfo.userType;
    state.telPhone = userInfo.telPhone;
  },

  SET_ROLES: (state, roles) => {
    if (typeof roles === "string") {
      state.roles = roles.split("/");
      // console.log('roles是字符串');
    } else {
      state.roles = roles;
    }
    state.roles.forEach(item => {
      if (item == "home") {
        state.statRoutes[0].children.push({
          path: item,
          name: item,
          meta: { isAuth: true, keepAlive: true },
          component: () => import(`@/views/${item}`)
        });
      } else {
        state.statRoutes[0].children.push({
          path: item,
          name: item,
          meta: { isAuth: true },
          component: () => import(`@/views/${item}`)
        });
      }
      // router.addRoute([...state.statRoutes])
      if (item == "home") {
        router.addRoute("Layout", {
          path: item,
          name: item,
          meta: { isAuth: true, keepAlive: true },
          component: () => import(`@/views/${item}`)
        });
      } else {
        router.addRoute("Layout", {
          path: item,
          name: item,
          meta: { isAuth: true },
          component: () => import(`@/views/${item}`)
        });
      }
    });
  },
  SET_TIME: (state, time) => {
    state.time = time;
  }
};

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo;
    return new Promise((resolve, reject) => {
      api.hotelAdmin
        .hotelStaffLogin({ username: username.trim(), password: password })
        .then(response => {
          // console.log(response);
          const { data } = response;
          commit("SET_TOKEN", data.token);
          commit("SET_USERINFO", data);
          commit("SET_ROLES", data.authority);
          setToken("cook", data.token);
          setToken("user", username);
          setToken("password", password);
          // console.log("resolve")
          resolve();
        })
        .catch(error => {
          // console.log("error");
          reject(error);
        });
    });
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token)
        .then(response => {
          const { data } = response;

          if (!data) {
            reject("Verification failed, please Login again.");
          }

          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_USERINFO", data);
          resolve(data);
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // user logout
  logout({ commit, state }) {
    removeToken("cook"); // must remove  token  first
    // resetRouter()
    removeToken("user");
    removeToken("password");
    commit("RESET_STATE");
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // removeToken() // must remove  token  first
      commit("RESET_STATE");
      resolve();
    });
  },

  // set User Routes
  setUserRoutes({ commit }) {
    commit("SET_ROLES", data);
  }
};

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