<template>
	<view class="hzIndex">
		<hzHeader title="健康打卡"></hzHeader>
	<!-- 	<view class="tab-banner">
			<image class="image" src="/static/images/epidemic/jkdk-header1.jpeg"></image>
		</view> -->
		<view class="hzContent" style="padding-top: 200upx;">
		<view style="background-color: #E5F4FF;color: #666666;font-size: 28upx;padding: 20upx;margin: 20upx;">
			所有人员每日需打卡一次，打卡人对自己打卡结果负责，承担相应责任。
		</view>
		<view style="padding: 10upx 20upx;">
			<view v-if="list.length>0" class="box box-align-center" style="background-color: #6ED478;padding: 20upx;border-radius: 10upx;color:white">
				<view>
					<image style="width: 80upx;height: 80upx;" src="/static/images/epidemic/dk-cg.png"></image>
				</view>
				<view style="padding-left: 20upx;">
					<view style="font-size: 38upx;">
						您今日已打卡成功！
					</view>
					<view style="font-size: 28upx;padding: 2upx 0px;">
						打卡人：{{list[0].USER_NAME}}
					</view>
					<view style="font-size: 28upx;padding: 2upx 0px;">
						打卡时间：{{formatDate(list[0].GMT_CREATED,'dateTime')}}	
					</view>
					<view style="font-size: 28upx;padding: 2upx 0px;">
						打卡地点：{{list[0].LOCATION}}
					</view>
				</view>
			</view>
			<!-- <view v-if="list.length>0&&cardInfo==1" class="box box-align-center" style="background-color: orangered;padding: 20upx;border-radius: 10upx;color:white">
				<view>
					<image style="width: 80upx;height: 80upx;" src="/static/images/epidemic/dk-error.png"></image>
				</view>
				<view style="padding-left: 20upx;">
					<view style="font-size: 38upx;">
						您今日打卡信息异常！
					</view>
					<view style="font-size: 28upx;padding: 2upx 0px;">
						打卡人：{{list[0].USER_NAME}}
					</view>
					<view style="font-size: 28upx;padding: 2upx 0px;">
						打卡时间：{{formatDate(list[0].GMT_CREATED,'dateTime')}}	
					</view>
					<view style="font-size: 28upx;padding: 2upx 0px;">
						打卡地点：{{list[0].LOCATION}}
					</view>
				</view>
			</view> -->
		</view>
		<view style="padding: 0px 20upx ; ">
			<view class="form-box-ud" style="border-radius: 10upx;">
				<view class="form-item" v-for="(item, index) in questions" :key="index">
					<text class="label"><text v-if="item.required" style="color: red;">*</text>{{index+1+'.'+item.title}}</text>
					<view class="ipt-box">
						<radio-group v-if="item.type=='radius'" @change="changeRadioGroup($event,item.formName)">
							<label class="uni-list-cell uni-list-cell-pd radio-group" v-for="(obj, index1) in item.options" :key="index1" >
								<view>
									<radio  color="#4db4ea" :value="obj" :checked="obj==formData[item.formName]" />
								</view>
								<view>{{obj}}</view>
							</label>
						</radio-group>
						<view class="img-box" v-if="item.imgName">
							<view class="img-item" v-if="formData[item.imgName]">
								<image class="remove-btn" @click="removeImg(item.imgName)" src="/static/icons/delete-icon.png" mode=""></image>
								<image class="img" :src="img[item.imgName][0].replace(/[\r\n]/g,'')" mode=""></image>
							</view>
							<view v-else class="img-item upload-btn" @click="chooseImg(item.imgName)" ><image class="img" src="/static/imgs/tianjia-img.png" mode=""></image></view>
						</view>
					</view>
				</view>
			</view>
		</view>
		</view>
		<view class="occupied"></view>
		<view class="footer-btn" @click="submit"><view class="btn-blue">提交</view></view>
	</view>
</template>

<script>
	import { healthyClockAdd,healthyClockList} from '@/common/api.js';
	import { callbackRequest,callbackRequestNoLoading, getStorage, alertTip, convertImgToBase64, formatDate,wxSdk,uploadImg,formatImgUrl  } from '@/common/util.js';
	export default {
		data() {
			return {
				formatImgUrl:formatImgUrl,
				formatDate:formatDate,
				questions:[
					{
						title:'用工类型',
						formName:'userType',
						type:'radius',
						required:true,
						requiredText:'请选择用工类型',
						options:[
							'全民职工','社会用工'
						]
					},
					{
						title:'目前健康状况',
						formName:'healthState',
						type:'radius',
						required:true,
						requiredText:'请选择目前健康状态',
						options:[
							'正常','核酸阳性（核酸异常）','无症状感染者','确诊'
						]
					},
					{
						title:'今日出行情况',
						formName:'cityOut',
						type:'radius',
						required:true,
						requiredText:'请选择您是否有市外出行',
						options:[
							'市内','市外省内','省外','涉外归国'
						]
					},
					{
						title:'目前状态',
						formName:'dangerRegion',
						type:'radius',
						required:true,
						requiredText:'请选择目前状态',
						options:[
							'在岗','居家办公','收到排查短信（居家隔离）','管控（居家隔离）','封闭（居家隔离）','集中隔离'
						]
					},
					{
						title:'健康码颜色',
						formName:'healthCode',
						type:'radius',
						required:true,
						requiredText:'请选择健康码颜色',
						// imgName:'healthCodeImg',
						options:[
							'绿色','灰色','黄色','红色'
						]
					},
					// {
					// 	title:'健康码',
					// 	type:'img',
					// 	required:true,
					// 	requiredText:'请上传健康码',
					// 	imgName:'healthCodeImg',
					// },
					// {
					// 	title:'行程码',
					// 	type:'img',
					// 	required:true,
					// 	requiredText:'请上传行程码',
					// 	imgName:'tourCodeImg',
					// },
					// {
					// 	title:'今日核酸是否已采',
					// 	formName:'nucleic',
					// 	type:'radius',
					// 	required:true,
					// 	requiredText:'请选择今日核酸是否已采',
					// 	options:[
					// 		'否','是'
					// 	]
					// },
				],
				img:{
					healthCodeImg:[],
					tourCodeImg:[],
				},
				formData:{
					userId: getStorage('userInfo').userId,
					userName: getStorage('userInfo').userName,
					phone: getStorage('userInfo').telnumber,
					orgId: getStorage('userInfo').department_id,
					orgName: getStorage('userInfo').departmentName,
					userType:'',
					healthState:'',
					cityOut:'',
					dangerRegion:'',
					healthCode:'',
					healthCodeImg:'',
					tourCodeImg:'',
					nucleic:'',
					location:''
				},
				submitFlag:true,
				list:[],
				cardInfo:0
			}
		},
		onLoad() {
			this.getLocation();
			this.healthyClockList();
		},
		watch: {
			formData: {
				handler(newValue,oldValue){
					if(this.formData.healthState!='正常'||this.formData.cityOut=='是'||this.formData.dangerRegion=='是'||
						this.formData.healthCode!='绿色'||this.formData.nucleic=='否'
					){
						this.cardInfo=1;
					}else{
						this.cardInfo=0;
					}
				},
				deep:true
			}
		},
		methods: {
			getLocation(){
				let _this = this;
				wxSdk.invoke("ext_SGMap_Location", {
					"data": {
						"function": 'onceLocation',
						"data": {
							"locationWithReGeocode": true,//连续定位是否返回逆地理信 息，默认 NO。 
							"locationTimeout": 5//外部定位设备。默认 false 
						}
					}
				}, function (res) { 
					let data = JSON.parse(res.data);
					_this.formData.location = data.address;
					console.log(_this.formData.location,'ext_SGMap_Location');
				})
			},
			
			submit(){
				
				if(this.submitFlag){
					this.submitFlag = false;
					if(!this.verificationForm()){
						this.submitFlag = true;
						return false;
					}
					let params = {
						method: healthyClockAdd,
						data: this.formData
					};
					callbackRequest(params).then(res => {
						res = res.data;
						if (res.returnCode == 1) {
							this.submitFlag = true;
							alertTip(res.returnMsg);
							setTimeout(_ => {
								this.customNavigateBack()
							}, 1500);
						} else {
							this.submitFlag = true;
							alertTip(res.returnMsg);
						}
					});
				}
			},
			customNavigateBack() {
				// 自定义返回逻辑
				const pages = getCurrentPages(); // 获取页面栈
				const len = pages.length;
				let backPage = ''; // 要返回的页面路径
				for (let i = len - 2; i >= 0; i--) {
					// 从倒数第二个页面开始遍历，找到第一个不是当前页面的页面
					if (pages[i].route !== 'pages/A/A') {
						backPage = pages[i].route;
						break;
					}
				}
				if (backPage) {
					uni.navigateBack({
						delta: len - 1 - pages.findIndex(page => page.route === backPage) // 返回到已存在的页面
					});
				}
			},
			verificationForm(){
				for(let i=0;i<this.questions.length;i++){
					let obj = this.questions[i];
					if(obj.required){
						if(obj.type=='radius'){
							if(!this.formData[obj.formName]){
								alertTip(obj.requiredText);
								return false;
							}
						}else if(obj.type=='img'){
							if(!this.formData[obj.imgName]){
								alertTip(obj.requiredText);
								return false;
							}
						}
						
					}
				}
				return true;
			},
			
			healthyClockList() {
				let that = this;
				let params = {
					method: healthyClockList,
					data: {
						userId: getStorage('userInfo').userId,
					}
				};
				callbackRequestNoLoading(params).then(res => {
					if (res.data.returnCode == 1) {
						this.list = res.data.returnData||[];
						if(this.list.length>0){
							this.formData.healthState = this.list[0].HEALTH_STATE;
							this.formData.cityOut = this.list[0].CITY_OUT;
							this.formData.dangerRegion = this.list[0].DANGER_REGION;
							this.formData.healthCode = this.list[0].HEALTH_CODE;
							this.formData.healthCodeImg = this.list[0].HEALTH_CODE_IMG?this.list[0].HEALTH_CODE_IMG.split('webImageDir/')[1]:'';
							this.formData.tourCodeImg = this.list[0].TOUR_CODE_IMG?this.list[0].TOUR_CODE_IMG.split('webImageDir/')[1]:'';
							this.formData.nucleic = this.list[0].NUCLEIC;
							this.formData.location = this.list[0].LOCATION||'';
							this.img.healthCodeImg[0] = this.formatImgUrl(this.list[0].HEALTH_CODE_IMG);
							this.img.tourCodeImg[0] = this.formatImgUrl(this.list[0].TOUR_CODE_IMG);
							this.formData.userType = this.list[0].USER_TYPE;
							
						}
					} 
				});
			},
			
			changeRadioGroup(e,radioData){
				this.formData[radioData] = e.detail.value;
				console.log(this.formData);
				// console.log(data);
			},
			
			async chooseImg(obj) {
				let chec = 0;
				let sty = [];
				let _this = this;
				uni.showActionSheet({
					itemList:['拍照','相册'],
					success:function(resp){
						chec = resp.tapIndex;
						if (chec == 0) {
							sty = ['camera']; //从相册相机选择 
						} else {
							sty = ['album']; //从相册相机选择
						}
						uni.chooseImage({
							count:1,
							sizeType: ['compressed'],
							sourceType: sty, 
							quality: 1,
							success: async function(res){
								let resData = res.tempFilePaths;
								for(let i=0;i<resData.length;i++){
									console.log(_this.img[obj].length>1,_this.img[obj].length);
									if(_this.img[obj].length>1){
										break;
									}
									uni.getImageInfo({
										src: resData[i],
										success:async (path) => {
											convertImgToBase64(path.path, async function(base64) {
												if(_this.img[obj].length<1){
													// _this.imgs.push(base64);
													uni.showLoading({
														title: '图片上传中'
													})
													let blength = base64.length;
													let glength = 7500;
													if(blength<=glength){
														let uploadParam = {
															base64: base64,
															userId:  getStorage('userInfo').userId+i,
															groupEnd: '1'
														}
														await uploadImg(uploadParam).then(resu => {
															resu = resu.data ;
															uni.hideLoading();
															if (resu.returnCode != 1) {
																alertTip(resu.returnMsg);
															}else{
																_this.img[obj].push(base64);
																_this.formData[obj]=resu.returnData+".jpg";
															}
														});
													}else{
														let fnum = parseInt(blength/glength);
														for(let j=1;j<fnum+1;j++){
															if(j==fnum){
																let groupBase = base64.slice((j-1)*glength);
																console.log(groupBase.length,"groupBaselength");
																let uploadParam = {
																	base64: groupBase,
																	userId: getStorage('userInfo').userId+i,
																	groupEnd: '1'
																}
																await uploadImg(uploadParam).then(resu => {
																	resu = resu.data ;
																	if (resu.returnCode == 1) {
																		_this.img[obj].push(base64);
																		_this.formData[obj]=resu.returnData+".jpg";
																	} else {
																		uni.hideLoading();
																		alertTip(resu.returnMsg);
																		return;
																	}
																});
															}else{
																let groupBase = base64.slice((j-1)*glength,glength*j);
																let uploadParam = {
																	base64: groupBase,
																	userId: getStorage('userInfo').userId+i,
																	groupEnd: '0'
																}
																await uploadImg(uploadParam).then(resu => {
																	resu = resu.data ;
																	if (resu.returnCode == 1) {
																	} else {
																		uni.hideLoading();
																		alertTip(resu.returnMsg);
																		return;
																	}
																});
															}
															
														}
														uni.hideLoading();
													}
													
													
												}
												
											});
										},
									});
								}
								
							}
						});
					},
					fail:function(resp){
						console.log(resp.errMsg);
					}
				});
			},
			removeImg(obj) {
				this.img[obj] = [];
				this.formData[obj]='';
			},
		}
	}
</script>

<style lang="scss">
	uni-page-body {
		background-color:#F5F5F5!important;
		min-height: 100% !important;
		height: auto !important;
	}
.box {
	display: flex;
	display: -webkit-flex;
}

.box-row-reverse {
	flex-direction: row;
}

.box-column {
	flex-direction: column;
}

.box-left {
	justify-content: flex-start;
}

.box-right {
	justify-content: flex-end;
}

.box-center {
	justify-content: center;
}

.box-between {
	justify-content: space-between;
}
.box-around {
	justify-content: space-around;
}
.box-align-center {
	align-items: center;
}

.box-wrap {
	flex-wrap: wrap;
	margin-left: 28upx;
}	
	
.tab-banner{
	width: 100%;
	.image{
		width: 100%;
		height: 300upx;
	}
}
.form-box-ud {
	background: #fff;
	.form-item {
		overflow: hidden;
		// border-bottom: 1px solid #eee;
		padding: 30upx 20upx 10upx 20upx;
		.label {
			width: 150upx;
			font-size: 28upx;
			color: #333;
			font-weight: bold;
			line-height: 50upx;
		}
		.ipt-box {
			margin-left: 40upx;
			margin-top: 20upx;
			input {
				width: 100%;
				height: 70upx;
				line-height: 70upx;
				font-size: 28upx;
				color: #666;
				border: 1px solid #e5e5e5;
				padding-left: 20upx;
				border-radius: 10upx;
				// padding: 40upx 20upx;
			}
			.radio-group{
				font-size: 26upx;
				display: flex;
				justify-content: flex-start;
				align-items: center;
				margin-right: 40upx;
				min-width: 140upx;
				margin-bottom: 20upx;
			}
		}
		.select {
			.arrow {
				float: right;
				width: 16upx;
				height: 29upx;
				margin-top: 10upx;
			}
			.picker {
				height: 50upx;
				line-height: 50upx;
				font-size: 26upx;
				color: #666;
				margin-left: 10upx;
			}
		}
	}
}

.occupied{
	height:200upx;
}
.footer-btn{
	position:fixed;
	bottom:0;
	left:0;
	width:100%;
	z-index:10;
	.btn{
		margin:20upx 30upx;
		// background: #007aff;
		background:linear-gradient(to right, #ffc200,#ff9000);/*设置按钮为渐变颜色*/
		font-size:32upx;
		color:#fff;
		text-align:center;
		line-height:90upx;
		border-radius:6upx;
	}
	.btn-blue{
		margin:20upx 30upx;
		// background: #007aff;
		background: linear-gradient( 90deg, #50CBA1 0%, #06AEA6 100%), #C1EFEA;
		font-size:32upx;
		color:#fff;
		text-align:center;
		line-height:90upx;
		border-radius:50upx;
	}
}
.img-box {
	overflow: hidden;
	padding-top: 20rpx;
	padding-bottom: 10rpx;

	.img-item {
		float: left;
		width: 200upx;
		height: 200upx;
		border: 1px solid #ddd;
		margin: 0 22rpx 20upx 0upx;
		position: relative;
		box-sizing: border-box;

		.img {
			display: block;
			width: 100%;
			height: 100%;
		}

		.remove-btn {
			position: absolute;
			top: -18upx;
			right: -18upx;
			width: 44upx;
			height: 44upx;
			z-index: 2;
		}
	}

	.upload-btn {
		.img {
			width: 60upx;
			height: 60upx;
			margin: 70upx auto 0;
		}
	}
}
</style>
