import queryString from 'query-string';

export default {
  namespace: 'globalModel',
  state: {
    token: null,
    userInfo: null,
  },
  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    }
  },
  effects: {
    *setTokenModel({ payload: params }, { select, call, put }) {
      console.log("===== globalModel setTokenModel =====");
      const { token, userInfo, themeColor } = params;
      yield put({ type: "updateState", payload: { token, userInfo, themeColor }});
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      console.log("===== globalModel subscriptions =====");

      /**
       * 监听父IFrame传递的消息
       */
      window.addEventListener("message", function (args) {
        // 拦截非法监
        if (!args.data.isAuth) return;

        // window缓存父IFrame传递的参数
        const token = args.data.token;
        const userInfo = args.data.userInfo;
        const themeColor = args.data.themeColor;
        window._TOKEN_ = token;
        window._USERINFO_ = userInfo ? JSON.parse(userInfo) : userInfo;
        window._THEMECOLOR_ = themeColor;
        dispatch({type: "setTokenModel", payload: {token, userInfo, themeColor}});

        // sessionStorage缓存
        sessionStorage.token = window._TOKEN_;
        sessionStorage.userInfo = JSON.stringify(window._USERINFO_);
        sessionStorage.themeColor = themeColor;

        // 第一次渲染IFrame时TOKEN未取到，等TOKEN带过来后再次访问页面
        const pathname = window.location.pathname;
        console.log("===== System app listener pathname " + pathname + " =====");
        if (pathname === "/home") {
          history.push({pathname});
        }
      });
    },
  }
};
