<template>
	<div class="messageboard_container">
		<div class="main_top">
			<el-input
				v-model="search_txt"
				clearable
				placeholder="留言/用户昵称"
				style="width: 280px;margin-right: 20px;"
				prefix-icon="el-icon-search"
				@change="seachHandle"
			/>
			<el-checkbox v-model="isUnread" @change="unReadChange">只看未读留言</el-checkbox>
		</div>	
		<div class="main">
			<div class="left-cont section-item">
				<div class="left-top">
					<el-cascader
						v-model="classify"
						:options="classifyOptions"
						class="classify-select"
						:show-all-levels="false"
						style="width: 150px"
						clearable
						placeholder="选择报告"
						@change="getReportList"
					/>
				</div>
				<ul class="report-ul report-rapper" v-if="report_total">
					<li class="report-item" v-for="report_item in reportList" :key="report_item.ReportId">
						<div :class="['report-item-cont',{ act: select_report.ReportId===report_item.ReportId }]" @click="clickReportItemHandle(report_item)">
							<div class="title">
								<span v-if="report_item.ReportChapterList">{{report_item.Title}}</span>
								<span v-else>{{report_item.Title}}({{report_item.CreateTime.substring(5,7)}}{{report_item.CreateTime.substring(8,10)}}) </span>
								<template v-if="report_item.ReportChapterList">
									<i class="el-icon-arrow-up" v-show="report_item.isSlide"/>
									<i class="el-icon-arrow-down" v-show="!report_item.isSlide"/>
								</template>
							</div>

							<div class="item-bot">
								<span v-if="report_item.PublishTime">发布时间：{{ report_item.PublishTime | formatDate }}</span>
								<span v-else></span>
								<div>
									<span class="unread-icon" v-if="report_item.CommentUnreadNum>0">{{report_item.CommentUnreadNum}}</span>
									<span v-if="report_item.CommentNum">{{report_item.CommentNum}}条</span> 
								</div>
							</div>
						</div>
						
						<ul class="sublist-ul report-ul" v-show="report_item.ReportChapterList && report_item.isSlide">
							<li class="subreport-item" v-for="sub_item in report_item.ReportChapterList" :key="sub_item.ReportChapterId">
								<div :class="['report-item-cont',{ act: select_report.ReportChapterId===sub_item.ReportChapterId }]" @click="clickReportItemHandle(sub_item,report_item)">
									<div class="title">
										<span>{{sub_item.Title}}</span>
									</div>

									<div class="item-bot">
										<span>{{sub_item.PublishTime | formatDate}}</span>
										<div>
											<!-- <span class="unread-icon" v-if="sub_item.CommentUnreadNum">{{sub_item.CommentUnreadNum}}</span> -->
											<span v-if="sub_item.CommentNum">{{sub_item.CommentNum}}条</span> 
										</div>
									</div>
								</div>
							</li>	
						</ul>
					</li>
				</ul>
				<div class="nodata" v-else>
					<img src="~@/assets/img/cus_m/nodata.png" alt="" style="display:block;width:128px;height:128px;margin: 0 auto;">
					<span>暂无报告</span>
				</div>
				<div style="height: 40px;margin-top: 10px; padding: 0 20px;" v-if="report_total">
					<!-- <m-page
						:page_no="report_page_no"
						:pageSize="20"
						:pagercount="1"
						:total="report_total"
						@handleCurrentChange="handleCurrentChange"
					/> -->
					<el-pagination
						layout="total,prev,pager,next" 
						background
						:current-page="report_page_no"
						@current-change="handleCurrentChange"
						:page-size="20"
						:total="report_total"
						:pager-count="5"
						style="float:right;"
					>
					</el-pagination>
					
				</div>
			</div>
			<div class="right-cont section-item">
				<ul class="status-cont">
					<li 
					:class="['status-item',{'act': select_status === item.key }]" 
					v-for="item in statusArr" 
					:key="item.label"
					@click="changeStatusHandle(item)"
					>
						{{ item.label }}
						<span v-if="item.count && item.count>0"> ({{item.count}})</span>
					</li>
				</ul>
				<ul class="message-list" v-if="messageList.length">
					<li class="messgae-item" v-for="message_item in messageList" :key="message_item.CommentId">
						<div 
							class="message-item-cont" 
							@mouseenter=" $set(message_item,'isHover',true)"
							@mouseleave=" message_item.isHover = false"
						>
							<img :src="message_item.HeadImgUrl" alt="" class="avatar">
							<div class="right-info">
								<h4 class="nick-name text_oneLine">{{message_item.NickName}}</h4>
								<p class="message">{{ message_item.Content }}</p>
								<div class="info-bottom">
									<div class="createtime">
										{{message_item.CreateTime | formatTime}}
										{{ `(来自: ${message_item.SourceAgent === 1 ? '小程序' : 'PC'})` }}
										<span v-if="!message_item.Enabled"  class="editsty" style="margin-left:10px;">该留言已被用户删除</span>
									</div>
									<div class="action-list" v-show="message_item.isHover">
										<template v-if="message_item.Enabled">
											<!-- <el-button type="text" :class="['btn-item',{del: message_item.IsHot}]" @click="actionHandle(message_item,'select')">{{!message_item.IsHot ? '设为精选' : '取消精选'}}</el-button> -->
											<el-button type="text" :class="['btn-item',{del: message_item.IsTop}]" @click="actionHandle(message_item,'top')">{{!message_item.IsTop ? '设为置顶' : '取消置顶'}}</el-button>
											<el-button type="text" class="btn-item" @click="actionHandle(message_item,'reply')">回复</el-button>
										</template>
										<el-button type="text" class="btn-item del" @click="actionHandle(message_item,'del','message')">删除</el-button>
									</div>
								</div>
								
							</div>
						</div>
						<div class="reply-content" v-if="message_item.isReply">
							<el-input
								v-model="message_item.reply_msg"
								type="textarea"
								:autosize="{ minRows: 3, maxRows: 4 }"
								placeholder="请输入回复"
								maxlength="150"
								show-word-limit
							>
							</el-input>
							<div class="reply-bottom">
								<div class="left">
									<el-button type="primary" @click="replyMessage(message_item)">回复</el-button>
									<el-tooltip 
										content="至多输入150字，超出部分不予显示" 
										placement="right"
									>
										<img :src="$icons.message_tip_icon" style="width:20px;">
									</el-tooltip>
								</div>
								<span @click="message_item.isReply = false">收起 <i class="el-icon-arrow-up"/></span>
							</div>
						</div>

						<ul class="replylist-cont" v-if="message_item.ReplyList">
							<li class="messgae-item sub-item" v-for="sub_item in message_item.ReplyList" :key="sub_item.CommentId">
								<div 
									class="message-item-cont"
									@mouseenter=" $set(sub_item,'isHover',true)"
									@mouseleave=" sub_item.isHover = false"
								>
									<img :src="sub_item.AdminImgUrl" alt="" class="sub-avatar">
									<div class="right-info">
										<h4 class="nick-name text_oneLine">{{sub_item.AdminName}}</h4>
										<p class="message">{{ sub_item.Content }}</p>
										<div class="info-bottom">
											<span class="createtime">
												{{sub_item.CreateTime | formatTime}}
											</span>
											<div class="action-list" v-show="sub_item.isHover">
												<el-button type="text" class="btn-item del" @click="delAction(sub_item,'reply',message_item)">删除</el-button>
											</div>
										</div>
									</div>
								</div>	
							</li>
						</ul>
					</li>
				</ul>
				<div class="nodata" v-else>
					<img src="~@/assets/img/cus_m/nodata.png" alt="" style="display:block;width:128px;height:128px;margin: 0 auto;">
					<span>暂无数据</span>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
import { classifylist,interactiveInterface } from '@/api/api';
import mPage from '@/components/mPage.vue'
import moment from 'moment';
export default {
	name:'',
	components: { mPage },
	filters: {
		formatTime(val) {
			let newval = val.replace(/-/g,'/');
			const time = new Date(newval);
			const now = new Date();
			const infer_time = parseInt((now.getTime() - time.getTime())/1000/60/60/24);//时间差
			const infer_year = parseInt(now.getFullYear() - time.getFullYear());// 年限差

			//当天
			if(infer_time === 0) {
				return moment(time).format('HH:mm:ss')
			} else if(infer_time === 1) {
				return `昨天 ${moment(time).format('HH:mm:ss')}`
			} else if(infer_time === 2) {
				return `前天 ${moment(time).format('HH:mm:ss')}`
			} else if( infer_time >=3 && infer_time <=7 ) { //周内
				return moment(time).format('ddd HH:mm:ss')
			} else if(infer_year === 0) {
				return moment(time).format('MM-DD HH:mm:ss')
			} else {
				return moment(time).format('YYYY-MM-DD HH:mm:ss')
			}
		},
		formatDate(e){
			return moment(e).format('MM-DD')
		}
	},
	data () {
		return {
			search_txt:  '',
			isUnread: false,//

			classify: [],
			classifyOptions: [],//分类列表

			report_page_no: 1,
			report_total: 0,
			reportList: [],//报告列表
			ReportId:'',

			select_report: {},//选中的报告
			select_status: '',
			statusArr: [
				{
					label: '全部',
					key: '',
					countKey: 'AllNum',
				},
				// {
				// 	label: '精选',
				// 	key: '1',
				// 	countKey: 'HotNum',
				// },
				{
					label: '置顶',
					key: '2',
					countKey: 'TopNum',
				},
			],//状态
			message_page_no: 1,
			messageList: [],//留言列表
		};
	},
	methods: {

		/* 获取分类 */
		getClassify() {
			let params={CurrentIndex:0,PageSize:1000,KeyWord:''};
			classifylist(params).then((res) => {
					if(res.Ret !== 200) return

					const { List } = res.Data;

					List.forEach(item=>{
						let newitem={label:item.ClassifyName,value:item.Id};
						if( item.Child ){
							let childnode=[];
							item.Child.forEach(itemchild=>{
								childnode.push({label:itemchild.ClassifyName,value:itemchild.Id});
							});
							newitem.children=childnode;
						}
						this.classifyOptions.push(newitem);
					});
			});
		},

		/* 页码改变 */
		handleCurrentChange(page) {
			this.report_page_no = page;
			this.getReportList();
		},

		seachHandle() {
			this.report_page_no = 1;
			this.getReportList();
		},

		unReadChange(){
			if(this.$route.query.from=='notice'){
				console.log('aaa');
				this.ReportId=''
				this.$router.push({
					query:{}
				})
			}

			this.getReportList()
		},

		/* 获取报告列表 */
		getReportList() {
			interactiveInterface.reportlist({
				ClassifyIdFirst: this.classify[0] || '',
				ClassifyIdSecond: this.classify[1] || '',
				Keyword: this.search_txt,
				UnRead: this.isUnread ? 1 : '',
				ReportId:this.ReportId||'',//如果是从消息列表点进来的从路由中取这个
				PageSize: 20,
				CurrentIndex: this.report_page_no
			}).then(res => {
				if(res.Ret !== 200) return
				const { List,Paging } = res.Data

				this.reportList = List ? List.map(item => ({ ...item,isSlide: false })) : [];
				this.report_total = Paging.Totals;
				this.initMessage();

				// 如果是从留言板点击进入的 1000后清除状态
				if(this.$route.query.from=='notice'){
					if(this.reportList.length>0){
						this.clickReportItemHandle(this.reportList[0])
					}
					setTimeout(() => {
						this.ReportId=''
						this.$router.push({
							query:{}
						})
					}, 1000);
					
				}
			})

		},

		/* 重置留言板 */
		initMessage() {
			this.message_page_no = 1;
			this.select_report = {};
			this.select_status = '';
			this.messageList = [];
			this.statusArr.forEach(_ => { 
				if(_.count)  _.count = 0;
			});
		},

		/* 获取留言 */
		getMessageList() {
			const { ReportId,ReportChapterId,parentId } = this.select_report;
			interactiveInterface.messgaelist({
				Keyword: this.search_txt,
				UnRead: this.isUnread ? 1 : '',
				CurrentIndex: this.message_page_no,
				PageSize: 10000,
				ReportId: ReportId || parentId || '',
				ReportChapterId: ReportChapterId || '',
				HotTopType: this.select_status
			}).then(res => {
				if(res.Ret !== 200) return

				const { List,StatNum } = res.Data;
				this.statusArr.forEach(_ => { _.count = StatNum[_.countKey] });
				this.messageList = List || [];
			})
		},

		/* 点击报告获取留言或展开 */
		clickReportItemHandle(item,parentItem={}) {
			//有2级分类 展开
			if(item.ReportChapterList) {
				item.isSlide = !item.isSlide
			}else {
				//查看留言板
				this.select_report = parentItem.ReportId ? { ...item,parentId:parentItem.ReportId } : item;
				parentItem.ReportId ? parentItem.CommentUnreadNum = parentItem.CommentUnreadNum - item.CommentUnreadNum : item.CommentUnreadNum = 0;
				console.log(parentItem.CommentUnreadNum,item.CommentUnreadNum)
				this.message_page_no = 1;
				this.getMessageList();
			}
		},

		/* 切换状态 */
		changeStatusHandle({ key }) {
			this.select_status = key;
			if(!this.select_report.ReportId && !this.select_report.ReportChapterId) return
			this.message_page_no = 1;
			this.getMessageList();
		},

		/* 回复留言 */
		replyMessage(item) {
			const { CommentId,reply_msg,ReplyList } = item;
			if(!reply_msg) return this.$message.warning('回复内容不能为空')
			if( ReplyList && ReplyList.length >=5 ) return this.$message.warning('超过回复条数')

			interactiveInterface.reply({ CommentId,content: reply_msg })
				.then(res => {
					if( res.Ret !== 200 ) return
					this.$message.success('回复成功')
					item.reply_msg = '';
					item.isReply = false;
					
					item.ReplyList = res.Data.ReplyList;
				})
		},

		/* 留言操作 */
		actionHandle(item,key,type='') {
			const dynamic_obj = {
				select: this.selectAction,
				top: this.setTopAction,
				reply: this.replyAction,
				del: this.delAction,
			}
			dynamic_obj[key](item,type);
		},

		/* 设置留言精选 */
		selectAction(item) {
			const {CommentId} = item;
			interactiveInterface.setHot({ CommentId })
				.then(res => {
					if(res.Ret !== 200) return

					const { IsHot } = res.Data;
					this.$message.success('设置成功')
					item.IsHot = IsHot;

					this.statusArr.forEach(x => {
						if(x.countKey === 'HotNum') {
							x.count = IsHot ? x.count + 1 : x.count -1
						}
					})
					
					//取消精选即取消置顶
					if(item.IsTop) {
						item.IsTop = IsHot ? item.IsTop : 0;
						this.statusArr.forEach(x => {
							if(x.countKey === 'TopNum') {
								x.count = IsHot ? x.count : x.count - 1
							}
						})
					}

				})
		},

		/* 设置置顶 */
		setTopAction(item) {
			const {CommentId} = item;
			interactiveInterface.setTop({ CommentId })
				.then(res => {
					if(res.Ret !== 200) return

					const { IsTop } = res.Data;
					this.$message.success('设置成功')
					item.IsTop = IsTop;

					this.statusArr.forEach(x => {
						if(x.countKey === 'TopNum') {
							x.count = IsTop ? x.count + 1 : x.count -1
						}
					})

					//设置置顶即精选
					if(!item.IsHot) {
						item.IsHot = IsTop ? 1 : item.IsHot;
						this.statusArr.forEach(x => {
							if(x.countKey === 'HotNum') {
								x.count = IsTop ? x.count + 1 : x.count
							}
						})
					}

				})
		},

		/* 点击回复 展开输入框*/
		replyAction(item) {
			this.$set(item,'isReply',true)
			this.$set(item,'reply_msg','')
		},

		/* 删除留言 */
		delAction(item,type,parentItem=null) {
			const { CommentId,ReplyList,IsHot,IsTop } = item;

			const message = type === 'reply' ? '删除后无法恢复，确定删除该回复吗?' 
				: ReplyList ? '删除后无法恢复，确定删除该留言及其所有回复吗?' 
				: '删除后无法恢复，确定删除该留言吗?';
			this.$confirm(
				message,
				'提示',
				{ type:'warning'})
			.then( async() => {
				const { Ret } = type === 'reply' ? await interactiveInterface.delReply({ CommentId }) : await interactiveInterface.delMsg({ CommentId });

				if(Ret !== 200) return;
				this.$message.success('删除成功')

				if(type === 'reply') {
					let index = parentItem.ReplyList.findIndex(_ => _.CommentId === item.CommentId);
					parentItem.ReplyList.splice(index,1);
				} else {
					let index = this.messageList.findIndex(_ => _.CommentId === item.CommentId);
					this.messageList.splice(index,1);
					this.statusArr.forEach(x => {
							x.count =  (x.countKey === 'AllNum'
								|| (x.countKey === 'TopNum' &&  IsTop)
								|| (x.countKey === 'HotNum' &&  IsHot))
								? x.count - 1
								: count;
					})

				}
			
			}).catch(() => {});
		}

	},
	mounted() {
		if(this.$route.query.from=='notice'){
			this.ReportId=Number(this.$route.query.reportid)
			this.isUnread=true
		}
		this.getClassify();
		this.getReportList();
	},
}
</script>
<style lang='scss' scoped>
*{ box-sizing: border-box;}
.messageboard_container {
	.main_top {
		display: flex;
		align-items: center;
		margin-bottom: 20px;
		padding: 20px 30px;
		background: #fff;
		border: 1px solid #ececec;
		border-radius: 4px;
		box-shadow: 0 3px 6px rgba(0, 0, 0, 0.05);
	}
	.main {
		display: flex;
		.section-item {
			background: #fff;
			padding: 20px 0;
			border: 1px solid #ececec;
			border-radius: 4px;
			box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
			height: calc(100vh - 220px);
			overflow: hidden;
			position: relative;
			.left-top {
				margin-bottom: 15px;
				padding: 0 20px;
			}
			&.left-cont {
				width: 350px;
				margin-right: 20px;
			}
			&.right-cont {
				flex: 1;
				/* overflow-y: auto; */
			}
			.nodata {
				text-align: center;
				color: #999;
				font-size: 16px;
				padding-top: 10%;
			}
		}
		.report-rapper {
			height: calc(100vh - 370px);
			overflow-y: auto;
			padding: 0 20px;
		}
		.report-ul {
			.report-item:first-child {
				border-top: 1px solid #dcdfe6;
			}
			.report-item,.subreport-item {
				.report-item-cont {
					border-bottom: 1px solid #DCDFE6;
					padding: 10px 0;
					.title {
						font-size: 16px;
						display: flex;
						align-items: center;
						justify-content: space-between;
					}
					.item-bot {
						display: flex;
						margin-top: 10px;
						align-items: center;
						justify-content: space-between;
						color: #999;
					}
					&.act {
						background-color: #F3F7FF;
						.title { color: #409EFF; }
					}
					&:hover {
						background-color: #F3F7FF;
						.title { color: #409EFF; }
					}
					.unread-icon {
						width: 18px;
						height: 18px;
						background-color: #D62020;
						border-radius: 50%;
						text-align: center;
						line-height: 18px;
						color: #fff;
						font-size: 12px;
						display: inline-block;
					}

				}
			}
			&.sublist-ul {
				border-top: none;
				.subreport-item .report-item-cont{
					padding-left: 20px;
				}
			}
		}

		.status-cont {
			display: flex;
			align-items: center;
			padding: 0 20px;
			.status-item {
				padding: 10px 22px;
				cursor: pointer;
				&.act {
					background-color: #409EFF;
					color: #fff;
					border-radius: 4px;
				}
			}
		}
		.message-list {
			padding: 20px 20px 30px;
			height: calc(100vh - 290px);
			overflow-y: auto;
			.messgae-item {
				border-bottom: 1px solid #DCDFE6;
				padding: 15px 0;
				.message-item-cont {
					display: flex;
					&:hover {
						cursor: pointer;
						background-color: #F3F7FF;
					}
				}
				&.sub-item {
					padding-left: 55px;
					border: none;
				}
				.avatar {
					width: 45px;
					height: 45px;
					margin-right: 10px;
				}
				.sub-avatar {
					width: 36px;
					height: 36px;
					margin-right: 10px;
				}
				.right-info {
					/* flex: 1; */
					width: 92%;
					.nick-name {
						color: #666;
						font-size: 16px;
					}
					.message {
						margin-top: 5px;
					}
					.info-bottom {
						display: flex;
						align-items: center;
						justify-content: space-between;
						height: 40px;
						.createtime {
							color: #999;
						}
						.action-list {
							display: flex;
							.btn-item {
								margin-right: 20px;
								&:last-child { margin-right: 0; }
								&.del {
									color: #f00;
								}
							}
						}
					}
				}

				.reply-content {
					margin-top: 15px;
					padding-left: 55px;
					.reply-bottom {
						margin-top: 10px;
						display: flex;
						align-items: center;
						justify-content: space-between;
						color: #666;
						.left {
							display: flex;
							align-items: center;
							.el-button {
								padding: 10px 20px;
								margin-right: 5px;
							}
						}
					}
				}
			}
		}
	}
}
</style>
<style lang="scss">
.messageboard_container {
	.classify-select {
		.el-input__inner {
			height: 34px;
			line-height: 34px;
			border-color: #409EFF;
			color: #409EFF;
		}
	}

}
</style>