<template>
	<view class="nocheckBox">
		<navigation-bar :isBack="true" @toBack="toBackHandle"></navigation-bar>
		<view class="container">
			<view class="warningBox">
				<text class="title">基本信息</text>
				<view class="content">
					<view class="item">
						<text class="title">地块编号</text>
						<text class="val">{{ objs.dkbh || '' }}</text>
					</view>
					<view class="item">
						<text class="title">面积(亩)</text>
						<text class="val">{{ objs.mj || ''}}</text>
					</view>
					<view class="item">
						<text class="title">地块位置</text>
						<text class="val">{{ objs.dkwz || ''}}</text>
					</view>
					<view class="item">
						<text class="title">地块现状</text>
						<text class="val">{{ objs.dkxz || '' }}</text>
					</view>
					<view class="item">
						<text class="title">管地单位</text>
						<text class="val">{{ objs.gddw || '' }}</text>
					</view>
					<view class="item">
						<text class="title">联系人</text>
						<text class="val">{{ objs.lxr || '' }}</text>
					</view>
					<view class="item itemAuto">
						<text class="title">联系电话</text>
						<text class="val">{{ objs.lxdh || '' }}</text>
					</view>
					<view class="item szfw">
						<text class="title">四至范围</text>
						<text class="val">
							<text>{{ objs.szfw || '' }}</text>
						</text>
					</view>
				</view>
			</view>
			<view class="location" @click="checkLocationInfo"></view>
			<view class="checkResultBox">
				<text class="title">巡查情况</text>
				<view class="content">
					<view class="formGroup">
						<text class="label">现状描述：</text>
						<view class="formInput">
							<textarea name="" id="" cols="30" rows="10" v-model="baseFormData.xzms"
								placeholder="请输入现状描述"></textarea>
						</view>
					</view>
					<view class="formGroup noBetween">
						<text class="label">现场照片：</text>
						<view class="formFile">
							<uni-file-picker @delete="deleteImage" :value="fileImgList" :del-icon="true"
								:imageStyles="imageStyles" auto-upload="false" le-mediatype="image"
								:sourceType="['camera']" @select="selectFileChange">
								<view class="icon_camera">
									<image src="../../static/images/images.png"></image>
								</view>
							</uni-file-picker>
						</view>
					</view>
				</view>
				<button class="btn" @tap="saveWarning">确认上报</button>
				<button style="background: #ff9900;" class="btn" @tap="temporaryXcjl">暂存</button>
			</view>
		</view>
		<view class="dialog_box" v-show="dialogShow">
			<view class="dialog_bg"></view>
			<view class="dialog_container">
				<view class="dialog_header">定位效验</view>
				<view class="dialog_content">
					<view v-for="(item, index) in checkInfos" :key="index">
						<image :src="item['type'] === 1 ? '../../static/images/success_icon.png' : '../../static/images/error_icon.png'"></image>{{item['message']}}
					</view>
				</view>
				<view class="dialog_footer">
					<view class="dialog_btn" @click="dialogConfirm(0)">取消</view>
					<view class="dialog_btn" @click="dialogConfirm(1)">{{isLocationAuthorize ? '确定' : '去授权'}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import navigationBar from '../../components/navigationBar/navigationBar.vue';
	import httpAjax from '@/utils/https.js';
	import CustomMixins from '@/mixins/CustomMixins.js';
	const FormData = require('@/utils/formData/formData.js');

	export default {
		mixins: [CustomMixins],
		components: {
			navigationBar,
		},
		data() {
			return {
				lat: '',
				long: '',
				queryParams: {
					xcryId: '',
					xzms: '',
					xcryName: '',
					xcryMobile: '',
					dksyh: '',
					imgList: [{
						fileId: '',
						lng: '',
						lat: '',
					}, ],
				},
				objs: {},
				fileList: [],
				fileImgList: [],
				imageStyles: {
					width: 64,
					height: 64,
				},
				baseFormData: {
					xzms: ''
				},
				dialogShow: false,
				checkInfos: [],
				isLocationAuthorize: true,	//是否开启定位授权
				isLocation: true,
				bz: ''
			};
		},
		onReady() {
			uni.showTabBar();
		},
		onLoad(option) {
			this.checkAuthorize()
			this.objs = JSON.parse(option['obj']);
			this.queryIsLocation().then((result) => {
				if (result) {
					this.isLocation = result['data']
				}
			})
			if (this.objs && this.objs.dksyh) {
				const tempXcjl = uni.getStorageSync(this.objs.dksyh)
				if (tempXcjl) {
					this.fileList = tempXcjl['fileList']
					this.fileImgList = tempXcjl['fileImgList']
					this.baseFormData = tempXcjl['baseFormData']
				}
			}
		},
		methods: {
			checkAuthorize() {
				this.getLocationEnabled().then((enabled)=>{
					if(enabled){
						this.getWxLocation().then(res => {
							if (res === 0) {
								this.getWxSetting();
							}
						})
					}
				})
			},
			getLocationEnabled(){
				return new Promise((resolve, reject)=>{
					uni.getSystemInfo({
						async success(result) {
							if(!result.locationEnabled){
								uni.showModal({
								  title: '提示',
								  content:
									'小程序需要基于您的手机定位信息为您提供服务，当前检测到您的手机并未打开定位开关，请关闭小程序后前往 "设置 - 定位服务/位置信息" 开启手机定位，然后重新进入小程序~',
								  showCancel: false,
								  confirmText: '我已知悉'
								})
							}
							resolve(result.locationEnabled)
						}
					})
				})
			},
			getWxLocation() {
				return new Promise((resolve, reject) => {
					wx.authorize({
						scope: 'scope.userLocation',
						success: (res) => {
							wx.getLocation({
								success: (res) => {
									resolve(res)
								},
								fail: (err) => {
									resolve(-1)
								},
							});
						},
						fail: (err) => {
							resolve(0)
						},
					});
				})
			},
			getWxSetting() {
				uni.getSetting({
					success: function(res) {
						var statu = res.authSetting;
						if (!statu['scope.userLocation']) {
							uni.showModal({
								title: '提示',
								content: '需要获取您的地理位置，请确认授权，否则拍照功能将无法使用',
								success: function(res) {
									if (res.confirm) {
										uni.openSetting();
									}
								}
							});
						}
					},
				});
			},
			checkLocationInfo(){
				const that = this;
				that.checkInfos = []
				this.getLocationEnabled().then(async (enabled)=>{
					if(!enabled) return;
					that.checkInfos.push({
						type: 1,
						message: '手机定位已开启！'
					})
					const wxResult = await that.getWxLocation();
					if(wxResult === 0){
						that.isLocationAuthorize = false;
						that.checkInfos.push({
							type: 0,
							message: '小程序定位权限获取失败！'
						})
					}else{
						that.isLocationAuthorize = true;
						that.checkInfos.push({
							type: 1,
							message: '小程序定位权限获取成功！'
						})
					}
					that.dialogShow = true;
				})
			},
			dialogConfirm(action){
				this.dialogShow = false;
				if(action && !this.isLocationAuthorize){
					uni.openSetting();
				}
			},
			async getDistance(lat, lng) {
				return await httpAjax({
					url: `api/oss/isWithinBufferRange?lat=${lat}&lng=${lng}&dksyh=${this.objs.dksyh}`,
					method: 'GET'
				})
			},
			async queryIsLocation(lat, lng) {
				return await httpAjax({
					url: 'api/oss/location',
					method: 'GET'
				})
			},
			saveWarning() {
				//上报
				if (this.baseFormData.xzms === '') {
					uni.showToast({
						title: '现状描述不能为空',
						icon: 'none',
						duration: 1500,
					});
					return;
				}
				if (!(this.fileList.length > 0)) {
					uni.showToast({
						title: '现场照片不能为空',
						icon: 'none',
						duration: 1500,
					});
					return;
				}
				this.relationFileById(this.fileList);
			},
			async relationFileById(fileObj) {
				//文件上传
				let _that = this;
				let files = [];
				let laycenterArr = [];
				fileObj.forEach((item) => {
					let obj = {
						fileId: item.fileId,
						lat: item.lat,
						lng: item.lng,
					};
					files.push(obj);
					let obj1 = {
						lat: item.lat,
						lng: item.lng,
					};
					laycenterArr.push(obj1);
				});

				let isSubmit = true;
				if (this.isLocation) {
					for (let i = 0; i < laycenterArr.length; i++) {
						const resultData = await this.getDistance(
							laycenterArr[i].lat,
							laycenterArr[i].lng
						);
						if (!resultData['data']) {
							isSubmit = false;
							break;
						}
					}
				}
				if(!isSubmit){
					uni.showModal({
						title: '提示',
						content: `超出地块拍摄范围`,
						confirmText: '继续',
						success: function(res) {
							if (res.confirm) {
								_that.submitXcjlHandle(files);
							}
						},
					});
				}else{
					_that.submitXcjlHandle(files);
				}
			},
			submitXcjlHandle(files){
				const _that = this;
				this.addXcjlAjax(files).then((result) => {
					if (result && result.data) {
						uni.showModal({
							title: '提示',
							content: '上报成功，是否返回首页',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/main/index',
									});
								} else if (res.cancel) {
									uni.navigateTo({
										url: `/pages/receivedDetail/index?obj=${JSON.stringify(_that.objs)}`,
									});
								}
							},
						});
					}else{
						uni.showModal({
							title: '提示',
							content: '上报异常，请联系管理员'
						});
					}
					if (_that.objs && _that.objs.dksyh) {
						uni.removeStorageSync(_that.objs.dksyh)
					}
				});
			},
			addXcjlAjax(files = []) {
				const sendData = {
					xcryId: uni.getStorageSync('userInfo').id,
					xzms: this.baseFormData.xzms,
					xcryName: uni.getStorageSync('userInfo').xcry,
					xcryMobile: uni.getStorageSync('userInfo').lxdh,
					dksyh: this.objs.dksyh,
					status: 1,
					bz: '',
					imgList: files,
				};
				if(!this.lat || !this.long){
					sendData['status'] = 0
				}
				return new Promise((resolve, reject)=>{
					httpAjax({
						url: 'app/xc/addXcjl',
						method: 'POST',
						data: sendData,
					}).then((result)=>{
						resolve(sendData['status'] === 0 ? null : result);
					}).catch(err=>{
						reject(err)
					})
				})
			},
			temporaryXcjl() {
				if (this.objs && this.objs.dksyh) {
					const obj = {
						fileImgList: this.fileImgList,
						fileList: this.fileList,
						baseFormData: this.baseFormData
					}
					uni.setStorageSync(this.objs.dksyh, obj);
					uni.showToast({
						title: '暂存成功！'
					})
				}
			},
			selectFileChange(file) {
				const that = this;
				const tempFilePath = file.tempFilePaths[0];
				uni.getImageInfo({
					src: tempFilePath,
					success: function(image) {
						const fileName = file['tempFiles'][0]['name'];
						that.fileUploadAjax(tempFilePath);
					},
				});
			},
			async fileUploadAjax(tempFile) {
				const formData = new FormData();
				formData.appendFile('file', tempFile);
				const sendData = formData.getData();
				let header = {
					'content-type': sendData.contentType,
				};
				const result = await httpAjax({
					url: 'api/oss/upload',
					method: 'POST',
					header,
					data: sendData.buffer,
				});
				if(!result || !result['data']) return;
				const fileInfo = result['data'];
				this.setFileImgList(fileInfo['name'], tempFile, fileInfo['path']);
				const res = await this.getWxLocation()
				if (res === 0) {
					this.getWxSetting();
				}else{
					this.lat = res.latitude;
					this.long = res.longitude;
				}
				fileInfo.lat = this.lat;
				fileInfo.lng = this.long;
				fileInfo.fileId = fileInfo.id;
				fileInfo.warningId = this.warningId;
				this.fileList.push(fileInfo);
			},
			setFileImgList(name, url, path2) {
				const extnames = name.match(/\.(jpg|jpeg|png|GIF|JPG|PNG)$/);
				const extname = extnames[0];
				this.fileImgList.push({
					name,
					url,
					path2,
					extname,
				});
			},
			async deleteImage(item) {
				const that = this;
				const result = await httpAjax({
					url: 'api/oss/delete?filePath=' + item['tempFile']['path2'],
					method: 'GET',
				})
				const data = result['data'];
				if (data) {
					for (let i = 0; i < that.fileImgList.length; i++) {
						const imgItem = that.fileImgList[i];
						if (imgItem['path2'] === item['tempFile']['path2']) {
							that.fileImgList.splice(i, 1);
							break;
						}
					}
					for (let i = 0; i < that.fileList.length; i++) {
						const fileItem = that.fileList[i];
						if (fileItem['path'] === item['tempFile']['path2']) {
							that.fileList.splice(i, 1);
							break;
						}
					}
				}
			},
			toBackHandle() {
				uni.navigateBack();
			},
		},
	};
</script>

<style lang="scss">
	@import './index.scss';
</style>