<template>
	<view>
		<view class="fixedheader">
			<headers :showBack="true">
				<view class="headerName">
					{{pageTitle}}
				</view>
			</headers>
		</view>
		<view class="content" :style="{paddingTop: (mobileTopHeight + 50) * 1.5 + 'rpx'}">
			<view class="type flex">
				<view class="name"><text class="star">*</text>路线名称：</view>
				<input class="inpuStyle" v-model="form.routeName" placeholder="请输入"></input>
			</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"><text class="star">*</text>通知人员：</view>
				<g-picker style="flex: 1" v-model="noticeUserName" :columns="accountList" :filter="{label: 'workerName', value: 'userId'}" input-align="left" @confirm="handleChangeAccount"></g-picker>
			</view>
			<view class="type flex">
				<view class="name large-2"><text class="star">*</text>计划检查时间：</view>
				<picker mode="date" :value="form.startTime" @change="startTimeChange">
					<view v-if="!form.startTime" style="color: #c0c4cc; font-size: 28rpx;">开始时间</view>
					<view v-else class="uni-input">{{form.startTime}}</view>
				</picker>
				<span style="color: gray;margin:0 12rpx">一</span>
				<picker mode="date" :value="form.endTime" @change="endTimeChange">
					<view v-if="!form.endTime" style="color: #c0c4cc; font-size: 28rpx;">结束时间</view>
					<view v-else class="uni-input">{{form.endTime}}</view>
				</picker>
			</view>
			<view class="type flex">
				<view class="name large-2"><text class="star">*</text>检查频次：</view>
				<input disabled="true" v-model="form.frequencyNum" />
				<picker mode="selector" :range="frequencyOptions" @change="handleChangeFrequency" filterable>
					<view class="picker">
						<view class="" style="color: #c0c4cc; font-size: 28rpx;" v-if="!form.frequencyType">
							请选择
						</view>
						<view style="flex-shrink: 0; white-space: nowrap;" v-else>
							{{frequencyOptions[form.frequencyType - 1]}}
							<u-icon style="margin-left: 8rpx;" name="arrow-right"></u-icon>
						</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">
						<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">
						<label for="pointId">巡检点：</label>
						<picker id="pointId" class="c_picker" mode="selector" :range="inspectPointList" range-key="checkingPointName" @change="(e)=> handleInspectPoint(e, item)" filterable>
							<view class="picker">
								<view class="" style="color: #c0c4cc; font-size: 28rpx;" v-if="!item.checkingPointId">
									请选择
									<u-icon style="margin-left: 8rpx;" name="arrow-right"></u-icon>
								</view>
								<view class="c_picker_value" v-else>
									{{item.checkingPointName}}
									<u-icon style="margin-left: 8rpx;" name="arrow-right"></u-icon>
								</view>
							</view>
						</picker>
						<label for="sortId">排序：</label>
						<input type="number" id="sortId" class="c_input" v-model="item.sort" placeholder="数字越大排序越靠后" />
					</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"
	import dateTimePiccker from '@/components/dateTimePicker/index.vue'
import deepClone from "../../../uview-ui/libs/function/deepClone";
	export default {
		components: {
			gPicker,
			dateTimePiccker
		},
		data() {
			return {
				editId: "",
				coordType: "gcj02",
				standOptions: [30, 50, 100, 200, 300],
				mobileTopHeight: 0,
				projectSn: '',
				userInfo: {},
				areaData: {},
				enterpriseData: {},
				chargerList: [],
				enterpriseList: [],
				accountList: [],
				inspectPointList: [],
				pageTitle: "新增巡检计划",
				checkEnterpriseName: "",
				enterpriseName: "",
				inspectUserName: "",
				noticeUserName: "",
				detailData: {},
				form: {
					routeName: "",
					position: "",
					// qualityRegionId: "", // 区域ID
					enterpriseId: "", // 责任企业
					inspectUserIds: "", //检查人
					noticeUserIds: "", //通知人
					startTime: "",
					endTime: "",
					frequencyType: 1,
					frequencyNum: 1,
					standArea: 100, //范围
					latitude: "", //纬度
					longitude: "", //经度
					addr: "", //地图区域
				},
				dyFormData: [{
					sort: null,
					checkingPointId: null,
					checkingPointName: null
				}],
				frequencyOptions: ["次", "次/日", "次/周", "次/月", "次/年"]
			}
		},
		onLoad(option) {
			this.projectSn = JSON.parse(uni.getStorageSync('projectDetail')).projectSn;
			this.userInfo = JSON.parse(uni.getStorageSync('userInfo'));
			
			this.editId = ""
			
			this.init();
			// 编辑
			if(option.id) {
				this.pageTitle = "编辑巡检计划"
				this.editId = option.id;
				this.detailData = JSON.parse(option.detail);
				console.info(this.detailData, 'option')
			}
		},
		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.getEnterpriseList();
				await this.getAccountList();
				await this.getPointList();
				if(this.editId) await this.getData()
			},
			// 编辑回显
			getData() {
			 	return new Promise((resolve, reject) => {
					console.info("getData", new Date().getTime())
					this.sendRequest({
						url: 'xmgl/xzCheckingRoute/queryById',
						method: 'get',
						data: {
							id: this.editId
						},
						success: (res) => {
							if(res.code === 200) {
								this.form = res.result
								
								this.enterpriseName = this.detailData.enterpriseName;
								this.inspectUserName = this.detailData.inspectUserNames;
								this.noticeUserName = this.detailData.noticeUserNames;
								
								const list = deepClone(this.accountList)
								this.chargerList = list.filter((item) => {
									return this.form.enterpriseId.includes(item.enterpriseId);
								});

								let tempArr = this.form.routeToPointList || []
								tempArr.forEach(item => {
									item.checkingPointName = this.inspectPointList.find(it => it.id === item.checkingPointId).checkingPointName
								})
								// 动态表单
								this.dyFormData = tempArr
								resolve(res)
							}
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			// 获取分包单位列表
			getEnterpriseList() {
				return new Promise((resolve, reject) => {
					let requestData = {
						projectSn: this.projectSn,
					};
					this.sendRequest({
						url: 'xmgl/enterpriseInfo/list',
						method: 'post',
						data: requestData,
						success: (res) => {
							console.log(res);
							this.enterpriseList = res.result;
							resolve(res)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			// 获取通知人员列表
			getAccountList() {
				return new Promise((resolve, reject) => {
					let requestData = {
						projectSn: this.projectSn,
					};
					this.sendRequest({
						url: 'xmgl/systemUser/getProjectChilderSystemUserList',
						method: 'post',
						data: requestData,
						success: (res) => {
							console.log(res);
							let data = res.result;
							data.forEach(item => {
								item.workerName = item.workerName || item.userId;
								item.realName = item.realName || item.userId;
							})
							this.accountList = data;
							resolve(res)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})
			},
			// 获取巡检点列表
			getPointList() {
				return new Promise((resolve, reject) => {
				  let requestData = {
					pageNo: 10,
					pageSize: -1,
					projectSn: this.projectSn,
				  };
				  this.sendRequest({
					url: 'xmgl/checkingPoint/selectPage',
					method: 'post',
					data: requestData,
					success: (res) => {
						this.inspectPointList = res.result.records || [];
						resolve(res)
					},
					fail: (err) => {
						reject(err)
					}
				  })
			    })
			},
			// 切换责任企业
			handleChangeEnterprise(e,values,labels) {
				this.form.enterpriseId = values.join(',');
				this.$nextTick(() => {
					if(this.form.enterpriseId) {
						const list = deepClone(this.accountList)
						this.chargerList = list.filter((item) => {
						  return this.form.enterpriseId.includes(item.enterpriseId);
						});
						if (this.form.inspectUserIds) {
						  this.form.inspectUserIds = "";
						  this.inspectUserName = "";
						}
					} else {
						this.chargerList = [];
						this.form.inspectUserIds = "";
						this.inspectUserName = "";
					}
				})
			},
			// 切换责任人
			handleChangeCharger(e,values,labels) {
				this.form.inspectUserIds = values.join(',');
			},
			// 切换通知人员
			handleChangeAccount(e,values,labels) {
				this.form.noticeUserIds = values.join(',');
			},
			// 切换检查频次
			handleChangeFrequency(e) {
				console.info(e,'eee')
				this.form.frequencyType = e.detail.value + 1;
			},
			handleInspectPoint(e, data) {
				let item = this.inspectPointList[e.detail.value]
				data.checkingPointId = item.id;
				data.checkingPointName = item.checkingPointName
				console.info(e, '----', data)
			},
			addFormInput() {
			    this.dyFormData.push({
					sort: null,
					checkingPointId: null,
					checkingPointName: null
			    })
			},
			delFormInput(i) {
			    this.dyFormData.splice(i, 1);
			},
			startTimeChange(e) {
				console.info(e, 'ee')
				this.form.startTime = e.detail.value
			},
			endTimeChange(e) {
				this.form.endTime = e.detail.value
			},
			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);
				params.routeToPointList = newDyForm;
				
				let apiUrl = 'xmgl/xzCheckingRoute/add';
				let msg = "添加成功"
				
				// 编辑
				if(this.editId) {
					apiUrl = "xmgl/xzCheckingRoute/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/inspectionPlan'
								})
							}, 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.routeName) {
					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.noticeUserIds) {
					uni.showToast({
						title: '请选择通知人员',
						icon: 'none'
					})
					return false
				}
				if(!this.form.startTime || !this.form.endTime) {
					uni.showToast({
						title: '请输入计划检查时间',
						icon: 'none'
					})
					return false
				}
				if(!this.dyFormData.length) {
					uni.showToast({
						title: '请添加巡检路线',
						icon: 'none'
					})
					return false
				}
				const bool = this.dyFormData.some(item => {
					if(!item.sort || !item.checkingPointId) {
						return true
					}
				})
				if(bool) {
					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;
		}
		:deep( .headerBox ){
			background-color: #5181F6;
			color: white;
			.uni-icons{
				color: white !important;
			}
		}
	}
	.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: 40rpx 30rpx;
	}
	
	.type {
		font-size: 30rpx;
		line-height: 80rpx;
		margin-bottom: 16rpx;
		/* 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: 64rpx;
	}
	
	.textarea {
		width: calc(79% - 64rpx);
		border-radius: 10rpx;
		border: 1px solid rgba(42, 43, 91, 0.3);
		padding: 8px 30rpx;
		box-sizing: border-box;
		height: 100rpx;
	}
	
	.inpuStyle {
		// width: calc(80% - 70rpx);
		flex: 1;
		border-radius: 10rpx;
		// border: 1px solid rgba(42, 43, 91, 0.3);
		// padding: 8px 30rpx;
		box-sizing: border-box;
		height: 70rpx;
		color: #000;
	}
	.areaStyle {
		width: calc(80% - 70rpx);
		color: #000;
		line-height: 35rpx;
		height: 70rpx;
		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;
				justify-content: flex-end;
				align-items: center;
				// border-bottom: solid 1px rgba(187, 187, 187, 0.14);
				.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: 24rpx;
					&:last-child {
						margin-right: 0;
					}
				}
				.c_picker {
					width: 180rpx;
					margin-right: 24rpx;
					.c_picker_value {
						flex-shrink: 0;
						white-space: nowrap;
						overflow: hidden;
						text-overflow: ellipsis;
					}
				}
			}
		}
	}
	.save-btn {
		width: 100%;
		position: fixed;
		bottom: 0;
	}
</style>