import { login, usergetinfo } from "@/apis/user";
import configRouter from "@/router/data";
import {
  getToken,
  setToken,
  removeToken,
  getMenu,
  setMenu,
  removeMenu,
  getBtn,
  get_company_list,
  set_company_list,
  remove_company_list,
  get_business_company,
  set_business_company,
  remove_business_company,
  get_business_companyNo,
  set_business_companyNo,
  remove_business_companyNo,
} from "@/utils/auth";
const state = {
  token: getToken(),
  name: "",
  avatar: require("@/assets/img/avatar.gif"),
  introduction: "",
  roles: ["admin"],
  btnList: getBtn(),
  navList: getMenu(),
  company_list: get_company_list() || [],
  business_company: get_business_company() || "",
  business_companyNo: get_business_companyNo() || "",
};
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_MENU: (state, menu) => {
    state.menu = menu;
  },
  SET_HAS: (state, has) => {
    state.has = has;
  },
  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;
  },
  navListFn(state, val) {
    if (!val) {
      val = [];
    }
    state.navList = val;
    setMenu(val);
  },
  business_company(state, val) {
    state.business_company = val;
    set_business_company(val);
  },
  business_companyNo(state, val) {
    state.business_companyNo = val;
    set_business_companyNo(val);
  },
  company_list(state, val) {
    state.company_list = val;
    set_company_list(val);
  },
};

const actions = {
  change_company({ commit }, companyInfo) {
    const { supplierNo, supplierName } = companyInfo ?? {};
    return new Promise((resolve, reject) => {
      // 保存默认业务公司名称
      commit("business_company", supplierName);
      // 保存默认业务公司编号
      commit("business_companyNo", supplierNo);
      resolve("ok");
    });
  },
  // user login
  login({ commit }, userInfo) {
    const { mobile, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ mobile: mobile.trim(), password: password })
        .then((response) => {
          const { code, data, message } = response;

          if (code === 0) {
            const { token, supplier_list } = data ?? {};
            const arr = supplier_list.filter(
              (item) => item.status + "" === "1"
            );
            if (arr && arr.length > 0) {
              commit("SET_TOKEN", token);
              // 保存默认业务公司名称
              commit("company_list", supplier_list);

              const { supplierName, supplierNo } = arr[0];
              // 保存默认业务公司名称
              commit("business_company", supplierName);
              // 保存默认业务公司编号
              commit("business_companyNo", supplierNo);
              setToken(token);
              resolve({
                code: 0,
                message: message,
              });
            } else {
              resolve({
                code: 1,
                message:
                  supplier_list.length === 0
                    ? "该账户未绑定公司，不允许登录！"
                    : "该账户绑定的公司已禁用，不允许登录！",
              });
            }
          } else {
            resolve({
              code: 2,
              message: message,
            });
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  // user login
  login({ commit }, userInfo) {
    const { mobile, password } = userInfo;
    return new Promise((resolve, reject) => {
      login({ mobile: mobile.trim(), password: password })
        .then((response) => {
          const { code, data, message } = response;

          if (code === 0) {
            const { token } = data ?? {};
            setToken(token);
            commit("SET_TOKEN", token);
            resolve({
              code: 0,
              message: message,
            });
          } else {
            resolve({
              code: 2,
              message: message,
            });
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },
  async getMenuList({ commit, that }) {
    return new Promise(async (resolve, reject) => {
      if (!getToken()) {
        resolve("noToken");
      } else {
        const { ucode, udata, umsg } = await getUserInfo();
        console.log(ucode);
        if (ucode >= 101 && ucode <= 104) {
          resolve("noToken");
        } else if (ucode !== 0) {
          resolve({ code: ucode, data: udata, massage: umsg });
        } else {
          const { supplier_list } = udata;
          const arr = supplier_list.filter((item) => item.status + "" === "1");
          if (arr && arr.length > 0) {
            // 保存默认业务公司名称
            commit("company_list", supplier_list);

            const { supplierName, supplierNo } = arr[0];
            // 保存默认业务公司名称
            commit("business_company", supplierName);
            // 保存默认业务公司编号
            commit("business_companyNo", supplierNo);
            const { mcode, mdata, mmsg } = await getRoleMenuList();
            console.log(mdata);
            if (mcode >= 101 && mcode <= 104) {
              resolve("noToken");
            } else if (mcode !== 0) {
              resolve({ code: mcode, data: {}, massage: mmsg });
            } else {
              const { arrag } = mdata;
              // 生成页面权限
              commit("navListFn", arrag);
              // 生成路由
              initRouter(arrag, that);
              // state.commit("loginInfoCommit", res.data);
              resolve("success");
            }
          } else {
            resolve(supplier_list.length === 0 ? "notlist" : "notPowers");
          }
        }
      }
    });
  },

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

      removeMenu();
      remove_business_company();
      commit("business_company", "");
      commit("business_companyNo", "");
      remove_business_companyNo();
      commit("company_list", []);
      remove_company_list();
      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch("tagsView/delAllViews", null, { root: true });
      resolve();
    });
  },

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

async function getRoleMenuList() {
  let arrag = [];
  let list = [];

  list = configRouter;
  console.log(configRouter);
  list = list.filter((item) => item.child && item.child.length > 0);
  list.forEach((v1) => {
    const pItem = {
      name: v1.menu_route,
      path: `/${v1.menu_route}`,
      hidden: v1.hidden,
      alwaysShow: v1.alwaysShow,
      meta: {
        title: v1.menu_name,
        icon: v1.menu_img,
      },
      children: [],
    };
    v1.child.forEach((v2) => {
      const item = {
        path: v2.menu_route,
        name: v2.menu_route,
        hidden: parseInt(v2.is_display + "") === 0,
        alwaysShow: v2.alwaysShow,
        meta: {
          title: v2.menu_name,
          icon: v2.menu_img,
          noCache: v2.noCache,
          breadcrumb: v2.breadcrumb,
        },
        url: v2.menu_url,
      };
      pItem.children.push(item);
    });
    arrag.push(pItem);
  });
  return {
    mcode: 0,
    mdata: {
      arrag,
    },
    mmsg: "",
  };
}

function initRouter(arr) {
  const IndexRoute = [
    // // 个人信息
    // {
    //   path: "/person",
    //   component: () => import("@/layout/index"),
    //   redirect: "/person/my-message",
    //   hidden: true,
    //   alwaysShow: true,
    //   meta: {
    //     title: "个人中心",
    //     icon: "user",
    //   },
    //   children: [
    //     {
    //       path: "my-message",
    //       component: () => import("@/views/person-infor/my-message"),
    //       name: "MyMessage",
    //       alwaysShow: true,
    //       meta: { title: "我的信息", noCache: true, breadcrumb: true },
    //     },
    //     {
    //       path: "change-password",
    //       component: () => import("@/views/person-infor/change-password"),
    //       name: "ChangePassword",
    //       alwaysShow: true,
    //       meta: { title: "修改密码", noCache: true, breadcrumb: true },
    //     },
    //   ],
    // },
    // //欢迎页
    // {
    //   path: "/welcome",
    //   component: () => import("@/layout/index"),
    //   redirect: "/welcome/dashboard",
    //   children: [
    //     {
    //       path: "dashboard",
    //       component: () => import("@/views/dashboard/index"),
    //       name: "Dashboard",
    //       meta: { title: "首页", icon: "dashboard", affix: true },
    //     },
    //   ],
    // },
  ];

  arr.map((v1) => {
    v1.component = (resolve) => require([`@/layout/index.vue`], resolve);
    if (v1.children && v1.children.length > 0) {
      v1.redirect = `/${v1.name}/${v1.children[0].name}`;
      v1.children.map((v2) => {
        v2.component = (resolve) => require([`@/views/${v2.url}.vue`], resolve);
        return v2;
      });
    }
    return v1;
  });
  IndexRoute.push(...arr);
  IndexRoute.push({
    path: "404",
    component: () => import("@/views/error-page/404"),
    hidden: false,
    noCache: true,
  });

  IndexRoute.push({
    path: "*",
    redirect: "/404",
  });
  window.vm.$router.addRoutes(IndexRoute);
}
async function getUserInfo() {
  const { code, data, meaasge } = await usergetinfo({});
  return {
    ucode: code,
    udata: data,
    umsg: meaasge,
  };
}
export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
