<template>
	<view class="">
		<view class="navBox">
			<view class="status_bar" :style="{height: iStatusBarHeight + 'px'}"></view>
			<view class="nav">
				<view class="navLeft" >
					<!-- <image src="../static/img/nav_icon_back.png" mode="aspectFit" class="backImg" @click="goback"></image> -->
				</view>
				<view class="title">询价信息</view>
				<view class="goVin" @click="vinScanFn">车架号查询</view>
			</view>
		</view>
		<view class="status_bar" :style="{height: iStatusBarHeight + 'px'}"></view>
		<view style="height: 44px;"></view>
		<!-- <view @click="tuichu">退出</view> -->
		<scroll-view class="conversations" scroll-y="true">
		
		  <view>
			<!--  <video src="https://66-goesay.oss-accelerate.aliyuncs.com/goeasy-im-dmsIMTest/3369051043664274_uni-video.mp4" id="videoPlayer"
			         ></video> -->
		  </view>
		  <view v-if="conversations.length > 0">
		    <view class="scroll-item" v-for="(conversation, key) in conversations" :key="key">
		      <view class="item-head">
		       <!-- <image :src="conversation.data.avatar" class="head-icon"></image> -->
			    <image src="/static/img/pic_def_ava@2x.png" class="head-icon"></image>
		        <view class="item-head_unread" v-if="conversation.unread">{{ conversation.unread }}</view>
		      </view>
		      <view class="scroll-item_info" @click="chat(conversation)">
		        <view class="item-info-top">
		          <text class="item-info-top_name">{{ conversation.data.name }}</text>
		          <view class="item-info-top_time">{{ formatDate(conversation.lastMessage.timestamp) }}</view>
		        </view>
		        <view class="item-info-bottom">
		          <view class="item-info-bottom-item">
		            <view class="item-info-top_content" v-if="!conversation.lastMessage.recalled">
		              <text class="unread-text">
		                {{ conversation.lastMessage.read === false && conversation.lastMessage.senderId === currentUser.id ? '[未读]' : '' }}
		              </text>
		
		              <text v-if="conversation.lastMessage.senderId === currentUser.id">我: </text>
		              <text v-else>{{ conversation.type === 'group' ? conversation.lastMessage.senderData.name : conversation.data.name }}: </text>
		              <text v-if="conversation.lastMessage.type === 'text'">{{ conversation.lastMessage.payload.text }}</text>
		              <text v-else-if="conversation.lastMessage.type === 'video'">[视频消息]</text>
		              <text v-else-if="conversation.lastMessage.type === 'audio'">[语音消息]</text>
		              <text v-else-if="conversation.lastMessage.type === 'image'">[图片消息]</text>
		              <text v-else-if="conversation.lastMessage.type === 'file'">[文件消息]</text>
		              <text v-else-if="conversation.lastMessage.type === 'order'">[自定义消息:订单]</text>
		              <text v-else-if="conversation.lastMessage.type === 'pic'">[图片消息]</text>
					  <text v-else-if="conversation.lastMessage.type === 'car'">[车辆信息]</text>
					  <text v-else>[[未识别内容]]</text>
		            </view>
		            <view class="item-info-top_content" v-else>
		              <text>
		                {{conversation.lastMessage.recaller.id === currentUser.id ? '你' : conversation.lastMessage.recaller.data.name}}撤回了一条消息
		              </text>
		            </view>
		            <view class="item-info-bottom_action" @click.stop="showAction(conversation)"></view>
		          </view>
		        </view>
		      </view>
		    </view>
		  </view>
		 
		  <view class="no-conversation" v-else>
		    <span v-if="imLoginUrlGo">{{conversations.length > 0?"正在加载中":'正在加载中'}}</span>
			<span v-else>{{conversations.length > 0?"暂无消息":'暂无消息'}}</span>
		  </view>
		 <!-- <view>chushihuaNUm:{{chushihuaNUm}}</view> -->
		<!-- <view @click="setClipboardData">token:{{token}}</view>
		<view>imLoginUrlGo:{{imLoginUrlGo}} {{chushihuaNUm}} {{liebNUm}}</view>
		<view>conversations:{{conversations.length}}</view>
		<view>this.currentUser:{{currentUser.id}}</view>
		<view>onFailedError:{{onFailedError.code}}:{{onFailedError.content}}</view> -->
		  <view class="action-container" v-if="actionPopup.visible">
		    <view class="layer" @click="actionPopup.visible = false"></view>
		    <view class="action-box">
		      <view class="action-item" @click="topConversation">
		        {{ actionPopup.conversation.top ? '取消置顶' : '置顶聊天' }}
		      </view>
		      <view class="action-item" @click="deleteConversation">删除聊天</view>
		    </view>
		  </view>
		</scroll-view>
	</view>
 
</template>

<script>
  import {formatDate} from '../lib/utils';
  import restApi from '../lib/restapi';

  const GoEasy = uni.$GoEasy;
  const GRTC = uni.$GRTC;
  export default {
    name: 'conversation',
    data() {
      return {
        conversations: [],

        actionPopup: {
          conversation: null,
          visible: false
        },
        currentUser: null,
		iStatusBarHeight:'',
		token:'',
		imLoginUrlGo:true,
		chushihuaNUm:0,
		liebNUm:0,
		onFailedError:'',
      }
    },
	onLoad(opt) {
		  this.token=opt.token
		  uni.setStorageSync('token',  this.token);
		  this.iStatusBarHeight = uni.getSystemInfoSync().statusBarHeight;
		  if (GoEasy.getConnectionStatus() === 'disconnected') {
		     this.imLoginUrl()
		  }else{
		  	this.tuichu2()
		  }
		
	},
    onShow() {
		/* if (GoEasy.getConnectionStatus() === 'disconnected') {
		  if(this.token){
		  	this.imLoginUrl()
		  } 
		}else{
			this.tuichu2()
		} */
	  /* if(this.token){
		  this.imLoginUrl()
	  } */
      /* uni.$currentUser = uni.getStorageSync('currentUser');
      this.currentUser = uni.$currentUser;
	  console.log(this.currentUser)
      if (!this.currentUser) {
        uni.navigateTo({ url: './login' });
        return;
      }
      if (GoEasy.getConnectionStatus() === 'disconnected') {
        this.connectGoEasy(); //连接goeasy
        this.subscribeGroup(); //建立连接后，就应该订阅群聊消息，避免漏掉
      }
      this.loadConversations(); //加载会话列表
      this.initGoEasyListeners(); */
    },
    onHide() {
      if (GoEasy.getConnectionStatus() === 'disconnected') {
        return
      }else{
		 // this.tuichu()
	  }
      GoEasy.im.off(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderConversations);
    },
    methods: {
      formatDate,
      connectGoEasy() {
        uni.showLoading();
		console.log(this.currentUser.id)
        GoEasy.connect({
          id: this.currentUser.id,
          data: {
            name: this.currentUser.name,
            avatar: this.currentUser.avatar
          },
          onSuccess: () => {
			  this.chushihuaNUm=1
			  this.loadConversations(); //加载会话列表
			  this.initGoEasyListeners();
            console.log('GoEasy connect successfully.')
          },
          onFailed: (error) => {
			   uni.hideLoading();
			   this.onFailedError=error
			 // this.imLoginUrl()
			  this.imLoginUrlGo=false
			  this.chushihuaNUm=2
			  
			  this.logout2()
			
            console.log('Failed to connect GoEasy, code:' + error.code + ',error:' + error.content);
          },
          onProgress: (attempts) => {
			  this.chushihuaNUm=3
			   uni.hideLoading();
            console.log('GoEasy is connecting', attempts);
          }
        });
      },
	  tuichu(){
		  GoEasy.disconnect({
			 onSuccess: function(){
				 console.log("GoEasy disconnect successfully.")
				
			 },
			 onFailed: function(error){
				
				 console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
			 }
			});
	  },
	  tuichu2(){
		  var that=this;
	  		  GoEasy.disconnect({
	  			 onSuccess: function(){
	  				 console.log("GoEasy disconnect successfully.")
	  				if(that.token){
	  					that.imLoginUrl()
	  				} 
	  			 },
	  			 onFailed: function(error){
	  				
	  				 console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
	  			 }
	  			});
	  },
	  logout2(){
		  var that=this;
		 setTimeout(that.logout(), 1000)  
	  },
	  logout(){
		  var that=this;
		  GoEasy.disconnect({
				 onSuccess: function(){
					 console.log("GoEasy disconnect successfully.")
					 that.imLoginUrlGo=true
					 
					 that.imLoginUrl()
				 },
				 onFailed: function(error){
					that.imLoginUrlGo=true
					that.imLoginUrl()
					 console.log("Failed to disconnect GoEasy, code:"+error.code+ ",error:"+error.content);
				 }
			});
	  },
	  setClipboardData(){
		  uni.setClipboardData({
		    data: this.token,
		    success: () => {
		      uni.showToast({
		        title: '复制成功'
		      });
		    }
		  });
	  },
	  chooseImage(){
		  uni.chooseImage({
		  	count: 6, //默认9
		  	sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		  	sourceType: ['album'], //从相册选择
		  	success: function (res) {
		  		console.log(JSON.stringify(res.tempFilePaths));
		  	},
			fail(err) {
				
			}
		  });
	  },
	  imLoginUrl(){
		  if(!this.imLoginUrlGo){
			  return false
		  }
		  this.imLoginUrlGo=false
			  uni.showLoading({
				title: '加载中'
			  })
	  			   this.$http('imSys/imLoginUrl', {
	  			      token:this.token,
	  			     },'POST').then(res => {
						 this.imLoginUrlGo=true
	  			    		 uni.hideLoading();
						  if(res.code!=0){
							  uni.showModal({
							  	title: '提示',
							  	content: res.msg,
								showCancel:false,
							  	success: function (res) {
							  		if (res.confirm) {
							  			console.log('用户点击确定');
							  		} else if (res.cancel) {
							  			console.log('用户点击取消');
							  		}
							  	}
							  });
							 
							  return false
						  }
	  			   		  var users={
	  						  userId:res.data.userId,
	  						  name:res.data.users.name,
	  						  avatar:'',
							  id:res.data.userId,
	  					  }
	  					  this.currentUser=users
	  					//  this.connectGoEasy()
	  					 uni.setStorageSync('users', users);
						 uni.setStorageSync('currentUser', users);
						 console.log(this.currentUser)
						 if (!this.currentUser) {
						   uni.navigateTo({ url: './login' });
						   return;
						 }
						 if (GoEasy.getConnectionStatus() === 'disconnected') {
						   this.connectGoEasy(); //连接goeasy
						   //this.subscribeGroup(); //建立连接后，就应该订阅群聊消息，避免漏掉
						 }
						 this.loadConversations(); //加载会话列表
						 this.initGoEasyListeners();
	  			     }) 
	  },
	  goBack(){
		  //app交互
		  var standalone = window.navigator.standalone
		  var userAgent = window.navigator.userAgent.toLowerCase()
		  var safari = /safari/.test(userAgent)
		  var ios = /iphone|ipod|ipad|mac/.test(userAgent)
		  var android = /android/.test(userAgent)
		  if (ios) {
			 if ( true) {//!standalone&& !safari
			   window.webkit.messageHandlers.goMyNav.postMessage(null)
			 }
		  } else if (android) {
		  	  window.android.postMessage()
		  }
	  },
	  vinScanFn(){
		  //app交互
		  var standalone = window.navigator.standalone
		  var userAgent = window.navigator.userAgent.toLowerCase()
		  var safari = /safari/.test(userAgent)
		  var ios = /iphone|ipod|ipad|mac/.test(userAgent)
		  var android = /android/.test(userAgent)
		  if (ios) {
				 if ( true) {//!standalone&& !safari
				   window.webkit.messageHandlers.vinScan.postMessage(null)
				 }
		  } else if (android) {
		  		 window.android.vinScan()
		  }
	  },
      initGoEasyListeners() {
        GoEasy.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.renderConversations); //监听会话列表变化
        GoEasy.im.off(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.setUnreadAmount); // 移除之前的设置角标回调，防止重复回调
        GoEasy.im.on(GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, this.setUnreadAmount); // 设置角标
        // #ifdef APP-PLUS || H5
        GRTC.off(GRTC.EVENT.RING, this.onRing); //移除之前的监听来电事件，防止重复回调
        GRTC.on(GRTC.EVENT.RING, this.onRing); //监听来电事件
        // #endif
      },
      onRing() {
        const currentCall = GRTC.currentCall();
        if (currentCall.groupId) {
          uni.navigateTo({
            url: `./rtc/group/ring`,
          })
        } else {
          uni.navigateTo({
            url: `./rtc/private/ring`,
          })
        }
      },

      // 加载最新的会话列表
      loadConversations() {
        GoEasy.im.latestConversations({
          onSuccess: (result) => {
            uni.hideLoading();
			this.liebNUm=1
            let content = result.content;
            this.renderConversations(content);
            this.setUnreadAmount(content);
          },
          onFailed: (error) => {
			  this.liebNUm=2
            uni.hideLoading();
            console.log('获取最新会话列表失败, error:', error);
          }
        });
      },
      renderConversations(content) {
        this.conversations = content.conversations;
		console.log("消息列表")
		console.log(this.conversations)
      },
      setUnreadAmount(content) {
        const unreadTotal = content.unreadTotal;
        if(unreadTotal > 0) {
          uni.setTabBarBadge({
            index: 0,
            text: unreadTotal.toString()
          });
        }else{
          uni.removeTabBarBadge({index: 0});
        }
        // #ifdef APP-PLUS
        GoEasy.setBadge({
          badge: unreadTotal,
          onSuccess: function () {
            console.log("setBadge successfully.")
          },
          onFailed: function (error) {
            console.log("Failed to setBadge,error:" + error);
          }
        });
        // #endif
      },
      subscribeGroup() {
        let groups = restApi.findGroups(this.currentUser);
        let groupIds = groups.map(item => item.id);
        GoEasy.im.subscribeGroup({
          groupIds: groupIds,
          onSuccess: function () {
            console.log('订阅群消息成功');
          },
          onFailed: function (error) {
            console.log('订阅群消息失败:', error);
          }
        });
      },
      topConversation() {  //会话置顶
        this.actionPopup.visible = false;
        let conversation = this.actionPopup.conversation;
        let description = conversation.top ? '取消置顶' : '置顶';
        GoEasy.im.topConversation({
          conversation: conversation,
          top: !conversation.top,
          onSuccess: function () {
            uni.showToast({
              title: description + '成功',
              icon: 'none'
            });
          },
          onFailed: function (error) {
            console.log(description, '失败：', error);
          }
        });
      },
      deleteConversation() {
        uni.showModal({
          content: '确认删除这条会话吗？',
          success: (res) => {
            if (res.confirm) {
              let conversation = this.actionPopup.conversation;
              this.actionPopup.visible = false;
              GoEasy.im.removeConversation({
                conversation: conversation,
                onSuccess: function () {
                  console.log('删除会话成功');
                },
                onFailed: function (error) {
                  console.log(error);
                },
              });
            } else {
              this.actionPopup.visible = false;
            }
          },
        })
      },
      chat(conversation) {
		  console.log(conversation)
		  var url='http://goeasytest.66km.com.cn/#/pages/privateChatWeb?to=' + conversation.userId+"&token="+this.token+'&supplierName='+conversation.data.name
		  
		  var standalone = window.navigator.standalone
		  var userAgent = window.navigator.userAgent.toLowerCase()
		  var safari = /safari/.test(userAgent)
		  var ios = /iphone|ipod|ipad|mac/.test(userAgent)
		  var android = /android/.test(userAgent)
		  if (ios) {
		  	 if ( true) {//!standalone&& !safari
		  		   window.webkit.messageHandlers.privateChatWeb.postMessage(url)
		  	 }
		  } else if (android) {
		  		window.android.privateChatWeb(url)
		  }
		  
		  
		  
		  
		  return false
        let path = conversation.type === GoEasy.IM_SCENE.PRIVATE ?
          './privateChatWeb?to=' + conversation.userId+'&supplierName='+conversation.data.name+"&token="+this.token:
          './groupChat?to=' + conversation.groupId;
		
		  var friend={
			  id:conversation.userId,
			  supplierName:conversation.data.name,
			  avatar:conversation.data.avatar,
		  }
		 
		
		  uni.setStorage({
		  		key: 'friend',
		  		data: friend,
		  		 success: function () {	
		  				/* uni.navigateTo({
		  				  url: './privateChat?to=' + friend.ID
		  				});	 */
						uni.navigateTo({ url: path });
		  		 }
		  });
		  		
        
      },
      showAction(conversation) {
        this.actionPopup.conversation = conversation;
        this.actionPopup.visible = true;
      }
    }
  }
</script>

<style>
  page {
    height: 100%;
  }

  .conversations {
    width: 750rpx;
    overflow-x: hidden;
    display: flex;
    flex-direction: column;
    height: 100%;
  }

  .conversations .scroll-item {
    height: 152rpx;
    display: flex;
    align-items: center;
    padding-left: 32rpx;
  }

  .conversations .scroll-item .head-icon {
    width: 88rpx;
    height: 88rpx;
    margin-right: 28rpx;
  }

  .conversations .scroll-item_info {
    height: 151rpx;
    width: 590rpx;
    padding-right: 32rpx;
    border-bottom: 1px solid #EFEFEF;
  }

  .conversations .scroll-item_info .item-info-top {
    padding-top: 20rpx;
    height: 60rpx;
    line-height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;

  }

  .conversations .item-info-top_name {
    font-size: 30rpx;
    color: #1C1C1C;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
	width: 370rpx;
  }

  .conversations .item-info-top_time {
    font-size: 24rpx;
   color: #BFBFBF;
  }

  .conversations .item-info-bottom {
    height: 40rpx;
    line-height: 40rpx;
    overflow: hidden;
  }

  .conversations .item-info-bottom-item {
    display: flex;
    justify-content: space-between;
  }

  .item-info-bottom .item-info-top_content {
    font-size: 26rpx;
    color: #b3b3b3;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

  }

  .item-info-bottom .item-info-bottom_action {
    width: 50rpx;
    height: 50rpx;
    font-size: 34rpx;
    background: url("../static/images/action.png") no-repeat center;
    background-size: 28rpx 30rpx;
  }

  .no-conversation {
    width: 100%;
    text-align: center;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 34rpx;
    color: #9D9D9D;
  }

  .item-head {
    position: relative;
  }

  .item-head .item-head_unread {
    padding: 6rpx;
    background-color: #EE593C;
    color: #FFFFFF;
    font-size: 34rpx;
    line-height: 28rpx;
    border-radius: 24rpx;
    min-width: 24rpx;
    min-height: 24rpx;
    text-align: center;
    position: absolute;
    top: 0;
    right: 15rpx;
  }

  .action-container {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .action-container .layer {
    position: absolute;
    top: 0;
    left: 0;
    background: rgba(51, 51, 51, 0.5);
    width: 100%;
    height: 100%;
    z-index: 99;
  }

  .action-box {
    width: 400rpx;
    height: 240rpx;
    background: #ffffff;
    position: relative;
    z-index: 100;
    border-radius: 20rpx;
    overflow: hidden;
  }

  .action-item {
    text-align: center;
    line-height: 120rpx;
    font-size: 34rpx;
    color: #262628;
    border-bottom: 1px solid #EFEFEF;
  }

  .unread-text {
    color: #d02129;
  }
.backImg{
		width: 44rpx;
		height: 44rpx;
		
		/* margin-left: 10rpx; */
		/* margin-right: 20rpx; */
	}
	.nav{
		height: 44px;
		display: flex;
		justify-content: space-between;
	    background: #fff;
		align-items: center;
		border-bottom: 1px solid #eaeaea;
	}
.goVin{
	width: 200rpx;
	color: #3F90F7;
	text-align: right;
	padding-right: 20rpx;
	font-size: 26rpx;
}
.navLeft{
	width: 200rpx;
	padding-left: 20rpx;
}
.navBox{
	position: fixed;
	left: 0;
	top: 0;
	z-index: 11;
	width: 100vw;
}
</style>
