import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

let lifeData = {};

try {
  // 尝试获取本地是否存在lifeData变量，第一次启动APP时是不存在的
  lifeData = uni.getStorageSync("lifeData");
} catch (e) {}

// 需要永久存储，且下次APP启动需要取出的，在state中的变量名
let saveStateKeys = [
  "vuex_teacherInfo",
  "vuex_user",
  "vuex_token",
  "vuex_userType",
  "vuex_msgUser",
];

// 保存变量到本地存储中
const saveLifeData = function (key, value) {
  // 判断变量名是否在需要存储的数组中
  if (saveStateKeys.indexOf(key) != -1) {
    // 获取本地存储的lifeData对象，将变量添加到对象中
    let tmp = uni.getStorageSync("lifeData");
    // 第一次打开APP，不存在lifeData变量，故放一个{}空对象
    tmp = tmp ? tmp : {};
    tmp[key] = value;
    // 执行这一步后，所有需要存储的变量，都挂载在本地的lifeData对象中
    uni.setStorageSync("lifeData", tmp);
  }
};
const store = new Vuex.Store({
  state: {
    vuex_teacherInfo: lifeData.vuex_teacherInfo
      ? lifeData.vuex_teacherInfo
      : "",
    // 如果上面从本地获取的lifeData对象下有对应的属性，就赋值给state中对应的变量
    // 加上vuex_前缀，是防止变量名冲突，也让人一目了然
    vuex_userType: lifeData.vuex_userType ? lifeData.vuex_userType : 0, // 0:学生 1:教师
    vuex_user: lifeData.vuex_user ? lifeData.vuex_user : "",
    vuex_token: lifeData.vuex_token ? lifeData.vuex_token : "",
    // 如果vuex_version无需保存到本地永久存储，无需lifeData.vuex_version方式
    vuex_version: "1.0.0",
    // 智能客服消息组列表
    vuex_aiMessageGroups: [],
    vuex_aiActiveDMid: "",
    vuex_isTransferChat: false,
    // 当前聊天窗口消息列表（数组
    vuex_msgList: [],
    // 最近联系人/会话列表
    vuex_userMsgList: [],
    // 当前聊天用户对象
    vuex_msgUser: lifeData.vuex_msgUser ? lifeData.vuex_msgUser : {},
    // 消息窗口滚动位置
    vuex_msgScrollTop: 0,
    // 记录会话ID与在线咨询类型的映射，区分在线咨询/人工转接
    vuex_dialogueTypeMap: {},
    // 自定义tabbar数据
    vuex_iPhone: lifeData.vuex_iPhone ? lifeData.vuex_iPhone : false,
    // tabbar相关配置
    vuex_tabbar_config: {
      activeColor: "#3CB5FB",
      inactiveColor: "#666666",
    },
    vuex_tabbar: [
      {
        pagePath: "pages/home/index/index",
        iconPath: "/static/common/tabbar/index.png",
        selectedIconPath: "/static/common/tabbar/selectindex.png",
        text: "首页",
      },
      {
        pagePath: "pages/message/msgList/msgList",
        iconPath: "/static/common/tabbar/message.png",
        selectedIconPath: "/static/common/tabbar/selectmessage.png",
        // count: 2, //提示数量
        // 初始化红点：基于未读计数
        isDot: lifeData.vuex_msgList ? true : false, // 显示红色小点
        text: "消息",
      },
      // {
      //     pagePath: "/pages/main/index/index",
      //     iconPath: "/static/common/tabbar/findFriends.png",
      //     selectedIconPath: "/static/common/tabbar/selectFindFridend.png",
      //     text: "找校友"
      // },
      // {
      //     pagePath: "/pages/AlumniCircle/alumnus/alumnus",
      //     iconPath: "/static/common/tabbar/AlumniCircle.png",
      //     selectedIconPath: "/static/common/tabbar/selectAlumniCircle.png",
      //     text: "校友圈"
      // },

      // {
      //     pagePath: "/pages/my/my/my",
      //     iconPath: "/static/common/tabbar/my.png",
      //     selectedIconPath: "/static/common/tabbar/selectmy.png",
      //     text: "我的"
      // }
    ],
  },
  mutations: {
    $uStore(state, payload) {
      // 判断是否多层级调用，state中为对象存在的情况，诸如user.info.score = 1
      let nameArr = payload.name.split(".");
      let saveKey = "";
      let len = nameArr.length;
      if (len >= 2) {
        let obj = state[nameArr[0]];
        for (let i = 1; i < len - 1; i++) {
          obj = obj[nameArr[i]];
        }
        obj[nameArr[len - 1]] = payload.value;
        saveKey = nameArr[0];
      } else {
        // 单层级变量，在state就是一个普通变量的情况
        state[payload.name] = payload.value;
        saveKey = payload.name;
      }
      // 保存变量到本地，见顶部函数定义
      saveLifeData(saveKey, state[saveKey]);
    },

    // ===== 消息中心：列表、当前聊天、消息推送等 =====
    // 设置会话列表（服务端返回）
    set_UserMsgList(state, list) {
      state.vuex_userMsgList = Array.isArray(list) ? list.slice() : [];
      if (state.vuex_msgUser && state.vuex_msgUser.friendId) {
        state.vuex_userMsgList = state.vuex_userMsgList.map((item) => {
          if (item && item.friendId === state.vuex_msgUser.friendId) {
            return { ...item, unReadCount: 0 };
          }
          return item;
        });
      }
    },
    // 设置当前聊天用户
    set_MsgUser(state, user) {
      state.vuex_msgUser = user || null;
      if (state.vuex_msgUser && state.vuex_msgUser.friendId) {
        state.vuex_userMsgList = (state.vuex_userMsgList || []).map((item) => {
          if (item && item.friendId === state.vuex_msgUser.friendId) {
            return { ...item, unReadCount: 0 };
          }
          return item;
        });
      }
    },
    // 更新当前聊天用户的部分属性
    update_MsgUser(state, payload) {
      if (state.vuex_msgUser) {
        state.vuex_msgUser = { ...state.vuex_msgUser, ...payload };
      } else {
        state.vuex_msgUser = payload;
      }
    },
    // 现在没有id，先覆盖整个list
    push_MsgList(state, list) {
      state.vuex_msgList = list || [];
    },
    // 追加历史消息到头部（分页加载）
    prepend_MsgList(state, list) {
      const prev = state.vuex_msgList || [];
      const next = Array.isArray(list) ? list : [];
      const merged = [...next, ...prev];

      const seen = new Set();
      state.vuex_msgList = merged.filter((item) => {
        const id = item && item.id;
        if (!id) return true;
        if (seen.has(id)) return false;
        seen.add(id);
        return true;
      });
    },
    // 推送一条新消息（去重）
    push_Msg(state, msg) {
      //   注：现在的消息没有id，无法去重，暂时用push_MsgList
      if (!msg || !msg.id) return;
      const exists = (state.vuex_msgList || []).some(
        (item) => item && item.id === msg.id,
      );
      if (!exists) {
        state.vuex_msgList.push(msg);
      }
    },
    // 插入历史消息到头部
    unshift_Msg(state, msg) {
      if (!msg) return;
      state.vuex_msgList.unshift(msg);
    },

    // ===== 智能客服：消息组列表维护（参照 vuex_msgList 维护方式） =====
    set_AiActiveDMid(state, dmid) {
      state.vuex_aiActiveDMid = dmid || "";
    },
    set_IsTransferChat(state, val) {
      state.vuex_isTransferChat = !!val;
    },
    push_AiLiveAgentMsg(state, msg) {
      if (!msg) return;
      const msgId = msg.id || msg.Id;
      if (!msgId) return;

      const exists = (state.vuex_aiMessageGroups || []).some(
        (item) => item && item.id === msgId,
      );
      if (exists) return;

      const userId =
        (state.vuex_user && (state.vuex_user.Id || state.vuex_user.id)) || "";
      const senderId = msg.senderId || msg.SenderId || "";
      const isSelf = userId && senderId && String(userId) === String(senderId);

      state.vuex_aiMessageGroups.push({
        id: msgId,
        message: msg.message || msg.Message || "",
        sendDate: msg.sendDate || msg.SendDate || "",
        isSend: true,
        isRead: true,
        interactMode: isSelf ? 0 : 8,
        messageType: msg.messageType || msg.MessageType || 0,
        sendUserType: msg.sendUserType,
        timeLabel: 0,
        displayTime: "",
      });
    },
    // 覆盖整个列表
    push_AiMsgList(state, list) {
      state.vuex_aiMessageGroups = Array.isArray(list) ? list : [];
    },
    // 追加历史消息到头部（分页加载）
    prepend_AiMsgList(state, list) {
      const prev = state.vuex_aiMessageGroups || [];
      const next = Array.isArray(list) ? list : [];
      const merged = [...next, ...prev];

      const seen = new Set();
      state.vuex_aiMessageGroups = merged.filter((item) => {
        const id = item && item.id;
        if (!id) return true;
        if (seen.has(id)) return false;
        seen.add(id);
        return true;
      });
    },
    // 推送一条新消息（去重）
    push_AiMsg(state, msg) {
      if (!msg || !msg.id) return;
      const exists = (state.vuex_aiMessageGroups || []).some(
        (item) => item && item.id === msg.id,
      );
      if (!exists) {
        state.vuex_aiMessageGroups.push(msg);
      }
    },
    // 插入一条消息到头部
    unshift_AiMsg(state, msg) {
      if (!msg) return;
      state.vuex_aiMessageGroups.unshift(msg);
    },
    // 更新置顶状态（本地）
    update_TopState(state, { friendId, isTop }) {
      state.vuex_userMsgList = (state.vuex_userMsgList || []).map((item) => {
        if (item && item.friendId === friendId) {
          return { ...item, isTop: !!isTop };
        }
        return item;
      });
    },
    // WebSocket 实时消息：更新会话列表的未读数、文案与时间
    apply_RealtimeMessageToList(
      state,
      { dialogueId, message, sendDate, senderId, receiverId },
    ) {
      if (!dialogueId) return;
      const activeId =
        state.vuex_msgUser?.dialogueManagementId ||
        state.vuex_msgUser?.friendId ||
        state.vuex_msgUser?.id;
      const isActive = activeId && activeId === dialogueId;

      let found = false;
      state.vuex_userMsgList = (state.vuex_userMsgList || []).map((item) => {
        const itemId =
          item?.dialogueManagementId ||
          item?.DialogueManagementId ||
          item?.friendId ||
          item?.id;
        if (itemId === dialogueId) {
          found = true;
          const currentUnread =
            Number(
              item?.unReadCount ?? item?.unreadCount ?? item?.unread ?? 0,
            ) || 0;
          const nextUnread = isActive ? 0 : currentUnread + 1;
          return {
            ...item,
            lastMessage: message ?? item?.lastMessage ?? "",
            lastMessageTime: sendDate ?? item?.lastMessageTime ?? "",
            unReadCount: nextUnread,
            unreadCount: nextUnread,
          };
        }
        return item;
      });

      // 未在列表中则插入一条最小信息的会话（保持实时感知）
      if (!found) {
        const nextUnread = isActive ? 0 : 1;
        state.vuex_userMsgList.unshift({
          id: dialogueId,
          dialogueManagementId: dialogueId,
          DialogueManagementId: dialogueId,
          friendId: receiverId || senderId || dialogueId,
          name: "",
          avatar: "",
          lastMessage: message || "",
          lastMessageTime: sendDate || "",
          unReadCount: nextUnread,
          unreadCount: nextUnread,
        });
      }
    },
    // 更新消息窗口滚动位置
    set_MsgScrollTop(state, top) {
      state.vuex_msgScrollTop = Number(top) || 0;
    },
    // 清空消息相关状态（登出/切换账号）
    clear_MessageState(state) {
      state.vuex_msgList = [];
      state.vuex_userMsgList = [];
      state.vuex_msgUser = null;
      state.vuex_msgScrollTop = 0;
      state.vuex_aiActiveDMid = "";
      state.vuex_isTransferChat = false;
    },
    // 统一登出清理：清除 token 与用户数据，并同步到本地存储
    // 注意：仅清理与登录态相关的关键字段，避免影响其他持久化数据
    logout(state) {
      // 清除登录令牌
      state.vuex_token = "";
      state.vuex_teacherInfo = "";
      state.vuex_user = "";
      // 清理消息相关状态
      state.vuex_msgList = [];
      state.vuex_userMsgList = [];
      state.vuex_msgUser = null;
      state.vuex_msgScrollTop = 0;
      state.vuex_aiActiveDMid = "";
      state.vuex_isTransferChat = false;
      // 同步更新本地持久化
      saveLifeData("vuex_token", state.vuex_token);
      saveLifeData("vuex_teacherInfo", state.vuex_teacherInfo);
      saveLifeData("vuex_user", state.vuex_user);
    },
    // 合并会话类型映射（在线咨询类型）
    upsert_DialogueTypeMap(state, { list = [], type }) {
      if (!type) return;
      const next = { ...(state.vuex_dialogueTypeMap || {}) };
      list.forEach((item) => {
        const id =
          item?.dialogueManagementId ||
          item?.DialogueManagementId ||
          item?.dialogueId ||
          item?.friendId ||
          item?.id;
        if (id) next[id] = type;
      });
      state.vuex_dialogueTypeMap = next;
    },
  },
  actions: {
    // 获取聊天列表（最近联系人）
    async getUserlist({ commit, state }) {
      // 在 Vuex action 中没有组件 this，上下文不包含 $u
      // 通过 Vue.prototype.$u 使用 uView 的 http 实例
      return Vue.prototype.$u.api.GetDialogueListApi().then((res) => {
        const list = (res && res.data.item1 ? res.data.item1 : []).map(
          (item) => {
            const unReadCount =
              state.vuex_msgUser &&
              state.vuex_msgUser.friendId === item.friendId
                ? 0
                : item.unReadCount || 0;
            return {
              ...item,
              // avatar: item.avatar,
              unReadCount,
            };
          },
        );
        commit("set_UserMsgList", list);
        return list;
      });
    },
    // 设置当前聊天用户
    setMsgUser({ commit, dispatch }, user) {
      console.log("setMsgUser执行了", user);

      commit("set_MsgUser", user);
      // 刷新列表，清零未读
      dispatch("getUserlist");
    },
    // 获取聊天记录（私聊）——仅在进入聊天页时加载一次
    async fetchChatRecord(
      { commit },
      { dialogueManagementId, PageIndex = 1, PageSize = 20 },
    ) {
      return Vue.prototype.$u.api
        .GetChatHistoryDataApi({
          "Item1.DialogueManagementId": dialogueManagementId,
          PageIndex,
          PageSize,
        })
        .then((res) => {
          const list = (
            res && res.data && Array.isArray(res.data.item1)
              ? res.data.item1
              : []
          )
            .slice()
            .reverse();
          commit("push_MsgList", list);
          return list;
        });
    },

    // 获取下一页历史消息（滚动到顶部触发）
    async fetchChatRecordNextPage(
      { commit },
      { dialogueManagementId, PageIndex = 1, PageSize = 20 },
    ) {
      return Vue.prototype.$u.api
        .GetChatHistoryDataApi({
          "Item1.DialogueManagementId": dialogueManagementId,
          PageIndex,
          PageSize,
        })
        .then((res) => {
          const list = (
            res && res.data && Array.isArray(res.data.item1)
              ? res.data.item1
              : []
          )
            .slice()
            .reverse();
          if (!list.length) return [];
          commit("prepend_MsgList", list);
          return list;
        });
    },
    // 设置消息置顶（服务端 + 本地）
    async setTopMsgUser({ commit, dispatch }, user) {
      if (!user || !user.friendId) return;
      if (user.isTop) {
        return;
      } else {
        Vue.prototype.$u.api
          .OverheadOneDialogueApi({ dialogueManagementId: user.friendId })
          .then((res) => {
            commit("update_TopState", { friendId: user.friendId, isTop: true });
            dispatch("getUserlist");
          });
      }
    },

    // 点击聊天记录，切换到该会话
    selectTeacherChatItem(
      { commit, dispatch },
      { id, receiverId, navigate = true } = {},
    ) {
      if (!id || !receiverId) return;
      // 清空消息列表，避免旧消息干扰
      commit("push_MsgList", []);

      return Vue.prototype.$u.api
        .GetReceiverUserInfoApi({ Id: receiverId })
        .then((res) => {
          if (res.succeed && res.data) {
            commit("update_MsgUser", { ...res.data, dialogueManagementId: id });
            if (navigate) {
              uni.navigateTo({
                url: `/pages/chat/index`,
              });
            }
            return res.data;
          }
        });
    },

    // 点击立即提问进入会话
    // 1) 创建新会话
    // 2) 获取接收者信息
    // 3) 进入会话
    async createDialogue({ commit, state, dispatch }, user) {
      const { id, dialogueManagementId } = user || {};
      if (!id) return Promise.reject(new Error("缺少 id"));

      // 清空消息列表，避免旧消息干扰
      commit("push_MsgList", []);

      if (
        dialogueManagementId &&
        dialogueManagementId !== "00000000-0000-0000-0000-000000000000"
      ) {
        // 有会话ID，直接进入会话
        Vue.prototype.$u.api.GetReceiverUserInfoApi({ Id: id }).then((res) => {
          if (res.succeed && res.data) {
            commit("set_MsgUser", { ...res.data, dialogueManagementId });
            uni.navigateTo({
              url: `/pages/chat/index`,
            });
          }
        });
        return;
      }

      // 没有会话id创建新会话
      const res1 = await Vue.prototype.$u.api.AddDialogueApi({
        receiverId: id,
        onlineConsultationType: 1, // 创建在线咨询固定传1
      });

      const resId = res1.data?.dialogueManagementId || "";

      if (res1 && res1.succeed) {
        Vue.prototype.$u.api.GetReceiverUserInfoApi({ Id: id }).then((res) => {
          if (res.succeed && res.data) {
            commit("set_MsgUser", { ...res.data, dialogueManagementId: resId });
            uni.navigateTo({
              url: `/pages/chat/index`,
            });
          }
        });
        return;
      }

      return Promise.reject(new Error(res?.error || "创建会话失败"));
    },
  },
});

export default store;
