// import { user_info, login } from '@/api/user'
import { eduGet, getUser, eduLogout } from "@/api/user";
import { getToken, removeToken, setToken } from "@/utils/auth";
import { API_CONFIG } from "@/common/apiConfig";
import axios from '@/common/axios.config'; // 引入 axios 配置实例

// import { Message } from 'element-ui'
// import { loginOut } from '@/api/user';

const getDefaultState = () => {
  return {
    token: getToken(),
    id: "",
    roles: [],
    name: "",
    username: "",
    avatar: "",
    is_init: false,
    userinfo: {},
    userinfo2:{},
    // 应用权限
    fromL: {
      basics: {
        title: "",
        brief: "",
        logo: "",
      },
      //桌面  管理平台首页  管理平台侧边栏
      desktop: {
        list: [],
      },
      admin: {
        index: {
          list: [],
        },
        sidebar: {
          list: [],
        },
      },
    },
    // 应用标识
    appSign:''

  };
};

const state = getDefaultState();
const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  },
  SET_ID: (state, id) => {
    state.id = id;
  },
  SET_FROM: (state, from) => {
    state.fromL = from;
  },
  SET_AppSIGN: (state, sign) => {
    state.appSign = sign;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_USERNAME: (state, name) => {
    state.username = name;
  },
  SET_IS_INIT: (state, is_init) => {
    state.is_init = is_init;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_USERINFO: (state, userinfo) => {
    state.userinfo = userinfo;
  },
  SET_USERINFO2: (state, userinfo2) => {
    state.userinfo2 = userinfo2;
    window.topU.US.userInfo = state.userinfo2 && Object.keys(state.userinfo2).length ? state.userinfo2 : state.userinfo
  },
};

const actions = {
  login({ commit }) { //, dispatch
    return new Promise((resolve, reject) => {
      let loginType = window.topU ? window.topU.U.UF.Cookie.get("cocoroboLoginType") : window.parent.U.UF.Cookie.get("cocoroboLoginType");
      if(loginType != 1){
        eduGet()
          .then((response) => {
            console.log(response);
            var _user = response.data[0][0];
            // const allowedIds = [
            //   "0abcb118-9110-11eb-80ad-005056b86db5",
            //   "b7ccc834-aae5-11ea-a8d4-52540005ab01",
            //   "a77e9404-efec-11e9-96f9-028edca3b798",
            //   "0e8d50c3-50b5-2f1c-9f1a-bd346a0bf817",
            //   "5943e08c-b7d4-11ed-8d51-005056b86db5"
            // ];
            // if (allowedIds.includes(_user.userid)) {
              commit("SET_ID", _user.userid);
              commit("SET_TOKEN", _user.userid);
              setToken(_user.userid);
              resolve(_user.userid);
              
            // } else if(_user.userid){
            //   loginOut()
            //   .then(async () => {
            //     dispatch('user/logout', null, { root: true });
            //   })
            //   .catch(err => {
            //     console.error(err);
            //   });
            //   Message({
            //     message: "该用户ID不允许登录",
            //     type: "error"
            //   });
            //   reject("该用户ID不允许登录");
            // }
          })
          .catch((error) => {
            // var _user = { userid: "a9c5c04d-1b6f-11f0-a66a-005056924926" }; //刘玉彤
            // var _user = { userid: "e1d282f8-2325-11f0-99d3-005056924926" }; //zjm
            // var _user = { userid: "0c3735c9-a2ef-11ef-9b30-005056b86db5" }; //yym教师
            // var _user = { userid: "cd9c6879-2498-11ef-bee5-005056b86db5" }; //yym学生

            // var _user = { userid: "5943e08c-b7d4-11ed-8d51-005056b86db5" }; //cs111
            // var _user = { userid: "6c56ec0e-2c74-11ef-bee5-005056b86db5" }; //qgt
            // var _user = { userid: "4fda23d4-1b6f-11f0-a66a-005056924926" }; //管理员
            // var _user = { userid: "17c14552-41ee-11f0-b60f-005056924926" }; //普通
            // var _user = { userid: "a77e9404-efec-11e9-96f9-028edca3b798" }; //徐嘉伟


            // commit("SET_ID", _user.userid);
            // commit("SET_TOKEN", _user.userid);
            // setToken(_user.userid);
            // resolve(_user.userid);
            reject(error);
          });
        }
    });
  },
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // getToken()
      commit("SET_ID", state.token);

      getUser({ userid: state.token })
        .then((response) => {
          console.log(response);
          // const { data } = response
          const data = response.data[0][0];
          if (!data) {
            reject("验证失败，请重新登录。");
          }
          // console.log(response)
          commit("SET_USERINFO", data);
          resolve(data);
          // resolve()
        })
        .catch((error) => {
          reject(error);
        });
    });
  },

  async getschPerInfo({ commit,state }) {
      let params = [{
          functionName: API_CONFIG.ajax_schoolPermission.functionName, // 调用存储过程的名称
          org: state.userinfo.org, //组织id
          oid: state.userinfo.organizeid, //学校id
        }];

      // console.log('params',params);
      // 获取学校权限与组织权限,优先使用学校权限,其次使用组织权限
      // 第一步
      let res = await axios.post(API_CONFIG.baseUrl, params)
      let perData= JSON.parse(res.data[0][0].json)
      
      // 第二步
      let params2 = [
				{
					functionName: "select_desktopToolByPage",
					status: "",
					page: 1,
					lim: 9999999,
				},
			];
      let res2 = await axios.post(API_CONFIG.baseUrl, params2)
      let toolList = res2.data[0];
      toolList.forEach((i) => {
        i.url = JSON.parse(i.url);
        i.json = JSON.parse(i.json);
        i.argumentList = JSON.parse(i.argumentList);
      });

      let params3 = [
				{
					functionName: "select_schUsuallyApp",
					userid: "",
					stand: "cn",
				},
			];
			let res3 = await axios.post(API_CONFIG.baseUrl, params3)
      

			let _list = res3.data[0]

			_list.forEach((i) => {
				i.json = JSON.parse(i.json);
			});

			let appList = _list;

      // 第三步
      perData.desktop.list.forEach((i, index) => {
				let _index = toolList.findIndex((i2) => i == i2.id);
				if (_index != -1) {
					perData.desktop.list[index] = toolList[_index];
				} else {
					console.log("无工具", i);
				}
			});
      
      
      // if (perData.admin.cocoFlow) {
			// 	perData.admin.cocoFlow.forEach((i, index) => {
			// 		let _index = appList.findIndex((i2) => i.id == i2.id);
			// 		if (_index != -1) {
			// 			let _setData = appList[_index];
			// 			_setData.setIcon = i.setIcon;
			// 			perData.admin.cocoFlow[index] = _setData;
			// 		} else {
			// 			console.log("无应用", i);
			// 		}
			// 	});
			// }

      // if (perData.admin.cocoFlow2) {
      //   perData.admin.cocoFlow2.forEach((i, index) => {
      //     let _index = appList.findIndex((i2) => i.id == i2.id);
      //     if (_index != -1) {
      //     let _setData = appList[_index];
      //     _setData.setIcon = i.setIcon;
      //     perData.admin.cocoFlow2[index] = _setData;
      //   } else {
      //     console.log("无应用", i);
      //   }
      //   });
      // }


      if (perData.admin.CampusF && perData.admin.CampusF.appList) {
				perData.admin.CampusF.appList.forEach((i, index) => {
					let _index = appList.findIndex((i2) => i.id == i2.id);
          
					if (_index != -1) {
						let _setData = appList[_index];
						_setData.setIcon = i.setIcon;
						perData.admin.CampusF.appList[index] = _setData;
					} else {
						console.log("无应用", i);
					}
				});
        perData.admin.CampusF.appList = perData.admin.CampusF.appList.filter(Boolean);
			}


			perData.admin.index.list.forEach((i, index) => {
				let _index = toolList.findIndex((i2) => i == i2.id);
				if (_index != -1) {
					perData.admin.index.list[index] = toolList[_index];
          perData.admin.index.list[index].hovered = false
				} else {
					console.log("无工具", i);
				}
			});
			perData.admin.sidebar.list.forEach((i, index) => {
				if (i.children) {
					i.children.forEach((i2, index2) => {
						let _toolList = JSON.parse(JSON.stringify(toolList))
						let _index = _toolList.findIndex((i3) => i2 == i3.id);
						
						if (_index != -1) {
							perData.admin.sidebar.list[index].children[index2] = _toolList[_index];
							perData.admin.sidebar.list[index].children[index2].typeId = perData.admin.sidebar.list[index].typeId + "," +_toolList[_index].id;
						} else {
							console.log("无工具", i);
						}
					});
				} else {
					let _toolList = JSON.parse(JSON.stringify(toolList))
					let _index = _toolList.findIndex((i2) => i == i2.id);
					if (_index != -1) {
						perData.admin.sidebar.list[index] = _toolList[_index];
						perData.admin.sidebar.list[index].typeId =
            perData.admin.sidebar.list[index].id;
					} else {
						console.log("无工具", i);
					} 
				}
			});

      commit('SET_FROM', perData)
      // console.log('state.fromL',state.fromL);
  },
  async logout({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      commit("SET_USERINFO2", {});
      removeToken();
      commit("RESET_STATE");
      window.topU.US.userInfo = {}
      eduLogout().then(() => {
        window.topU.location.reload();
        resolve();
      });
    });
  },

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

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