<template>
	<view class="content">
		<u-form :model="form" ref="form" label-width="140">
			<u-form-item label="请假类型" prop="type" required>
				<u-input v-model="form.type" placeholder="请选择请假类型" :select-open="leaveTypeShow" type="select" @click="leaveTypeShow = true" />
			</u-form-item>
			<u-form-item :label="form.type === '病假'?'开始时间':'请假时间'" prop="leaveTime" required>
				<u-input v-model="form.leaveTime" placeholder="请选择请假时间" :select-open="leaveTimeShow" type="select" @click="leaveTimeShow = true" />
			</u-form-item>
			<u-form-item label="上传证明" v-if="form.type === '病假'" prop="leavePic" required>
				<u-upload :action="action" :header="header" :file-list="fileList" max-count="1" :multiple="false" :show-progress="false" @on-success="handlePicSuccess"></u-upload>
			</u-form-item>
			<u-form-item label="请假理由" prop="leaveReason" required>
				<u-input v-model="form.leaveReason" placeholder="请输入请假理由" type="text" />
			</u-form-item>
			<u-form-item v-if="form.type === '病假'">
				学员重新上课时，教练进行结束病假
			</u-form-item>
		</u-form>
		<u-picker mode="selector" v-model="leaveTypeShow" :range="selectorObj" range-key="cateName" @confirm="handleGetType"></u-picker>
		<u-calendar v-model="leaveTimeShow" mode="date" :active-bg-color="mainColor" btn-type="error" availableText="有课"
		 :available="availableList" activeText="已请假" :activeList="activeList" @change="setLeaveTime" max-date="2300-12-31"></u-calendar>
		<view class="handle-fix-box">
			<u-button type="warning" shape="circle" :ripple="true" :custom-style="customStyle" @click="submitForm()">提交</u-button>
		</view>
		<u-top-tips ref="uTips"></u-top-tips>
	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex'
	const NET = require('@/utils/request')
	const API = require('@/config/api')
	export default {
		computed: {
			...mapGetters([
				'mainColor',
				'customStyle',
			])
		},
		data() {
			return {
				action: API.uploadFile,
				header: {
					Authorization: uni.getStorageSync('token')
				},
				classId: '',
				studentId: '',
				form: {
					type: '病假',
					leaveTime: '',
					leavePic: '',
					leaveReason: '',
				},
				rules: {
					leaveTime: [{
						required: true,
						message: '请选择请假时间',
						trigger: 'change'
					}],
					leaveReason: [{
						required: true,
						message: '请输入请假理由',
						trigger: 'change'
					}],
					leavePic: [{
						required: true,
						message: '请上传证明照片',
						trigger: 'change'
					}],
				},
				leaveTypeShow: false,
				selectorObj: [
					{
						cateName: '病假',
						type: 1
					},
					{
						cateName: '事假',
						type: 2
					}
				],
				leaveTimeShow: false,
				availableList: [],
				activeList: [],
				fileList: []
			}
		},
		onLoad(options) {
			this.classId = options.id
			this.studentId = options.studentId
			NET.request(API.getLeaveList, {
				id: this.classId
			}, 'POST').then(res => {
				// type: 0:有课  1:请假
				// 有课的日期数据
				this.availableList = res.data.filter(site => site.type == 0).map(site => {
					return this.formatDatedel0(site.lastDate)
				})
				// 请假的日期数据
				this.activeList = res.data.filter(site => site.type == 1).map(site => {
					return this.formatDatedel0(site.lastDate)
				})
				console.log(this.activeList)
			}).catch(error => {
				this.$refs.uTips.show({
					title: error.message,
					type: 'warning',
				})
			})
		},
		onReady() {
			this.$refs.form.setRules(this.rules);
		},
		methods: {
			//  选择请假类型
			handleGetType(args) {
				this.form.type = this.selectorObj[args[0]]['cateName']
				this.form.leaveTime = ''
				this.form.leavePic = ''
				this.form.leaveReason = ''
				// 移除表单校验结果
				this.$nextTick(() => {
					this.$refs.form.resetFields()
				})
			},
			// 图片上传成功
			handlePicSuccess(args) {
				if(args.status == 10000) {
					this.form.leavePic = args.data.url
				} else {
					this.$refs.uTips.show({
						title: args.message,
						type: 'warning',
					})
				}
			},
			//  设置请假日期
			setLeaveTime(object) {
				// 今天0点的时间戳
				let d = new Date()
				let year = d.getFullYear()
				let month = d.getMonth() + 1
				let day = d.getDate()
				let dateNow = year+'/'+month +'/'+day
				const nowTimeStamp = this.dateFormatTimeStamp(dateNow)
				console.log(nowTimeStamp)
				// 今天后3天的时间戳
				const nextThreeDayTimeStamp = nowTimeStamp + 86400
				let dateIos = object.year + '/' + object.month + '/' + object.day
				let date = object.year + '-' + object.month + '-' + object.day
				// 当天是否可请假
				if (this.availableList.filter(site => site == date).length) {
					// 是否为病假
					if(this.form.type === '事假') {
						// 病假需提前3天请
						if(this.dateFormatTimeStamp(dateIos) >= nextThreeDayTimeStamp) {
							this.form.leaveTime = date
						} else {
							this.form.leaveTime = ''
							this.$refs.uTips.show({
								title: '事假需提前1天请',
								type: 'error',
							})
						}
					} else {
						let dateStr=this.dateFormatTimeStamp(dateIos)
						console.log(dateStr)
						if(dateStr >= nowTimeStamp) {
							this.form.leaveTime = date
						} else {
							this.form.leaveTime = ''
							this.$refs.uTips.show({
								title: '不能选择今天之前',
								type: 'error',
							})
						}
					} 
				} else {
					this.form.leaveTime = ''
					this.$refs.uTips.show({
						title: '请选择可用日期',
						type: 'error',
					})
				}
			},
			// 日期转时间戳
			dateFormatTimeStamp(date = null,second = true) {
			    if (!date) return parseInt(new Date().getTime() / (second ? 1000 : 1))
			    return parseInt(new Date(date).getTime() / (second ? 1000 : 1))
			},
			formatDate(str) {
			  // 根据 - 符号拆分
			  return str
			    .split("-")
			    .map((item) => {
			      // +item 将item字符串转换为数字
			      // 小于10的时候就补全一个前缀0
			      if (+item < 10) {
			        return "0" + +item;
			      }
			 
			      // 大于10的时候不用补0
			      return item;
			    })
			    .join("-"); // 最后重组回来
			},
			formatDatedel0(str) {
			  // 根据 - 符号拆分
			  return str
			    .split("-")
			    .map((item) => {
			      // +item 将item字符串转换为数字
			      // 小于10的时候就补全一个前缀0
			      if (+item < 10) {
			        return Number(item);
			      }
			 
			      // 大于10的时候不用补0
			      return item;
			    })
			    .join("-"); // 最后重组回来
			},
			//  提交表单
			submitForm() {
				this.$refs.form.validate(valid => {
					if (valid) {
						this.form.leaveTime=this.formatDate(this.form.leaveTime)
						NET.request(API.submitLevelForm, {
							classId: this.classId,
							studentId: this.studentId,
							...{ ...this.form, type:  this.form.type == '事假' ?  1 : 2  }
						}, 'POST').then(res => {
							this.$refs.uTips.show({
								title: '请假成功',
								type: 'success',
							})
							setTimeout(() => {
								uni.navigateBack()
							}, 1000)
						}).catch(error => {
							this.$refs.uTips.show({
								title: error.message,
								type: 'warning',
							})
						})
					}
				});
			},
		},
	}
</script>

<style>
	page {
		width: 100%;
		height: 100%;
		position: relative;
	}
</style>
<style lang="scss" scoped>
	@import "@/static/css/themes.scss";

	.content {
		width: 100%;
		float: left;
		padding: 0 15px 60px 15px;
		box-sizing: border-box;
	}
</style>
