<template>
	<view>
		<cu-custom :backUrl="'/pages/index/index'" :isBack="true" bgColor="bg-gradual-blue">
			<block slot="content">会议室预约</block>
		</cu-custom>
		<u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules"
			ref="inputForm" v-if="!nodeFlag">
			<u-form-item label="标题" prop="title" borderBottom :required="true">
				<u--input v-model="inputForm.title" placeholder="请输入会议标题" clearable></u--input>
			</u-form-item>
			<u-form-item label="会议室编号" prop="meetNumber" borderBottom :required="true">
				<jp-picker @input='checkTime' v-model="inputForm.meetNumber" rangeKey="label" rangeValue="value" :range="[
						        { label: '九楼会议室一', value: '1' },
						        { label: '九楼会议室二', value: '2' },
						        { label: '十楼会议室一', value: '3' },
						        { label: '十楼会议室二', value: '4' },
						    ]"></jp-picker>
			</u-form-item>


			<u-form-item label="会议开始时间" prop="startDate" borderBottom :required="true">
				<el-date-picker
						v-model="inputForm.startDate"
						type="date"
						placeholder="请选择日期"
						style="width:50%"
						size="default"
						value-format="yyyy-MM-dd"
						placement="bottom-start"
						@change="checkTime"
						:picker-options="pickerOptions"
						clearable>
				</el-date-picker>
				<el-select v-model="inputForm.startTime" placeholder="请选择时间" style="width:50%;" clearable>
					<el-option v-for="item in dateList" :disabled="item.disabled" :key="item.value" :label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</u-form-item>

			<u-form-item label="会议时长" prop="duration" borderBottom :required="true">
				<jp-picker v-model="inputForm.duration" rangeKey="label" rangeValue="value" :range="[
						        { label: '30分钟', value: '30' },
						        { label: '1小时', value: '1' },
						        { label: '2小时', value: '2' },
						        { label: '3小时', value: '3' },
						        { label: '4小时', value: '4' },
						        { label: '5小时', value: '5' },
						        { label: '6小时', value: '6' },
						        { label: '全天', value: '24' },
						    ]"></jp-picker>
			</u-form-item>

			<u-form-item label="会议发起人" prop="createByName" borderBottom>
				<u--input :disabled="true" v-model="inputForm.createByName"></u--input>
			</u-form-item>

			<u-form-item label="会议说明" prop="remarks" borderBottom>
				<u--textarea placeholder="请输入说明" :rows="5" :maxlength="500" style="width:100%"
					v-model="inputForm.remarks" show-word-limit></u--textarea>
			</u-form-item>
		</u--form>
		<u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules"
			ref="inputForm" v-if="nodeFlag">
		
			<u-form-item label="标题" prop="title" borderBottom :required="true">
				<u--input v-model="inputForm.title" disabled placeholder="请输入会议标题" clearable></u--input>
			</u-form-item>
		
			<u-form-item label="会议室编号" prop="meetNumber" borderBottom :required="true">
				<jp-picker v-model="inputForm.meetNumber" disabled rangeKey="label" rangeValue="value" :range="[
						        { label: '九楼会议室一', value: '1' },
						        { label: '九楼会议室二', value: '2' },
						        { label: '十楼会议室一', value: '3' },
						        { label: '十楼会议室二', value: '4' },
						    ]" @input="checkTime"></jp-picker>
			</u-form-item>
		
			<u-form-item label="会议开始时间" prop="startDate" borderBottom :required="true">
				<el-date-picker
						:disabled="true"
						v-model="inputForm.startDate"
						type="date"
						placeholder="请选择日期"
						style="width:50%"
						size="default"
						placement="bottom-start"
						@change="checkTime"
						clearable>
				</el-date-picker>
				<el-select v-model="inputForm.startTime" disabled placeholder="请选择时间" style="width:50%;" clearable>
					<el-option v-for="item in dateList" 
						:disabled="item.disabled" 
						:key="item.value" 
						:label="item.label"
						:value="item.value">
					</el-option>
				</el-select>
			</u-form-item>
		
			<u-form-item label="会议时长" prop="duration" borderBottom :required="true">
				<jp-picker v-model="inputForm.duration" disabled rangeKey="label" rangeValue="value" :range="[
						        { label: '30分钟', value: '30' },
						        { label: '1小时', value: '1' },
						        { label: '2小时', value: '2' },
						        { label: '3小时', value: '3' },
						        { label: '4小时', value: '4' },
						        { label: '5小时', value: '5' },
						        { label: '6小时', value: '6' },
						        { label: '全天', value: '24' },
						    ]"></jp-picker>
			</u-form-item>
		
			<u-form-item label="会议发起人" prop="createByName" borderBottom>
				<u--input disabled v-model="inputForm.createByName"></u--input>
			</u-form-item>
			<u-form-item label="会议说明" prop="remarks" borderBottom>
				<u--textarea disabled placeholder="请输入说明" :rows="5" :maxlength="500" style="width:100%"
					v-model="inputForm.remarks" show-word-limit></u--textarea>
			</u-form-item>
		</u--form>
	</view>
</template>

<script>
	import XEUtils from 'xe-utils'
	import meetingRoomService from '@/api/dailyOfficeWork/MeetingRoomService'
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'
	import CommonApi from '@/api/common/CommonApi'
	export default {
		props: {
			businessId: {
				type: String,
				default: ''
			},
			formReadOnly: {
				type: Boolean,
				default: false
			},
			status: {
				type: String,
				default: ''
			}
		},
		computed: mapState({
			userInfo: (state) => state.user.userInfo,
			avatar: (state) => state.user.avatar
		}),
		data() {
			return {
				title: '',
				method: '',
				nodeFlag: false,
				loading: false,
				inputForm: {
					id: '',
					title: '',
					startTime: '',
					startDate: '',
					duration: '',
					createById: '',
					createByName: '',
					createDate: '',
					remarks: '',
					meetNumber: '',
					procInsId: '',
				},
				baseKey: '',
				keyWatch: '',
				dateList: [],
				rules: {
					'title': [
						{
							required: true,
							message: '标题不能为空',
							trigger: ['blur', 'change']
						}
					],
					'startTime': [
						{
							required: true,
							message: '会议日期不能为空',
							trigger: ['blur', 'change']
						}
					],
					'startDate': [
						{
							required: true,
							message: '会议时间不能为空',
							trigger: ['blur', 'change']
						}
					],
					'duration': [
						{
							required: true,
							message: '会议时长不能为空',
							trigger: ['blur', 'change']
						}
					],
					'meetNumber': [
						{
							required: true,
							message: '会议室编号不能为空',
							trigger: ['blur', 'change']
						}
					],
				},
				pickerOptions:{ //禁用当前日期之前的日期
					disabledDate(time) {
					return time.getTime() < Date.now() - 8.64e7;
					},
				}
			}
		},
		commonApi: null,
		created() {
			console.log('jld ')
			console.log('userInfo ',this.userInfo)
			this.commonApi = new CommonApi()
			this.inputForm.createByName = this.userInfo.name
			this.inputForm.createById = this.userInfo.id
		},
		mounted() {},
		activated() {},
		components: {

		},
		watch: {
			'businessId': {
				handler (newVal) {
					if (this.businessId) {
						this.init(this.businessId)
					} else {
						this.$nextTick(() => {
							// this.$refs.inputForm.reset()
						})
					}
				},
				immediate: true,
				deep: false
			}
		},
		methods: {
			init(id) {
				this.nodeFlag = true
				this.inputForm.id = id	
				console.log('da',this.status)
				if (id) {
					meetingRoomService.queryById(this.inputForm.id).then((data) => {
						// 只有从我发起的还有已办事项抄送给我 进入流程页面的时候才会有这个值
						if (this.status === 'testSee') {
							this.nodeFlag = true
						} else {
							this.commonApi.getTaskNameByProcInsId(data.procInsId).then((data) => {
								if (this.isNotEmpty(data)) {
									if (data === '调整重新发起' || this.isEmpty(data)) {
										this.nodeFlag = false
									} else {
										this.nodeFlag = true
									}
								}
							})
						}

						this.inputForm = this.recover(this.inputForm, data)
						this.inputForm.createById=data.createById
						this.inputForm.createByName=data.createName
						this.inputForm.duration = String(data.duration)
						if (this.isEmpty(data.duration)) {
							this.inputForm.duration = ''
						}
						if (this.isNotEmpty(this.inputForm.startDate)) {
							this.checkTime()
						}
						if (this.isEmpty(this.inputForm.createDate)) {
							this.inputForm.createDate = this.moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
						}
						if (this.isNotEmpty(data.startTime)) {
							this.inputForm.startTime = data.startTime
						}
					})
				}
			},
			saveForm(callback) {
				return new Promise(async (resolve, reject) => {
					let errors = [];
					if (this.isEmpty(this.inputForm.startDate) || this.isEmpty(this.inputForm.startTime)) {
						errors.push('请选择会议开始时间')
					}
					if (this.isEmpty(this.inputForm.duration)) {
						errors.push('请选择会议时长')
					}
					if (this.isEmpty(this.inputForm.title)) {
						errors.push('请输入会议标题')
					}
					if (this.isEmpty(this.inputForm.meetNumber)) {
						errors.push('请选择会议室编号')
					}
					if (this.isNotEmpty(this.inputForm.startTime)) {
						console.log('this.dateList', this.dateList)
						for (let i = 0; i < this.dateList.length; i++) {
							if (this.dateList[i].disabled === true && this.dateList[i].value === this.inputForm
								.startTime) {
								errors.push('会议室当前无空余,请选择其他时间')
							}
						}
					}
					if (errors.length > 0) {
						// 存在错误，显示提示信息
						errors.forEach(error => {
							uni.showToast({
								title: error,
								icon: 'none',
								duration: 1500
							});
						});
						reject('Form validation failed');
					} else {
						this.$refs.inputForm.validate().then(res => {
							this.inputForm.status = '2'
							meetingRoomService.saveForm(this.inputForm).then((data) => {
								this.inputForm.id = data.businessId
								console.log('da',data)
								callback(data.businessTable, data.businessId)
								this.$refs.inputForm.resetFields()
								this.loading = false
							}).catch(() => {
								this.$refs.inputForm.resetFields()
								this.loading = false
							})
						})
					}
					
				})				
			},
			async agreeForm(callback) {
				console.log('进入方法')
				this.loading = true
				await meetingRoomService.queryById(this.inputForm.id).then((data) => {
					// if (data.status !== '2' ) { // status的值不等于“审核中”，就弹出提示
					// 	this.loading = false
					// 	this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					// 	throw new Error()
					// } else {
					this.inputForm.status = '5'
					let param = {
						status: this.inputForm.status,
						id: this.inputForm.id
					}
					this.inputForm = JSON.stringify(this.inputForm)
					meetingRoomService.updateStatusById(param).then(() => {
						callback(data.businessTable, data.businessId, this.inputForm)
						this.loading = false
					}).catch(() => {
						this.loading = false
					})
					// }
				})
			},
			reapplyForm(callback) {
				this.loading = true
				meetingRoomService.queryById(this.inputForm.id).then((data) => {
					if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
					this.doSubmit('reapply', callback)
					}
				})
			},
			isEmpty(value) {
				let result = false;
				if (value == null || value == undefined) {
					result = true;
				}
				if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
					result = true;
				}
				if (typeof value == "object" && value instanceof Array && value.length === 0) {
					result = true;
				}
				return result;
			},
			isNotEmpty (value) {
				return !this.isEmpty(value)
			},
			// 表单提交
			async doSubmit(status, callback) {
				return new Promise(async (resolve, reject) => {
					let errors = [];
					if (this.isEmpty(this.inputForm.startDate) || this.isEmpty(this.inputForm.startTime)) {
						errors.push('请选择会议开始时间')
					}
					if (this.isEmpty(this.inputForm.duration)) {
						errors.push('请选择会议时长')
					}
					if (this.isEmpty(this.inputForm.title)) {
						errors.push('请输入会议标题')
					}
					if (this.isEmpty(this.inputForm.meetNumber)) {
						errors.push('请选择会议室编号')
					}
					if (this.isNotEmpty(this.inputForm.startTime)) {
						console.log('this.dateList', this.dateList)
						for (let i = 0; i < this.dateList.length; i++) {
							if (this.dateList[i].disabled === true && this.dateList[i].value === this.inputForm
								.startTime) {
								errors.push('会议室当前无空余,请选择其他时间')
							}
						}
					}
					if (errors.length > 0) {
						// 存在错误，显示提示信息
						errors.forEach(error => {
							uni.showToast({
								title: error,
								icon: 'none',
								duration: 1500
							});
						});
						reject('Form validation failed');
					} else {
						this.$refs.inputForm.validate().then(res => {
							this.inputForm.status = '2'
							meetingRoomService.saveForm(this.inputForm).then((data) => {
								this.inputForm.id = data.businessId
								callback(data.businessTable, data.businessId, this.inputForm)
								this.$refs.inputForm.resetFields()
								this.loading = false
							}).catch(() => {
								this.$refs.inputForm.resetFields()
								this.loading = false
							})
						})
					}
					
				})
			},
			close() {
				this.inputForm = {
					id: '',
					title: '',
					startTime: '',
					startDate: '',
					duration: '',
					createById: '',
					createByName: '',
					createDate: '',
					remarks: '',
					meetNumber: ''
				}
				this.visible = false
			},
			async updateStatusById(type, callback) {
				console.log('type',type)
				this.loading = true
				if (type === 'reject' || type === 'reback') {
					meetingRoomService.queryById(this.inputForm.id).then((data) => {
						// if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
						// 	this.loading = false
						// 	this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						// 	throw new Error()
						// } else {
						// if (type === 'agree') {
						//   // 同意
						//   this.inputForm.status = '5'
						// }
						if (type === 'reject') {
							// 驳回
							this.inputForm.status = '4'
						}
						if (type === 'reback') {
							// 撤回
							this.inputForm.status = '3'
						}
						if (type === 'reject' || type === 'reback') {
							let param = {
								id: this.inputForm.id,
								status: this.inputForm.status
							}
							meetingRoomService.updateStatusById(param).then(() => {
								this.loading = false
								callback()
							})
						}
						// }
					})
				} else if (type === 'hold') {
					meetingRoomService.queryById(this.inputForm.id).then((data) => {
						// if (data.status !== '4') { // status的值不等于“驳回”就弹出提示
						// 	this.loading = false
						// 	this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						// 	throw new Error()
						// } else {
						// 终止
						let param = {
							status: '1',
							id: this.inputForm.id
						}
						meetingRoomService.updateStatusById(param).then(() => {
							this.loading = false
							callback()
						})
						// }
					})
				}

			},
			//禁用日期
			disableDate(time) {
				const now = new Date(); // 获取当前时间
				const fivePM = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 17, 0, 0); // 设置下午五点的时间
				// 判断当前时间是否在下午五点之前
				if (now.getTime() < fivePM.getTime()) {
					//Date.now()是javascript中的内置函数，它返回自1970年1月1日00:00:00 UTC以来经过的毫秒数。
					return time.getTime() < Date.now() - 8.64e7;
				} else {
					return time.getTime() < Date.now()
				}


			},
			//禁用小时
			disabledHour() {
				const arrs = []
				arrs.push(0, 1, 2, 3, 4, 5, 6, 7, 8, 12, 13, 18, 19, 20, 21, 22, 23)
				return arrs;
			},
			//禁用分钟
			disabledMinute(time) {
				const arrs = []
				if (time === 17) {
					for (let i = 0; i < 59; i++) {
						arrs.push(i + 1)
					}
				}
				if (time === 11) {
					for (let i = 0; i < 59; i++) {
						arrs.push(i + 31)
					}
				}
				return arrs;
			},
			async checkTime() {
				let list = []
				list = this.$dictUtils.getDictList('meeting_date')
				console.log('this.dateList', list)
				this.inputForm.startTime = ''
				if (this.isNotEmpty(this.inputForm.startDate) && this.isNotEmpty(this.inputForm
						.meetNumber)) {
					meetingRoomService.checkTime(this.inputForm.startDate, this.inputForm.meetNumber).then((data) => {
						console.log('par', data)
						if (this.isNotEmpty(data)) {
							const timeArray = Object.values(data);
							var num = [];
							for (var key in data) {
								console.log(data[key])
								let date1=data[key].replace(/:/g, '')

								for (let i=0;i<list.length;i++){
									let date2=list[i].value.replace(/:/g, "")
									console.log('date2',date2)
									if (date1===date2){
										num.push(i)
									}
								}

							}
							 
							console.log('num', num)
							for (let i = 0; i < num.length; i++) {
								console.log('num[i]', num[i])
								list[num[i]].disabled = true
							}
							this.dateList = list

						}
					})
				}


			}

		}

	}
</script>
<style scoped>
	.cu-form-group .title {
		min-width: calc(4em + 40px);
	}
</style>