<template>
	<view>
		<view style="padding:5rpx 20rpx 45rpx 20rpx;">
			<view>
				<view>
					<view class="desc">
						<uni-row>
							<uni-col :span="5">
								<view class="desc" style="font-size: 25rpx;">
									请假类型
								</view>
							</uni-col>
							<uni-col :span="19">
								<view>
									<uni-data-select v-model="form.type" :localdata="actions" :clear="false">
									</uni-data-select>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view>
						<view class="desc">
							<view class="desc" style="font-size: 25rpx;">
								请假事由:
							</view>
							<view>
								<uni-easyinput primaryColor="#37babd" type="textarea" autoHeight v-model="form.reason">
								</uni-easyinput>
							</view>
						</view>
					</view>
					<view class="desc">
						<uni-row>
							<uni-col :span="8">
								<view style="font-size: 25rpx;">
									是否为中层领导
								</view>
							</uni-col>
							<uni-col :span="16">
								<view>
									<uni-row>
										<radio-group @change="radioChange2">
											<uni-col :span="12" v-for="(item, index) in radiolist2">
												<label :key="item.value">
													<radio color="rgb(55,186,189)" :value="item.value"
														:checked="index === current">
														{{item.value}}
													</radio>
												</label>
											</uni-col>
										</radio-group>
									</uni-row>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="desc">
						<uni-row>
							<uni-col :span="5">
								<view class="desc" style="font-size: 25rpx;">
									开始时间
								</view>
							</uni-col>
							<uni-col :span="19">
								<view>
									<uni-datetime-picker type="date" :clear-icon="false" v-model="form.leaveStartTime"
										@maskClick="maskClick" @change="onchange()" />
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="desc">
						<uni-row>
							<uni-col :span="5">
								<view class="desc" style="font-size: 25rpx;">
									结束时间
								</view>
							</uni-col>
							<uni-col :span="19">
								<view>
									<uni-datetime-picker type="date" :clear-icon="false" v-model="form.leaveEndTime"
										@maskClick="maskClick" @change="onchange()" />
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="desc">
						<uni-row>
							<uni-col :span="5">
								<view class="desc" style="font-size: 25rpx;">
									天数
								</view>
							</uni-col>
							<uni-col :span="19">
								<view>
									<uni-easyinput primaryColor="#37babd" v-model="calculateDayNum" placeholder="天数">
									</uni-easyinput>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view style="color: #c4c4c4;font-size: 24rpx;">
						注：1天按照8小时计算，如请4小时，即4/8=0.5天；
					</view>
					<view class="desc">
						<uni-row>
							<uni-col :span="5">
								<view style="font-size: 25rpx;">
									是否离沪
								</view>
							</uni-col>
							<uni-col :span="19">
								<view>
									<uni-row>
										<radio-group @change="radioChange">
											<uni-col :span="12" v-for="(item, index) in radiolist1">
												<label :key="item.value">
													<radio color="rgb(55,186,189)" :value="item.value"
														:checked="index === current">
														{{item.value}}
													</radio>
												</label>
											</uni-col>
										</radio-group>
									</uni-row>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="desc">
						<uni-row>
							<uni-col :span="5">
								<view class="desc" style="font-size: 25rpx;">
									出行方式
								</view>
							</uni-col>
							<uni-col :span="19">
								<view>
									<uni-easyinput primaryColor="#37babd" v-model="form.tripMode" placeholder="出行方式">
									</uni-easyinput>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view class="desc">
						<uni-row>
							<uni-col :span="5">
								<view class="desc" style="font-size: 25rpx;">
									出行地址
								</view>
							</uni-col>
							<uni-col :span="19">
								<view>
									<pickerAddress @change="changeAddress">
										<view v-if="form.tripAddress"
											style="font-size: 30rpx;color: #848484;padding: 12rpx 0;">
											{{form.tripAddress}}
										</view>
										<view v-else style="color: #c4c4c4;font-size: 30rpx;padding: 12rpx 0;">
											选择地址
										</view>
									</pickerAddress>
								</view>
							</uni-col>
						</uni-row>
					</view>
					<view>
						<view class="desc">
							<view class="desc" style="font-size: 25rpx;">
								详细地址:
							</view>
							<view>
								<uni-easyinput primaryColor="#37babd" type="textarea" autoHeight
									v-model="form.detailAddr">
								</uni-easyinput>
							</view>
						</view>
					</view>
					<view class="desc">
						<view>
							图片
						</view>
						<view style="width: 100%;overflow-x: scroll;white-space: nowrap">
							<u-upload style="margin: 0;" :fileList="fileList" @afterRead="afterRead" @delete="deletePic"
								name="1" multiple :maxCount="6" width="120" height="120" uploadIcon="plus-circle">
							</u-upload>
						</view>
					</view>
				</view>
			</view>
		</view>
		<u-gap height="70" bgColor="#ffffff"></u-gap>
		<view class="bottim_view">
			<view>
				<u-row>
					<u-col span="11">
						<u-button :disabled="isDisabled" class="btnDoPay" shape="circle" @click="submit"
							color="rgb(55,186,189)" text="提交"></u-button>
					</u-col>
				</u-row>
			</view>
		</view>
		<!-- 普通弹窗 -->
		<uni-popup ref="popup" background-color="#fff" @change="propChange">
			<view style="height: 800rpx;">
				<view class="desc">
					<uni-row>
						<uni-col :span="10">
							<view style="font-size: 40rpx;color: rgb(145, 145, 145);">
							</view>
						</uni-col>
						<uni-col :span="11">
							<view style="font-size: 40rpx;color: rgb(98, 98, 98);">
								下一步
							</view>
						</uni-col>
						<uni-col :span="3">
							<view @click="submitPass" style="font-size: 40rpx;color: rgb(55,186,189);">
								确认
							</view>
						</uni-col>
					</uni-row>
				</view>
				<view class="desc">
					<uni-row>
						<uni-col>
							<view style="padding: 10rpx 30rpx;">
								<uni-data-picker ref="picker" placeholder="请选择" :popup-title="selectTitle"
									:localdata="dataTree" v-model="hxForm.candidate" @change="nextApprovalChange">
								</uni-data-picker>
							</view>
						</uni-col>
					</uni-row>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import pickerAddress from '../address/pickerAddress.vue'
	export default {
		components: {
			pickerAddress
		},
		data() {
			return {
				header: {
					"Authorization": "Bearer " + uni.getStorageSync('token')
				},
				selectTitle: '',
				type: 0,
				current: 0,
				data: uni.getStorageSync("approval"),
				fileList: [],
				// uni.getStorageSync("listImg"),
				disabled1: false,
				tips: '',
				value: '',
				showCalendar: false,
				showBirthday: false,
				model1: {},
				isDisabled: false,
				radiolist1: [{
						value: '不离沪'
					},
					{
						value: '离沪'
					}
				],
				radiolist2: [{
						value: '否'
					},
					{
						value: '是'
					}
				],
				imageStyles: {
					width: 100,
					height: 100,
					display: 'block'
				},
				form: {
					isMiddleLevelLeader: '否',
					isLh: '不离沪'
				},
				showSex: false,
				birthday: Number(new Date()),
				actions: [],
				rules: {
					type: {
						type: 'string',
						max: 1,
						required: true,
						message: '请选择请假类型',
						trigger: ['blur', 'change']
					},
					reason: {
						type: 'string',
						min: 3,
						required: true,
						message: '不低于3个字',
						trigger: ['change']
					},
					hotel: {
						type: 'string',
						min: 2,
						required: true,
						message: '请选择请假时间',
						trigger: ['change']
					},
				},
				dataTree: [],
				hxForm: {
					taskId: '',
					candidate: '',
					applyUserName: ''
				},
				app_vacate_type: [],
				imageValue: [{
					"name": "",
					"extname": "",
					"url": ""
				}]

			}
		},
		onReady() {
			// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
			//this.$refs.form.setRules(this.rules)
		},
		onLoad() {
			this.actions = []
			this.app_vacate_type = uni.getStorageSync('app_vacate_type')
			for (var i = 0; i < this.app_vacate_type.length; i++) {
				this.actions.push({
					value: this.app_vacate_type[i].dictValue,
					text: this.app_vacate_type[i].dictLabel
				})
			}
			if (this.data) {
				this.form = {
					isLh: this.data.formData.is_lh,
					isMiddleLevelLeader: this.data.formData.is_middle_level_leader,
					type: this.data.formData.type,
					title: this.data.formData.title,
					leaveStartTime: this.data.formData.leave_start_time.slice(0, 10).replace('/', '-').replace('/',
						'-'),
					reason: this.data.formData.reason,
					leaveEndTime: this.data.formData.leave_end_time.slice(0, 10).replace('/', '-').replace('/', '-'),
					candidate: this.data.formData.candidate,
					totalTime: this.data.formData.total_time,
					tripMode: this.data.formData.trip_mode,
					detailAddr: this.data.formData.detail_addr,
					tripAddress: this.data.formData.trip_address,
					applyUserName: this.data.formData.apply_user_name,
					applyUserId: this.data.formData.apply_user_id
				}
				if (this.data.formData.is_lh === '离沪') {
					this.current = 1
				} else {
					this.current = 0
				}
			}
		},
		computed: {
			calculateDayNum() {
				if (this.form.leaveStartTime &&
					this.form.leaveEndTime) {
					if (this.form.leaveStartTime >
						this.form.leaveEndTime) {
						this.$showModal('开始时间不能小于结束时间')
						return
					}
					let dayNum = ((new Date(this.form.leaveEndTime).getTime() -
						new Date(this.form.leaveStartTime).getTime()) / (1000 * 60 * 60 * 24)) + 1
					this.form.totalTime = dayNum
					return dayNum
				}
			},
			updateAddress() {
				return this.form.tripAddress
			}
		},
		methods: {
			propChange(e) {
				if (e.show) {
					// this.zindeButtion = 0
				} else {
					// this.zindeButtion = 1
				}
			},
			nextApprovalChange(e) {
				// console.log('onchange:', e.detail.value[1].text);
				this.hxForm.applyUserName = e.detail.value[1].text
				this.hxForm.candidate = e.detail.value[1].value
			},
			radioChange: function(evt) {
				this.form.isLh = evt.detail.value
			},
			radioChange2: function(evt) {
				this.form.isMiddleLevelLeader = evt.detail.value
			},
			// 获取上传状态
			select(e) {
				console.log('选择文件：', e)
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},
			// 上传成功
			success(e) {
				console.log('上传成功')
			},
			changeAddress(data) {
				this.form.tripAddress = data.data.join('')
				this.$forceUpdate()
			},
			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			myIsNaN(value) {
				return typeof value === 'number' && !isNaN(value)
			},
			changeType(e) {
				// console.log("e:", e);
				// this.form.type = e
			},
			async submitPass() {
				if (!this.hxForm.candidate) {
					uni.showModal({
						content: '请选择' + this.dataTree[0].text,
						title: '提交失败',
						showCancel: false,
					})
				}
				const {
					data: res
				} = await this.$httpRequest({
					url: '/app/task/submit/candidate?taskId=' + this.hxForm.taskId +
						'&candidate=' + this.hxForm.candidate + '&applyUserName=' + this.hxForm.applyUserName,
					method: 'get',
				});
				if (res.code === 200) {
					uni.showModal({
						content: '已提交给审批人员',
						title: '提交成功',
						showCancel: false,
						success() {
							uni.navigateBack()
						}
					})
				} else {
					uni.showModal({
						content: res.msg,
						title: '提交失败',
						showCancel: false,
						success() {
							uni.navigateBack()
						}
					})
				}
			},
			maskClick(e) {},
			datetimerange(newval) {
				// console.log('范围选:', newval);
				// if (newval.length !== 0) {
				// 	this.form.totalTime = parseFloat((new Date(newval[1]).getTime() - new Date(newval[0]).getTime()) / (
				// 		1000 *
				// 		60 *
				// 		60)).toFixed(2);
				// 	this.form.leaveStartTime = newval[0]
				// 	this.form.leaveEndTime = newval[1]
				// }
			},
			// 删除图片
			deletePic(event) {
				this.fileList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen
				if (this.fileList) {
					fileListLen = this.fileList.length
				} else {
					this.fileList = []
					fileListLen = 0
				}
				lists.map((item) => {
					this.fileList.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.fileList[fileListLen]
					this.fileList.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.$BASE_URL + result
					}))
					fileListLen++
				}
				// uni.setStorageSync("listImg", this.fileList)
				// console.log(this.fileList)
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$BASE_URL + '/common/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						header: this.header,
						success: (res) => {
							// console.log(JSON.parse(res.data).url);
							setTimeout(() => {
								resolve(JSON.parse(res.data).url)
							}, 1000)
						}
					});
				})
			},
			onchange(e) {
				// setTimeout(() => {
				// 	this.calculateDayNum()
				// }, 200)
			},
			async submit() {
				this.isDisabled = true
				setTimeout(() => {
					this.isDisabled = false
				}, 1000)
				if (!this.form.type) {
					this.isDisabled = false
					uni.showModal({
						content: '请选择请假类型',
						title: '提交失败',
						showCancel: false
					})
					return
				}
				if (!this.form.reason) {
					this.isDisabled = false
					uni.showModal({
						content: '请填写请假事由',
						title: '提交失败',
						showCancel: false
					})
					return
				}
				if (!this.form.leaveStartTime) {
					this.isDisabled = false
					uni.showModal({
						content: '请选择请假时间',
						title: '提交失败',
						showCancel: false
					})
					return
				}
				if (!this.myIsNaN(parseFloat(this.form.totalTime))) {
					this.isDisabled = false
					uni.showModal({
						content: '请填写正确的请假天数',
						title: '提交失败',
						showCancel: false
					})
					return
				}

				let userInfo = uni.getStorageSync("userInfo")
				this.form.applyUserId = userInfo.userName
				this.form.applyUserName = userInfo.nickName
				this.form.imgUrls = this.fileList
				this.form.title = this.app_vacate_type[parseInt(this.form.type)].dictLabel + '申请'
				const {
					data: res
				} = await this.$httpRequest({
					url: '/app/submitApply/leave',
					method: 'post',
					data: this.form
				});
				if (res.code === 200) {
					this.dataTree = res.data.tree
					this.hxForm.taskId = res.data.taskId
					this.$refs.popup.open('bottom')
					this.selectTitle = "请选择" + this.dataTree[0].text
					this.isDisabled = false
				} else {
					this.$showModal(res.msg)
				}
				this.isDisabled = false
			},
			navigateBack() {
				uni.navigateBack()
			},
			typeSelect(e) {
				this.form.type = e.id
				this.form.typeText = e.name
				this.form.title = e.name + "申请"
				this.$refs.form.validateField('form.type')
			},
			formatter(day) {
				const d = new Date()
				let month = d.getMonth() + 1
				const date = d.getDate()
				return day
			},
			calendarConfirm(e) {
				// this.showCalendar = false
				// this.form.hotel = `${e[0]} / ${e[e.length - 1]}`
				// this.form.leaveStartTime = e[0]
				// this.form.leaveEndTime = e[e.length - 1]
				// this.$refs.form.validateField('hotel')
			},
			calendarClose() {
				this.showCalendar = false
				this.$refs.form.validateField('hotel')
			},

			reset() {
				const validateList = ['type', 'title', 'leaveStartTime', 'leaveEndTime', 'reason',
					'hotel'
				]
				this.$refs.form.resetFields()
				this.$refs.form.clearValidate()
				setTimeout(() => {
					this.$refs.form.clearValidate(validateList)
					//this.$refs.form.setRules(this.rules)
					// 或者使用 this.$refs.form.clearValidate()
				}, 10)
			},
			hideKeyboard() {
				uni.hideKeyboard()
			}
		}
	}
</script>

<style lang="scss" scoped>
	.desc {
		padding: 15rpx 5rpx;
	}

	.bottim_view {
		padding: 5px 20px 30px;
		position: fixed;
		left: 0px;
		bottom: 0px;
		width: 100%;
		height: 40px;
		background-color: #ffffff;
	}

	.title {
		font-size: 14px;
		font-weight: bold;
		margin: 20px 0 5px 0;
	}

	.data-pickerview {
		height: 400px;
		border: 1px #e5e5e5 solid;
	}

	.popper__arrow {
		top: -6px;
		left: 50%;
		margin-right: 3px;
		border-top-width: 0;
		border-bottom-color: #EBEEF5;
	}

	.popper__arrow {
		top: -6px;
		left: 50%;
		margin-right: 3px;
		border-top-width: 0;
		border-bottom-color: #EBEEF5;
	}
</style>
