<template>
  <PageLayout title="消息记录">
    <view class="card-list" v-if="list && list.length > 0">
    <view
      v-for="(item, index) in list"
      :key="index"
      class="card-item"
      @tap="clickItem(item.url)"
    >
      <view class="item">
        <view class="title">{{ item.name }}</view>
        <view class="desc" v-html="item.desc"></view>
        <view class="content">
          <image :src="item.img" class="item-img" />
          <view class="icon"></view>
        </view>
      </view>
    </view>
  </view>
  </PageLayout>
</template>

<script setup>
import PageLayout from "@/components/layout/Page.vue";
import { OAType } from "@/common/enums/msg.ts";
import ossConfig from "@/common/config/oss.js";
import { ref, computed } from "vue";
import { onShow, onLoad } from '@dcloudio/uni-app';
import { getOAList } from "@/common/api/msg/index";
import { useUserStore } from '@/common/store/user';
import { useChatStore } from "@/common/store/im/chatStore.js";
import { useFriendStore } from '@/common/store/im/friendStore.js';
import { useGroupStore } from '@/common/store/im/groupStore.js';
import { useIMUserStore } from '@/common/store/im/imUserStore.js';
import * as wsApi from '@/common/config/wssocket';
import config from "@/common/config/index.js";
import http from '@/common/request/im.js';
import { MESSAGE_TYPE } from '@/common/enums/im.ts';

const friendStore = useFriendStore();
const groupStore = useGroupStore();
const chatStore = useChatStore();
const imUserStore = useIMUserStore();
const userStore = useUserStore();
const loginUserId = userStore.getUserInfo?.id;
const list = ref([
  {
    unread: 0,
    name: "新闻",
    url: "/pages/msg/index?type=" + OAType.NEWS,
    img: ossConfig.staticImgUrl+"/img/msg/news.png",
    desc: "及时掌握相关动态",
  },
  {
    unread: 0,
    name: "通知公告",
    url: "/pages/msg/index?type=" + OAType.NOTIFICATIONS,
    img: ossConfig.staticImgUrl+"/img/msg/notifications.png",
    desc: "暂无未读消息",
  },
  {
    unread: 0,
    name: "日程管理",
    url: "/pages/msg/index?type=" + OAType.SCHEDULE,
    img: ossConfig.staticImgUrl+"/img/msg/schedule.png",
    desc: "管理日程工作安排",
  },
  {
    unread: 0,
    name: "工作流审批",
    url: "/pages/workflow/index?type=todo",
    img: ossConfig.staticImgUrl+"/img/msg/todo.png",
    desc: "查看待办审批",
  },
  {
    unread: 0,
    name: "工作流传阅",
    url: "/pages/workflow/index?type=circulated",
    img: ossConfig.staticImgUrl+"/img/msg/circulation.png",
    desc: "高效传递、便捷审批",
  },
  {
    unread: 0,
    name: "IM",
    url: "/pages/msg/im/chat/chat",
    img: ossConfig.staticImgUrl+"/img/msg/im.png",
    desc: "暂无未读消息",
  },
]);
onShow(()=>{
  getDatas();
  init();
})

list.value[5].desc = computed(() => {
  let count = 0;
  chatStore.chats.forEach((chat) => {
    count += chat.unreadCount;
  });
  console.log('unreadCount', count)
  return count > 0? `<span>您有<span style="color:#EE3E33">${count}</span>条未读消息</span>` : '暂无未读消息';
});

const init = () => {
  // 加载数据
  imUserStore.loadUser()
    .then(() => {
      friendStore.loadFriend();
      groupStore.loadGroup();
      chatStore.loadChat();
      // 初始化websocket
      initWebSocket();
      // 加载离线消息
      loadPrivateMessage(chatStore.privateMsgMaxId);
      loadGroupMessage(chatStore.groupMsgMaxId);
    })
    .catch((e) => {
      console.log(e);
    });
};

const initWebSocket = () => {
  let loginInfo = uni.getStorageSync("loginInfo");
  wsApi.init();
  wsApi.connect(config.IM_WS_URL, loginInfo.accessToken);
  wsApi.onMessage((cmd, msgInfo) => {
    if (cmd == 2) {
      // 异地登录，强制下线
      uni.showModal({
        content: "您已在其他地方登陆，将被强制下线",
        showCancel: false,
      });
      exit();
    } else if (cmd == 3) {
      // 私聊消息
      handlePrivateMessage(msgInfo);
    } else if (cmd == 4) {
      // 群聊消息
      handleGroupMessage(msgInfo);
    }
  });
  wsApi.onClose((res) => {
    // 3000是客户端主动关闭
    if (res.code != 3000) {
      // 重新连接
      uni.showToast({
        title: "连接已断开，尝试重新连接...",
        icon: "none",
      });
      let loginInfo = uni.getStorageSync("loginInfo");
      wsApi.reconnect(process.env.WS_URL, loginInfo.accessToken);
    }
  });
};
const loadPrivateMessage = (minId) => {
  chatStore.updateLoadingPrivateMsg(true);
  http({
    url: "/message/private/loadMessage?minId=" + minId,
    method: "GET",
  }).then((msgInfos) => {
    msgInfos.forEach((msgInfo) => {
      msgInfo.selfSend = msgInfo.sendId == imUserStore.userInfo.id;
      let friendId = msgInfo.selfSend ? msgInfo.recvId : msgInfo.sendId;
      let friend = friendStore.friends.find(
        (f) => f.id == friendId
      );
      if (friend) {
        insertPrivateMessage(friend, msgInfo);
      }
    });
    if (msgInfos.length == 100) {
      // 继续拉取
      loadPrivateMessage(msgInfos[99].id);
    } else {
      chatStore.updateLoadingPrivateMsg(false);
    }
  });
};
const loadGroupMessage = (minId) => {
  chatStore.updateLoadingGroupMsg(true);
  http({
    url: "/message/group/loadMessage?minId=" + minId,
    method: "GET",
  }).then((msgInfos) => {
    msgInfos.forEach((msgInfo) => {
      msgInfo.selfSend = msgInfo.sendId == imUserStore.userInfo.id;
      let groupId = msgInfo.groupId;
      let group = groupStore.groups.find((g) => g.id == groupId);
      if (group) {
        insertGroupMessage(group, msgInfo);
      }
    });
    if (msgInfos.length == 100) {
      // 继续拉取
      loadGroupMessage(msgInfos[99].id);
    } else {
      chatStore.updateLoadingGroupMsg(false);
    }
  });
};
const handlePrivateMessage = (msg) => {
  // 标记这条消息是不是自己发的
  msg.selfSend = msg.sendId == imUserStore.userInfo.id;
  // 好友id
  let friendId = msg.selfSend ? msg.recvId : msg.sendId;
  // 消息已读处理
  if (msg.type == MESSAGE_TYPE.READED) {
    if (msg.selfSend) {
      // 我已读对方的消息，清空已读数量
      let chatInfo = {
        type: "PRIVATE",
        targetId: friendId,
      };
      chatStore.resetUnreadCount(chatInfo);
    } else {
      // 对方已读我的消息，修改消息状态为已读
      chatStore.readedMessage({ friendId: friendId });
    }
    return;
  }
  loadFriendInfo(friendId).then((friend) => {
    insertPrivateMessage(friend, msg);
  });
};
const insertPrivateMessage = (friend, msg) => {
  let chatInfo = {
    type: "PRIVATE",
    targetId: friend.id,
    showName: friend.nickName,
    headImage: friend.headImage,
  };
  // 打开会话
  chatStore.openChat(chatInfo);
  // 插入消息
  chatStore.insertMessage(msg);
  // 播放提示音
  // !msg.selfSend && playAudioTip();
};
const handleGroupMessage = (msg) => {
  // 标记这条消息是不是自己发的
  msg.selfSend = msg.sendId == imUserStore.userInfo.id;
  let groupId = msg.groupId;
  // 消息已读处理
  if (msg.type == MESSAGE_TYPE.READED) {
    // 我已读对方的消息，清空已读数量
    let chatInfo = {
      type: "GROUP",
      targetId: groupId,
    };
    chatStore.resetUnreadCount(chatInfo);
    return;
  }
  loadGroupInfo(groupId).then((group) => {
    // 插入群聊消息
    insertGroupMessage(group, msg);
  });
};
const insertGroupMessage = (group, msg) => {
  let chatInfo = {
    type: "GROUP",
    targetId: group.id,
    showName: group.remark,
    headImage: group.headImageThumb,
  };
  // 打开会话
  chatStore.openChat(chatInfo);
  // 插入消息
  chatStore.insertMessage(msg);
  // 播放提示音
  // !msg.selfSend && playAudioTip();
};
const loadFriendInfo = (id) => {
  return new Promise((resolve, reject) => {
    let friend = friendStore.friends.find((f) => f.id == id);
    if (friend) {
      resolve(friend);
    } else {
      http({
        url: `/friend/find/${id}`,
        method: "get",
      }).then((friend) => {
        friendStore.addFriend(friend);
        resolve(friend);
      });
    }
  });
};
const loadGroupInfo = (id) => {
  return new Promise((resolve, reject) => {
    let group = groupStore.groups.find((g) => g.id == id);
    if (group) {
      resolve(group);
    } else {
      http({
        url: `/group/find/${id}`,
        method: "get",
      }).then((group) => {
        resolve(group);
        groupStore.addGroup(group);
      });
    }
  });
};
async function getDatas() {  
	try {
		let res = await getOAList({limit: 1, size:10, type: 1,enabledMark:1, loginUserId });
		res.data.list.forEach((o) => {
			if (!o.readId) list.value[0].unread += 1; 
		})
		let res1 = await getOAList({ limit: 1, size:10,type: 2,enabledMark:1, loginUserId });
		let total=0;
		res1.data.list.forEach((o) => {
			if (!o.readId){
				total+=1;
			} 
		}); 
		list.value[1].unread  = total; 
		list.value[1].desc=total>0?"您有"+total+"条未读消息":'暂无未读消息';
	} catch (error) { 
	}
}
function clickItem(url) {
  if (url) {
    uni.navigateTo({ url });
  }
}
</script>

<style lang="scss">
.card-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .card-item {
    flex-basis: 50%;
    .item {
      margin-right: 28rpx;
      margin-bottom: 28rpx;
      background: #ffffff;
      border-radius: 19rpx 19rpx 19rpx 19rpx;
      padding: 34rpx 38rpx;
    }
  }
  .title {
    font-size: 31rpx;
    font-weight: bold;
    color: #253954;
    line-height: 36rpx;
  }
  .desc {
    font-size: 23rpx;
    font-weight: bold;
    color: #bdc3d6;
    line-height: 27rpx;
    margin: 12rpx 0 28rpx 0;
  }
  .content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .icon {
    width: 0;
    height: 0;
    border-color: transparent transparent transparent #253954;
    border-width: 12rpx 0 12rpx 10rpx;
    border-style: solid;
    border-radius: 2rpx 2rpx 2rpx 2rpx;
  }
  .item-img {
    width: 76rpx;
    height: 76rpx;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>

