<template>
	<view class="es content es-bc-white" style="position:relative;flex-direction: column;" @touchmove.stop>
		 <view class="comtentBox es-bc-white es-pb-40 es-br-20 flex"  >
			<view class="es es-h-60" >
				<view class="es es-ac es-view-w-x es-h-44  es-mt-25"  >
					<image class="es-w-35 es-h-31" src="/static/images/course/comment2.png"></image>
					<text class="es-ml-20 es-fs-28 es-fw-600 es-f1">评论</text>
					<text class="es-ml-1 es-fs-30 es-c-99">（{{totalNum}}）</text>
				</view>
				<image @tap="closePopup()" style="position: absolute;right:30rpx;top:20rpx" class="es-w-40 es-h-40" src="/static/images/close40.png"></image>
			</view>
			<view class="es-view-w-x es-mt-15" >
				<view class="es es-ac es-mt-25 es-c" style="border-bottom: 1px #FAFAFA solid;">
					<view class="es-on-act nav es-icon-auto es es-ac es-pc x-c es-br-10"  :class="sortType==1?'ac':'br'" @tap="tapCommentType(1)">
						<image src="/static/images/course/icon-2.png" class="es-icon-20"></image>
						<text class="es-ml-19 es-fs-28 es-c" :class="1?'es-fw-600':''">热度</text>
					</view>
					
					<view class="es-on-act nav es-icon-auto es es-ac es-pc es-br-10 es-ml-14" :class="sortType==2?'ac':'br'" @tap="tapCommentType(2)">
						<image src="/static/images/course/icon-2.png" class="es-icon-20"></image>
						<text class="es-ml-19 es-fs-28 es-c" :class="0?'es-fw-600':''">时间</text>
					</view>
				</view>
				
				<list loadmoreoffset="100" @loadmore="loadmore" :style="{'height':listHei+'px'}" >
						<refresh @pullingdown='onpullingdown' @refresh="onrefresh" :display=" refreshing ? 'show' : 'hide' " class="refresh x-c ">
							<loading-indicator style="width: 22px;height: 22px;color:#999;"></loading-indicator>
							<text class="es-fs-32 es-ml-8">{{refreshText}}</text>
						</refresh>
						<cell v-for="(item, index) in dataList"  :key="index">
							
							 <view   class="es es-mt-30" >
								<image class="es-icon-80 es-br" :src="isEmpty(item.avatar)?defHeadImg:item.avatar"></image>
								<view  class="es-f1 es-ml-21" style="display:flex;flex:1;">
									<text class="es-fs-28 es-fw">{{ isEmpty(item.nickName)?"暂无昵称":item.nickName  }}</text>
									<text class="es-c-99 es-fs-22 es-mt-4">{{ formatDate(item.createTime) }}</text>
									<text class="es-fs-26 es-fw-500 es-pt-24 es-pb-25">{{item.content}}</text>
									<view class="es es-c-99  es-pb-10">
										<view class="es es-ac" @tap="doLike(item,index)">
											<image class="es-icon-28" :src="item.isLike?'/static/images/course/dianzan_on_icon.png':'/static/images/course/dianzan_icon.png'"></image>
											<text class="es-ml-11 es-fs-26">{{item.likes}}</text>
										</view>
										<view class="es es-ac es-ml-23" @tap="doReply(item)">
											<image class="es-icon-28" src="/static/images/course/pingjia_icon.png"></image>
											<text class="es-ml-11 es-fs-26">{{item.replyCount}}</text>
										</view>
										<view class="es-f1"></view>
										<view class="es es-ac es-pc es-icon-33" style="position:absolute;right:20rpx;"  v-if="isMySend(item)"  @tap="delComment(item)">
											<image src="/static/images/course/more_icon16.png" class="es-w-32 es-h-32"></image>
										</view>
									</view>
									<view v-if="item.replyList && item.replyList.length>0" class="es-br-20 es-pt-10 es-pb-10 es-view-w-x es-mt-25"
										style="background-color: #F5F7FA;">
										<view class="es es-pt-20 es-pb-20" :class="cIndex<item.replyList.length-1?'comment-reply-item':''"  v-for="(cItem,cIndex) in item.replyList"    :key="cIndex">	
											<image class="es-icon-60 es-br" :src="isEmpty(cItem.avatar)?defHeadImg:cItem.avatar"></image>
											<view class="es-f1 es-ml-11" style="display:flex;flex:1;">
												<text class="es-fs-24 es-fw-600">{{cItem.nickName || '暂无昵称'}}</text>
												<text class="es-fs-22 es-c-99 es-mt-10 es-mb-10">{{ formatDate(cItem.createTime) }}</text>
												<text class="es-fs-24 es-fw-500 es-pb-20">{{cItem.content}}</text>
												
												<view class="es-f1 es-c-99">
													<view class="es es-ac" @tap="doLike(cItem,index,cIndex,1)">
														<image class="es-icon-28" :src="cItem.isLike?'/static/images/course/dianzan_on_icon.png':'/static/images/course/dianzan_icon.png'"></image>
														<text class="es-ml-11 es-fs-26">{{cItem.likes}}</text>
													</view>
													
													<view class="es es-ac es-pc es-icon-33" style="position:absolute;right:0"  v-if="isMySend(cItem)"  @tap="delComment(cItem)">
														<image src="/static/images/course/more_icon16.png" class="es-w-32 es-h-32"></image>
													</view>
												</view>
											</view>
										</view>
										
										<view @tap="replayClick(item,index)" v-if="item.replyList && item.replyList.length>3"  class="es es-ac es-mt-20 es-pb-20">
											<view class="es-f1"></view>
											<text v-if="item.expand==undefined"  class="es es-ac es-fs-22 es es-ac es-pc es-view-w-x es-pt-10 es-pb-10 es-br es-brc es-c">
												{{item.replyList.length-3}}条回复>
											</text>
										</view>
									</view>
								
								</view>
							</view>
						</cell>
				 
						<cell v-if="showLoadMore || dataList.length > 4">
							  <view class="loading-more">
								  <text class="loading-more-text">{{loadMoreText}}</text>
							  </view>
						</cell>
						
						<cell>
							<view v-if="totalNum==0 && reqDataCode!=0"  class="y-f" style="height: 300px;padding-top: 200rpx;" >
								<image @tap="refreshPage()" class="es-w-124 es-h-80" style="width:187rpx;height:120rpx;" src="/static/image/nodata.png"></image>
								<text @tap="refreshPage()" class="es-c-33">{{reqDataCode==1?'暂无数据':'请求超时'}}</text>
							</view>
						</cell>
				</list>
			  
			</view>
		</view>
    
		<view  :style="'height:'+(KeyHight)+'px'" style="background-color: red;" v-if="KeyHight>0"></view>
		<view class="es-h-120 es-auto-bottom" v-else></view>
	
		<cover-view class="fix-bottom  es-b-t" >
			<view class="es-h-120  es-view-w-x es es-ac flex" >
				<view class="es-f1 es-br es-ipt flex ac es-h-70 es-pl-20 es-pr-20 es-pt-10" >
					<input style="width:100%;font-size: 28rpx;" ref="txtPing" v-model="pingContent" :focus="isInputFocus" 
					 @blur="onblur" :placeholder="placeholder" placeholder-class="es-c" />
				</view>  
				<text class="es-w-120 es-h-60 es-fs-30 es-fw-600 es-ml-20 es-c " style="text-align: center;line-height: 60rpx;" :adjust-position="false"
					:always-system="true" @tap="doSend">发布</text>
			</view>
			<view class="es-auto-bottom" v-if="!KeyHight"></view>
		</cover-view>

	</view>
</template>

<script>   
	
	import { getCourseById,getCommentList,addComment,updateComment,commentDoLike,deleteComment } from '@/api/course'
	import { isLogin,isEmpty } from '@/utils/common'
	import { showLoginPage } from '@/utils/login'
	import dayjs from 'dayjs';
	export default {
		data() {
			return {
				pingContent: '',
				KeyHight:0,
				cateId:5,
				courseId:0,
				totalNum:0,
				courseData:{},
				pageHei:400,
				downOption: {
					auto: false ,// 不自动加载 (mixin已处理第一个tab触发downCallback)
					use:true
				},
				upOption: {
					use:true,
					auto: false, // 不自动加载
					page: {
						num: 0, // 当前页码,默认0,回调之前会加1,即callback(page)会从1开始
						size: 10 // 每页数据的数量
					},
					empty:{
						tip: '~ 暂无数据 ~', // 提示
						btnText: '去看看'
					},
					noMoreSize: 4, //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看; 默认5
				   
				},
				pingType:1,//1:评论   2:回复
				dataList: [], //列表数据
				replyParentId:null,
				txtPing:null,
				sortType:1,
				isInputFocus:false,
				showBoottom:true,
				placeholder:"发布一条友善的评论",
				defHeadImg:"/static/images/hall/my_heads_icon.png",
				myUserInfo:{userId:0},
				delCommentId:null,
				mescroll:null,
				adpid: '',
		        loadMoreText:"加载中...",
		        showLoadMore:false,
				isLastPage:false,
				refreshing: false,
				refreshText: '下拉刷新',
				pageNum:1,
				listHei:0,
				reqDataCode:0 //1:正常加载 -1 请求超时
			}
		},
		mounted() {
			try {
				console.log("qxj commentN mounted");
				let that=this;
				this.subNVue= uni.getSubNVueById('commentN');
				uni.$on('comment', (data) => {  
				    that.videoId=data.videoId;
					that.courseId=data.courseId;
					that.getCourseInfo();
					that.upCallback();
				}); 
				
				const res = uni.getSystemInfoSync();
				// this.listHei=res.windowHeight*1;
				// this.listHei=uni.upx2px(1150 - 240);
				this.listHei= res.windowHeight*0.85 - uni.upx2px(324);
				
				this.txtPing = this.$refs["txtPing"];
				uni.onKeyboardHeightChange(this.boardHeightChange);
				
				if(this.isLogin()){
					let useInfo=uni.getStorageSync('userInfo');
					if(!!useInfo && useInfo!=null){
						this.myUserInfo=JSON.parse(useInfo);
					}
				}
			
			} catch (e) {
				
			}
		},
		onUnload() {
			console.log("qxj commentN onUnload");
			uni.offKeyboardHeightChange(this.boardHeightChange);
			uni.$off("comment");
		},
		methods: {
		    getCourseInfo(){
		       getCourseById(this.courseId).then(res => {
		    		if(res.code==200){
		    			this.courseData=res.data;
		    		}
		    	},
		    	rej => {}
		       );
		    },
			onpullingdown(e) {
			    if (this.refreshing) return;
				if (Math.abs(e.pullingDistance) > Math.abs(e.viewHeight)) {
					this.refreshText = '下拉更新'
				} else {
					this.refreshText = '释放更新'
				}
			 },
			 onrefresh(e) {
			   console.log('onRefreshing...');
			    this.refreshing = true;
				this.pageNum=1;
			    this.upCallback();
			    if (this.refreshing) return;
			},
			loadmore(){
				if(this.isLastPage){
					return;
				}
				console.log("loadmore");
				this.pageNum++;
				this.showLoadMore = true;
				setTimeout(() => {
					this.upCallback();
				}, 300);
			},
			/*下拉刷新的回调 */
			upCallback() {   	
				/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
				const params={"courseId":this.courseId,"sortType":this.sortType};
				uni.showLoading({title:""});
				getCommentList(params,this.pageNum).then(res => {
					    uni.hideLoading();
						if(res.code==200){
							setTimeout(()=>{
								//this.mescroll.endByPage(res.data.list.length, res.data.pages);
								if(this.pageNum == 1) this.dataList = []; //如果是第一页需手动制空列表
								this.dataList=this.dataList.concat(res.data.list); //追加新数据
								this.totalNum=res.data.total;
								this.reqDataCode=1;
								this.refreshing = false;
								this.isLastPage=res.data.isLastPage;
								if(this.isLastPage){
									this.refreshText = '加载完成'
								}
								if(res.data.isLastPage){
									this.loadMoreText = "";
									this.showLoadMore=false;
								}
							},200);
						}else{
							this.refreshing = false;
							this.refreshText = '加载完成';
							this.reqDataCode=-1;
						}
					},
					rej => {}
				).catch(()=>{
					//联网失败, 结束加载
					this.refreshing = false;
					this.refreshText = '加载完成';
					this.reqDataCode=-1;
				});
			},
			closePopup() {
			   const subNVue = uni.getSubNVueById('commentN');
			   subNVue.hide('slide-out-bottom');
			},
			refreshPage(){
				 this.pageNum=1;
			     this.upCallback();
			},
			tapCommentType(type){
				this.sortType=type;
				this.refreshPage();
			},
			isMySend(item){
				if(this.myUserInfo!=null && this.myUserInfo.userId==item.userId){
					return true;
				}
				return false;
			},
			doSend(){
			   
			     if(this.isEmpty(this.pingContent)){
			     	uni.showToast({title: '评论内容不能为空',icon: 'none'});
			     	return;
			     }
				 if(!isLogin()){
					showLoginPage();
					return;
				  }
			     let params={"courseId":this.courseId,"content":this.pingContent,"type":this.pingType};
			     if(!!this.replyParentId){
			     	params["parentId"]=this.replyParentId;
			     }
			     uni.showLoading({title:""});
			     addComment(params).then(res => {
			     		uni.hideLoading();
			     		if(res.code==200){
			     			uni.showToast({title: '添加评论成功',icon: 'none'});
			     		}else{
			     			uni.showToast({title: res.msg,icon: 'none'});
			     		}
			     		this.placeholder="发布一条友善的评论";
			     		this.pingType=1;
			     		this.pingContent='';
			     		this.refreshPage();
			     		
			     	},
			     	rej => {}
			     );
			     			
			},
			doReply(item){
				this.replyParentId=item.commentId;
				this.pingType=2;
				let placeHolder=this.isEmpty(item.nickName)?"回复":"回复"+item.nickName;
				this.placeholder=placeHolder;
				this.pingContent='';
				//this.isInputFocus=true;
			    this.$nextTick(()=>{
			    	this.$refs.txtPing.focus();
			    });
			
			},
			replayClick(item,index){
				item.expand=true;  
				this.dataList[index]=item;
				this.$forceUpdate(); // 如果你需要强制刷新，可以调用 $forceUpdate()
			},
			expandReplyAct(item,idx){
				return true
			},
			onblur(){
				console.log("qxj onblur");
			    
			},
			doLike(item,index,childIdx,type){
				if(!this.isLogin()){
					showLoginPage();
					return;
				}
				const params={"commentId":item.commentId};
				uni.showLoading({title:""});
				commentDoLike(params).then(res => {
						uni.hideLoading();
						if(res.code==200){
							if(item.isLike==0){
								item.likes+=1;
								item.isLike=1;
							}else{
								item.likes=1;
								item.isLike=0;
							}
							// 	this.dataList[index]=item;
							// this.$forceUpdate();
							uni.showToast({title: '操作成功',icon: 'none'});
						}else{
							uni.showToast({title: res.msg,icon: 'none'});
						}
						
					},
					rej => {}
				);
			},
			delComment(item){
				this.delCommentId=item.commentId;
				let that = this;
				uni.showModal({
				      title:  '系统提示',
				      content:  '确定删除吗',
				      success:  function  (res)  {
				          if  (res.confirm)  {
							    console.log("qxj confirm");
				                that.delCommentAct();
				          }  else if  (res.cancel)  {
				               console.log("qxj cancel");
				          }
				      }
				});
			},
			delCommentAct(){
				if(!this.isLogin()){
					showLoginPage();
					return;
				}
				uni.showLoading({title:""});
				deleteComment(this.delCommentId).then(res => {
						uni.hideLoading();
						if(res.code==200){
							uni.showToast({title: '操作成功',icon: 'none'});
						}else{
							uni.showToast({title: res.msg,icon: 'none'});
						}
						this.refreshPage();
					},
					rej => {}
				);
			},
			boardHeightChange:function(res){
				console.log('changeHeight', res.height);
				if(res.height==0){
					this.placeholder="发布一条友善的评论";
					//this.pingContent='';
					this.isInputFocus=false;
				}else{
					this.isInputFocus=true;
					
				}
				this.KeyHight = res.height;
			},
		    isLogin() {
		    	let obj=uni.getStorageSync("AppToken");
		    	return !!obj;
		    },
			isEmpty(obj) {
				if (typeof obj == "undefined" || obj == null || obj == "") {
					return true;
				} else {
					return false;
				}
			},
			formatDate(dateStr) {
				let formatStr = "";
				let formatDate;
				if(dateStr==null){
					return formatStr;
				}
				let date = dayjs(dateStr,'YYYY-MM-DD HH:mm:ss');
				let today = dayjs();
				if (date.year() != today.year()) {
					formatDate = date.format('YYYY-MM-DD HH:mm');
				} 
				else if (date.month() === today.month()) {
					switch (date.date() - today.date()) {
						case 0:
							formatDate = date.format('今天 HH:mm');
							break;
						case -1:
							formatDate = date.format('昨天 HH:mm');
							break;
						case 1:
							formatDate = date.format('明天 HH:mm');
							break;
						default:
							formatDate = date.format('MM-DD HH:mm');
							break;
					}
				} 
				else if (date.month() - today.month() === 0 && date.date() === 1) {
					formatDate = date.format('明天 HH:mm');
				} 
				else {
					formatDate = date.format('MM-DD HH:mm');
				}
				return formatDate;
			}
			
		},
		onHide() {
			 console.log("qxj commentN onHide");
		},
		onClose() {
			 console.log("qxj commentN onClose");
		},
		beforeDestroy() {
		    console.log("qxj commentN beforeDestroy");
		    uni.$off('comment');
		},
		destroyed() {
			console.log("qxj commentN destroyed");
			// 注销全局配置监听
			uni.$off("comment");
		}
	}
</script>

<style scoped>
	
	page {
		background-color: white;
	}
	
	.fl-row{
		display: flex;
		flex-direction: row;
	}
	  
	.comtentBox{
		background-color:#171a1d;
		box-sizing: border-box;
	}

	.banner {
		height: 430rpx;
	}

	.es-icon-course-bg {
		background-image: url(/static/images/course/bg.png);
	}

	.es-icon-course-icon-1 {
		background-image: url(/static/images/course/icon-1.png);
	}

	.es-icon-course-icon-2 {
		background-image: url(/static/images/course/icon-2.png);
	}

	.es-icon-course-icon-3 {
		background-image: url(/static/images/course/icon-3.png);
	}

	.es-icon-course-close {
		background-image: url(/static/images/course/close.png);
	}

	.es-icon-course-info {
		background-image: url(/static/images/course/info.png);
	}

	.es-icon-course-bg2 {
		background-image: url(/static/images/course/bg2.png);
	}

	.es-icon-course-bg3 {
		background-image: url(/static/images/course/bg3.png);
	}

	.es-icon-course-comment {
		background-image: url(/static/images/course/comment.png);
	}

	.es-icon-course-comment2 {
		background-image: url(/static/images/course/comment2.png);
	}

	.es-icon-course-nav-bg,
	.nav {
		background-image: url(/static/images/course/nav-bg.png);
	}

	.es-icon-course-nav-bg-ac,.ac {
		background-color: #ffd8c4;
	}

	.es-icon-course-point {
		background-image: url(/static/images/course/point.png);
	}

	.es-icon-course-share {
		background-image: url(/static/images/course/share.png);
	}

	.es-icon-course-like2 {
		background-image: url(/static/images/course/like2.png);
	}

	.es-icon-course-like2-ac {
		background-image: url(/static/images/course/like2-ac.png);
	}

	.item {
		width: calc(33.33% - 14rpx);
	}

	.nav {
		width: 216rpx;
		height: 60rpx;
	}

	.comment-reply-item {
		/* border-bottom: 1px #fff solid; */
	}


	.br{
	  border: 1px solid #FF5C03;
	}
	
	.fix-bottom{
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		/* width: 100%; */
		z-index: 999;
		background-color: white;
	
	}
	
	.refresh {
		display: flex;
		flex-direction: row; 
	    justify-content: center;
		height: 50px;
	}
	
	.loading-more {
		  align-items: center;
		  justify-content: center;
		  padding-top: 14px;
		  padding-bottom: 14px;
		  text-align: center;
	}
	
	.loading-more-text {
		  font-size: 28rpx;
		  color: #999;
	}
	
	
 
</style>