import { createStore } from "vuex";
import api from "../apis/fetch";
import router from "../router";
import { asyncRouterList } from "../router";
import menuData from "../auth/menuData";
console.log(import.meta.env.VITE_PROJECT_ENV);
let baseurl = import.meta.env.VITE_BASEURL;

const store = createStore({
  state: {
    isLogin: false,
    firstTitle: "",
    secondTitle: "",
    currentMenuItem: "/cargoOwnerManage/cargoOwnerList",
    baseurl,
    basePermissionData: [],
    userPermission: [],
    menuData: [],
    baseParentNodes: [],
  },
  getters: {},
  mutations: {
    changefirstTitle(state, text) {
      state.firstTitle = text;
    },
    changeTitleSecond(state, text) {
      state.secondTitle = text;
    },
    changeLogin(state, b) {
      state.isLogin = b;
    },
    setCurrentMenuItem(state, index) {
      state.currentMenuItem = index;
    },
    setBasePermissionData(state, data) {
      state.basePermissionData = data;
    },
    setUserPermissionData(state, data) {
      state.userPermission = data;
    },
    setMenuData(state, data) {
      state.menuData = data;
    },
    setBaseParentNodes(state, data) {
      state.baseParentNodes = data;
    },
  },
  actions: {
    GetBasePermissionData({ commit }, loginAccountId) {
      return new Promise((resolve, reject) => {
        api.getPermisiionData({ loginAccountId }).then((e) => {
          let data = e.data.result;
          let arr = [];
          function getParentNodes(data) {
            for (let i of data) {
              if (i.children.length) {
                arr.push(i.code);
                getParentNodes(i.children);
              }
            }
          }
          getParentNodes(data);
          commit("setBaseParentNodes", arr);
          commit("setBasePermissionData", data);
          resolve(1);
        });
      });
    },
    GetUserPermission({ commit }, loginAccountId) {
      return new Promise((resolve, reject) => {
        api.getPermissionByUserId({ loginAccountId }).then((e) => {
          let res = e.data.result || [];
          let arr = [...new Set([...res])];
          commit("setUserPermissionData", arr);
          localStorage.setItem("rolePermission", arr);
          let data = [];
          for (let i in menuData) {
            // if (menuData[i].title == "航次管理") {
            //   data[i] = menuData[i];
            // } else {
            if (arr.indexOf(menuData[i].code) != -1) {
              data[i] = menuData[i];
              let arr0 = [];
              for (let j in data[i].items) {
                if (arr.indexOf(data[i].items[j].code) != -1) {
                  arr0.push(data[i].items[j]);
                }
              }
              data[i].items = arr0;
            }
            // }
          }
          data = data.filter((item) => {
            return item;
          });
          commit("setMenuData", data);
          resolve(1);
        });
      });
    },
  },
});

export default store;
