import { createStore } from "vuex";
import router from "@/router/index";
import dayjs from "dayjs";
import { terminalType } from "@/utils/index";
import { getUserInfo } from "@/api/index";

console.log("process.env.NODE_ENV", process.env.NODE_ENV);
export default createStore({
  state: {
    // token:
    //   process.env.NODE_ENV !== "development"
    //     ? terminalType === "Browser" && localStorage.getItem("token")
    //     : "",
    token: terminalType === "Browser" && localStorage.getItem("token"),
    // userInfo:
    //   process.env.NODE_ENV !== "development"
    //     ? terminalType === "Browser" && localStorage.getItem("userInfo")
    //       ? JSON.parse(localStorage.getItem("userInfo"))
    //       : {}
    //     : {
    //         account: "csht003",
    //         userName: "csht003",
    //         imgUrl:
    //           "https://thirdwx.qlogo.cn/mmopen/vi_32/t5O6btVlibCehoxtZWXc4AYefp92pxGWorCNskBo6hLsj3MJclkPpyoI0d5OW5QDsqfanS5IdicfPfEvYvQ6S7uQ/132",
    //       },
    userInfo:
      terminalType === "Browser" && localStorage.getItem("userInfo")
        ? JSON.parse(localStorage.getItem("userInfo"))
        : {},
    authorityList:
      process.env.NODE_ENV !== "development"
        ? terminalType === "Browser" && localStorage.getItem("authorityList")
          ? JSON.parse(localStorage.getItem("authorityList"))
          : []
        : // : [{ starttime: 0, endtime: Number.MAX_SAFE_INTEGER, mid: 2 }] // mockData
          [1212],
    // endtime	权限结束时间	integer(int64)	mid	权限id	string	starttime	权限开始时间	integer(int64)
    interactMsgObj: {
      retainMsgNum: 100, // 保留消息条数
      // 直播间互动消息
      msgListIds: [], // 所有互动消息的id集合
      msgListIdObj: {}, // 所有互动消息，key为互动消息id，value为消息对象
      replyBasicInformMsgObj: {}, // 所有回复消息的集合
      isScrollToBottom: true, // 用户互动区滚动条是否滚动到底部
      temUserInteractMsgList: [], // 用户互动区滚动条没有滚动到底部，将其他用户新发的互动消息暂时存起来
      temUserInteractShowNum: 0, // 用户互动区需要展示还未展示的消息数
      userInteractMsgList: [], // 用户互动消息
      isTgScrollToBottom: true, // 讲师互动区滚动条是否滚动到底部
      temTgInteractMsgList: [], // 讲师区滚动条没有滚动到底部，将其他用户新发的互动消息暂时存起来
      temTgInteractShowNum: 0, // 讲师需要展示还未展示的消息数
      tgInteractMsgList: [], // 讲师互动消息
      newTreeMsg: [], // 最新的三条互动消息
      msgTimeList: [], // 互动区时间汇总
      tgMsgTimeList: [], // 投顾互动区时间汇总
      msgTimeObj: {}, // 用户互动区区消息以发言时间为key，value为消息对象
      tgMsgTimeObj: {}, // 讲师互动区消息以发言时间为key，value为消息对象
      hasHisMsg: true, // 用户是否有历史消息
      tgHasHisMsg: true, // 讲师互动区否有历史消息
    },
    forbidLogin: false, // 是否禁止用户登录
  },
  getters: {
    authorityIdList: (state) => {
      const now = Date.now();
      return state.authorityList
        .filter((item) => {
          return item.starttime < now && item.endtime > now;
        })
        .map((item) => item.mid);
    },
  },
  mutations: {
    setIsScrollToBottom(state, payload) {
      let key = payload.isTg ? "isTgScrollToBottom" : "isScrollToBottom";
      state.interactMsgObj[key] = payload.data;
    },
    setReplyMsgObj(state, payload) {
      state.interactMsgObj.replyBasicInformMsgObj[payload.id] = payload;
    },
    setInteractMsg(state, payload) {
      let isST = state.interactMsgObj.isScrollToBottom; // 讲师互动区是否滚动到底部了
      let isTgST = state.interactMsgObj.isTgScrollToBottom; // 用户互动区是否滚动到底部了
      let msgArr = Array.isArray(payload.data) ? payload.data : [payload.data];
      let tgMsgArr = [];

      msgArr.forEach((item) => {
        let chatTime = dayjs(item.createTime).format("MM-DD HH:mm");
        item.show =
          (!item.replyBasic && item.isOpen !== 2) ||
          state.userInfo.userId === item.phone ||
          (item.replyBasic &&
            (item.replyBasic.isOpen === 1 ||
              state.userInfo.userId === item.replyBasic.userId));
        if (payload.type === 1) {
          // 新消息
          //  公开的或者是本人发的文本消息
          if (
            ((item.userId && item.isOpen === 1) ||
              item.phone === state.userInfo.userId) &&
            item.type === 1
          ) {
            state.interactMsgObj.newTreeMsg.push(item);
          }

          // 用户互动区最新消息数量提醒
          if (item.show && !isST) state.interactMsgObj.temUserInteractShowNum++;
          // 讲师互动区新消息数量提醒
          if (item.show && !isTgST) state.interactMsgObj.temTgInteractShowNum++;

          // 将全部评论按1s为维度进行汇总
          if (
            !state.interactMsgObj.msgTimeList.includes(chatTime) &&
            item.show
          ) {
            state.interactMsgObj.msgTimeList.push(chatTime);
            item.chatTime = chatTime;
            state.interactMsgObj.msgTimeObj[chatTime] = item;
          } else {
            delete item.chatTime;
          }

          // 将讲师评论按1s为维度进行汇总
          if (
            !state.interactMsgObj.tgMsgTimeList.includes(chatTime) &&
            item.show
          ) {
            state.interactMsgObj.tgMsgTimeList.push(chatTime);
            item.tgChatTime = chatTime;
            state.interactMsgObj.tgMsgTimeObj[chatTime] = item;
          } else {
            delete item.tgChatTime;
          }
        } else {
          // 历史
          if (payload.isTg) {
            // 将讲师评论按1s为维度进行汇总
            if (
              !state.interactMsgObj.tgMsgTimeList.includes(chatTime) &&
              item.show
            ) {
              state.interactMsgObj.tgMsgTimeList.push(chatTime);
              item.tgChatTime = chatTime;
              state.interactMsgObj.tgMsgTimeObj[chatTime] = item;
            } else if (
              state.interactMsgObj.tgMsgTimeList.includes(chatTime) &&
              item.show
            ) {
              item.tgChatTime = chatTime;
              delete state.interactMsgObj.tgMsgTimeObj[chatTime].tgChatTime;
              state.interactMsgObj.tgMsgTimeObj[chatTime] = item;
            }
          } else {
            // 将全部评论按1s为维度进行汇总
            if (
              !state.interactMsgObj.msgTimeList.includes(chatTime) &&
              item.show
            ) {
              state.interactMsgObj.msgTimeList.push(chatTime);
              item.chatTime = chatTime;
              state.interactMsgObj.msgTimeObj[chatTime] = item;
            } else if (
              state.interactMsgObj.msgTimeList.includes(chatTime) &&
              item.show
            ) {
              item.chatTime = chatTime;
              delete state.interactMsgObj.msgTimeObj[chatTime].chatTime;
              state.interactMsgObj.msgTimeObj[chatTime] = item;
            }
          }
        }

        state.interactMsgObj.msgListIds.push(item.id);
        state.interactMsgObj.msgListIdObj[item.id] = item;

        // 筛选出讲师的发言
        if (item.advisorId) {
          tgMsgArr.push(item);
        }
      });

      if (payload.type === 1) {
        // 新消息
        if (isST) {
          // 用户互动区新消息处理
          state.interactMsgObj.userInteractMsgList =
            state.interactMsgObj.userInteractMsgList.concat(msgArr);
          if (
            state.interactMsgObj.userInteractMsgList.length >
            state.interactMsgObj.retainMsgNum
          ) {
            state.interactMsgObj.userInteractMsgList =
              state.interactMsgObj.userInteractMsgList.slice(
                state.interactMsgObj.userInteractMsgList.length -
                  state.interactMsgObj.retainMsgNum
              );
            state.interactMsgObj.msgListIds =
              state.interactMsgObj.msgListIds.slice(
                state.interactMsgObj.msgListIds.length -
                  state.interactMsgObj.retainMsgNum
              );
            state.interactMsgObj.hasHisMsg = true;
            state.interactMsgObj.msgTimeList = [];
            state.interactMsgObj.msgTimeObj = {};
            state.interactMsgObj.userInteractMsgList.forEach((item) => {
              // 互动消息按秒重新归类
              const chatTime = dayjs(item.createTime).format("MM-DD HH:mm");
              if (
                !state.interactMsgObj.msgTimeList.includes(chatTime) &&
                item.show
              ) {
                state.interactMsgObj.msgTimeList.push(chatTime);
                item.chatTime = chatTime;
                state.interactMsgObj.msgTimeObj[chatTime] = item;
              } else {
                delete item.chatTime;
              }
            });
          }
        } else {
          state.interactMsgObj.temUserInteractMsgList =
            state.interactMsgObj.temUserInteractMsgList.concat(msgArr);
        }

        if (isTgST) {
          // 讲师互动区新消息处理
          state.interactMsgObj.tgInteractMsgList =
            state.interactMsgObj.tgInteractMsgList.concat(tgMsgArr);
          if (
            state.interactMsgObj.tgInteractMsgList.length >
            state.interactMsgObj.retainMsgNum
          ) {
            state.interactMsgObj.tgInteractMsgList =
              state.interactMsgObj.tgInteractMsgList.slice(
                state.interactMsgObj.tgInteractMsgList.length -
                  state.interactMsgObj.retainMsgNum
              );
            state.interactMsgObj.tgHasHisMsg = true;
            state.interactMsgObj.tgMsgTimeList = [];
            state.interactMsgObj.tgMsgTimeObj = {};
            state.interactMsgObj.tgInteractMsgList.forEach((item) => {
              // 互动消息按秒重新归类
              const chatTime = dayjs(item.createTime).format("MM-DD HH:mm");
              if (
                !state.interactMsgObj.tgMsgTimeList.includes(chatTime) &&
                item.show
              ) {
                state.interactMsgObj.tgMsgTimeList.push(chatTime);
                item.tgChatTime = chatTime;
                state.interactMsgObj.tgMsgTimeObj[chatTime] = item;
              } else {
                delete item.tgChatTime;
              }
            });
          }
        } else {
          state.interactMsgObj.temTgInteractMsgList =
            state.interactMsgObj.temTgInteractMsgList.concat(tgMsgArr);
        }
      } else {
        // 历史消息
        if (payload.isTg) {
          state.interactMsgObj.tgHasHisMsg = payload.hasNext;
          state.interactMsgObj.tgInteractMsgList = tgMsgArr
            .reverse()
            .concat(state.interactMsgObj.tgInteractMsgList);
        } else {
          state.interactMsgObj.hasHisMsg = payload.hasNext;
          state.interactMsgObj.userInteractMsgList = msgArr
            .reverse()
            .concat(state.interactMsgObj.userInteractMsgList);
        }
      }
    },
    interactMsgMerge(state, payload) {
      let key1, key2, key3, numKey, timeKey, childTimeKey, msgTimeObjKey;
      if (payload.isTg) {
        key1 = "tgInteractMsgList";
        key2 = "temTgInteractMsgList";
        key3 = "tgHasHisMsg";
        numKey = "temTgInteractShowNum";
        timeKey = "tgMsgTimeList";
        childTimeKey = "tgChatTime";
        msgTimeObjKey = "tgMsgTimeObj";
      } else {
        key1 = "userInteractMsgList";
        key2 = "temUserInteractMsgList";
        key3 = "hasHisMsg";
        numKey = "temUserInteractShowNum";
        timeKey = "msgTimeList";
        childTimeKey = "chatTime";
        msgTimeObjKey = "msgTimeObj";
      }
      state.interactMsgObj[key1] = state.interactMsgObj[key1].concat(
        state.interactMsgObj[key2]
      );
      if (
        state.interactMsgObj[key1].length > state.interactMsgObj.retainMsgNum
      ) {
        state.interactMsgObj[key1] = state.interactMsgObj[key1].slice(
          state.interactMsgObj[key1].length - state.interactMsgObj.retainMsgNum
        );
        state.interactMsgObj.msgListIds = state.interactMsgObj.msgListIds.slice(
          state.interactMsgObj.msgListIds.length -
            state.interactMsgObj.retainMsgNum
        );
        state.interactMsgObj[key3] = true;

        state.interactMsgObj[timeKey] = [];
        state.interactMsgObj[msgTimeObjKey] = {};
        state.interactMsgObj[key1].forEach((item) => {
          let chatTime = dayjs(item.createTime).format("MM-DD HH:mm");
          if (!state.interactMsgObj[timeKey].includes(chatTime) && item.show) {
            state.interactMsgObj[timeKey].push(chatTime);
            item[childTimeKey] = chatTime;
            state.interactMsgObj[msgTimeObjKey][chatTime] = item;
          } else {
            delete item[childTimeKey];
          }
        });
      }
      state.interactMsgObj[key2] = [];
      state.interactMsgObj[numKey] = 0;
    },
    resetInteractMsgObj(state) {
      state.interactMsgObj = {
        retainMsgNum: 100, // 保留消息条数
        // 直播间互动消息
        msgListIds: [], // 所有互动消息的id集合
        msgListIdObj: {}, // 所有互动消息，key为互动消息id，value为消息对象
        replyBasicInformMsgObj: {}, // 所有回复消息的集合
        isScrollToBottom: true, // 用户互动区滚动条是否滚动到底部
        temUserInteractMsgList: [], // 用户互动区滚动条没有滚动到底部，将其他用户新发的互动消息暂时存起来
        temUserInteractShowNum: 0, // 用户互动区需要展示还未展示的消息数
        userInteractMsgList: [], // 用户互动消息
        isTgScrollToBottom: true, // 讲师互动区滚动条是否滚动到底部
        temTgInteractMsgList: [], // 讲师区滚动条没有滚动到底部，将其他用户新发的互动消息暂时存起来
        temTgInteractShowNum: 0, // 讲师需要展示还未展示的消息数
        tgInteractMsgList: [], // 讲师互动消息
        newTreeMsg: [], // 最新的三条互动消息
        msgTimeList: [], // 互动区时间汇总
        tgMsgTimeList: [], // 投顾互动区时间汇总
        msgTimeObj: {}, // 用户互动区区消息以发言时间为key，value为消息对象
        tgMsgTimeObj: {}, // 讲师互动区消息以发言时间为key，value为消息对象
        hasHisMsg: true, // 用户是否有历史消息
        tgHasHisMsg: true, // 讲师互动区否有历史消息
      };
    },
    setToken(state, payload) {
      localStorage.setItem("token", payload);
      state.token = payload;
    },
    setUserInfo(state, payload) {
      localStorage.setItem("userInfo", JSON.stringify(payload));
      state.userInfo = payload;
    },
    setAuthorityList(state, payload) {
      localStorage.setItem("authorityList", JSON.stringify(payload));
      state.authorityList = payload;
    },
    outLogin(state) {
      state.token = "";
      state.userInfo = {};
      localStorage.clear();
      router.push("/");
    },
    setForbidLogin(state) {
      state.forbidLogin = true;
    },
  },
  actions: {
    // 登录
    Login({ commit }, { token, refreshToken }) {
      return new Promise((resolve, reject) => {
        getUserInfo({
          token,
          refreshToken,
          loginType: 2, // 1：账号密码登录 2：token登录
          clientType: 1,
        })
          .then((ret) => {
            if (ret.code === 0) {
              commit("setToken", ret.data.upToken);
              commit(
                "setUserInfo",
                Object.assign({ account: ret.data.userId }, ret.data)
              );
              resolve(ret);
            } else {
              reject();
            }
          })
          .catch(() => {
            reject();
          });
      });
    },
  },
  modules: {},
});
