<!--
 * @Title: 
 * @Description: 巡检计划创建
 * @Author: swp
 * @Date: 2022-08-24 10:49:21
 * @LastEditors: 
 * @LastEditTime: 2022-08-24 10:49:21
-->
<template>
	<view class="container">
		<uni-nav-bar dark :fixed="true" backgroundColor="#3F9EFF" statusBar="false" left-icon="left" left-text="返回"
			@clickLeft="toBack">
			<view style="width: 100%;display: flex;flex-direction: row;justify-content: center;align-items: center;">
				<text style="color: white;font-size: 1rem;">{{title}}</text>
			</view>
		</uni-nav-bar>
		<uni-forms ref="baseForm" :model="formData" :rules="rules">
			<uni-card title="巡检标题" :is-shadow="false">
				<uni-forms-item name='planTitle' label-width="0px" required>
					<uni-easyinput :styles="styles" v-model="formData.planTitle" placeholder="录入巡检标题" />
				</uni-forms-item>
			</uni-card>
			<uni-card title="巡检内容" :is-shadow="false">
				<uni-forms-item name='planDesc' label-width="0px" required>
					<uni-easyinput :styles="styles" type="textarea" :autoHeight="true" v-model="formData.planDesc"
						placeholder="录入巡检内容" />
				</uni-forms-item>
			</uni-card>
			<uni-card title="巡检设定" :is-shadow="false">
				<uni-forms-item name="planScheduledType" label="计划类型" label-width="100px" required>
					<uni-data-checkbox v-model="formData.planScheduledType"
						:localdata="planScheduledTypeItems.items"></uni-data-checkbox>
				</uni-forms-item>
				<view v-if="formData.planScheduledType==1">
					<uni-forms-item name='inspectionCompleteTime' label="截止时间" label-width="100px" required>
						<uni-datetime-picker type="date" v-model="formData.inspectionCompleteTime"
							@change="completeDateTimeChange" />
					</uni-forms-item>
				</view>
				<view v-else-if="formData.planScheduledType==2">
	<!-- 				<uni-forms-item name='inspectionStartTime' label="开始时间" label-width="100px" required>
						<uni-datetime-picker type="date" v-model="formData.inspectionStartTime"
							@change="completeDateTimeChange" />
					</uni-forms-item>
					<uni-forms-item name='inspectionEndTime' label="结束时间" label-width="100px" required>
						<uni-datetime-picker type="date" v-model="formData.inspectionEndTime"
							@change="completeDateTimeChange" />
					</uni-forms-item> -->
					<uni-forms-item name='timeType' label="执行周期" label-width="100px">
						<uni-data-checkbox v-model="formData.timeType"
							:localdata="timeTypeItems.items"></uni-data-checkbox>
					</uni-forms-item>
				</view>
			</uni-card>
		</uni-forms>
		<view class="footer">
			<view class="control">
				<view class="view-flex-inline-center">
					<view class="block"
						style="width: 160px;height:32px;margin-left: 10px;margin-right: 10px;border-radius:7px;background-color:lightsalmon"
						@click="toSubmit()">
						<view class="view-flex-cc">
							<uni-icons class="input-uni-icon" type="checkmarkempty" size="18" color="#ffffff" />
						</view>
						<view class="view-flex-cc" style="padding-left:5px;">
							<text style="color:black;font-size:0.7rem">立即提交</text>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		role
	} from "@/api/role.js";
	import http from '@/http/api.js';
	import {
		oss,
		imgPath,
		devUrl,
		prodUrl
	} from '@/common/setting';

	export default {
		components: {},
		data() {
			return {
				title: '巡检保养计划',
				desc: '',
				styles: {
					color: '#333',
					borderColor: '#e5e5e5',
					disableColor: '#FFFFFF'
				},
				baseURL: '',
				baseOSS: '',
				videoImg: '/static/images/video.png',
				formData: {
					planTitle:'',
					planDesc:'',
					planScheduledType: 1,
					timeType: 1,
					inspectionCompleteTime:'',
					// inspectionStartTime:'',
					// inspectionEndTime:'',
				},
				rules: {
					planTitle: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}]
					},
					planDesc: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}, ]
					},
					planScheduledType: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}, ]
					},
					timeType: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}, ]
					},
					inspectionCompleteTime: {
						rules: [{
							required: true,
							errorMessage: '选择巡检截止时间',
						}, ]
					},
					// inspectionStartTime: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '必填项',
					// 	}, ]
					// },
					// inspectionEndTime: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '必填项',
					// 	}, ]
					// },
				},
				uuid: '',
				planScheduledTypeItems: {
					items: [{
						'value': 1,
						'text': '仅一次'
					}, {
						'value': 2,
						'text': '定期'
					}],
					current: 1,
				},
				timeTypeItems: {
					items: [{
						'value': 1,
						'text': '按天'
					}, {
						'value': 2,
						'text': '按周'
					}, {
						'value': 3,
						'text': '按月'
					}],
					current: 1,
				},
			}
		},
		computed: {

		},
		onLoad(options) {
			this.baseURL = process.env.NODE_ENV === 'development' ? devUrl : prodUrl;
			this.baseOSS = oss;
			this.uuid = this.getUuid();
		},
		onReady() {
			//console.log("onReady++++++++++++++")
			// 需要在onReady中设置规则
			 this.$refs.baseForm.setRules(this.rules)
		},
		onShow() {
			let that = this;
			this.uuid = this.getUuid();
			// uni.$once("lngLat", function(data) {
			// 	let p = JSON.parse(data)
			// 	that.formData.longitude = p.lng;
			// 	that.formData.latitude = p.lat;
			// 	that.formData.address = p.add;
			// })
			// uni.$once("taskOwnerInfo", function(data) {
			// 	let p = JSON.parse(data)
			// 	that.formData.taskOwnerId = p.taskOwnerId;
			// 	that.formData.taskOwnerName = p.taskOwnerName;
			// })
		},
		methods: {
			toOss(path) {
				return this.baseOSS + path;
			},
			toBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			getUuid() {
				return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
					var r = (Math.random() * 16) | 0,
						v = c == 'x' ? r : (r & 0x3) | 0x8;
					return v.toString(16);
				});
			},
			completeDateTimeChange(e) {
				console.log('change事件:', e);
			},
			onTaskOwnerSelectClick() {
				var url = '/pages/serviceperson/taskOwnerSelect';
				uni.navigateTo({
					url: url
				})
			},
			onMapAddClick() {
				var url = '/pages/map/maplocation';
				uni.navigateTo({
					url: url
				})
			},
			onCheckPhotoAdd() {
				let that = this;
				uni.chooseImage({
					sourceType: ['album ', 'camera'],
					sizeType: ['compressed'],
					success: (res) => {
						const len = res.tempFilePaths.length;
						if (len === 1) {
							res.tempFilePaths.forEach(path => {
								that.uploadPhoto(path);
							})
						} else {
							uni.showModal({
								content: '只能选择一张图片，请确认！',
								showCancel: false
							});
						}
					}
				})
			},
			uploadPhoto(imagePath) {
				let that = this;
				uni.showLoading({
					title: '上传中'
				});
				uni.uploadFile({
					url: this.baseURL + '/galaxy-resource/oss/endpoint/put-file-attach?Blade-Auth=' +
						uni.getStorageSync('accessToken'),
					fileType: 'image',
					filePath: imagePath,
					name: 'file',
					success: (uploadFileRes) => {
						if (uploadFileRes.statusCode == 200) {
							let data = JSON.parse(uploadFileRes.data);
							if (data.success) {
								let path = data.data['name'];
								that.orderPhotos.push(path);
							}
						}
					},
					fail: (err) => {
						console.log(err);
						reject('err')
					},
					complete() {
						uni.hideLoading()
					}
				});
			},
			onPhotoDel(index) {
				this.orderPhotos.splice(index, 1);
			},
			onCheckVideoAdd() {
				let that = this;
				uni.chooseVideo({
					sourceType: ['camera'],
					maxDuration: 10,
					success: (res) => {
						that.uploadVideo(res.tempFilePath);
					}
				})
			},
			uploadVideo(videoPath) {
				let that = this;
				uni.showLoading({
					title: '上传中'
				});
				uni.uploadFile({
					url: this.baseURL + '/galaxy-resource/oss/endpoint/put-file-attach?Blade-Auth=' +
						uni.getStorageSync('accessToken'),
					filePath: videoPath,
					name: 'file',
					success: (uploadFileRes) => {
						if (uploadFileRes.statusCode == 200) {
							let data = JSON.parse(uploadFileRes.data);
							if (data.success) {
								let path = data.data['name'];
								that.orderVideos.push(path);
							}
						}
					},
					fail: (err) => {
						console.log(err);
						reject('err')
					},
					complete() {
						uni.hideLoading()
					}
				});
			},
			onVideoDel(index) {
				this.orderVideos.splice(index, 1);
			},
			openVideo(item) {
				let url = '/pages/check-order/videoView?url=' + item;
				uni.navigateTo({
					url: url
				})
			},
			toSubmit() {
				let that = this;
				this.$refs.baseForm.validate().then(res => {
					that.submitData();
					//console.log('提交');
				}).catch(err => {
					console.log('表单错误信息：', JSON.stringify(err));
					uni.showModal({
						content: "录入错误，请检查录入内容!",
						showCancel: false,
						success(res) {
							if (res.confirm) {
								//that.$refs.baseForm.clearValidate();
							}
						}
					});
				})
			},
			submitData() {
				let formdata = this.formData;
				formdata['batchId'] = this.uuid;
				// if (this.orderPhotos.length > 0) {
				// 	let photos = '';
				// 	for (let i = 0; i < this.orderPhotos.length; i++) {
				// 		if (photos.length > 0) {
				// 			photos = photos + ',';
				// 		}
				// 		photos = photos + this.orderPhotos[i];
				// 	}
				// 	formdata['orderPhotos'] = photos;
				// }
				// if (this.orderVideos.length > 0) {
				// 	let videos = '';
				// 	for (let i = 0; i < this.orderVideos.length; i++) {
				// 		if (videos.length > 0) {
				// 			videos = videos + ',';
				// 		}
				// 		videos = videos + this.orderVideos[i];
				// 	}
				// 	formdata['orderVideos'] = videos;
				// }
				let that = this;
				http.request({
					url: '/galaxy-business/equipment/inspection/plan/save',
					method: 'POST',
					data: formdata
				}).then(res => {
					if (res.success) {
						uni.showModal({
							content: '已成功提交',
							showCancel: false,
							success(res) {
								that.toBack();
							}
						});
					} else {
						uni.showModal({
							content: '' + res.msg,
							showCancel: false
						});
					}
				}).catch(err => {
					console.log(err)
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		padding: 0 0 100rpx;
	}



	.view-flex-cc {
		display: flex;
		flex-direction: column;
		justify-content: center;
	}
</style>