<!--
 * @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-group>
				</uni-forms-item>
				<view class="view-flex-inline">
					<text style="color: black;font-size: 1rem;margin-bottom: 10px;">工单描述</text>
				</view>
				<uni-forms-item name='orderDesc' label-width="0px" required>
					<uni-easyinput :styles="styles" type="textarea" :autoHeight="true" v-model="formData.orderDesc"
						placeholder="录入工单描述内容" />
				</uni-forms-item>
			</uni-group>
			<uni-card title="拍摄照片" extra="点击下方按钮开始拍摄" :is-shadow="false">
				<view class="view-flex-rs-flex-wrap">
					<view v-for="(item, index) in orderPhotos" :key="index" class="view-flex-cc" style="width: 80px;">
						<view class="img-container">
							<view class="note-image-box">
								<view class="note-image-item">
									<view class="close-icon" @click="onPhotoDel(index)">
										<uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
									</view>
									<view class="image-box">
										<image :src="toOss(item)" mode="widthFix">
										</image>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="view-flex-cc" style="width: 80px;">
						<view class="img-container">
							<view class="note-image-box">
								<view class="note-image-item" @click="onCheckPhotoAdd()">
									<view class="image-box">
										<uni-icons type="plusempty" size="50" color="#eee"></uni-icons>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-card>
			<uni-card title="拍摄视频" extra="点击下方按钮开始拍摄" :is-shadow="false">
				<view class="view-flex-rs-flex-wrap">
					<view v-for="(item, index) in orderVideos" :key="index" class="view-flex-cc" style="width: 80px;">
						<view class="img-container">
							<view class="note-image-box">
								<view class="note-image-item">
									<view class="close-icon" @click="onVideoDel(index)">
										<uni-icons type="closeempty" size="18" color="#fff"></uni-icons>
									</view>
									<view class="image-box">
										<image :src="videoImg" mode="widthFix" @click="openVideo(item)">
										</image>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="view-flex-cc" style="width: 80px;">
						<view class="img-container">
							<view class="note-image-box">
								<view class="note-image-item" @click="onCheckVideoAdd()">
									<view class="image-box">
										<uni-icons type="plusempty" size="50" color="#eee"></uni-icons>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</uni-card>
			<uni-card title="指定人员" :is-shadow="false"> 
				 <view class="view-flex-inline" style="height: 40px;">
				 	<text v-if="formData.taskOwnerName"
				 		style="color: gray;font-size: 0.8rem;padding-left: 0px">已选择人员:【{{formData.taskOwnerName}}】</text>
				 	
				 </view>
			      <view class="item-button-group">
			      	<view class="item-button mid-size" @click="onTaskOwnerSelectClick()">
			      		<view class="items-line">
			      			<uni-icons class="input-uni-icon" type="map-pin-ellipse" size="18" color="coral" />
			      			<text class="button-text">选择</text>
			      		</view>
			      	</view>
			      </view>
			</uni-card>
			<uni-card title="时限设定" :is-shadow="false">
				<uni-forms-item name='completeDateTime' label="完成时限" label-width="100px">
					<uni-datetime-picker type="date" v-model="formData.orderCompleteTime" @change="completeDateTimeChange" />
				</uni-forms-item>
			</uni-card>
			<uni-card title="地图位置添加" :is-shadow="false">
				<view class="view-flex-inline" style="height: 40px;">
					<text v-if="formData.longitude"
						style="color: gray;font-size: 0.8rem;padding-left: 0px">经度:【{{formData.longitude}}】</text>
					<text v-if="formData.longitude"
						style="color: gray;font-size: 0.8rem;padding-left: 5px">纬度:【{{formData.latitude}}】</text>
				</view>
				<uni-forms-item name='address' label="地址" label-width="100px">
					<uni-easyinput v-model="formData.address" placeholder="请录入地址" />
				</uni-forms-item>
				<view class="item-button-group">
					<view class="item-button mid-size" @click="onMapAddClick()">
						<view class="items-line">
							<uni-icons class="input-uni-icon" type="map-pin-ellipse" size="18" color="coral" />
							<text class="button-text">定位</text>
						</view>
					</view>
				</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: {
					orderType: 0,
					orderDesc: '',
					longitude: '',
					latitude: '',
					address: '',
					orderCompleteTime: '',
					taskOwnerId:'',
					taskOwnerName:''
				},
				rules: {
					orderTypeOption: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}]
					},
					orderDesc: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}, ]
					},
				},
				orderPhotos: [],
				orderVideos: [],
				uuid: '',
			}
		},
		computed: {
			videoImage() {
				return imgPath + "logo_pc.png";
			}
		},
		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();
				}).catch(err => {
					//console.log('表单错误信息：', 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/order/xjgd/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>