<template>
	<view>
		<view class="fixedheader">
			<headers :showBack="true">
				<view class="headerName">
					{{pageTitle}}
				</view>
			</headers>
		</view>
		<view class="content" :style="{paddingTop: mobileTopHeight + 50 + 'px'}">
			<view class="type flex">
				<view class="name"><text class="star">*</text>巡检点名称：</view>
				<input class="inpuStyle" v-model="form.checkingPointName" placeholder="请输入"></input>
			</view>
			<view class="type flex">
				<view class="name"><text class="star">*</text>巡检点位置：</view>
				<input class="inpuStyle" v-model="form.position" placeholder="请输入"></input>
			</view>
			<view class="type flex">
				<view class="name"><text class="star">*</text>所属区域：</view>
				<picker mode="selector" :range="pointAreaList" range-key="regionName" @change="handleChangeRegion" filterable>
					<view class="picker">
						<view class="" style="color: #c0c4cc; font-size: 28rpx;" v-if="!form.qualityRegionId">
							请选择
						</view>
						<view class="" v-else>
							{{areaData.regionName}}
						</view>
					</view>
				</picker>
			</view>
			<view class="type flex">
				<view class="name"><text class="star">*</text>责任企业：</view>
				<g-picker style="flex: 1" v-model="enterpriseName" :columns="enterpriseList" :filter="{label: 'enterpriseName', value: 'id'}" input-align="left" @confirm="handleChangeEnterprise"></g-picker>
			</view>
			<view class="type flex">
				<view class="name"><text class="star">*</text>责任人：</view>
				<g-picker style="flex: 1" v-model="inspectUserName" :columns="chargerList" :filter="{label: 'realName', value: 'userId'}" input-align="left" @confirm="handleChangeCharger"></g-picker>
			</view>
			<view class="type flex">
				<view class="name large"><text class="star">*</text>最低巡检时长(分钟)：</view>
				<input v-model="form.minInspectTime" type="number" placeholder="请输入" />
			</view>
			<view class="type flex">
				<view class="name">巡检点定位：</view>
				<view v-if="form.addr" class="areaStyle" @click="handleJumpMap">
					{{form.addr}}
				</view>
				<view v-else style="color: #c0c4cc; font-size: 28rpx;" @click="handleJumpMap">
					去获取定位
				</view>
			</view>
			<view class="type flex">
				<view class="name large-2"><text class="star">*</text>自定义范围(米)：</view>
				<picker mode="selector" :range="standOptions" @change="handleChangeStandArea" filterable>
					<view class="picker">
						<view class="" style="color: #c0c4cc; font-size: 28rpx;" v-if="!form.standArea">
							请选择
						</view>
						<view class="" v-else>
							{{form.standArea}}
						</view>
					</view>
				</picker>
			</view>
			<view class="dy_form">
				<view class="dy_head">
					<view class="head_left">
						<image class="ic" src="@/static/icon/form.svg"></image>
						<text class="title">动态表单</text>
					</view>
					<button @click="addFormInput" class="add_btn" size="mini" type="primary" plain="true"><u-icon style="margin-right: 8rpx;" size="16" name="plusempty" color="#007aff"></u-icon>新增项</button>
				</view>
				<view class="dy_content" v-for="(item, index) in dyFormData" :key="index">
					<view class="c_colum">
						<input v-model="item.title" />
						<button @click="delFormInput(index)" class="del_btn" size="mini" type="warn" plain="true">删除<u-icon style="margin-left: 8rpx;" size="16" name="closeempty" color="#e64340"></u-icon></button>
					</view>
					<view class="c_body">
						<input class="c_input" v-model="item.value" :placeholder="`请输入${item.title}`" />
						<radio-group @change="((e) => handleChangeRadio(e.detail.value, item))">
							<radio style="margin-right: 12rpx;" value="1" :checked="item.isRequired == '1'">必填</radio>
							<radio value="2" :checked="item.isRequired == '2'">非必填</radio>
						</radio-group>
					</view>
				</view>
			</view>
		</view>
		<button style="visibility: hidden;">占位用</button>
		<button class="save-btn" type="primary" @click="save">保存</button>
	</view>
</template>

<script>
	import gPicker from "@/components/g-picker/g-picker.vue"
	export default {
		components: {
			gPicker
		},
		data() {
			return {
				editId: "",
				coordType: "gcj02",
				standOptions: [30, 50, 100, 200, 300],
				mobileTopHeight: 0,
				projectSn: '',
				userInfo: {},
				pointAreaList: [],
				areaData: {},
				enterpriseData: {},
				chargerList: [],
				enterpriseList: [],
				pageTitle: "新增巡检点",
				checkEnterpriseName: "",
				enterpriseName: "",
				inspectUserName: "",
				form: {
					checkingPointName: "",
					position: "",
					qualityRegionId: "", // 区域ID
					enterpriseId: "", // 责任企业
					inspectUserIds: "", //检查人
					noticeUserIds: "", //通知人
					startTime: "",
					endTime: "",
					frequencyType: 1,
					frequencyNum: 1,
					minInspectTime: undefined,
					standArea: 100, //范围
					latitude: "", //纬度
					longitude: "", //经度
					addr: "", //地图区域
				},
				dyFormData: [{
					title: "表单标题",
					name: "",
					isRequired: "1",
					value: "",
				}]
			}
		},
		onLoad(option) {
			let that = this;
			uni.$on('locationSuccessEvent',function(data){
				console.log('监听到事件来自 locationSuccessEvent', data);
				const { latitude, longitude, standArea, address } = data;
				that.form.latitude = latitude;
				that.form.longitude = longitude;
				that.form.standArea = standArea;
				that.form.addr = address;
			})
			this.projectSn = JSON.parse(uni.getStorageSync('projectDetail')).projectSn;
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
			
			this.editId = ""
			
			// 编辑
			if(option.id) {
				this.pageTitle = "编辑巡检点"
				this.editId = option.id;
				this.init();
			} else {
				this.getPointAreaFn();
				this.mapGetLocation();
			}
		},
		mounted() {
			var that = this
			uni.getSystemInfo({
				success(res) {
					that.mobileTopHeight = res.statusBarHeight ? res.statusBarHeight : 0;
					uni.setStorageSync('systemInfo',res)
					console.log(res)
				}
			})
			console.log('this.mobileTopHeight',this.mobileTopHeight)
		},
		methods: {
			// 消除异步
			async init() {
				await this.getPointAreaFn();
				await this.getData()
			},
			// 编辑回显
			getData() {
			 	return new Promise((resolve, reject) => {
					console.info("getData", new Date().getTime())
					this.sendRequest({
						url: 'xmgl/checkingPoint/queryById',
						method: 'get',
						data: {
							id: this.editId
						},
						success: (res) => {
							if(res.code === 200) {
								this.form = res.result
								
								// 区域
								const obj = this.pointAreaList.find(item => item.id === this.form.qualityRegionId)
								this.areaData = obj || {}
								
								// 责任企业
								this.enterpriseList = this.areaData.enterpriseInfos || [];
								const eObj = this.enterpriseList.filter(item => this.form.enterpriseId.includes(item.id))
								this.enterpriseName = eObj.map(item => item.enterpriseName).join(',')
								
								// 责任人
								this.chargerList = this.areaData.systemUsers.filter((item) => {
								  return this.form.enterpriseId.includes(item.enterpriseId);
								}) || [];
								this.inspectUserName = this.chargerList.filter(item => this.form.inspectUserIds.includes(item.userId)).map(item => item.realName).join(',')
								
								let tempArr = JSON.parse(this.form.template) || []
								tempArr.forEach(item => item.isRequired = item.isRequired ? "1" : "2")
								// 动态表单
								this.dyFormData = tempArr
								
								console.info(eObj, 'eObj', this.dyFormData, tempArr)
								resolve(res)
							}
							console.log(res, 'xiangqing');
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			// 获取区域列表
			getPointAreaFn() {
				return new Promise((resolve, reject) => {
					console.info("getPointAreaFn", new Date().getTime())
					let requestData = {
						projectSn: this.projectSn,
					};
					this.sendRequest({
						url: 'xmgl/qualityRegion/notTreeList',
						method: 'post',
						data: requestData,
						success: (res) => {
							console.log(res);
							this.pointAreaList = res.result;
							console.info("getPointAreaFn处理结束", new Date().getTime())
							resolve(res)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			// 切换区域
			handleChangeRegion(e) {
				let index = e.detail.value;
				let findItem = this.pointAreaList[index];
				this.form.qualityRegionId = findItem.id;
				this.form.enterpriseId = "";
				this.form.inspectUserIds = "";
				this.enterpriseData = {};
				console.log(findItem);
				this.areaData = findItem;
				this.chargerList = findItem.systemUsers;
				this.enterpriseList = findItem.enterpriseInfos;
				console.info(this.enterpriseList, 'enlist')
			},
			// 切换责任企业
			handleChangeEnterprise(e,values,labels) {
				this.form.enterpriseId = values.join(',');
				this.$nextTick(() => {
					if(this.form.enterpriseId) {
						this.chargerList = this.areaData.systemUsers.filter((item) => {
						  return this.form.enterpriseId.includes(item.enterpriseId);
						});
						if (this.form.inspectUserIds) {
						  this.form.inspectUserIds = "";
						  this.inspectUserName = "";
						}
					} else {
						this.chargerList = this.areaData.systemUsers;
						this.form.inspectUserIds = "";
						this.inspectUserName = "";
					}
				})
			},
			// 切换责任人
			handleChangeCharger(e,values,labels) {
				this.form.inspectUserIds = values.join(',');
			},
			// 切换选中范围
			handleChangeStandArea(e) {
				console.info(e,'eee')
				this.form.standArea = this.standOptions[e.detail.value];
			},
			handleChangeRadio(e, item) {
				item.isRequired = e;
			},
			handleJumpMap() {
				uni.navigateTo({
				  url: `/pages/projectEnd/InspectionRoute/mapLocatoin/mapLocatoin?standArea=${this.form.standArea}&latitude=${this.form.latitude}&longitude=${this.form.longitude}&addr=${this.form.addr}`
				})
			},
			mapGetLocation() {
				let that = this
				uni.getLocation({
					type: that.coordType,
					geocode: true,
					isHighAccuracy: "true",
					accuracy: "best", // 精度值为20m
					success: function(res) {
						console.log('当前位置的经度：' + res.longitude);
						console.log('当前位置的纬度：' + res.latitude);
						console.log(res, 'res..')
						that.form.latitude = res.latitude;
						that.form.longitude = res.longitude;
						const { country, province, city, district, street, streetNum, poiName } = res.address;
						that.form.addr = country + province + city + district + street + streetNum + poiName;
					},
					fail: function(msg) {
						console.log("获取位置失败", msg)
					}
				});
			},
			addFormInput() {
			    this.dyFormData.push({
					title: '表单标题',
					name: '',
					isRequired: "1",
					value: ''
			    })
			},
			delFormInput(i) {
			    this.dyFormData.splice(i, 1);
			},
			save() {
				const res = this.verify();
				if(!res) return;
				
				// 新增
			    const params = { ...this.form };
			    params.projectSn = this.projectSn;
			    params.createUserId = this.userInfo.userId;
			    params.createUserName = this.userInfo.account;
				let newDyForm = this.deepClone(this.dyFormData);
				newDyForm.forEach(item => {
					item.isRequired = item.isRequired == "1" ? true : false
				})
				params.template = JSON.stringify(newDyForm);
				
				let apiUrl = 'xmgl/checkingPoint/add';
				let msg = "添加成功"
				
				// 编辑
				if(this.editId) {
					apiUrl = "xmgl/checkingPoint/edit"
					msg = "保存成功";
				}
				this.sendRequest({
					url: apiUrl,
					method: 'post',
					data: params,
					success: res => {
						console.info(res,'res')
						if (res.code == 200) {
							uni.showToast({
								title: msg
							})
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/projectEnd/InspectionRoute/inspectionPointList'
								})
							}, 1200)
						} else {
							uni.showToast({
								title: res.message,
								icon: 'none'
							})
						}
					}
				})
			},
			// 深度克隆
			deepClone (obj) {
				if([null, undefined, NaN, false].includes(obj)) return obj;
			    if(typeof obj !== "object" && typeof obj !== 'function') {
			        return obj;
			    }
			    var o = Object.prototype.toString.call(obj) === '[object Array]' ? [] : {};
			    for(let i in obj) {
			        if(obj.hasOwnProperty(i)){
			            o[i] = typeof obj[i] === "object" ? this.deepClone(obj[i]) : obj[i];
			        }
			    }
			    return o;
			},
			verify() {
				if(!this.form.checkingPointName) {
					uni.showToast({
						title: '请输入巡检点名称',
						icon: 'none'
					})
					return false
				}
				if(!this.form.position) {
					uni.showToast({
						title: '请输入巡检点位置',
						icon: 'none'
					})
					return false
				}
				if(!this.form.qualityRegionId) {
					uni.showToast({
						title: '请选择所属区域',
						icon: 'none'
					})
					return false
				}
				if(!this.form.enterpriseId) {
					uni.showToast({
						title: '请选择责任企业',
						icon: 'none'
					})
					return false
				}
				if(!this.form.inspectUserIds) {
					uni.showToast({
						title: '请选择责任人',
						icon: 'none'
					})
					return false
				}
				if(!this.form.minInspectTime) {
					uni.showToast({
						title: '请输入最低巡检时长',
						icon: 'none'
					})
					return false
				}
				if(!this.form.standArea) {
					uni.showToast({
						title: '请选择自定义范围',
						icon: 'none'
					})
					return false
				}
				return true
			}
		}
	}
</script>

<style lang="less">
	.fixedheader{
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		z-index: 2;
		.headerName{
			z-index: 1;
		}
	}
	.flex {
		display: flex;
		align-items: center;
	}
	
	.flex2 {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}
	
	.flex3 {
		display: flex;
	}
	
	.content {
		width: 100%;
		box-sizing: border-box;
		padding: 20px 30rpx;
	}
	
	.type {
		font-size: 30rpx;
		line-height: 40px;
		margin-bottom: 8px;
		/* border-bottom: 1px solid rgba(194, 194, 194, 0.2); */
	}
	
	.type .name {
		margin-right: 6px;
		width: 185rpx;
		text-align: left;
		white-space: nowrap;
		&.large {
			width: 300rpx;
		}
		&.large-2 {
			width: 240rpx;
		}
	}
	.uni-input {
		line-height: 32px;
	}
	
	.textarea {
		width: calc(79% - 32px);
		border-radius: 5px;
		border: 1px solid rgba(42, 43, 91, 0.3);
		padding: 8px 15px;
		box-sizing: border-box;
		height: 50px;
	}
	
	.inpuStyle {
		width: calc(80% - 35px);
		border-radius: 5px;
		// border: 1px solid rgba(42, 43, 91, 0.3);
		padding: 8px 15px;
		box-sizing: border-box;
		height: 35px;
		color: #000;
	}
	.areaStyle {
		width: calc(80% - 35px);
		color: #000;
		line-height: 35rpx;
		height: 35px;
		display: flex;
		align-items: center;
	}
	.dy_form {
		display: flex;
		flex-direction: column;
		width: 100%;
		.dy_head {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 32rpx;
			.head_left {
				display: flex;
				align-items: center;
				.ic {
					width: 48rpx;
					height: 48rpx;
					margin-right: 8rpx;
				}
				.title {
					color: rgba(16, 16, 16, 1);
					font-size: 28rpx;
					font-weight: 600;
				}
			}
			.add_btn {
				margin: 0;
			}
		}
		.dy_content {
			display: flex;
			flex-direction: column;
			margin-bottom: 40rpx;
			.c_colum {
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: solid 1px rgba(187, 187, 187, 0.14);
				padding: 0 0 16rpx 16rpx;
				.text {
					color: rgba(16, 16, 16, 1);
					font-size: 32rpx;
				}
				.del_btn {
					margin: 0;
				}
			}
			.c_body {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 32rpx;
				.c_input {
					flex: 1;
					border: 2rpx solid rgba(220, 224, 231, 0.4);
					border-radius: 6rpx;
					height: 72rpx;
					padding: 0 12rpx;
					margin-right: 52rpx;
				}
			}
		}
	}
	.save-btn {
		width: 100%;
		position: fixed;
		bottom: 0;
	}
</style>