import axios from "axios";
import router from "@/router";
import Layout from "@/layout/index.vue";
import { genFileId, ElMessage, ElMessageBox } from "element-plus";

// 声明变量
const state = {
  collapse: false,
  activeIndex: "", // 记录当前路由
  username: "",
  password: "",
  api: "/kpi/template", // 线上
  // api: "/jgcloudApi/jgcloud/api", // 测试
  roleList: [
    // {
    //   path: "homePage",
    //   name: "homePage",
    //   component: () => import("@/views/home/homePage.vue"),
    //   meta: { title: "首页", icon: "homePage" },
    // },
    // {
    //   path: "project",
    //   name: "project",
    //   component: () => import("@/views/project/project.vue"),
    //   meta: { title: "项目管理", icon: "project" },
    // },
    // {
    //   path: "role",
    //   name: "role",
    //   component: () => import("@/views/role/role.vue"),
    //   meta: { title: "角色管理", icon: "role" },
    // },
    // {
    //   path: "menu",
    //   name: "menu",
    //   component: () => import("@/views/menu/menu.vue"),
    //   meta: { title: "菜单管理", icon: "menu" },
    // },
    // {
    //   path: "user",
    //   name: "user",
    //   component: () => import("@/views/user/user.vue"),
    //   meta: { title: "用户管理", icon: "user" },
    // },
    // {
    //   path: "system",
    //   name: "system",
    //   component: () => import("@/views/system/system.vue"),
    //   meta: { title: "系统管理", icon: "system" },
    // },
  ],
  roles: [],
  hasRoutes: false,
};

// 修改变量（state不能直接赋值修改，只能通过mutations）
const mutations = {
  menuClose: (state, value) => {
    state.collapse = value;
  },
  indexUp: (state, value) => {
    sessionStorage.setItem("sidevarItem", value);
    state.activeIndex = value;
    // if (!value) {
    //   let roleId = sessionStorage.getItem("roleId");
    //   state.user.roles.forEach((item) => {
    //     if (item.roles == roleId) {
    //       state.activeIndex = `/jianguanCloud/${item.list[0]}`;
    //       sessionStorage.setItem(
    //         "sidevarItem",
    //         `/jianguanCloud/${item.list[0]}`
    //       );
    //     }
    //   });
    // } else {
    //   sessionStorage.setItem("sidevarItem", value);
    // }
  },
  SET_ROUTES_STATE: (state, value) => {
    state.hasRoutes = value;
  },
  userName: (state, value) => {
    state.username = value;
  },
  passWord: (state, value) => {
    state.password = value;
  },
  ROLELIST: async (state, value) => {
    let roleList = JSON.parse(sessionStorage.getItem("roleList"));
    console.log(roleList, "roleList");
    if (roleList) {
      // let roleList = {
      //   path: "homePage",
      //   name: "homePage",
      //   component: () => import("@/views/home/homePage.vue"),
      //   meta: { title: "首页", icon: "homePage" },
      // };
      router.addRoute({
        path: "/process",
        name: "process",
        // component: modules[`../views/${item.name}/${item.name}.vue`],
        component: Layout,
        children: [
          {
            path: "home",
            name: "home",
            component: () => import("@/views/homePage/home.vue"),
            meta: { title: "获取token页面", icon: "home" },
          },
        ],
      });
      let roles = []; // 真实拥有的菜单权限
      roleList.forEach((item) => {
        if (item.state == 1) {
          roles.push(item);
        }
        let arr = {
          path: item.url,
          name: item.url,
          meta: { title: item.menuName, icon: item.url },
          component: () => import(`../../views/${item.url}/${item.url}.vue`),
        };
        router.addRoute("process", arr);
      });
      if (roleList) {
        if (sessionStorage.getItem("sidevarItem")) {
          let sidevarItem = sessionStorage.getItem("sidevarItem");
          let flag = roles.some((i) => {
            return sidevarItem.includes(i.url);
          });
          console.log(flag);
          if(flag){
            router.push({
            path: `${sessionStorage.getItem("sidevarItem")}`,
          });
          }else{
            router.push({
              path: `/process/${roles[0].url}`,
            });
          }
        } else {
          sessionStorage.setItem("sidevarItem", `/process/${roleList[0].url}`);
          router.push({
            path: `/process/${roles[0].url}`,
          });
        }
      }
    }

    // const roleId = sessionStorage.getItem("roleId");
    // console.log(roleId);

    // if (roleId) {
    //   state.roles.forEach((item) => {
    //     if (item.roles == roleId) {
    //       // let modules = import.meta.glob("../views/**/*.vue");
    //       // router.addRoute({
    //       //   path: "/jianguanCloud",
    //       //   name: "jianguanCloud",
    //       //   // component: modules[`../views/${item.name}/${item.name}.vue`],
    //       //   component: Layout,
    //       //   children: [],
    //       // });
    //       // item.list.forEach((item) => {
    //       //   let arr = {
    //       //     path: item.name,
    //       //     name: item.name,
    //       //     // component: modules[`../views/${item.name}/${item.name}.vue`],
    //       //     component: () =>
    //       //       import(`../../views/${item.name}/${item.name}.vue`),
    //       //   };
    //       //   // state[0].roleList.children.push(arr);
    //       //   router.addRoute("jianguanCloud", arr);
    //       // });
    //     }
    //   });
    // }
  },
};
// mutations的值由actions传入(异步)
const actions = {
  newsAsync: async ({ commit, state }) => {
    let data = new FormData();
    let res = await axios({
      method: "post",
      url: state.api + "/carBook/usermesUnRead.action",
      headers: {
        token: sessionStorage.getItem("token"),
      },
      data: data,
    });
    console.log(res, "系统消息");

    commit("newsUp", res.data.u_count);
    sessionStorage.setItem("newsNum", res.data.u_count);
    console.log("vuex", res.data.u_count);
  },
  // 系统扫码时间
  login: async ({ commit, state }, data) => {
    return new Promise(async (resolve, reject) => {
      let res = await axios({
        method: "post",
        url: state.api + "/login/Login",
        data: data,
      });

      console.log(res, "登录账号");
      if (res.data.code == 200) {
        sessionStorage.setItem("userName", res.data.data.userName);
        sessionStorage.setItem("token", res.data.data.token);
        sessionStorage.setItem("roleId", res.data.data.roleId);
        sessionStorage.setItem("userhead", res.data.data.userhead);
        sessionStorage.setItem("provinceId", res.data.data.provinceId);
        sessionStorage.setItem("cityId", res.data.data.cityId);
        sessionStorage.setItem("districtId", res.data.data.districtId);
        sessionStorage.setItem("address", res.data.data.address);
        sessionStorage.setItem("addressId", res.data.data.addressId);

        commit("userName", res.data.data.userName);
        commit("ROLELIST", "");
        if (res.data.data.roleId == 1) {
          router.push({ path: "/jianguanCloud/project" });
          commit("indexUp", "/jianguanCloud/project");
        } else {
          router.push({ path: "/jianguanCloud/home" });
          commit("indexUp", "/jianguanCloud/home");
        }
        resolve("success");
      } else {
        resolve({ name: "reject", data: res });
      }
    });
  },
};

export default {
  state,
  mutations,
  actions,
};
