import router from "@/router";

import asyncRequest from "@/apis/user";

import {
  getToken,
  setToken,
  removeToken,
  getMenu,
  setMenu,
  removeMenu,
  getBtn,
  setBtn,
  removeBtn,
  get_business_company,
  set_business_company,
  remove_business_company,
  get_business_companyNo,
  set_business_companyNo,
  remove_business_companyNo,
  get_private_field,
  set_private_field,
  remove_private_field,
  get_action_data,
  set_action_data,
  remove_action_data,
  get_role_level,
  getUserCompany,
  setUserCompany,
  removeUserCompany,
  setUserInfo as _setUserInfo,
  getUserInfo as _getUserInfo,
  removeUserInfo as _removeUserInfo,
  getCompanyType as _getCompanyType,
  setCompanyType as _setCompanyType,
  removeCompanyType as _removeCompanyType
} from '@/utils/auth'


import { MessageBox } from "element-ui";
import { convertCompanylist } from "@/utils";

export const userStoreActions = {
  reloadMenu: 'user/reloadMenulist',
  loginByToken: 'user/loginByToken',
  setCompanyList: 'user/setCompanylist',
  setCurrentLevel: 'user/setCurrentLevel',
  setCurrentCompany: 'user/setCurrentCompany'
}

const state = {
  token: getToken(),
  name: "",
  avatar: require("@/assets/img/avatar.gif"),
  introduction: "",
  roles: ["admin"],
  btnList: getBtn(),
  navList: getMenu(),
  role_level:get_role_level() || "1",
  business_company: get_business_company() || "",
  business_companyNo: get_business_companyNo() || "",
  private_field: get_private_field() || [],
  roleProcess: get_action_data() || [],
  currentCompany: getUserCompany() ? getUserCompany().code : '',
  userInfo: _getUserInfo(),
  isSupertube: false,
  companylist:[],
  originLevel: "0",
  currentLevel: "0"
};

const companyTypes = {
  'business': 'business',
  'supplier': 'supplier'
}

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);
  },
  btnListFn(state, val) {
    if (!val) {
      val = [];
    }
    state.btnList = val;
    setBtn(val);
  },

  setSupplier(state,val){
    state.isSupplier = 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);
  },
  roleProcess(state, val) {
    state.roleProcess = val;
    set_action_data(val);
  },
  private_field(state, val) {
    state.private_field = val;
    set_private_field(val);
  },

  setCurrentLevel(state, val){
    state.currentLevel = val
  },

  setOriginLevel(state, val){
    state.originLevel = val
  },

  setUserInfo(state, info){
    state.userInfo = info
    _setUserInfo(info)
  },

  setCurrentCompany(state, code){
    //获取当前公司详细信息
    const company = state.companylist.find(({code: _code}) => _code === code)
    setUserCompany(company)
    state.currentCompany = code;
  },

  setCompanyType(state, code){
    const isBusiness = code.indexOf('GS') >= 0
    state.companyType = isBusiness ? companyTypes.business : companyTypes.supplier
  },

  setCompanylist(state,val){
    state.companylist = val
  },
  setSupertube(state, val) {
    state.isSupertube = val;
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo;
    try{
      const response = await asyncRequest.login({username: username.trim(),password})
      const { code, data } = response
      if(Number(code) === 1){
        const { token } = data;
        commit('SET_TOKEN',token)
        setToken(token)
      }
      return response
    }catch (err){
      throw err
    }
  },
    // user login
    async mobileLogin({ commit }, userInfo) {
      try{
        const response = await asyncRequest.mobileLogin(userInfo)
        const { code, data } = response
        if(Number(code) === 1){
          const { token } = data;
          commit('SET_TOKEN',token)
          setToken(token)
        }
        return response
      }catch (err){
        throw err
      }
    },

  dingUserInfor({ commit }, code) {
    return new Promise(async (resolve, reject) => {
      asyncRequest.dingdingdetail(code)
        .then((response) => {
          const { data } = response;
          if (response.code === 0) {
            commit("SET_TOKEN", data.token);
            setToken(data.token);
            resolve("success");
          } else {
            resolve("error");
          }
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  async loginByToken({commit, dispatch}, token) {
    setToken(token)
    await commit('SET_TOKEN')
    await dispatch('getMenuList')
  },

  async getRoleInfo({commit, that, dispatch}, _current_company_){
    return new Promise(async resolve => {
      //查找默认的业务公司 设置到全局的currentCompany
      const { roleid } = _current_company_;

      //根据角色获取流程节点权限
      const { pcode, pdata, pmsg } = await asyncRequest.getRoleProcess(roleid);
      if (pcode === 0) {
        commit("roleProcess", pdata ?? []);
      }
      if (pcode >= 100 && pcode <= 104) {
        resolve("noToken");
        return
      }
      //根据角色获取角色详情 获取关键字字段
      const {code: rcode, data: rdata, message: rmsg} = await asyncRequest.reuqsetRoleInfo({ roleid: roleid })

      if(rcode === 0){
        commit("private_field", rdata.private_field ? rdata.private_field.split(',') : []);
      }

      if (rcode >= 100 && rcode <= 104) {
        resolve("noToken");
        return
      }
    })
  },

  async getMenuList({ commit, that, dispatch }) {
    return new Promise(async (resolve) => {
      const isok = false
      if (!getToken()) {
        resolve("noToken");
      } else {
        const { ucode, udata, umsg } = await getUserInfo({});
        if (ucode === 101) {
          resolve("noToken");
        } else if (ucode !== 1) {
          resolve({ code: ucode, data: udata, massage: umsg })
        } else {
            const { menus, btnList } = convertMenus(udata.action); // TODO..
            
            commit("setUserInfo", udata)
            // 生成页面权限
            commit("navListFn", menus);
            // 生成按钮权限
             commit("btnListFn", btnList);
            // 生成路由
            initRouter(menus, that);
            resolve(isok ? "success-dataV" : "success");
          }
      }
    });
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_MENU", "");
      commit("SET_HAS", "");
      _removeUserInfo()
      removeBtn();
      removeMenu();
      removeToken();
      remove_business_company();
      commit("business_company", "");
      commit("business_companyNo", "");
      remove_business_companyNo();
      remove_private_field();
      commit("private_field", []);
      remove_action_data();
      commit("action_data", []);
      removeUserCompany()
      commit("action_data", []);
      // removeMainList()
      // 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 getUserInfo() {
  const { code, data, msg } = await asyncRequest.usergetinfo({
    token:getToken()
  });

  return {
    ucode: code,
    udata: data,
    umsg: msg,
  };
}

function convertMenus(_list){
  const arrag = []

  let btnList = [];
  let list = [];
    list = _list.filter((item) => item.children && item.children.length > 0);
    console.log(_list)
    list.forEach((v1) => {
      const { menu_route, children } = v1;
      if (menu_route === "bigScreen" && children.length) {
        isok = true;
      }
      let pItem = {
        name: v1.menu_route,
        path: `/${v1.menu_route}`,
        meta: {
          title: v1.menu_name,
          icon: v1.menu_img,
        },
        children: [],
      };
      v1.children.forEach((v2) => {
        let item = {
          path: v2.menu_route,
          name: v2.menu_route,
          hidden: parseInt(v2.is_private + "") === 0,
          meta: {
            title: v2.menu_name,
            icon: v2.menu_img,
          },
          url: v2.menu_url,
        };
        let model = {
          menu_route: v2.menu_route,
          action: v2.action,
        };
        btnList.push(model);
        pItem.children.push(item);
      });

      arrag.push(pItem);
    });

  return {
      menus:arrag,
      btnList,
  };
}


// async function getRoleMenuList(level = "") {
//   const { code, data, msg } = await asyncRequest.requestMenus({})

  
// }

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-phone",
          component: () => import("@/views/person-infor/change-phone"),
          name: "ChangePhone",
          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:'/reload',
          component:() => import('@/views/reload/index')
        }
      ],
    },
    //欢迎页
    {
      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: "/welcome/dashboard",
  })


  window.vm.$router.addRoutes(IndexRoute);
}

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