<template>
	<view class="fullHeight">
		<headers :showBack="true">
			<view class="headerName">
				{{pageTitle}}
			</view>
		</headers>
		<view class="formBox">
			<form @submit="formSubmit">
				<view class="uni-form-item">
					<view class="uni-form-label">
						<text class="star">*</text>安全培训类型
					</view>
					<view class="uni-form-input">
						<picker @change="bindPickerChange" :value="selectIndex" :range="selectList"
							range-key="locationName">
							<view class="uni-input uni-select cl" v-if="selectIndex==null">
								请选择 <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
							</view>
							<view class="uni-input uni-select" v-else>{{selectList[selectIndex]}}
								<image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
							</view>
						</picker>
					</view>
				</view>
				<view class="uni-form-item">
					<view class="uni-form-label">
						<text class="star">*</text>培训主题
					</view>
					<view class="uni-form-input">
						<input class="uni-input" placeholder-class="cl" name="eduCourseName" :value="form.eduCourseName"
							placeholder="请输入" />
					</view>
				</view>

				<view class="uni-form-item">
					<view class="uni-form-label">
						<text class="star">*</text>培训日期
					</view>
					<view class="uni-form-input">
						<picker mode="date" :value="form.eduTime" @change="bindDateChange">
							<view class="uni-input uni-select cl" v-if="form.eduTime==''">
								请选择 <image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
							</view>
							<view class="uni-input uni-select" v-else>{{form.eduTime}}
								<image class="icon-down" src="/static/icon-down-black.png" mode=""></image>
							</view>
						</picker>
					</view>

				</view>
				<view class="uni-form-item">
					<view class="uni-form-label">
						<text class="star">*</text>培训人
					</view>
					<view class="uni-form-input">
						<input class="uni-input" placeholder-class="cl" name="eduTeacher" :value="form.eduTeacher"
							placeholder="请输入" />
					</view>
				</view>
				<view class="uni-form-item">
					
					<view class="uni-form-label">
						
							<text class="star">*</text>
						培训开始时间
					</view>
					<view class="uni-form-input">
						<picker @change="changeDatetimePicker($event,'startTime')" mode="time">
							<view class="uni-input" style="display: flex;justify-content: space-between;align-items: center;">
							{{startTimeVal||'请选择'}}
							<image style="width: 22rpx;height: 22rpx;opacity:0.6;" class="icon-down" src="/static/icon-down-black.png" mode=""></image>
							</view>
							
						</picker>
					</view>
				</view>
				<view class="uni-form-item">
					<view class="uni-form-label">
						<text class="star">*</text>培训结束时间
					</view>
					<view class="uni-form-input">
						<picker v-if="startTimeVal&&startTimeVal!='请选择'" :start="startTimeVal" @change="changeDatetimePicker($event,'endTime')" mode="time">
							<view class="uni-input" style="display: flex;justify-content: space-between;align-items: center;">
							{{endTimeVal||'请选择'}}
							<image style="width: 22rpx;height: 22rpx;opacity:0.6;" class="icon-down" src="/static/icon-down-black.png" mode=""></image>
							</view>
							
						</picker>
						<picker v-else @change="changeDatetimePicker($event,'endTime')" mode="time">
							<view class="uni-input" style="display: flex;justify-content: space-between;align-items: center;">
							{{endTimeVal||'请选择'}}
							  <image style="width: 22rpx;height: 22rpx;opacity:0.6;" class="icon-down" src="/static/icon-down-black.png" mode=""></image>
							</view>
							
						</picker>
						<!-- <dateTimePiccker v-if="startTimeVal" placeholder="请选择整改结束时间" :defaultValue="defaultValueEnd" :start="endTimeVal" fields="minute"
							@change="changeDatetimePicker($event,'endTime')" class="uni-input"></dateTimePiccker>
						<dateTimePiccker v-else placeholder="请选择整改结束时间"  fields="minute"
							@change="changeDatetimePicker($event,'endTime')" class="uni-input"></dateTimePiccker> -->
					</view>
				</view>
				<view class="uni-form-item">
					<view class="uni-form-label">
						培训课时(分钟)
					</view>
					<view class="uni-form-input">
						<input class="uni-input" placeholder-class="cl" name="eduClasshour" :value="form.eduClasshour"
							placeholder="请输入" />
					</view>
				</view>
				<view class="uni-form-item">
					<view class="uni-form-label">
						<text class="star">*</text>培训的工人
					</view>
					<!-- <view class="uni-form-input" style="text-align: right;">
						共{{personList.length}}人
					</view> -->
				</view>
				<view class="personListBox" @click="goSelectPersonFn">
					<view class="personLeft">
						<view class="personItem" v-for="(item,index) in personList" :key="index" v-if="index<5">
							<view class="name">
								{{item.workerName}}
							</view>
							<view class="txt">
								{{item.teamName}}
							</view>
						</view>
						<view class="personItem total">
							共{{personList.length}}人
						</view>
					</view>
					<image src="/static/icon-right.png" class="icon-right"></image>

					<!-- <view class="personItem" @click="goSelectPersonFn">
						<image src="/static/icon-add.png" style="width: 19px;height: 40rpx;" class="name"></image>
						<view class="txt">
							手动添加
						</view>
					</view>
					<view class="personItem">
						<image src="/static/icon-add.png" style="width: 19px;height: 40rpx;" class="name"></image>
						<view class="txt">
							扫码添加
						</view>
					</view> -->
				</view>
				<view class="uplItem">
					<view class="uplImgEduBefore_title">
						培训前照片
						<text v-if="form.eduBeforePhoto" @click="delFile('eduBeforePhoto')"
							style="color:#F56C6C;margin-left:20rpx;">删除</text>
					</view>
					<view class="uplImgEduBefore" @click="uplImgEduBeforePhoto('eduBeforePhoto')">
						<image
							:src="form.eduBeforePhoto?url_config+'image/'+form.eduBeforePhoto:'/static/safeMange/upload_image.png'"
							class="icon-add" color="#F56C6C">
						</image>
					</view>
				</view>
				<view class="uplItem">
					<view class="uplImgEduBefore_title">
						培训中照片
						<text v-if="form.eduInPhoto" @click="delFile('eduInPhoto')"
							style="color:#F56C6C;margin-left:20rpx;">删除</text>
					</view>
					<view class="uplImgEduBefore" @click="uplImgEduBeforePhoto('eduInPhoto')">
						<image
							:src="form.eduInPhoto?url_config+'image/'+form.eduInPhoto:'/static/safeMange/upload_image.png'"
							class="icon-add" color="#F56C6C">
						</image>
					</view>
				</view>
				<view class="uplItem">
					<view class="uplImgEduBefore_title">
						培训后照片 <text v-if="form.eduAfterPhoto" @click="delFile('eduAfterPhoto')"
							style="color:#F56C6C;margin-left:20rpx;">删除</text>
					</view>
					<view class="uplImgEduBefore" @click="uplImgEduBeforePhoto('eduAfterPhoto')">
						<image
							:src="form.eduAfterPhoto?url_config+'image/'+form.eduAfterPhoto:'/static/safeMange/upload_image.png'"
							class="icon-add" color="#F56C6C">
						</image>
					</view>
				</view>
				<view class="uplItem">
					<view class="uplImgEduBefore_title">
						视频教学 <text v-if="form.uploadAttachments" @click="delFile('uploadAttachments')"
							style="color:#F56C6C;margin-left:20rpx;">删除</text>
					</view>
					<view v-if="!form.uploadAttachments" class="uplImgEduBefore"
						@click="uplImgEduBeforePhoto('uploadAttachments')">
						<image src="/static/safeMange/upload_image.png" class="icon-add" color="#F56C6C">
						</image>

					</view>
					<video v-else :src="url_config+'image/'+form.uploadAttachments" controls></video>
				</view>
				<button form-type="submit" type="primary" class="btn submitBtn big">保存</button>
			</form>
		</view>
	</view>
</template>

<script>
	import dateTimePiccker from '@/components/dateTimePicker/index.vue'
	export default {
		components: {
			dateTimePiccker
		},
		data() {
			return {
				pageTitle: '新增安全教育',
				selectIndex: null,
				selectList: ['入场三级教育', '定期安全教育', '安全技术交底', 'VR安全教育', '班前教育', '日常教育（日常违规教育）', '每日交底（专项方案交底）',
					'每日交底（安全技术交底）', '每日交底（大工程交底）'
				],
				form: {
					eduAddr: "",
					eduClasshour: 0,
					eduContent: "",
					eduCourseName: "",
					eduPhoto: "",
					eduTeacher: "",
					eduTime: "",
					eduType: 1,
					list: [],
					workernum: 0,
					projectSn: '',
					eduBeforePhoto: '',
					eduInPhoto: '',
					eduAfterPhoto: '',
					uploadAttachments: ''
				},
				personList: [],
				projectDetail: {},
				isAdd: true,
				startTime: '',
				startTimeVal: '',
				endTimeVal: '',
				eduClasshourObj: {
					startTimeValStamp:0,
					endTimeValStamp:0
				},
                defaultValueEnd:'',
				defaultValueStart:''

			}
		},
		watch: {
            eduClasshourObj:{
				handler(n,o){
					console.log(n,'nnnn');
					if(n.endTimeValStamp!=0&&n.startTimeValStamp!=0){
						let eduHour=n.endTimeValStamp-n.startTimeValStamp;
						this.form.eduClasshour=eduHour/60000;
					}else{
						this.form.eduClasshour=0
					}
					
					console.log(this.form.eduClasshour,'eduHour')
				},
				deep:true
			}
		},
		mounted() {
			// console.log(JSON.parse(uni.getStorageSync('projectDetail')))
			this.projectDetail = JSON.parse(uni.getStorageSync('projectDetail'))
		},
		onLoad(options) {
			if (options.id) {
				this.isAdd = false
				this.pageTitle = '编辑安全教育'
				this.getDetails(options.id)
			}
			
			// this.startTime = this.$formatDates(new Date().getTime());
			// this.endTimeVal = this.$formatDates(new Date().getTime());
		},
		onShow() {
			if (uni.getStorageSync('person')) {
				this.personList = JSON.parse(uni.getStorageSync('person'))
			}
		},
		methods: {
			changeDatetimePicker(date, t) {
				console.log('选择的日期时间数据：', date, t);
				// this.endTime = this.$formatDates(date.f10 + 1800000);
				// this.maxEndTime = this.$formatDates(date.f10 + (3 * 86400000));
				if (t == 'startTime') {
					this.startTimeVal = date.detail.value
					
					let date_edu=this.form.eduTime||this.$formatDates(new Date().getTime(),'yyyy-MM-dd');
					let dateStr=date_edu+" "+this.startTimeVal;
					this.eduClasshourObj.startTimeValStamp=new Date(dateStr).getTime();
					
                   
				} 
			
				this.endTimeVal = date.detail.value;
				let date_edu=this.form.eduTime||this.$formatDates(new Date().getTime(),'yyyy-MM-dd');
				let dateStr=date_edu+" "+this.endTimeVal;
				this.eduClasshourObj.endTimeValStamp=new Date(dateStr).getTime();
				// this.eduClasshourObj.endTimeValStamp = date.f10;
			},
			delFile(key) {
				this.form[key] = '';
			},
			// 选择培训前照片
			uplImgEduBeforePhoto(key) {

				let that = this;
				if (key == 'uploadAttachments') {

					uni.chooseVideo({
						count: 1,
						sourceType: ['camera', 'album'],
						mediaType: ['video'],
						success(res) {
							// tempFilePath可以作为img标签的src属性显示图片

							const tempFilePathsVideo = res.tempFilePath;
							console.log('tempFilePathsVideo', tempFilePathsVideo)
							uni.uploadFile({
								url: that.url_config + 'upload/image', //仅为示例，非真实的接口地址
								filePath: tempFilePathsVideo,
								name: 'files',
								success: (uploadFileRes) => {

									console.log(uploadFileRes)
									let fileArr = JSON.parse(uploadFileRes.data);
									console.log(fileArr)
									that.form[key] = (fileArr.data[0].imageUrl);
								},
								fail(e) {
									console.log(e)
								}
							});
						}
					})
				} else {
					uni.chooseImage({
						count: 1,
						sourceType: ['camera', 'album'],
						success(res) {
							// tempFilePath可以作为img标签的src属性显示图片
							console.log('res', res.tempFiles)
							const tempFilePaths = res.tempFilePaths;
							uni.uploadFile({
								url: that.url_config + 'upload/image', //仅为示例，非真实的接口地址
								filePath: tempFilePaths[0],
								name: 'files',
								success: (uploadFileRes) => {
									let data = {
										name: JSON.parse(uploadFileRes.data).data[0].filename,
										url: JSON.parse(uploadFileRes.data).data[0].imageUrl
									};
									console.log(uploadFileRes)
									let fileArr = JSON.parse(uploadFileRes.data);
									console.log(fileArr)
									that.form[key] = (fileArr.data[0].imageUrl);
								},
								fail(e) {
									console.log(e)
								}
							});
						}
					})
				}

			},
			goSelectPersonFn() {
				uni.navigateTo({
					url: './personList'
					// url:'../../selectPerson/selectPerson2'
				})
			},
			getDetails(id) {
				this.projectDetail = JSON.parse(uni.getStorageSync('projectDetail'))
				var that = this
				this.sendRequest({
					url: 'xmgl/workerSafeEducation/queryById',
					data: {
						id: id,
						projectSn: this.projectDetail.projectSn
					},
					method: "POST",
					success(res) {
							
						that.startTimeVal=res.result.workerSafeEducation.eduStartTime;
						that.endTimeVal=res.result.workerSafeEducation.eduEndTime;
					
						that.form = res.result.workerSafeEducation;
						that.personList = res.result.list;
						that.selectIndex = that.form.eduType - 1;
						uni.setStorageSync('person', JSON.stringify(that.personList));
					}
				})
			},
			bindPickerChange: function(e) {
				this.selectIndex = e.target.value
			},
			bindDateChange: function(e) {
				this.form.eduTime = e.target.value
			},
			formSubmit(e) {
				var that = this
				console.log(e)
				var params = e.detail.value
				params.projectSn = this.projectDetail.projectSn
				if (this.selectIndex == null) {
					uni.showToast({
						title: '请选择安全培训类型',
						icon: 'none'
					})
					return false;
				}
				if (params.eduCourseName == '') {
					uni.showToast({
						title: '请输入培训主题',
						icon: 'none'
					})
					return false;
				}
				if (!this.form.eduTime) {
					uni.showToast({
						title: '请选择培训日期',
						icon: 'none'
					})
					return false;
				}
				
				if (!this.startTimeVal&&this.startTimeVal!='请选择') {
					uni.showToast({
						title: '请选择开始培训时间',
						icon: 'none'
					})
					return false;
				}	
				if (!this.endTimeVal&&this.startTimeVal!='请选择') {
					uni.showToast({
						title: '请选择结束培训时间',
						icon: 'none'
					})
					return false;
				}	
				
				if (this.form.eduClasshour==0) {
					uni.showToast({
						title: '培训课时不能为零',
						icon: 'none'
					})
					return false;
				}
				
				if (!this.personList.length) {
					uni.showToast({
						title: '请选择参与培训的工人',
						icon: 'none'
					})
					return false;
				}

				params.eduBeforePhoto = this.form.eduBeforePhoto;
				params.eduInPhoto = this.form.eduInPhoto;
				params.eduAfterPhoto = this.form.eduAfterPhoto;
				params.uploadAttachments = this.form.uploadAttachments;

				params.eduType = this.selectIndex + 1;
				params.eduTime = this.form.eduTime;
				params.eduStartTime = this.startTimeVal;
				params.eduEndTime = this.endTimeVal;
				var arr = [];
				this.personList.forEach((element) => {
					var item = {
						isQualified: element.isQualified,
						score: element.score,
						workerId: element.workerId,
						projectSn: this.projectDetail.projectSn
					};
					if (!this.isAdd) {
						item.eduId = this.form.id;
						item.id = element.id;
					}
					arr.push(item);
				});
				params.list = arr;

				var url = 'xmgl/workerSafeEducation/edit'
				if (this.isAdd) {
					url = 'xmgl/workerSafeEducation/add'

				} else {
					params.id = this.form.id
				}
				this.sendRequest({
					url: url,
					data: params,
					method: "POST",
					success(res) {
						uni.showToast({
							title: '保存成功！'
						})
						uni.navigateBack({

						})
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.uplItem {
		font-size: 28rpx;
		margin-bottom: 20rpx;
	}

	.uplImgEduBefore_title {
		margin: 20rpx 0;
	}

	.uplImgEduBefore {

		border: 1px solid rgba(42, 43, 91, 0.1);
		background-color: #f6f5f8;
		width: 120rpx;
		height: 120rpx;
		display: inline-flex;
		align-items: center;
		justify-content: center;
		border-radius: 20rpx;
		font-size: 24rpx;
		margin-right: 12rpx;

		uni-image {
			width: 120rpx;
			height: 120rpx;
		}



	}

	.personListBox {
		// background-color: #f7f7f7;
		border-radius: 4px;
		overflow: hidden;
		border-left: 1px dashed #e6e6e6;
		position: relative;

		.personLeft {
			width: calc(100% - 20rpx);
		}

		.personItem {
			float: left;
			width: calc(33.33% - 21px);
			height: 54px;
			text-align: center;
			font-size: 24rpx;
			border-bottom: 1px dashed #e6e6e6;
			padding: 0px 20rpx 0;
			border-right: 1px dashed #e6e6e6;
			border-top: 1px dashed #e6e6e6;
			background-color: #f7f7f7;

			.name {
				font-size: 30rpx;
				padding-top: 16rpx;
			}

			.txt {
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
			}

			&.total {
				display: inline-flex;
				align-items: center;
				font-size: 30rpx;
				justify-content: center;
			}

			// &:nth-child(3n){
			// 	border-right: none;
			// }
		}

		.icon-right {
			position: absolute;
			right: 0;
			top: calc(50% - 7px);
			width: 16rpx;
			height: 28rpx;
		}
	}
</style>
