<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="请假人" borderBottom prop="createName">
				<u--input placeholder='请填写请假人'  v-model="inputForm.createName" disabled></u--input>
			</u-form-item>
			<u-form-item label="请假部门" borderBottom prop="officeName">
				<u--input placeholder='请填写请假部门'  v-model="inputForm.officeName" disabled></u--input>
			</u-form-item>
			<u-form-item label="请假类型" borderBottom prop="type" >
				<jp-picker v-model="inputForm.type" rangeKey="label" rangeValue="value" :range="[
						        { label: '年假', value: '1' },
						        { label: '事假', value: '2' },
						        { label: '病假', value: '3' },
						        { label: '调休假', value: '4' },
						        { label: '婚假', value: '5' },
						        { label: '产假', value: '6' },
						        { label: '陪产假', value: '7' },
						        { label: '其他', value: '8' },
						    ]"></jp-picker>
			</u-form-item>
			<u-form-item label="开始时间" borderBottom prop="startDay" :required="true">
				<el-date-picker
						v-model="inputForm.startDay"
						type="date"
						placeholder="请选择开始时间"
						style="width:100%"
						size="default"
						placement="bottom-start"
						@change="checkTime"
						clearable>
				</el-date-picker>
				<el-select v-model="inputForm.beginTime" style="width: 50%" placeholder="请选择开始时间" @change="checkTime">
					<el-option value="上午" label="上午"></el-option>
					<el-option value="下午" label="下午"></el-option>
				</el-select>
			</u-form-item>
			<u-form-item label="结束时间" borderBottom prop="endDay" :required="true">
				<el-date-picker
						v-model="inputForm.endDay"
						type="date"
						placeholder="请选择日期"
						style="width:100%"
						size="default"
						placement="bottom-start"
						@change="checkTime"
						clearable>
				</el-date-picker>
				<el-select v-model="inputForm.endTime" style="width: 50%" placeholder="请选择结束时间" @change="checkTime">
					<el-option value="上午" label="上午"></el-option>
					<el-option value="下午" label="下午"></el-option>
				</el-select>
			</u-form-item>
			<u-form-item label="请假天数" borderBottom prop="days" :required="true">
				<u--input placeholder='请填写请假天数'  v-model="inputForm.days" disabled></u--input>
			</u-form-item>
			<u-form-item label="请假原因" borderBottom prop="reason">
				<u--textarea  placeholder='请输入请假原因' :rows="5" :maxlength="500" v-model="inputForm.reason" ></u--textarea>
			</u-form-item>

			<u-form-item label="附件">
				<el-upload
						class="upload-demo"
						:action="`http://mn79i2.natappfree.cc/api/public-modules-server/oss/file/webUpload/upload`"
						:on-remove="(file, fileList) => handleRemove(file, fileList, '','')"
						:file-list="inputForm.files"
						:on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList,'','')"
						:limit="3">
					<el-button size="small" type="primary">点击上传</el-button>
					<div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
				</el-upload>
			</u-form-item>
		</u--form>
		<u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-else-if="nodeFlag">
			<u-form-item label="请假人" borderBottom prop="createName">
				<u--input placeholder='请填写请假人'  v-model="inputForm.createName" disabled></u--input>
			</u-form-item>
			<u-form-item label="请假部门" borderBottom prop="officeName">
				<u--input placeholder='请填写请假部门'  v-model="inputForm.officeName" disabled></u--input>
			</u-form-item>
			<u-form-item label="请假类型" borderBottom prop="type" >
				<jp-picker v-model="inputForm.type" rangeKey="label" rangeValue="value" disabled :range="[
						        { label: '年假', value: '1' },
						        { label: '事假', value: '2' },
						        { label: '病假', value: '3' },
						        { label: '调休假', value: '4' },
						        { label: '婚假', value: '5' },
						        { label: '产假', value: '6' },
						        { label: '陪产假', value: '7' },
						        { label: '其他', value: '8' },
						    ]"></jp-picker>
			</u-form-item>
			<u-form-item label="开始时间" borderBottom prop="startDay" :required="true">
				<el-date-picker
						v-model="inputForm.startDay"
						type="date"
						placeholder="请选择开始时间"
						style="width:100%"
						size="default"
						placement="bottom-start"
						@change="checkTime"
						:disabled="true"
						clearable>
				</el-date-picker>
				<el-select v-model="inputForm.beginTime" style="width: 50%" disabled placeholder="请选择开始时间" @change="checkTime">
					<el-option value="上午" label="上午"></el-option>
					<el-option value="下午" label="下午"></el-option>
				</el-select>
			</u-form-item>
			<u-form-item label="结束时间" borderBottom prop="endDay" :required="true">
				<el-date-picker
						:disabled="true"
						v-model="inputForm.endDay"
						type="date"
						placeholder="请选择日期"
						style="width:100%"
						size="default"
						placement="bottom-start"
						@change="checkTime"
						clearable>
				</el-date-picker>
				<el-select v-model="inputForm.endTime" style="width: 50%" disabled placeholder="请选择结束时间" @change="checkTime">
					<el-option value="上午" label="上午"></el-option>
					<el-option value="下午" label="下午"></el-option>
				</el-select>
			</u-form-item>
			<u-form-item label="请假天数" borderBottom prop="days" :required="true">
				<u--input placeholder='请填写请假天数'  v-model="inputForm.days" disabled></u--input>
			</u-form-item>
			<u-form-item label="请假原因" borderBottom prop="reason">
				<u--textarea  placeholder='请输入请假原因' :rows="5" :maxlength="500" v-model="inputForm.reason" disabled></u--textarea>
			</u-form-item>

			<u-form-item label="附件">
				<el-upload
						:disabled="true"
						class="upload-demo"
						:action="`http://localhost:2800/api/public-modules-server/oss/file/webUpload/upload`"
						:on-remove="(file, fileList) => handleRemove(file, fileList, '','')"
						:file-list="inputForm.files"
						:on-success="(response, file, fileList) => handleUploadSuccess(response, file, fileList,'','')"
						:limit="3">
					<el-button size="small" :disabled="true" type="primary">点击上传</el-button>
					<div slot="tip" class="el-upload__tip">只能上传不超过 3 个文件</div>
				</el-upload>
			</u-form-item>
		</u--form>
	</view>
</template>

<script>
	import holidayService from '@/api/jy/HolidayService'
	import CommonApi from '@/api/common/CommonApi'
	import {mapState, mapMutations, mapActions} from 'vuex'
	export default {
		components: {
		},
		computed: mapState({
			userInfo: (state) => state.user.userInfo,
			avatar: (state) => state.user.avatar
		}),
		data () {
			return {
				nodeFlag: false,
				loading: false,
				listData: [],
				fileList3: [],
				goodsListData: [],
				materialList: [],
				searchForm: {
					wareHouseType: '',
				},
				inputForm: {
					createName:'',
					officeName:'',
					id: '',
					startDay:"",
					beginTime:'',
					reason: '',
					endDay:"",
					endTime:'',
					type:'',
					files: [], // 附件信息
					procInsId: '',
					days:'',
				},
				rules: {
					'type': [
						{
							required: true,
							message: '请假类型不能为空',
							trigger: ['blur', 'change']
						}
					],
					'startDay': [
						{
							required: true,
							message: '开始时间不能为空',
							trigger: ['blur', 'change']
						}
					],
					'endDay': [
						{
							required: true,
							message: '结束时间不能为空',
							trigger: ['blur', 'change']
						}
					]
				}
			}
		},
		commonApi: null,
		// 页面加载时执行
		created() {
			this.commonApi = new CommonApi()
			this.inputForm.createName = this.userInfo.name
			this.inputForm.officeName = this.userInfo.officeDTO.name
		},
		props: {
			businessId: {
				type: String,
				default: ''
			},
			formReadOnly: {
				type: Boolean,
				default: false
			}
		},
		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
				if (id) {
					holidayService.queryById(id).then((data) => {

						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)

					})
				}
			},
			formatDate(date) {
				const dateNew = new Date(date); // 将日期字符串转换为 Date 对象
				const year = dateNew.getFullYear();
				const month = (dateNew.getMonth() + 1).toString().padStart(2, '0');
				const day = dateNew.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			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)
			},
			/**
			 * 判断是否为空
			 */
			isNull(val) {
				if (val instanceof Array) {
					if (val.length === 0) return true;
				} else if (val instanceof Object) {
					if (JSON.stringify(val) === "{}") return true;
				} else {
					if (
							val === "null" ||
							val == null ||
							val === "undefined" ||
							val === undefined ||
							val === ""
					)
						return true;
					return false;
				}
				return false;
			},
			formatDateNew(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
			},
			handleUploadSuccess (res, file, fileList, index, type) {

				// 将 fileList 转换为你期望的格式
				const formattedFiles = fileList.map(fileItem => {
					return {
						name: fileItem.name,
						size: fileItem.size,
						url: fileItem.response ? '/' + fileItem.response.url : fileItem.url,
						createBy: this.userInfo,
						by: this.userInfo.id,
						createTime: this.formatDateNew(new Date())
					};
				});
				this.inputForm.files = formattedFiles

				// 强制更新视图
				this.$forceUpdate();
			},
			handleRemove(file, fileList, index, type) {
				// 处理移除文件逻辑
				// file 是移除的文件
				// fileList 是当前文件列表
				const formattedFiles = fileList.map(fileItem => {
					return {
						name: fileItem.name,
						size: fileItem.size,
						url: '/' + fileItem.response.url,
						createBy: this.userInfo,
						by: this.userInfo.id,
						createTime: this.formatDateNew(new Date())
					};
				});
				this.inputForm.files = formattedFiles


				// 如果你想要更新文件列表，可以在这里更新 inputForm.fileInfoLost
				// this.inputForm.fileInfoLost = fileList;
			},
			saveForm(callback) {
				// 所有验证通过，执行保存操作

				if (this.isNotEmpty(this.inputForm.startDay)) {
					this.inputForm.startDay = this.formatDate(this.inputForm.startDay);
				}
				if (this.isNotEmpty(this.inputForm.endDay)) {
					this.inputForm.endDay = this.formatDate(this.inputForm.endDay);
				}

				return new Promise(async ( resolve, reject) => {

					let errors = [];

					if (this.isEmpty(this.inputForm.startDay) || this.isEmpty(this.inputForm.beginTime)){
						errors.push('请选择开始时间');
					}
					if (this.isEmpty(this.inputForm.endDay) || this.isEmpty(this.inputForm.endTime)){
						errors.push('请选择结束时间');
					}
					if (this.isEmpty(this.inputForm.type)){
						errors.push('请选择请假类型');
					}

					if (this.inputForm.type === '1'){
						if (this.isNotEmpty(this.inputForm.startDay) && this.isNotEmpty(this.inputForm.beginTime)
							&& this.isNotEmpty(this.inputForm.endDay) && this.isNotEmpty(this.inputForm.endTime)) {
							await holidayService.checkType(this.inputForm).then((data)=>{
								let day=data.split(",")
								if (!day[0].includes(this.inputForm.days)){
									errors.push(data);
								}
							})
						}

					}

					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'
							this.inputForm.userId = this.userInfo.id
							console.log('this.inputForm.files', this.inputForm.files)
							holidayService.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()
							}).catch((e) => {

							})
						})
					}
				});

				// this.$refs.inputForm.validate().then(() => {
				// 	uni.showLoading();
				// 	this.inputForm.status = '2';
				// 	this.holidayService.saveForm(this.inputForm).then(data => {
				// 		callback(data.businessTable, data.businessId,this.inputForm);
				// 	}).catch(error => {
				// 	});
				// }).catch(() => {
				// });
			},

			// 修改状态
			async updateStatusById (type, callback) {
				if (type === 'reject' || type === 'reback') {
					holidayService.queryById(this.inputForm.id).then((data) => {
						if (data.status !== '2') { // status的值不等于“审核中”，就弹出提示
							this.loading = false
							this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
							throw new Error()
						} else {
							if (type === 'reject') {
								// 驳回
								this.inputForm.status = '4'
							}
							if (type === 'reback') {
								// 撤回
								this.inputForm.status = '3'
							}
							if (type === 'reject' || type === 'reback') {
								let param = {status: this.inputForm.status, id: this.inputForm.id}
								holidayService.updateStatusById(param).then(() => {
									this.loading = false
									callback()
								})
							}
						}
					})
				} else if (type === 'hold') {
					holidayService.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}
							holidayService.updateStatusById(param).then(() => {
								this.loading = false
								callback()
							})
						}
					})
				}
			},
			reapplyForm (callback) {
				this.loading = true
				holidayService.queryById(this.inputForm.id).then((data) => {
					if (data.status !== '4') { // 审核状态不是“驳回”，就弹出提示
						this.loading = false
						this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
						throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
					} else {
						this.startFormTrue(callback)
					}
				})
			},
			// 送审
			async startFormTrue (callback) {

				if (this.isNotEmpty(this.inputForm.startDay)) {
					this.inputForm.startDay = this.formatDate(this.inputForm.startDay);
				}
				if (this.isNotEmpty(this.inputForm.endDay)) {
					this.inputForm.endDay = this.formatDate(this.inputForm.endDay);
				}

				return new Promise((resolve, reject) => {

					let errors = [];

					if (this.isEmpty(this.inputForm.startDay) || this.isEmpty(this.inputForm.beginTime)){
						errors.push('请选择开始时间');
					}
					if (this.isEmpty(this.inputForm.endDay) || this.isEmpty(this.inputForm.endTime)){
						errors.push('请选择结束时间');
					}
					if (this.isEmpty(this.inputForm.type)){
						errors.push('请选择请假类型');
					}

					if (this.inputForm.type === '1'){
						holidayService.checkType(this.inputForm).then((data)=>{
							let day=data.split(",")
							if (!day[0].includes(this.inputForm.days)){
								errors.push(data);
							}
						})
					}

					if (errors.length > 0) {
						// 存在错误，显示提示信息
						errors.forEach(error => {
							uni.showToast({
								title: error,
								icon: 'none',
								duration: 2000
							});
						});
						reject('Form validation failed');
					} else {
						this.$refs.inputForm.validate().then(res => {
							this.inputForm.status = '2'
							holidayService.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()
							}).catch((e) => {

							})
						})
					}
				});
			},
			// 通过
			async agreeForm (callback) {
				this.$refs.inputForm.validate().then(res => {
					if (this.inputForm.days >1) {
						this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
							if (this.isNotEmpty(data)) {
								if (data === '总经理审核') {
									this.inputForm.status = '5'
								} else {
									this.inputForm.status = '2'
								}
							}

							holidayService.saveForm(this.inputForm).then((data) => {
								callback(data.businessTable, data.businessId, this.inputForm)
								this.$refs.inputForm.resetFields()
								this.loading = false
							}).catch(() => {
								this.loading = false
								this.$refs.inputForm.resetFields()
							})
						})
					} else {
						this.inputForm.status = '5'
						holidayService.saveForm(this.inputForm).then((data) => {
							callback(data.businessTable, data.businessId, this.inputForm)
							this.$refs.inputForm.resetFields()
							this.loading = false
						}).catch(() => {
							this.loading = false
							this.$refs.inputForm.resetFields()
						})
					}
				})
			},
			checkType(){
				if (this.inputForm.type === '1'){
					holidayService.checkType(this.inputForm).then((data)=>{
						uni.showToast({
							title: data,
							icon: "none",
							duration:2000
						})
					})
				}
			},
			checkTime(){
				let differenceInDays =''
				let date1=new Date(this.inputForm.startDay)
				let date2=new Date(this.inputForm.endDay)
				if ((date2<date1) || (date2 === date1 && this.inputForm.beginTime === '下午' && this.inputForm.endTime === '上午')){
					uni.showToast({
						title: '开始时间不能小于结束时间',
						icon: "none",
						duration:2000
					})
					this.inputForm.startDay = ''
					this.inputForm.endDay = ''
					this.inputForm.beginTime = ''
					this.inputForm.endTime = ''
				}
				differenceInDays= Math.floor((date2 - date1) / (1000 * 60 * 60 * 24));
				if (differenceInDays === 0 || differenceInDays > 1){
					if ((this.inputForm.beginTime === '上午' && this.inputForm.endTime === '下午') ||(this.inputForm.beginTime === '下午' && this.inputForm.endTime === '上午') ){
						differenceInDays=differenceInDays+1
					}else if ((this.inputForm.beginTime === '上午' && this.inputForm.endTime === '上午') ||(this.inputForm.beginTime === '下午' && this.inputForm.endTime === '下午')){
						differenceInDays=differenceInDays+0.5
					}
				}else if (differenceInDays ===1){
					if ((this.inputForm.beginTime === '上午' && this.inputForm.endTime === '下午') ){
						differenceInDays=differenceInDays+1
					}else if ((this.inputForm.beginTime === '上午' && this.inputForm.endTime === '上午') ||(this.inputForm.beginTime === '下午' && this.inputForm.endTime === '下午')){
						differenceInDays=differenceInDays+0.5
					}else if (this.inputForm.beginTime === '下午' && this.inputForm.endTime === '上午'){
						differenceInDays
					}
				}
				if (this.isNotEmpty(this.inputForm.beginTime) && this.isNotEmpty(this.inputForm.endTime)){
					this.inputForm.days = differenceInDays
					this.checkType()
				}

			}
		}
	}
</script>

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