<template>
	<view class="container">
		<uni-nav-bar dark :fixed="true" backgroundColor="#3F9EFF" statusBar="false" left-icon="left" left-text="返回"
			@clickLeft="toBack">
			<view class="nav-title">
				<text>{{title}}</text>
			</view>
		</uni-nav-bar>
		<uni-forms ref="baseForm" :model="formData">
			<uni-card title="危险区" :is-shadow="false">
				<uni-forms-item name='dangerAreaPid' label="危险区编码" label-width="100px" required>
					<uni-row>
						<uni-col :span="24">
							<view v-if="formData.dangerAreaPid == ''"
								style="border-radius: 5px;border-width: 1px;border-color: lightgray;border-style: solid;height: 32px;width: 100%;"
								@click="toDangerAreaSelect">
								<view
									style="color: gray;font-size: 0.6rem;padding-left: 8px;height: 32px;display: flex;flex-direction: column;justify-content: center;">
									点击选择危险区</view>
							</view>
							<view v-else
								style="border-radius: 5px;border-width: 1px;border-color: lightgray;border-style: solid;height: 32px;width: 100%;"
								@click="toDangerAreaSelect">

								<view
									style="font-size: 0.7rem;color: dimgray;padding-left: 8px;height: 32px;display: flex;flex-direction: column;justify-content: center;">
									{{formData.dangerAreaName}}
								</view>
							</view>
							<!-- <uni-easyinput v-model="formData.dangerAreaPid" placeholder="请录入危险区编码" /> -->
						</uni-col>
						<!-- 			<uni-col :span="7" class="view-flex-inline-end">
							<image class="scan-icon" mode="widthFix" src="/static/images/scan.png"
								@click="onQrCodeClick">
							</image>
						</uni-col> -->
					</uni-row>
				</uni-forms-item>
			</uni-card>
			<uni-card title="住址定位信息" :is-shadow="false">
				<uni-forms-item name='longitude' label="经度" label-width="100px">
					<uni-easyinput v-model="formData.longitude" placeholder="请录入经度" />
				</uni-forms-item>
				<uni-forms-item name='latitude' label="纬度" label-width="100px">
					<uni-easyinput v-model="formData.latitude" placeholder="请录入纬度" />
				</uni-forms-item>
				<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-card title="群众家庭信息" :is-shadow="false">
				<uni-forms-item name='personName' label="户主姓名" label-width="100px" required>
					<uni-easyinput v-model="formData.personName" placeholder="请录入户主姓名" />
				</uni-forms-item>
				<uni-forms-item name='personId' label="手机号" label-width="100px" required>
					<uni-easyinput v-model="formData.personId" placeholder="请录入手机号" />
				</uni-forms-item>
			</uni-card>
			<uni-card title="家庭成员" :is-shadow="false">
				<uni-card v-for="(item, index) in familyMembersList" :key="index">
					<template v-slot:title>
						<view style="border-width: 0px 0px 1px 0px;border-color: lightgrey;border-style: solid">
							<uni-row>
								<uni-col :span="12">
									<view style="margin-top: 8px;font-size: 1rem;">{{index+1}}</view>
								</uni-col>
								<uni-col :span="12">
									<view style="display: flex;flex-direction: row;justify-content: flex-end;">
										<button class="button" size="mini"
											style="margin-left: 0px;margin-right: 0px;margin-top: 4px;margin-bottom: 3px;"
											type="default" @click="delFamilyMembers(index)">删除</button>
									</view>
								</uni-col>
							</uni-row>
						</view>
					</template>
					<uni-forms-item label="姓名" label-width="100px">
						<uni-easyinput v-model="formData.familyMembersFormData[item.personName]"
							placeholder="请录入户主姓名" />
					</uni-forms-item>
					<uni-forms-item label="手机号" label-width="100px">
						<uni-easyinput v-model="formData.familyMembersFormData[item.personId]" placeholder="请录入手机号" />
					</uni-forms-item>
				</uni-card>
				<view class="item-button-group">
					<view class="item-button" @click="onResidentAddClick()">
						<view class="items-line">
							<uni-icons class="input-uni-icon" type="plusempty" 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-rc">
					<view class="block"
						style="width: 120px;height:28px;margin-left: 10px;margin-right: 10px;border-radius:7px;background-color:lightpink"
						@click="toSubmit()">
						<view class="view-flex-cc">
							<uni-icons class="input-uni-icon" type="checkmarkempty" size="18" color="#999" />
						</view>
						<view class="view-flex-cc" style="padding-left:5px;">
							<text style="color:black;font-size:0.7rem">立即提交</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 		<uni-popup ref="popup">
			<view style="width: 100%;height: 400px;background-color: white;">
				<view class="view-flex-inline" style="width: 100%;height: 40px;background-color: #3F9EFF;">
					<text class="text" style="margin-left: 5px;font-size: 1rem;color:white">添加成员</text>
				</view>
				<uni-group>
					<uni-forms ref="familyMembersForm" :model="familyMembersFormData">
						<uni-forms-item name='personName' label="姓名" label-width="90px" required>
							<uni-easyinput @input="nameinput" placeholder="请录入姓名" />
						</uni-forms-item>
						<uni-forms-item name='personId' label="身份证号" label-width="90px" required>
							<uni-easyinput @input="idinput" placeholder="请录入身份证号" />
						</uni-forms-item>
					</uni-forms>
				</uni-group>
				<view class="item-button-group" style="padding-right: 10px;">
					<view class="item-button" @click="onResidentEditCloseClick()">
						<view class="items-line">
							<uni-icons class="input-uni-icon" type="closeempty" size="18" color="coral" />
							<text class="button-text">取消</text>
						</view>
					</view>
					<view class="item-button" @click="onResidentEditSubmitClick()">
						<view class="items-line">
							<uni-icons class="input-uni-icon" type="checkmarkempty" size="18" color="coral" />
							<text class="button-text">确定</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup> -->
	</view>
</template>

<script>
	import {
		role
	} from "@/api/role.js";
	import http from '@/http/api.js';
	import {
		devUrl,
		prodUrl
	} from '@/common/setting';
	export default {
		data() {
			return {
				title: '危险区群众登记',
				baseURL: '',
				warnId: '',
				formData: {
					latitude: '',
					longitude: '',
					address: '',
					personName: '',
					personId: '',
					dangerAreaPid: '',
					dangerAreaName: '',
					isHouseholder: 1,
					familyMembersFormData: {
						personName_1: '',
						personId_1: '',
					}
				},
				familyMembersFormData: {
					personName: '',
					personId: '',
				},
				rules: {
					personName: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}]
					},
					personId: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}, ]
					},
					dangerAreaPid: {
						rules: [{
							required: true,
							errorMessage: '必填项',
						}, ]
					},
				},
				keepPhotos: [],
				familyMembersList: [{

					personName: 'personName_1',
					personId: 'personId_1',
				}],
				checkItems: {
					items: [{
						'value': 0,
						'text': '否'
					}, {
						'value': 1,
						'text': '是'
					}],
					current: 0,
				},
				drawerWidth: 300,
				membersIndex: 1,
			}
		},
		onLoad(option) {
			let that = this;
			this.baseURL = process.env.NODE_ENV === 'development' ? devUrl : prodUrl;
			this.drawerWidth = uni.getWindowInfo().windowWidth - 100;
			uni.getLocation({
				type: 'wgs84',
				success: function(res) {
					that.formData.latitude = res.latitude;
					that.formData.longitude = res.longitude;
					that.getAddress(res.longitude, res.latitude);
				}
			});
		},
		computed: {

		},
		onShow() {
			let that = this;
			uni.$once("dangerAreaId", function(data) {
				//console.log("dangerAreaId "+data)
				let p = JSON.parse(data)
				that.formData.dangerAreaPid = p.dangerAreaId;
				that.formData.dangerAreaName = p.dangerAreaName;
			})
			
			uni.$once("lngLat", function(data) {
				//console.log("dangerAreaId "+data)
				let p = JSON.parse(data)
				that.formData.longitude = p.lng;
				that.formData.latitude = p.lat;
				that.formData.address = p.add;
			})
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.baseForm.setRules(this.rules)
		},
		methods: {
			//返回上一页
			toBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			onBackPress() {
				// #ifdef APP-PLUS
				plus.key.hideSoftKeybord();
				// #endif
			},
			getAddress(lng, lat) {
				let that = this;
				let url = 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + lat + ',' + lng +
					'&key=4HYBZ-EB23D-SLC42-HQ5R3-LP3LQ-OZFU5';
			//	console.log(url);
				http.request({
					url: url,
					method: 'GET',
				}).then(res => {
					//console.log(JSON.stringify(res));
				}).catch(err => {
					//console.log(JSON.stringify(err))
					that.formData.address = err.data.result.address;
				})
			},
			onMapAddClick(){
				var url = '/pages/yjxt/resident/dangerarearesidentlocation?type=1';
				uni.navigateTo({
					url: url
				})
			},
			onResidentAddClick() {
				//let index = this.familyMembersList.length + 1;
				this.membersIndex += 1;
				this.familyMembersList.push({
					personId: 'personId_' + this.membersIndex,
					personName: 'personName_' + this.membersIndex,
				})
				//this.familyMembersFormData.personId = '';
				//this.familyMembersFormData.personName = '';
				// this.$refs['showRight'].open();
				//this.$refs.popup.open('bottom')
			},
			delFamilyMembers(index) {
				//let index = this.dynamicLists.findIndex(v => v.id === id)
				this.formData.familyMembersFormData['' + this.familyMembersList[index].personId] = '';
				this.formData.familyMembersFormData['' + this.familyMembersList[index].personName] = '';
				this.familyMembersList.splice(index, 1)
			},
			onResidentEditCloseClick() {
				this.$refs.popup.close();
			},
			nameinput(e) {
				//console.log('输入内容：', e);
				this.familyMembersFormData.personName = e;
			},
			idinput(e) {
				//console.log('输入内容：', e);
				this.familyMembersFormData.personId = e;
			},
			toDangerAreaSelect() {
				var url = '/pages/yjxt/region/region';
				uni.navigateTo({
					url: url
				})
			},
			onResidentEditSubmitClick() {
				// this.$refs['showRight'].close();
				this.$refs.popup.close();
				if (this.familyMembersFormData.personId.length > 0 && this.familyMembersFormData.personName.length > 0) {
					let familyMember = {};
					familyMember['personId'] = this.familyMembersFormData.personId;
					familyMember['personName'] = this.familyMembersFormData.personName;
					this.familyMembersList.push(familyMember);
				} else {
					uni.showModal({
						content: "录入错误",
						showCancel: false
					});
				}
			},
			onCheckPhotoAdd() {
				let that = this;
				uni.chooseImage({
					sourceType: ['camera'],
					sizeType: ['compressed'],
					success: (res) => {
						const len = res.tempFilePaths.length;
						if (len === 1) {
							res.tempFilePaths.forEach(path => {
								that.uploadCheckPhoto(path);
							})
						} else {
							uni.showModal({
								content: '只能选择一张图片，请确认！',
								showCancel: false
							});
						}
					}
				})
			},
			uploadCheckPhoto(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.keepPhotos.push(path);
							}
						}
					},
					fail: (err) => {
						console.log(err);
						reject('err')
					},
					complete() {
						uni.hideLoading()
					}
				});
			},
			onCheckPhotoDel(index) {
				this.keepPhotos.splice(index, 1);
			},
			onQrCodeClick() {
				let that = this;
				uni.scanCode({
					scanType: ['qrCode'],
					success: function(res) {
						console.log('条码类型：' + res.scanType);
						console.log('条码内容：' + res.result);
						that.formData.dangerAreaPid = res.result;
					}
				});
			},
			toSubmit() {
				let that = this;
				this.$refs.baseForm.validate().then(res => {
					console.log('表单数据信息1：', res);
					that.submit();
				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showModal({
						content: "内容录入错误，请根据提示信息检查录入内容!",
						showCancel: false,
						success(res) {
							if (res.confirm) {
								//that.$refs.baseForm.clearValidate();
							}
						}
					});
				})
			},
			submit() {
				let familyMembers = [];
				for (let i = 0; i < this.familyMembersList.length; i++) {
					let personId = this.formData.familyMembersFormData['' + this.familyMembersList[i].personId];
					let personName = this.formData.familyMembersFormData['' + this.familyMembersList[i].personName];
					if (personId != undefined && personId != null && personId != '') {
						if (personName != undefined && personName != null && personName != '') {
							let f = {};
							f['personId'] = personId;
							f['personName'] = personName;
							familyMembers.push(f)
						}
					}
				}
				let formdata = this.formData;
				formdata.familyMembersFormData = {};
				formdata['familyMembers'] = familyMembers;
				console.log('toSubmit事件:', JSON.stringify(formdata));
				let that = this;
				http.request({
					url: '/galaxy-business/yj/resident/record',
					method: 'POST',
					data: formdata
				}).then(res => {
					//console.log('res ', JSON.stringify(res));
					if (res.success) {
						if (res.code == 200) {
							//that.clearCache();
							uni.showModal({
								content: '填报信息已成功提交',
								showCancel: false,
								success(res) {
									if (res.confirm) {
										that.toBack();
									}
								}
							});
						} else {
							uni.showModal({
								content: '提交失败',
								showCancel: false
							});
						}
					} else {

						uni.showModal({
							content: '提交失败',
							showCancel: false
						});
					}
				}).catch(err => {
					uni.showModal({
						content: '' + err.data.msg,
						showCancel: false
					});
				})
			},
		}
	}
</script>

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

	.scan-icon {
		/* #ifndef APP-NVUE */
		display: block;
		/* #endif */
		// margin-right: 10px;
		width: 30px;
		height: 30px;
	}

	.close {
		padding: 10px;
	}
</style>