<template>
	<view class="allocationPerson-page">
		<scroll-view class="scroll-y" scroll-y="true">
			<template>
				<view class="blockTitle">计划时间</view>
				<div class="date-view">
					<view class="row">
						<!-- 已经分配过的病区，再次修改禁止修改时间 -->
						<text class="label">开始时间</text>
						<view class="date-box">
							<date-time-picker :disabled="details.isDistribution" :height="100"
								:start="details.startDate" :end="details.planEndDate" :defaultValue="details.startDate"
								placeholder="请选择起始时间" pickType="startDate" @change="changeDateTime" />
						</view>
					</view>
					<view class="row">
						<text class="label">结束时间</text>
						<view class="date-box">
							<date-time-picker :disabled="details.isDistribution" :height="100"
								:start="details.planStartDate" :end="details.planEndDate"
								:defaultValue="details.endDate?details.endDate:details.planEndDate" placeholder="请选择结束时间" pickType="endDate"
								@change="changeDateTime" />
						</view>
					</view>
				</div>

				<view class="tabWrap" v-if="checkPointList.length >0">
					<view :class="[currentSelectedTab==0?'on tab':'tab']" @click="tabChangeHandle(0)">
						{{`查核人(${checkPresonList.length})`}}</view>
					<view :class="[currentSelectedTab==1?'on tab':'tab']" @click="tabChangeHandle(1)">
						{{`要点分类(${checkedPointList.length})`}}</view>
				</view>

				<view class="blockTitle noBottomBlockTitle" v-if="checkPointList.length == 0">
					查核人<text>{{`已选择${checkPresonList.length}人`}}</text></view>

				<view v-if="currentSelectedTab==0">
					<view class="filter">
						<view class="selecter" @click="selecterHandle">
							<text>{{selectedDeptStr}}</text>
							<image src="../../static/fillBlackArrow.png" mode=""></image>
						</view>
						<view class="searchBar">
							<image class="serachIcon" src="../../static/searchIcon.png" mode=""></image>
							<tm-input class="searchVal" :clear="ifclearSearch" @onChange="searchInputHandle"
								placeholder="请输入搜索姓名"></tm-input>
							<view class="searchBtn" @click="searchHandle">搜索</view>
						</view>
					</view>
					<view class="empListWrapper" v-if="empList.length>0" :style="{height:empListWrapperH}">
						<tm-checked-group :list="empList" :defaultValue='checkPresonList' :setting="{
						  value: 'employeeId',
						  name: 'label'
						}" :openkeys="[0]" @change="onCheckPerosonChanged" />
					</view>
					<view class="empty" v-if="empList.length==0">
						<image src="../../static/no-data.png" mode=""></image>
						<text>暂无内容</text>
					</view>
				</view>

				<tm-checked-group v-if="details.situationType == 3&&currentSelectedTab==1" :list="checkPointList"
					:defaultValue='checkedPointList' :setting="{
				  value: 'categoryId',
				  name: 'categoryName'
				}" :openkeys="[0]" @change="checkChanged" />

			</template>
		</scroll-view>
		<view class="fixed-buttom-btn" @click="sure">
			<text class="btn-text">确定</text>
		</view>
		<uni-popup ref="popup" type="bottom" :maskClick="true">
			<view class="selectableList">
				<scroll-view scroll-y="true" class="listWrap">
					<view :class="getClass(v.id)" v-for="(v,i) in departments" @click="listClickHandle(v)">{{v.name}}
					</view>
				</scroll-view>
				<!-- <view class="listWrap">
					<view :class="getClass(v.id)" v-for="(v,i) in departments" @click="listClickHandle(v)">{{v.name}}
					</view>
				</view> -->
				<view class="btnGroup">
					<view class="cancelBtn btn" @click="btnGroupClickHandle(false)">取消</view>
					<view class="confirmBtn btn" @click="btnGroupClickHandle(true)">确定</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	// 查核列表编辑 查核人和计划时间
	import {
		mapState
	} from "vuex";
	import moment from 'moment';
	export default {
		computed: {
			selectedDeptStr() {
				const {
					deptIdStr
				} = this.filter;
				return (deptIdStr.map(t => t.name)).join(',')
			},
			empListWrapperH() {
				if (this.checkPointList.length > 0) {
					return 'calc(100vh - 485rpx)'
				} else {
					return 'calc(100vh - 460rpx)'
				}
			},
			ifclearSearch() {
				return this.filter.keyword.length == 0
			},
		},
		watch: {
			filter(val, oldVal) {
				if (val.keyword.length == 0) {
					this.searchHandle();
				}
			}
		},
		data() {
			return {
				title: '', // 导航标题
				// 查核组员列表
				empList: [],
				// 组件信息
				details: {},
				//选中的查核人
				checkPresonList: [],
				//查核要点列表
				checkPointList: [],
				// 服务器时间
				dateStr: '',
				timer: null,
				// 点击确定按钮是否直接保存
				isSubmit: false,
				//选中的查核要点
				checkedPointList: [],
				//可选单位列表
				departments: [],
				currentSelectedTab: 0, //0 查核人 1 要点分类
				//筛选条件
				filter: {
					keyword: '',
					deptIdStr: [{
						name: '全部',
						id: 0
					}], //单位
				},
			}
		},
		onLoad(data) {
			
			const _details = JSON.parse(data.details);
			//初始化默认时间
			// console.log({data,_details});
			const currentDate = new Date();
			_details.startDate = `${currentDate.getFullYear()}-${currentDate.getMonth()+1}-${currentDate.getDate()} 00:00`;
			_details.endDate = _details.endDate;

			this.isZichaducha = _details.isZichaducha;
			this.departmentType = _details.departmentType;
			this.departmentId = _details.departmentId;
			this.editPlanIds = _details.ids;  //当前设置计划的id
			this.multiple = data.multiple; //是否批量
			
			// 强制刷新返回查核列表页面
			if (getCurrentPages().length === 1 && !this.isZichaducha) {
				const {
					situationId,
					checkId,
					checkGroupId,
					planStartDate,
					planEndDate,

				} = _details;
				uni.redirectTo({
					url: `/pages/editCheckList/editCheckList?situationId=${situationId}&checkId=${checkId}&checkGroupId=${checkGroupId}&startDate=${planStartDate}&endDate=${planEndDate}`
				});
			}
			this.pageQueryParams = _details;
			this.getComponentInfo(_details);
		},
		destroyed() {
			this.clearTimer();
		},
		methods: {
			tabChangeHandle(num) {
				this.currentSelectedTab = num;
			},
			getClass(id) {
				const index = this.filter.deptIdStr.findIndex(t => t.id == id)
				if (index != -1) {
					return "list on"
				}
				return "list"
			},
			searchHandle() {
				const {
					checkGroupId,
					situationType,
					checkedList,
				} = this.details;
				const deptId = checkedList?checkedList.join(','):'';
				this.getEmpDeptTree(checkGroupId, situationType, deptId)
			},
			/**
			 * @param {boolean} flag true确定按钮点击，false取消按钮
			 */
			btnGroupClickHandle(flag) {
				this.$refs.popup.close();
				//清空搜索
				this.filter = {
					...this.filter,
					keyword: ''
				}
			},
			listClickHandle(item) {
				const _filter = this.filter;
				const {
					deptIdStr
				} = _filter;
				const index = _filter.deptIdStr.findIndex(t => t.id == item.id);

				if (item.id == 0) {
					//全部
					this.filter = {
						...this.filter,
						deptIdStr: [{
							name: '全部',
							id: 0
						}]
					};
					return;
				}
				//去除全部选项选中
				deptIdStr.splice(_filter.deptIdStr.findIndex(t => t.id == 0), 1);

				if (index != -1) {
					deptIdStr.splice(index, 1)
				} else {
					deptIdStr.push({
						name: item.name,
						id: item.id
					})
				}
				this.filter = _filter;
			},
			selecterHandle() {
				this.$refs.popup.open();
			},
			/**
			 * @param {string} val
			 */
			searchInputHandle(val) {
				this.filter = {
					...this.filter,
					keyword: val
				};
			},
			getComponentInfo(details) {
				
				const {
					checkGroupId,
					situationType,
					checkId,
					// deptId,
					checkedList,
					empId,
					empName,
					categoryId
				} = details;
				
				this.details = details;
				
				const deptId = checkedList ? checkedList.join(',') : '';
				this.getEmpDeptTree(checkGroupId, situationType, deptId);
				//查核人回显
				if (empId && empName) {
					const empIdArr = empId.split(',');
					const empNameArr = empName.split(',');
					this.checkPresonList = empIdArr.map((item, index) => ({
						employeeId: Number(item),
						employeeName: empNameArr[index]
					}));
				}
				//查核要点回显
				if (categoryId) {
					this.checkedPointList = categoryId.map((item) => ({
						categoryId: Number(item),
					}));
				}

			},
			// 查询部门人员树
			getEmpDeptTree(checkGroupId, situationType, deptId) {

				if (this.isZichaducha) {
					//自查督查人员批量设置
					this.$store.dispatch({
						type: 'batchDistribution/commActions',
						key: "getZichaduchaEmpList",
						data: {
							departmentType: this.departmentType,
							departmentId: this.departmentId,
						}
					}).then((data) => {
						if (data) {

							this.empList = data.map(item => ({
								label: `${item.empName}`,
								employeeId: item.empId
							}));
							
							const deweight = (arr)=>{
							        let map = new Map();
							        for (let i of arr) {
							          if (!map.has(i.id)) {
							            map.set(i.id, i)
							          }
							        }
							        arr = [...map.values()]
							        return arr;
							}
							

							let departments = data.map(item => ({
								name: item.departmentName,
								id: item.departmentId
							}));

							this.departments = [{
								name: '全部',
								id: 0
							   }, 
							   ...deweight(departments)
							];
						}
					})

				} else {
					this.$store.dispatch({
						type: 'allocationPerson/commActions',
						key: "getGroupEmpList",
						data: {
							checkGroupId,
							situationType,
							deptId,
							name: this.filter.keyword,
							deptIdStr: (this.filter.deptIdStr.map(t => t.id == 0 ? '' : t.id)).join(',')
						}
					}).then(data => {
						if (data) {
							let empList = [];
							if (data.sysCheckGroupEmployees) {
								empList = data.sysCheckGroupEmployees.map(t => ({
									...t,
									label: `${t.employeeName}  |  ${t.code}  |  ${t.deptName}`
								}))
							} else {
								empList = [];
							}


							this.empList = empList;
							this.departments = [{
								name: '全部',
								id: 0
							}, ...data.departments] || [];
							if (situationType == 3) this.checkPointList = data.pointCategoryBOs || [];
						}
					});
				}

			},
			//查核要点选择回调
			checkChanged(data) {
				const {
					checkedList
				} = data;
				this.checkedPointList = checkedList;

			},
			//查核人选择回调
			onCheckPerosonChanged(data) {
				const {
					checkedList
				} = data;
				this.checkPresonList = checkedList;
			},
			// 指派查核人员改变
			changeDetails(selectVal, selectData, index) {
				this.details = {
					...this.details,
					empId: selectData.employeeId,
					empName: selectData.employeeName
				}
			},
			// 时间变化
			changeDateTime(dateObj, pickType) {
				if (pickType === 'startDate') { // 开始时间变化
					this.diffDateTime(dateObj.f3, this.details.endDate);
				} else {
					this.diffDateTime(this.details.startDate, dateObj.f3);
				}
				this.details = {
					...this.details,
					[pickType]: dateObj.f3
				};
			},
			// 开始时间和结束时间对比
			diffDateTime(startTime, endTime) {
				if (moment(startTime).valueOf() > moment(endTime).valueOf()) {
					this.showModal('开始时间不能大于结束时间');
				}
			},
			// 点击确定
			sure() {
				const {
					startDate,
					endDate,
					planEndDate
				} = this.details;
				
				console.log('this.details',this.details);
				
				const empId = (this.checkPresonList.map(item => item.employeeId)).join(',');
				const empName = (this.checkPresonList.map(item => item.employeeName)).join(',');

				if (!empId) {
					return this.showModal('请选择查核人');
				}
				if (!startDate) {
					return this.showModal('请选择开始时间');
				}
				if (!endDate&&!planEndDate) {
					return this.showModal('请选择结束时间');
				}
				if (this.checkPointList.length > 0 && this.checkedPointList.length == 0) {
					//当未选择要点分类时
					return this.showModal('请选择要点分类！');
				}
				
                
				if(this.isZichaducha){
					//自查督查计划修改
									
					if(this.multiple == 'false'){
						   
						   this.$store.dispatch({
						   	type: 'batchDistribution/commActions',
						   	key: 'saveZichaduchaPlanSet',
						   	data: {
						   		checkUser:this.checkPresonList.map(item=>({responsibleUserId:item.employeeId,responsibleUserName:item.label?item.label:item.employeeName})),
						   		departmentId:Number(this.departmentId),
						   		functionId:Number(this.editPlanIds),
						   		planStartDate:startDate,
						   		planEndDate:endDate?endDate:planEndDate
						   	}
						   }).then((data)=>{
						   	  if(data){
						   		     uni.navigateBack({
						   		     	delta: 1
						   		     });
						   	  }
						   })
					}else{
						//批量设置
						let ids = this.editPlanIds.split(',');
						this.$store.dispatch({
							type: 'batchDistribution/commActions',
							key: 'batchSaveZichaduchaPlanSet',
							data: {
								checkUser:this.checkPresonList.map(item=>({responsibleUserId:item.employeeId,responsibleUserName:item.label?item.label:item.employeeName})),
								functionId:ids.map(item=>Number(item)),
							}
						}).then((data)=>{
							  if(data){
								     uni.navigateBack({
								     	delta: 1
								     });
							  }
						})
					}
					
					
				}else{
					
					const {
						checkId,
						checkedList,
						checkNo,
						situationType
					} = this.details;
					const categoryIds = this.checkedPointList.map(item => item.categoryId);
					const data = {
						"checkId": checkId, //  计划id
						"deptId": JSON.parse(JSON.stringify(checkedList)), // 多个单位id列表
						"empId": empId, // 查核者id
						"empName": empName, // 查核者名字
						"startDate": startDate, // 开始时间
						"endDate": endDate?endDate:planEndDate, // 结束时间
						"checkNo": checkNo,
						"situationType": Number(situationType),
						"categoryIds": categoryIds
					
					}
					
					  this.$store.dispatch({
					  	type: 'batchDistribution/commActions',
					  	key: 'batchCheckEmp',
					  	data: {
					  		...data
					  	}
					  }).then(data => {
					  	if (data) {
					  		uni.showModal({
					  			title: '分配成功！',
					  			content: '',
					  			showCancel: false,
					  			success: function(res) {
					  				if (res.confirm) {
					  					// console.log('用户点击确定');
					  					let pages = getCurrentPages(); // 获取当前页面栈
					  					let prePage = pages[pages.length - 2]; // 上一个页面
					  					prePage.ifInit = true;
					  					uni.navigateBack({
					  						delta: 1
					  					});
					  
					  				}
					  			}
					  		});
					  	}
					  });
				}
			},


			// 获取当前时间
			getDateStr() {
				this.$store.dispatch({
					type: "commActions",
					key: "getDateStr",
				}).then((data) => {
					if (data) {
						this.dateStr = data;
					}
				});
			},
			showModal(content) {
				uni.showModal({
					content,
					showCancel: false
				});
			},
			// 清除定时器
			clearTimer() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			}
		},
	}
</script>

<style lang="less" scoped>
	.allocationPerson-page {
		height: 100%;

		.selectableList {
			display: flex;
			width: 100%;
			flex-direction: column;
			height: 50vh;
			padding-top: 50rpx;
			box-sizing: border-box;
			border-radius: 25rpx 25rpx 0px 0px;
			background-color: #FFFFFF;

			.listWrap {
				height: calc(50vh - 75rpx);
				overflow-y: scroll;

				.list {
					height: 87.5rpx;
					line-height: 87.5rpx;
					text-align: center;
					font-size: 30rpx;
					font-family: SourceHanSansCN-Normal, SourceHanSansCN;
					font-weight: 400;
					color: #8A8F99;

					&.on {
						font-weight: 500;
						color: #3377FF;
					}
				}
			}

			.btnGroup {
				display: flex;
				width: 100%;
				flex-direction: row;
				justify-content: center;
				align-items: center;

				.btn {
					width: 50%;
					height: 75rpx;
					line-height: 75rpx;
					text-align: center;
					font-size: 22.5rpx;
					font-family: SourceHanSansCN-Normal, SourceHanSansCN;
					font-weight: 400;
					color: #3377FF;
				}

				.cancelBtn {
					border-top: 0.62rpx solid #DADEE6;
				}

				.confirmBtn {
					color: #FFFFFF;
					background: #3377FF;
				}
			}
		}

		.scroll-y {
			height: calc(100% - 87.5rpx);
			padding-top: 15rpx;

			.blockTitle {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				font-size: 22.5rpx;
				font-family: SourceHanSansCN-Normal, SourceHanSansCN;
				font-weight: 400;
				color: #666F80;
				padding: 15rpx 25rpx;
				border-bottom: 0.62rpx solid #DADEE6;

				&.noBottomBlockTitle {
					border-bottom: none;
				}
			}

			.tabWrap {
				display: flex;
				flex-direction: row;
				justify-content: space-around;
				align-items: center;
				padding: 25rpx 0;
				padding-top: 12.5rpx;

				.tab {
					width: 250rpx;
					height: 50rpx;
					background: #FFFFFF;
					border-radius: 25rpx;
					font-size: 22.5rpx;
					font-family: SourceHanSansCN-Normal, SourceHanSansCN;
					font-weight: 400;
					text-align: center;
					line-height: 50rpx;
					;
					color: #525866;

					&.on {
						color: #FFFFFF;
						background: #3377FF;
					}
				}
			}

			.filter {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 15rpx;
				padding: 0 25rpx;
				background: #FFFFFF;

				.selecter {
					display: flex;
					width: 25%;
					height: 87.5rpx;
					flex-direction: row;
					justify-content: space-between;
					align-items: center;
					padding-right: 25rpx;
					border-right: 0.62rpx solid #DADEE6;

					&>text {
						width: 112.5rpx;
						font-size: 25rpx;
						font-family: SourceHanSansCN-Medium, SourceHanSansCN;
						font-weight: 500;
						color: #292C33;
						text-overflow: ellipsis;
						overflow: hidden;
						white-space: nowrap;

					}

					&>image {
						width: 11.25rpx;
						height: 7.5rpx;
					}
				}

				.searchBar {
					display: flex;
					width: 75%;
					flex-direction: row;
					align-items: center;
					height: 87.5rpx;
					padding-left: 25rpx;

					.serachIcon {
						width: 30rpx;
						height: 30rpx;
					}

					.searchVal {
						width: 79%;
						padding-left: 25rpx;
						font-size: 25rpx;
						font-family: SourceHanSansCN-Normal, SourceHanSansCN;
						font-weight: 400;
						color: #292C33;

					}

					.searchBtn {
						padding-left: 25rpx;
						font-size: 25rpx;
						font-family: SourceHanSansCN-Normal, SourceHanSansCN;
						font-weight: 400;
						color: #3377FF;
						white-space: nowrap;
						border-left: 1rpx solid #DADEE6;
					}
				}
			}

			.empListWrapper {
				// height: 40vh;
				overflow-y: scroll;
				margin-bottom: 25rpx;
				background-color: #FFFFFF;
			}

			.empty {
				display: flex;
				height: 40vh;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin-bottom: 25rpx;
				background-color: #FFFFFF;

				&>image {
					width: 175rpx;
					height: 190rpx;
					margin-bottom: 40rpx;
				}

				&>text {
					font-size: 22.5rpx;
					font-family: SourceHanSansCN-Normal, SourceHanSansCN;
					font-weight: 400;
					color: #828899;
				}
			}

			.date-view {
				padding: 0 25rpx;
				background: #fff;
				margin-bottom: 12.5rpx;
				border-bottom: 0.62rpx solid #DADEE6;

				.row {
					display: flex;
					align-items: center;
					height: 62.5rpx;
					border-bottom: 0.62rpx solid #DADEE6;

					.label {
						width: 112.5rpx;
						font-size: 22.5rpx;
						color: #292C33;
					}

					.date-box {
						padding-left: 25rpx;
						flex: 1;
					}

					&:last-child {
						border-bottom: 0;
					}
				}
			}
		}
	}
</style>
