<template>
	<view class="form-root">
		<uni-notice-bar v-if="networkType==='none'" text="当前无法连接网络,上报后的数据将存储在临时数据管理中" />

		<view class="form-group">
			<view class="uni-form-item form-item uni-column">
				<view class="form-control border-btm">
					<text class="form-label">当前经度</text>
					<view class="form-input">
						<input v-if="!locationLoading" class="uni-input" name="jd" :disabled="true" :value="jd" />
						<input v-if="locationLoading" class="uni-input" value="位置获取中..."></input>
					</view>
				</view>
			</view>
			<view class="uni-form-item form-item uni-column">
				<view class="form-control">
					<text class="form-label">当前纬度</text>
					<view class="form-input">
						<input v-if="!locationLoading" class="uni-input" name="wd" :disabled="true" :value="wd" />
						<input v-if="locationLoading" class="uni-input" value="位置获取中..."></input>
					</view>
				</view>
			</view>
		</view>
		<view class="form-group">
			<view class="uni-form-item form-item uni-column" style="padding: 12px 24px;">
				<view style="margin-bottom: 10px;">
					<text class="form-label">上传图片
						<text v-if="uploading" style="margin-left: 8px;color: aquamarine;">上传中...</text>
					</text>
				</view>
				<view class="form-input imgs">
					<view v-for="(img,index) in imgs" style="position: relative;" @click="preview(index)">
						<image :src="img" class="upload-img"></image>
						<image @click.stop="delImg(index)" src="../../static/remove.png"
							style="position: absolute;width:20px;height:20px;top: -10px;right: 0px;background-color: #fff;">
						</image>
					</view>
					<view class="upload-img" @click="chooseImg">
						<image src="/static/sctp.png" style="width: 48px;height: 48px;"></image>
					</view>
				</view>
			</view>
		</view>
		<view class="form-group">
			<view class="uni-form-item form-item uni-column" style="padding: 12px 24px;">
				<view class="form-input">
					<textarea name="nr" v-model="reason" placeholder="请输入上报内容(非必填)"></textarea>
				</view>
			</view>
		</view>
		<button v-if="!!submitText" class="submit" @click="submit" :loading="submiting">{{submitText}}</button>
	</view>
</template>

<script>
	import helper from '../../common/helper';
	import {
		pathToBase64
	} from '../../js_sdk/mmmm-image-tools'
	export default {
		data() {
			return {
				imgs: [],
				jd: null,
				wd: null,
				reason: '',
				uploading: false,
				imgStrs: [],
				submiting: false,
				token: '',
				id: null,
				submitText: '',
				imgPaths: [],
				locationLoading: false,
				networkType: ''
			}
		},
		onLoad(e) {
			if (e.id) {
				this.submitText = '保存'
			} else {
				this.submitText = '上报'
			}
			this.token = helper.tempToken;
			uni.getNetworkType({
				success: (res) => {
					console.log(res.networkType);
					this.networkType = res.networkType;
					if (!e.id) {
						this.locationLoading = true
						if (res.networkType !== 'none') {
							uni.getLocation({
								type: 'gcj02',
								success: (res) => {
									this.jd = res.longitude;
									this.wd = res.latitude;
									this.locationLoading = false
								},
								fail: (error) => {
									this.locationLoading = false
									uni.showModal({
										content: JSON.stringify(error),
										title: '定位失败'
									})
								}
							});
						} else {
							plus.geolocation.getCurrentPosition((res) => {
								this.jd = res.coords.longitude;
								this.wd = res.coords.latitude;
								this.locationLoading = false
							}, (error) => {
								this.locationLoading = false
								uni.showModal({
									content: JSON.stringify(error),
									title: '定位失败'
								})
							});
						}
					} else {
						this.id = e.id
						this.requestItem(e.id);
					}


				}
			});
		},
		methods: {
			delImg(index) {
				this.imgStrs.splice(index, 1);
				this.imgPaths.splice(index, 1);
				this.imgs.splice(index, 1);
			},
			preview(index) {
				uni.previewImage({
					urls: this.imgStrs,
					current: index
				})
			},
			requestItem(id) {
				uni.request({
					url: `${helper.serverUrl}/ffzy/ffzy/${id}`,
					header: {
						Authorization: `Bearer ${this.token}`
					},
					success: (resp) => {
						console.log(resp)
						if (resp.data.data) {
							const item = resp.data.data;
							const str = item.geom?.replace('POINT (', '').replace(')', '');
							console.log(str)
							const strs = str.split(' ');
							this.jd = parseFloat(strs[0]);
							this.wd = parseFloat(strs[1]);
							this.reason = item.reason;
							this.imgStrs = item.img?.split(',');
							this.imgs = item.img?.split(',');
						}
					},
				})
			},
			submit() {
				if (!this.jd || !this.wd) {
					uni.showToast({
						icon: 'error',
						title: '未获取到当前位置'
					})
					return;
				}
				if (this.imgStrs?.length <= 0 && this.imgs?.length <= 0) {
					uni.showToast({
						icon: 'error',
						title: '请上传现场照片'
					})
					return;
				}
				if (this.id) {
					uni.request({
						url: `${helper.serverUrl}/ffzy/ffzy`,
						method: 'PUT',
						data: {
							id: this.id,
							geom: `POINT(${this.jd} ${this.wd})`,
							img: this.imgStrs.join(','),
							reason: this.reason
						},
						header: {
							Authorization: `Bearer ${this.token}`
						},
						success: (resp) => {
							if (resp.data.code === 200) {
								uni.showToast({
									mask: true,
									icon: 'success',
									title: '保存成功'
								});
								setTimeout(() => {
									uni.navigateBack()
								}, 1500)
							}
							console.log(resp)
						},
						fail: () => {
							console.log(resp)
						},
						complete: () => {
							this.submiting = false;
						}
					})

				} else {
					// const data =
					if (this.networkType !== 'none') {
						this.submiting = true;
						uni.request({
							url: `${helper.serverUrl}/ffzy/ffzy`,
							method: 'POST',
							data: {
								geom: `POINT(${this.jd} ${this.wd})`,
								img: this.imgStrs.join(','),
								reason: this.reason
							},
							header: {
								Authorization: `Bearer ${this.token}`
							},
							success: (resp) => {
								if (resp.data.code === 200) {
									uni.showToast({
										mask: true,
										icon: 'success',
										title: '上报成功'
									});
									setTimeout(() => {
										uni.navigateBack()
									}, 1500)
								}
								console.log(resp)
							},
							fail: () => {
								console.log(resp)
								uni.showToast({
									title: '上报失败'
								})
							},
							complete: () => {
								this.submiting = false;
							}
						})
					} else {
						const date = new Date();
						this.saveTemp({
							geom: `POINT(${this.jd} ${this.wd})`,
							imgPaths: this.imgPaths,
							reason: this.reason,
							saveTime: `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
						});
					}
				}
			},
			_saveFile(index, imgPaths, callback, resultPaths) {
				if (!resultPaths) {
					resultPaths = [];
				}
				if (imgPaths[index]) {
					uni.saveFile({
						tempFilePath: imgPaths[index],
						success: (res) => {
							resultPaths.push(res.savedFilePath);
							this._saveFile(++index, imgPaths, callback, resultPaths);
						},
						fail: () => {
							this._saveFile(++index, imgPaths, callback, resultPaths);
						}
					})
				} else {
					callback(resultPaths);
				}
			},
			saveTemp(data) {
				this._saveFile(0, data.imgPaths, (paths) => {
					data.imgPaths = paths;
					uni.getStorage({
						key: 'sbsjTemp',
						success: (resp) => {
							console.log(resp);
							uni.setStorage({
								key: 'sbsjTemp',
								data: [...resp.data || [], data],
								success: () => {
									uni.showToast({
										title: '已保存到临时数据管理'
									})
									setTimeout(() => {
										uni.navigateBack();
									}, 1500)
								}
							})
						},
						fail: () => {
							uni.setStorage({
								key: 'sbsjTemp',
								data: [data],
								success: () => {
									uni.showToast({
										title: '已保存到临时数据管理'
									})
									setTimeout(() => {
										uni.navigateBack();
									}, 1500)
								}
							})
						}
					})

				})
			},
			chooseImg() {
				uni.chooseImage({
					count: 1,
					success: ({
						tempFilePaths,
						tempFiles
					}) => {
						console.log(tempFilePaths, tempFiles)
						const strs = [];
						tempFilePaths.forEach(path => {
							pathToBase64(path).then(r => {
								this.imgs = this.imgs.concat(r);
							}).catch(err => {
								console.log(err)
							});
						})
						const file = tempFiles?.[0];
						const filePath = tempFilePaths?.[0];
						if (filePath) {
							// const formData = new FormData();
							// formData.append('file', file);
							this.imgPaths.push(filePath);

							if (this.networkType !== 'none') {
								this.uploading = true
								uni.uploadFile({
									url: `${helper.serverUrl}/system/oss/upload`,
									method: 'POST',
									header: {
										Authorization: `Bearer ${this.token}`
									},
									files: tempFilePaths.map(path => {
										return {
											uri: path
										}
									}),
									// name: 'file',
									success: (resp) => {
										console.log(resp.data)
										let data = resp.data;
										if (typeof(resp.data) === 'string') {
											data = JSON.parse(resp.data);
										}
										console.log(data.data.url)
										this.imgStrs = [...this.imgStrs, data.data
											.url
										]
									},
									fail(resp) {
										console.log(resp)
									},
									complete: () => {
										console.log(111)
										this.uploading = false
									}
								})

							}
						}
					},
					fail() {

					}
				})
			}
		}
	}
</script>

<style>
	.imgs {
		display: flex;
		align-items: center;
		flex-wrap: wrap;
	}

	.submit {
		height: 64px;
		background: linear-gradient(-90deg, #01C4B4, #01DC7F);
		border-radius: 47px;
		font-weight: 400;
		font-size: 30px;
		color: #FFFFFF;
		margin-top: 36px;
		line-height: 64px;
	}

	.upload-img {
		width: 100px;
		height: 100px;
		background: #F5F6F8;
		display: flex;
		align-items: center;
		justify-content: center;
		/* margin: 12px 0; */
		margin-right: 8px;
		margin-bottom: 8px;
	}

	.form-label {
		padding-right: 16px;
	}

	.form-item {
		padding: 0px 24px;
	}

	.border-btm {
		border-bottom: 1px solid #d9d9d985;
	}

	.form-root {
		padding: 16px;
	}

	.form-control {
		display: flex;
		align-items: center;
		flex: 1;
		padding: 12px 0px;
	}

	.form-group {
		background: #FFFFFF;
		border-radius: 12px;
		margin-bottom: 16px;
	}
</style>