<template>
  <view class="content">
	  <image class="bg-img" src="/static/image/home/orange_home_top_bg.png"></image>
	  <view class="topbox ">
		  <view class="status-bar"></view>
		  <view class="topbox-a">消息</view>
	</view>
	  <Dialog
	    :visible="showDialog"
	    :styleConfig="styleConfig"
	    :handleClose="handleClose">
	    <view
	  		  v-for="(item, index) in chatList"
	  		  :key="index"
	  		  class="chat-container"
	  		  @click.stop="handleContentClick(item)">
	  		  <image
	  			class="item-icon"
	  			v-if="item.imgType === 'SINGLE'"
	  			src="../../assets/icon/singlePerson.svg"/>
	  		  <image class="item-icon" v-else src="../../assets/icon/multiPerson.svg" />
	  		  <view>{{ item.content }}</view>
	    </view>
	  </Dialog>
	  
	  <mescroll-body ref="mescrollRef" top="120rpx" bottom="0" @init="mescrollInit" @down="downCallback" @up="upCallback" :down="downOption" :up="upOption">
	  <view class="TUI-conversation">
	    <!-- <view class="create-group" @click="handleShow"> + 发起聊天</view> -->
	  		<myNotice v-for="(item,index) in noticeList" :key="index" :item="item"></myNotice>
	  		<TUIConversationList 
	  		  :noticeList='noticeList'
	  		  :currentID="currrentConversationID"
	  		  :conversationList="conversationList"
	  		  @handleGotoItem="handleCurrrentConversation"/>
	  </view>
	  </mescroll-body>
  </view>
</template>
<script lang="ts">
import { getLastAndReadStatus } from "@/api/user.js"
import { getSopCourseStudyList } from "@/api/courseAnswer.js"
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import { defineComponent, reactive, toRefs, computed, onMounted,watch } from "vue";
import { onNavigationBarButtonTap, onShow, onUnload } from "@dcloudio/uni-app";
import TUIConversationList from "./conversation-list";
import Dialog from "./components/dialog.vue";
import store from "@/store";
import { TUIConversationServer, TUIProfileServer } from "../../TUICore/server";
import {getOrderIdByIm} from '@/api/inquiryOrder.js'
import { isLogin,updateMsgDot } from "@/utils/common";
import { showLoginPage } from "@/utils/login";
import myNotice from "../../components/myNotice.vue";
const TUIConversation = defineComponent({
  name: "TUIConversation",
  mixins: [ MescrollMixin], //mescroll-body写在子组件时
  components: {
    TUIConversationList,
    Dialog,
	myNotice
  },
  setup(props) {
    const timStore = store.state.timStore;
    // uni.$TUIKit.TUIConversationServer = new TUIConversationServer();
    // uni.$TUIKit.TUIProfileServer = new TUIProfileServer();
    // const { t } = uni.$TUIKit.config.i18n.useI18n();
    const data: any = reactive({
      //conversationList: [],
	  conversationList: computed(() => timStore.conversationList),
      currrentConversationID: "",
      open: false,
      searchUserID: "",
      selectedList: [],
      searchUserList: [],
      step: 1,
      showDialog: false,
	  unredCount:0,
      item: {
        flow: "out",
        status: "success",
      },
      styleConfig: {
        width: "150px",
        // height: '160px',
        padding: "16px 16px 0px",
        top: "8px",
        right: "8px",
      },
      chatList: [
        {
          imgType: "SINGLE",
          type: uni.$TIM.TYPES.CONV_C2C,
          id: 1,
          content: "发起会话",
        },
        {
          imgType: "GROUP",
          type: uni.$TIM.TYPES.GRP_WORK,
          id: 1,
          content: "工作群",
        },
        {
          imgType: "GROUP",
          type: uni.$TIM.TYPES.GRP_PUBLIC,
          id: 2,
          content: "社交群",
        },
        {
          imgType: "GROUP",
          type: uni.$TIM.TYPES.GRP_MEETING,
          id: 3,
          content: "会议群",
        },
      ],
	  noticeLen: 0,
	  mescroll:null,
	  downOption: {   //下拉刷新
	   	use:true,
	  	auto: false // 不自动加载 (mixin已处理第一个tab触发downCallback)
	  },
	  upOption: {
	  	onScroll:false,
		auto: false,
	  	use: true, // 是否启用上拉加载; 默认true
	  	page: {
	  		pae: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
	  		size: 10 // 每页数据的数量,默认10
	  	},
	  	noMoreSize: 10, // 配置列表的总数量要大于等于5条才显示'-- END --'的提示
	  	textNoMore:"",
	  	empty: {
	  		use : false ,
	  		icon:'https://cos.his.cdwjyyh.com/fs/20240423/cf4a86b913a04341bb44e34bb4d37aa2.png',
	  		tip: '暂无数据'
	  	}
	  },
	  dataList: [],
	  sysmsg: '',
	  noticeList: [],
    });
	
	const newMsgUpdate = computed(() => { return store.getters['newMsg/updateTime']});
	// 监听在线推送通知更新
	watch(newMsgUpdate, (newVal: any, oldVal: any) => {
	  if (newVal) {
			  console.log('接收到在线推送通知更新:', newVal);
			  // 在这里处理更新逻辑
			  if(isLogin()) {
				getLastAndReadmsg()
				data.mescroll.resetUpScroll()
			  }
		}
	});
	
    onUnload(() => {
        uni.$TUIKit.TUIConversationServer.destroyed();
    });
    
    onNavigationBarButtonTap(() => {
      data.showDialog = !data.showDialog;
    });
    onShow(() => {
		if(isLogin()) {
			uni.$emit('refreshIM');
			store.commit("timStore/setConversationID", "");
			data.mescroll && data.mescroll.resetUpScroll();
			//getLastAndReadmsg();
			updateMsgDot();
		} else {
			showLoginPage()
		}
    });
    // 切换当前会话
    const handleCurrrentConversation = (value: any) => {
		if(value.lastMessage.cloudCustomData!=null && value.lastMessage.cloudCustomData!=''){
			try{
				var json=JSON.parse(value.lastMessage.cloudCustomData)
				store.commit("timStore/setImType", json.imType);
				store.commit("timStore/setOrderType", json.orderType);
				store.commit("timStore/setOrderId", json.orderId);
				store.commit("timStore/setFollowId", json.followId);
				store.commit("timStore/setType", json.type);
			}
			catch(e){
				
			}
		}
		data.currrentConversationID = value.conversationID;
		store.commit("timStore/setConversationID", value.conversationID);
		//uni.$TUIKit.TUIChatServer.updateStore(value.conversationID)
		uni.navigateTo({
		  url: `../TUIChat/index?conversationName=${handleItemName(value)}`,
		});
		uni.$TUIKit.TUIConversationServer.setMessageRead(value.conversationID);
		const curConversation = data.conversationList.filter((item: any) => {
		  return item.conversationID === value.conversationID;
		});
		store.commit("timStore/setConversation", curConversation);
		uni.$TUIKit.TUIConversationServer.getConversationProfile(
		  value.conversationID
		).then((res: any) => {
		  // 通知 TUIChat 关闭当前会话
		  store.commit("timStore/setConversation", res.data.conversation);
		  // uni.$TUIKit.getStore()['TUIChat'].conversation = res.data.conversation;
		});
      
    };
    const handleShow = () => {
      data.showDialog = true;
    };

    // dialog 内部有效区域点击
    const handleContentClick = (item) => {
      data.showDialog = false;
      uni.navigateTo({
         url: `../TUIConversation/create?title=${item.content}&type=${item.type}`,
      });
    };
    // 关闭 dialog
    const handleClose = () => {
        data.showDialog = false;
    };
    const handleItemName = (item: any) => {
      let name = "";
      switch (item.type) {
        case uni.$TIM.TYPES.CONV_C2C:
          name = item?.userProfile.nick || item?.userProfile?.userID || "";
          break;
        case uni.$TIM.TYPES.CONV_GROUP:
          name = item.groupProfile.name || item?.groupProfile?.groupID || "";
          break;
        case uni.$TIM.TYPES.CONV_SYSTEM:
          name = "系统通知";
          break;
      }
        return name;
    };
	const mescrollInit = (mescroll: any)=> {
		data.mescroll = mescroll;
		if(isLogin()) {
			data.mescroll.resetUpScroll()
		}
	}
	/*下拉刷新的回调 */
	const downCallback = (mescroll: any)=>{
		mescroll.resetUpScroll()
	}
	const upCallback = (page: any)=> {
		//联网加载数据
		// let that = this;
		let param = {
			pageNum: page.num,
			pageSize: page.size
		};
		getSopCourseStudyList(param).then(res => {
			if(res.code==200){  //设置列表数据
				if (page.num == 1) {
					data.dataList = res.data.list; 
				} else {
					data.dataList = data.dataList.concat(res.data.list);
				}
				data.mescroll.endBySize(res.data.list.length, res.data.total);
			}
			else{
				uni.showToast({
					icon:'none',
					title: "请求失败",
				});
				data.dataList = [];
				data.mescroll.endErr();
			}
			data.noticeList = uni.$u.deepClone(data.dataList);
			if(data.sysmsg){
				data.noticeList.push(data.sysmsg)
			}
		});
		getLastAndReadmsg()
	}
	const getLastAndReadmsg = ()=> {
		getLastAndReadStatus().then(res=>{
			if(res.code == 200) {
				data.sysmsg = res.data && res.data.id ? res.data : ''
				if(res.data && res.data.id) {
					data.sysmsg.mytype = 'other'
				}
			} else {
				data.sysmsg = ''
			}
			data.noticeList = uni.$u.deepClone(data.dataList)
			if(data.sysmsg) {
				data.noticeList.push(data.sysmsg)
			}
		})
	}
	
    return {
      ...toRefs(data),
      handleCurrrentConversation,
      handleContentClick,
      handleItemName,
      handleClose,
      handleShow,
	  mescrollInit,
	  downCallback,
	  upCallback,
	  getLastAndReadmsg,
	  newMsgUpdate
    };
  },
});
export default TUIConversation;
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		box-sizing: border-box;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #999999;
		// background-image: url("@/static/image/home/home_top_bg.png");
		background-repeat: no-repeat;
		background-size: 100%;
		position: relative;
		z-index: 2;
		.bg-img{
			position: absolute;
			width: 100%;
			height: 524rpx;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			z-index: 0;
		}
		.topbox{
			position: absolute;
			top: 0;
			z-index: 1;
			color: #222;
			font-size: 36rpx;
			width: 100%;
			text-align: center;
			.topbox-a{
			}
			.status-bar{
				height: var(--status-bar-height);
			}
		}
	}
.TUI-conversation {
	// background-color: #fff;
	// margin: 20rpx;
  .create-group {
    font-weight: 800px;
    padding: 10px;
    font-size: 14px;
    text-align: center;
  }
}

.chat-container {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #444444;

  .item-icon {
    display: inline-block;
    width: 21px;
    height: 21px;
    margin-right: 12px;
  }
}
</style>
