<template>
	<view class="content">
		<!-- 切换发起提交与提交记录 -->
		<view class="select-type" v-if="liutype" @click.stop="changeType">
			<view class="allday">发起提交</view>
			<view class="hourday_no">提交记录</view>
		</view>
		<view class="select-type" v-else @click.stop="changeType">
			<view class="allday2">发起提交</view>
			<view class="hourday_no2">提交记录</view>
		</view>
		<!-- 发起提交各选项表单 -->
		<view v-if="liutype">
			<view class="submit">
				<!-- 基础表单校验 -->
				<uni-forms ref="valiForm" :rules="rules" :modelValue="baseFormData">
					<uni-forms-item label="类型" name="companyName" required>
						<!-- <picker :range="baseFormData.submittype"> -->
							<view class="uni-input" style="margin-right: 40px;color: black;">
								<template>临时人员</template>
								<!-- <template v-else>{{baseFormData.submittype[baseFormData.indextype]}}</template>
								<text class="jiantou">〉</text> -->
							</view>
						<!-- </picker> -->
					</uni-forms-item>
					<view class="form-line"></view>
					<uni-forms-item label="上传附件" name="companyName">
						<uni-file-picker limit="9"
						@select='selectUpload'
						@delete="deleteHandle"
						@success='uploadSuccess'	
						@fail='uploadFail' 
						v-model='fileList'
						></uni-file-picker>
					</uni-forms-item>
					<view class="form-line"></view>
					<uni-forms-item label="开始时间" name="companyName" required>
						<uni-datetime-picker type="date" return-type="datetime" @change="changeStartTime" v-model="baseFormData.startTime" :start="baseFormData.mindate" :end="baseFormData.houDate"/>
					</uni-forms-item>
					<view class="form-line"></view>
					<uni-forms-item label="结束时间" name="companyName" required>
						<uni-datetime-picker type="date" return-type="datetime" @change="changeEndTime" v-model="baseFormData.endTime" :start="baseFormData.mindate" :end="baseFormData.houDate"/>
					</uni-forms-item>
					<view class="form-line"></view>
					<uni-forms-item label="房间数量" name="companyName" required>
						<view class="uni-input" style="margin-right: 40px;color: black;">
							<!-- <template v-if="baseFormData.indextype==null">请选择</template> -->
							<!-- <template>{{roomNum}}</template> -->
							<input type="number" v-model="roomNum" @input="shuInput" style="margin-top: 10px;"/>
							<!-- <text class="jiantou">〉</text> -->
						</view>
					</uni-forms-item>
					<!-- <uni-forms-item label="申请部门" name="companyName" required>
						<view class="uni-input" style="margin-right: 40px;color: black;">
							<template>
								<template v-if="baseFormData.bumen=='0'">其他</template>
								<template v-if="baseFormData.bumen=='1'">学生</template>
								<template v-if="baseFormData.bumen=='4'">教职工</template>
								<template v-if="baseFormData.bumen=='5'">校友</template>
								<template v-if="baseFormData.bumen=='6'">访客</template>
								<template v-if="baseFormData.bumen=='7'">临时人员</template>
							</template>
						</view>
					</uni-forms-item> -->
					<view style="width: 750rpx;height: 20rpx;background-color: rgba(242, 243, 245, 1);margin-left: -20px;"></view>
					<uni-forms-item label="申请原因" name="companyName" required>
					</uni-forms-item>
					<uni-easyinput type="textarea" v-model="baseFormData.remark" placeholder="请输入原因" maxlength="800" @input="input"></uni-easyinput>
					<text class="textsrea-txt">{{textNum}}/800</text>
					<view style="width:100%;height: 30px;"></view>
				</uni-forms>
			</view>
			<view class="submit_button" @click="submitshen">提交</view>
		</view>
		<!-- 提交记录 -->
		<view v-else style="min-height: 100vh;">
			<view class="select_submit">
				<view style="width: 80px;margin-left: 9rpx;position: absolute;">
					<uni-data-select
						v-model="value"
						:localdata="zhuangtai"
						@change="changezhuang"
					  ></uni-data-select>
				</view>
				<view style="width: 80px;margin-left: 196rpx;">
					<uni-data-select
						v-model="value2"
						:localdata="TimeRanges"
						@change="changetime"
					  ></uni-data-select>
				</view>
				<!-- 不同状态的记录 -->
				<view class="submit-list" v-for="(item,index) in submit" :key="index" @click="clickDetail(item.id,item.department)">
					<text class="submit-title">临时人员</text>
					<text class="submit-time">{{item.submissionTime}}</text>
					<view class="submit-line"></view>
					<view class="submit-start" style="color: rgba(0, 0, 0, 1);">附件：</view>
					<view class="submit-start" style="color: rgba(0, 0, 0, 1);">
						<!-- {{item.imageUrl!=null&&item.imageUrl!=''}}3{{(item.imageUrl).split(',')}} -->
						<text v-if="item.imageUrl!=null&&item.imageUrl!=''">
							<image @click.stop="clickImg2(item2)" style="color: rgba(0, 97, 255, 1);width: 200rpx;height: 200rpx;margin-left: 20rpx;" :src="item2" v-for="(item2,index2) in (item.imageUrl).split(',')" :key="index2">
							</image>
						</text>
					</view>
					<view class="submit-start">开始时间：{{item.startTime}}</view>
					<view class="submit-end">结束时间：{{item.endTime}}</view>
					<view class="submit-remark">
						部门：{{item.orgName}}
						<!-- <template v-if="item.orgName=='0'">其他</template>
						<template v-if="item.orgName=='1'">学生</template>
						<template v-if="item.orgName=='4'">教职工</template>
						<template v-if="item.orgName=='5'">校友</template>
						<template v-if="item.orgName=='6'">访客</template>
						<template v-if="item.orgName=='7'">临时人员</template> -->
					</view>
					<view class="submit-remark">提交人：{{item.usersName}}</view>
					<view class="submit-remark">房间数量：{{item.houseCount}}</view>
					<view class="submit-remark">申请原因：{{item.reasonApplication}}</view>
					<view class="submit-type1" v-if="item.status==0">已拒绝</view>
					<view class="submit-type1" v-if="item.status==1">待审批</view>
					<view class="submit-type2" v-if="item.status==2">处理中</view>
					<view class="submit-type" v-if="item.status==3">已同意</view>
					<view style="height: 10px;"></view>
				</view>

			</view>
		</view>
		<!-- 图片压缩 -->
		<Compress ref="Compress" />
	</view>
</template>

<script>
// 引入压缩组件
	import Compress from '@/components/compress/compress.vue'
	import {
		postLingshi,
		getOtherlist
	} from '../../utils/api_hotel.js'
	export default {
		components: { Compress },
		data() {
			return {
				liutype:true,//切换流程状态
				//表单数据
				baseFormData:{
					startTime:'',
					endTime:'',
					mindate:new Date().toISOString().slice(0, 10),
					houDate:'',
					remark:'',//备注
					bumen:localStorage.getItem('department'),
				},
				textNum:0,
				// 校验规则
				rules: {
					age: {
						rules: [{
							required: true,
							errorMessage: '年龄不能为空'
						}, {
							format: 'number',
							errorMessage: '年龄只能输入数字'
						}]
					}
				},
				// 提交记录 
				value: '',
				zhuangtai: [
				  { value: 0, text: "已拒绝" },
				  { value: 1, text: "待审批" },
				  { value: 2, text: "处理中" },
				  { value: 3, text: "已同意" },
				  { value: '', text: "全部" },
				],
				value2: 2,
				TimeRanges: [
				  { value: 0, text: "近一周" },
				  { value: 1, text: "本月" },
				  { value: 2, text: "全部" },
				],
				submit:[],
				page:1,
				size:10,
				startTime:'',
				endTime:'',
				nowTime: new Date().toISOString().slice(0, 10),//当前日期2024-07-23
				totalCount:0,
				roomNum:0,//房间数量
				fileList: [],//上传附件
				fileList2: [],
				fileList22:'',
				// 压缩后的图片路径(用于上传)
				file: null,
				// 预览base64图片
				base: null
			}
		},
		onLoad() {
		},
		onShow() {
			console.log(this.baseFormData.startTime)
			this.baseFormData.houDate=this.GetDateStr(8)
		},
		methods: {
			//点击放大图片
			clickImg2(item2) {
				// console.log(item.srcUrl)
				uni.previewImage({
					urls: [item2], //需要预览的图片http链接列表，多张的时候，url直接写在后面就行了
					current: '', // 当前显示图片的http链接，默认是第一个
					success: function(res) {},
					fail: function(res) {},
					complete: function(res) {},
				})
			},
			//获取日期
			GetDateStr(AddDayCount){
			var dd = new Date();
			dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期
			var y = dd.getFullYear();
			var m = dd.getMonth()+1;//获取当前月份的日期
			var d = dd.getDate();
			return y+"-"+m+"-"+d;
			},
			//切换
			changeType(){
				this.liutype=!this.liutype
				if(this.liutype==false){
					this.getOtherlist()
				}
				
			},
			//输入备注
			input(e){
				this.baseFormData.remark=e
				this.textNum=e.length
			},
			//输入房间数量
			shuInput(e){
				this.roomNum=e.detail.value
			},
			changeStartTime(e){
				this.baseFormData.startTime=e
			},
			changeEndTime(e){
				this.baseFormData.endTime=e
				if(parseInt(((new Date(this.baseFormData.endTime).getTime())-(new Date(this.baseFormData.startTime).getTime()))/1000/60/60/24)>2){
					uni.showToast({
						title: '预订时间不能超过两晚',
						icon: 'error',
						duration: 1500
					})
					this.baseFormData.endTime=''
					// this.roomNum=0
				}else{
					this.baseFormData.endTime=e
					// this.roomNum=parseInt(((new Date(this.baseFormData.endTime).getTime())-(new Date(this.baseFormData.startTime).getTime()))/1000/60/60/24)
				}
			},
			//提交审核
			submitshen(){
				if(this.baseFormData.endTime<=this.baseFormData.startTime){
					uni.showToast({
						title: '开始时间不能大于结束时间',
						icon: 'error',
						duration: 1500
					})
					return
				}
				let _self = this
				this.$axios.defaults.headers.common['token'] = localStorage.getItem('token');
				this.$axios.defaults.headers.common['request_token'] = this.submitToken;
				this.$axios.defaults.headers.common['Content-Type'] ='application/json'
				var data={
					"usersId": localStorage.getItem('usersId'), //申请人id
					"startTime": this.baseFormData.startTime, //开始时间
					"endTime": this.baseFormData.endTime, //结束时间
					"department": localStorage.getItem('department'), //部门
					"reasonApplication": this.baseFormData.remark ,//申请原因
					"houseCount":this.roomNum,
					"imageUrl":this.fileList22 //附件上传url
				}
				postLingshi(data).then((res) => {
					if (res.success) {
						uni.showToast({
							title: '提交成功',
							icon: 'success',
							duration: 1500
						})
						setTimeout(function(){
							_self.fileList22=''
							_self.fileList2=[]
							_self.baseFormData.startTime=''
							_self.baseFormData.endTime=''
							_self.roomNum=0
							_self.baseFormData.remark=''
							_self.liutype=false
							_self.getOtherlist()
						},1500);
					} else {
						uni.showToast({
							title: res.message,
							duration: 1500
						})
					}
				}).catch((err) => {
					uni.showToast({
						title: err.message
					})
				});
			},
			// 临时人员提交记录
			getOtherlist(){
				let _self = this
				// adminMenuId身份类型，4为教职工，7为临时人员localStorage.getItem('department')
				// 状态，0:已拒绝，1:待审批，2:处理中，3:已同意
				var data="?department="+localStorage.getItem('department')+"&userId="+localStorage.getItem('usersId')+"&startTime="+this.startTime+"&endTime="+this.endTime+"&status="+this.value+"&page="+this.page+"&size="+this.size
				getOtherlist(data).then((res) => {
					if (res.success) {
						this.totalCount=res.data.totalCount
						if (this.page == 1) {
							this.submit = res.data.list
						} else {
							this.submit = [...this.submit, ...res.data.list]
						}
						console.log(this.submit,'ooo')
						uni.stopPullDownRefresh();
						uni.hideLoading()
					} else {
						console.log('获取记录失败')
					}
				}).catch((err) => {
					uni.showToast({
						title: err.message
					})
				});
			},
			onReachBottom: function() {
				console.log('当前长度',this.submit.length,this.totalCount)
				
				if (this.submit.length < this.totalCount) {
					wx.showLoading({
					   title: '加载中...',
					 })
					this.page = this.page + 1;
					this.getOtherlist()
				} else {
					uni.showToast({
						title: '已经到底了',
						icon: 'none'
					})
				}
			},
			onPullDownRefresh: function() {
				this.page = 1;
				this.getOtherlist();
			},
			// 选择审批状态
			changezhuang(e) {
				this.value=e
				this.getOtherlist()
			},
			//获得本周的开始时间：
			getStartDayOfWeek(time) {
				let now = new Date(time); // 当前日期
				let nowDayOfWeek = now.getDay(); // 今天本周的第几天
				let day = nowDayOfWeek || 7;
				let nowDay = now.getDate(); // 当前日
				let nowMonth = now.getMonth(); // 当前月
				return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 1 - day));
			},
			//获得本周的结束时间：
			getEndDayOfWeek(time) {
				let now = new Date(time); // 当前日期
				let nowDayOfWeek = now.getDay(); // 今天本周的第几天
				let day = nowDayOfWeek || 7;
				let nowDay = now.getDate(); // 当前日
				let nowMonth = now.getMonth(); // 当前月
				return this.formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 7 - day));
			},
			//获得本月的开始时间：
			getStartDayOfMonth(time) {
				let now = new Date(time); // 当前日期
				let nowDay = now.getDate(); // 当前日
				let nowMonth = now.getMonth(); // 当前月
				return this.formatDate(new Date(now.getFullYear(), nowMonth, 1));
			},
			// 日期格式化
			formatDate(date) {
				let myyear = date.getFullYear();
				let mymonth = date.getMonth() + 1;
				let myweekday = date.getDate();
				if (mymonth < 10) {
					mymonth = '0' + mymonth;
				}
				if (myweekday < 10) {
					myweekday = '0' + myweekday;
				}
				return (myyear + '-' + mymonth + '-' + myweekday);
			},
			// 选择时间
			changetime(e) {
			    this.value2=e
				if(this.value2==0){
					this.startTime=this.getStartDayOfWeek(this.nowTime).slice(0, 10)+' 00:00:00'
					this.endTime=this.getEndDayOfWeek(this.nowTime).slice(0, 10)+' 23:59:59'
				}else if(this.value2==1){
					this.startTime=this.getStartDayOfMonth(this.nowTime).slice(0, 10)+' 00:00:00'
					this.endTime=this.nowTime+' 23:59:59'
				}else if(this.value2==2){
					this.startTime=''
					this.endTime=''
				}
				this.getOtherlist()
			},
			// 跳转到详情页面
			clickDetail(id,department){
				uni.navigateTo({
					url: "../liuchengO/detail/teach_detail?id="+id+"&department="+department
				})
			},
			
			// 上传附件
			uploadSuccess(e) {
			console.log('上传成功', e)
			},
			uploadFail(e) {
				console.log('上传失败：', e)
			},
			//删除文件
			deleteHandle(index){
				console.log(index)
				this.fileList2.splice(index.index,1)
				// console.log(this.fileList2)
				this.fileList22=this.fileList2.join(",")
			},
			selectUpload(e) {
				console.log('上传：', e)
				console.log((e.tempFiles[0].size / 1024 > 1024 * 2),'大小')
				for (let i = 0; i < e.tempFilePaths.length; i++) {
				   if ((e.tempFiles[i].size / 1024 > 1024 * 2)) {
				   	console.log('过大')
				   	this.yaimg(e.tempFilePaths[i])
				   }else{
				   	this.imgUpload(e.tempFiles[i].file);
				   }
				}
				
				 
			},
			//上传图片
			// const base_url = '/ihotel/auto'//线下
			// const base_url = '/hotel/ihotel/auto/'//线上
			async imgUpload(result){
				uni.showLoading({
					title: '上传中',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				});
				let data = new FormData();
				  data.set("file", result);
				  let res = await this.$axios({
				    method: "post",
				    url: "/hotel/ihotel/auto" + "/upload/save",
				    headers: {
						// tokenW: localStorage.getItem("token"),
						"Content-Type": "multipart/form-data"
				    },
				    data: data,
				  });
					// return res
				  console.log(res, "图片上传成功");
				  if (res.data.code == 200) {
				    this.fileList2.push(res.data.data.url);
					this.fileList22=this.fileList2.join(",")
					uni.hideLoading();
				  }else {
			    		uni.showToast({
							title: res.message,
							icon: 'none',
							duration:800
						});
						uni.hideLoading();
				    }
			},
			/**
			 * 压缩图片
			 * @description 由组件处理,只需传入临时路径
			 * @param {Object} url - 临时路径
			 * @return void
			 */
			yaimg(url) {
				uni.showLoading({
					title: '压缩中',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				});
				// 组件参数也有文档，详见文章的最底部！
				// const config = {
				// 	src: url,//要压缩的临时路径
				// 	maxSize: 800,//压缩后的最大尺寸
				// 	fileType: 'png',//压缩后的文件类型，可选值 jpg、png
				// 	quality: 0.6,//压缩后的质量(仅jpg类型有效，原因可自行阅读官方canvas文档)，可选值 0 ~ 1，值越大越清晰(图片也越大)
				// }
				// console.log(config)
				// 调用压缩方法
				this.$refs.Compress.compress({
					src: url,//要压缩的临时路径
					maxSize: 800,//压缩后的最大尺寸
					fileType: 'png',//压缩后的文件类型，可选值 jpg、png
					quality: 0.6,//压缩后的质量(仅jpg类型有效，原因可自行阅读官方canvas文档)，可选值 0 ~ 1，值越大越清晰(图片也越大)
				}).then((res) => {
					// console.log('返回的base64编码', res)
					this.base = res
			
					// 时间戳 + 随机数, 防止文件名重复
					let timestamp = new Date().getTime();
					let sunumber = Math.floor(Math.random()*999);
					// H5需要将base64转为file对象进行上传
					// 第一个参数是base64编码, 第二个是文件名
					var file = this.base64ToFile(res, timestamp + sunumber)
					
					// 最终压缩完毕的file对象
					console.log('压缩后的图片(File对象)', file)
					this.upload(file)
					this.file = file
					
					uni.hideLoading();
					//上传到服务器
					// this.upload(file)
				}).catch((err) => {
					console.log('压缩失败',err)
					uni.hideLoading();
				})
			},
			/**
			 * 压缩后上传到服务器
			 * @description 这块需要您自行处理
			 * @param {Object} file - 要上传的file对象
			 * @return void
			 */
			async upload(file){
				uni.showLoading({
					title: '上传中',
					mask: true, // 是否显示透明蒙层，防止触摸穿透
				});
				let data = new FormData();
				  data.set("file", file);
				console.log(data)
				  let res = await this.$axios({
				    method: "post",
				    url: "/testingServer/ihotel/auto" + "/upload/save",
				    headers: {
						// tokenW: localStorage.getItem("token"),
						"Content-Type": "multipart/form-data"
				    },
				    data: data,
				  });
					// return res
				  console.log(res, "图片上传成功",res.data.code == 200);
				  if (res.data.code == 200) {
				    this.fileList2.push(res.data.data.url);
					this.fileList22=this.fileList2.join(",")
					console.log(this.fileList22)
					uni.hideLoading();
				  }else {
			    		uni.showToast({
							title: res.message,
							icon: 'none',
							duration:800
						});
						uni.hideLoading();
				   }
			},
			/**
			 * base64 → File
			 * @description 转换函数
			 * @param {String} base64- base64完整字符串
			 * @param {String} name - 文件名
			 * @return Object
			 */
			base64ToFile(base64, name) {
			  if (typeof base64 != 'string') { return; }
				var arr = base64.split(',')
				var type = arr[0].match(/:(.*?);/)[1]
				var fileExt = type.split('/')[1]
				var bstr = atob(arr[1])
				var n = bstr.length
				var u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new File([u8arr], `${name}.` + fileExt, {
					type: type
				})
			},
		}
	}
</script>

<style>
	@import url("./css/liu_other.css");
</style>