<template>
	<u-swipe-action-item
		:index="source.conversationID"
		@click="clickConversationMenu($event, source)"
		:name="source.conversationID"
		:disabled="true"
		:options="getSwipeActions || []"
		@touchmove.stop>
		<view @tap.prevent="clickConversationItem" class="conversation_item">
				<view class="pinned" v-if="source.isPinned"></view>
				<view class="left_info">
					<my-avatar :isGroup="isGroup" :isNotify="isNotify" :src="source.faceURL" :desc="source.showName" size="48" >
					   <image v-if="getRole()==1" class="taoj"  src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/doctor.svg"></image>
					   <image v-if="getRole()==2" class="taoj"  src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/guanjia.svg"></image>
					</my-avatar>	
					<view class="details">
						<text class="conversation_name">{{ source.showName }}</text>
						<view class="lastest_msg_wrap">
							<text v-if="messagePrefix" class="lastest_msg_prefix" :class="{ lastest_msg_prefix_active: needActivePerfix }">{{ messagePrefix }}</text>
							<text class="lastest_msg_content">{{ latestMessage }}</text>
						</view>
					</view>
				</view>
				<view class="right_desc">
					<text class="send_time">{{ latestMessageTime }}</text>
					<image style="width: 16px; height: 16px" v-if="notAccept" src="https://bjyjb-1362704775.cos.ap-chongqing.myqcloud.com/shop/image/conversation_not_accept.png" />
					<u-badge v-else max="99" :value="source.unreadCount"></u-badge>
				</view>
		</view>
	</u-swipe-action-item>
</template>

<script>
import IMSDK, { GroupAtType, MessageReceiveOptType, SessionType } from 'openim-uniapp-polyfill';
import MyAvatar from './MyAvatar/index.vue';
// import UParse from '@/pages_im/components/gaoyia-parse/parse.vue';
import { getConversationContent, formatConversionTime, prepareConversationState, parseAt } from '@/pages_im/util/imCommon';
import { formatInputHtml,isDoctorAction } from '@/pages_im/util/common';

export default {
	components: {
		MyAvatar,
		// UParse
	},
	props: {
		source: {
			type: Object,
			default: () => {}
		}
	},
	computed: {
		messagePrefix() {
			let prefix = '';
			if (this.source?.recvMsgOpt !== MessageReceiveOptType.Nomal && this.source.unreadCount > 0) {
				prefix = `[${this.source.unreadCount}条] `;
			}
			if (this.source.groupAtType !== GroupAtType.AtNormal) {
				switch (this.source.groupAtType) {
					case GroupAtType.AtAll:
						prefix = '[所有人]';
						break;
					case GroupAtType.AtMe:
						prefix = '[有人@你]';
						break;
					case GroupAtType.AtAllAtMe:
						prefix = '[有人@你]';
						break;
					case GroupAtType.AtGroupNotice:
						prefix = '[群公告]';
						break;
				}
				return prefix;
			}
			if (this.source.draftText !== '') {
				return '[草稿]';
			}
			return prefix;
		},
		latestMessage() {
			if (this.source.latestMsg === '') return '';
			if (this.source.draftText && this.source.groupAtType === GroupAtType.AtNormal) {
				return parseAt(formatInputHtml(this.source.draftText), true);
			}
			let parsedMessage;
			try {
				parsedMessage = JSON.parse(this.source.latestMsg);
			} catch (e) {}
			if (!parsedMessage) return '';
			return getConversationContent(parsedMessage);
		},
		needActivePerfix() {
			return this.source.groupAtType !== GroupAtType.AtNormal || this.source.draftText;
		},
		latestMessageTime() {
			return this.source.latestMsgSendTime ? formatConversionTime(this.source.latestMsgSendTime) : '';
		},
		notAccept() {
			return this.source.recvMsgOpt !== MessageReceiveOptType.Nomal;
		},
		isGroup() {
			return this.source.conversationType === SessionType.WorkingGroup;
		},
		isNotify() {
			return this.source.conversationType === SessionType.Notification;
		},
		getSwipeActions() {
			let actions = [
				{
					text: `${this.source.isPinned ? '取消' : ''}置顶`,
					style: {
						backgroundColor: '#3c9cff'
					}
				},
				{
					text: '移除',
					style: {
						backgroundColor: '#FF381F'
					}
				}
			];
			if (this.source.unreadCount > 0) {
				actions = [
					{
						text: '标为已读',
						style: {
							backgroundColor: '#8E9AB0'
						}
					},
					...actions
				];
			}
			return actions;
		}
	},
	data() {
		return {
			isCustom:false,
		};
	},
	methods: {
		clickConversationItem() {
			console.log("qxj clickConversationItem:::");
			console.log(this.source);
			let userId=this.source.userID;
			let isDoctor=isDoctorAction(userId);
			if(!isDoctor){
				this.$store.commit("timStore/setImType",1);
			}
			else{
				//this.$store.commit("timStore/setImType",1);
				let ex=this.source.ex;
				if(this.source.latestMsg!=null && this.source.latestMsg!=''){
					let latestMsg=JSON.parse(this.source.latestMsg);
					if(!!latestMsg.ex && latestMsg.ex!=''){
						ex=latestMsg.ex;
					}
				}
				if(ex!=null || ex!=''){
					try{
						var json=JSON.parse(ex);
						this.$store.commit("timStore/setImType", json.imType);
						this.$store.commit("timStore/setOrderType", json.orderType);
						this.$store.commit("timStore/setOrderId", json.orderId);
						this.$store.commit("timStore/setFollowId", json.followId);
						this.$store.commit("timStore/setType", json.type);
					}
					catch(e){
						
					}
				}
			}
			this.$store.commit("timStore/setConversationID", this.source.conversationID);
			prepareConversationState(this.source);
		},
		
		clickConversationMenu({ name, index }, item) {
			console.log('clickConversationMenu');
			const noUnRead = this.getSwipeActions.length === 2;
			if (index === 0 && !noUnRead) {
				IMSDK.asyncApi(IMSDK.IMMethods.MarkConversationMessageAsRead, IMSDK.uuid(), item.conversationID).catch(() => uni.$u.toast('操作失败'));
			}
			if ((index === 0 && noUnRead) || (index === 1 && !noUnRead)) {
				IMSDK.asyncApi(IMSDK.IMMethods.PinConversation, IMSDK.uuid(), {
					conversationID: item.conversationID,
					isPinned: !item.isPinned
				}).catch(() => uni.$u.toast('置顶失败'));
			}

			if (index === 2 || (noUnRead && index === 1)) {
                  console.log("qxj conversationID:"+item.conversationID);
				  let that=this;
				  IMSDK.asyncApi(IMSDK.IMMethods.DeleteConversationAndDeleteAllMsg,IMSDK.uuid(),item.conversationID)
					  .then(() => {
						 console.log("移除成功!!!");
						 that.$store.dispatch('conversation/delConversationByCID', item.conversationID)
					}).catch(({ errCode, errMsg }) => {  // 调用失败
						 console.log("errMsg:",errCode);
						 uni.$u.toast('移除失败');
					});
			}
			//this.$emit('closeAllSwipe');
		},
		getRole(){
			let userType=0;
			let userId=this.source.userID;
			if(userId!=undefined  && (userId!="" || userId.length>0)){
				if(userId.indexOf('U')!==-1){
					userType=0;
				}
				if(userId.indexOf('D')!==-1){
					userType=1;
				}
				if(userId.indexOf('C')!==-1){
					userType=2;
				}
			}
			return userType;
		}
	}
};
</script>

<style lang="scss" scoped>
.conversation_item {
	@include btwBox();
	flex-direction: row;
	margin:0rpx 24rpx 0;
	padding: 20rpx 24rpx 22rpx;
	position: relative;
	border-radius: 16rpx;
	background: #fff;
	&::after {
		content: "";
		position: absolute;
		bottom: 0;
		left: 0;
		border-bottom: 1px solid #ECECEC;
		width: 100%;
		transform: scaleY(0.5);
		border-top-color: #ECECEC;
		border-right-color: #ECECEC;
		border-left-color: #ECECEC;
	}
    
	&_active {
		background-color: #f3f3f3;
	}

	.left_info {
		@include btwBox();
		.details {
			@include colBox(false);
			margin-left: 24rpx;
			height: 64px;
			color: $uni-text-color;
			justify-content: space-around;
			.conversation_name {
				@include nomalEllipsis();
				max-width: 40vw;
				font-size: 36rpx;
			}

			.lastest_msg_wrap {
				display: flex;
				font-size: 30rpx;
				margin-top: 10rpx;
				color: #666;
				.lastest_msg_prefix {
					margin-right: 6rpx;

					&_active {
						color: $u-primary;
					}
				}

				.lastest_msg_content {
					flex: 1;
					max-width: 75vw;
					// margin-right: 160rpx;
					// /deep/uni-view {
					@include ellipsisWithLine(1);
					// }
				}
			}
		}
	}

	.right_desc {
		@include colBox(true);
		align-items: flex-end;
		width: max-content;
		justify-content: space-between;
		height: 46px;

		.send_time {
			width: max-content;
			font-size: 28rpx;
			color: #999;
		}

		.u-badge {
			width: fit-content;
		}
	}

	.pinned {
		position: absolute;
		top: 0;
		right: 24rpx;
		width: 17rpx;
		height: 17rpx;
		background-image: linear-gradient(to bottom left, #314ffe 50%, white 50%);
	}
	
	.taoj{
		position: absolute;
		left: -1px;
		top: -1px;
		width: 50px;
		height: 50px;
		
	}
	
}
</style>
