<template>
	<!-- 顶部导航栏 -->
	<custom-nav-bar :left="true" leftText="" @leftClick="" :title="formData.scenarioName">
		<template v-slot:right>
			<view class="fixed">
				<view align="right" class="iconfont icon-liebiao icon" @click="groupPop = true"></view>
			</view>
		</template>
	</custom-nav-bar>
	<view class="text-intel" v-if="formData && formData.groups && formData.groups.length">
		<view>
			<span class="text">
				{{formData.groups[gIndex].groupName}}
			</span>
		</view>
		<view>
			<span>
				时长：{{formData.groups[gIndex].irrigateDuration}}h
			</span>
		</view>
		<view>
			<!-- <span>已选：{{formData.groups[gIndex].wos.length}}</span> -->
			<span>已选：{{Object.keys(select).length}}</span>
		</view>
	</view>

	<view class="card">
		<uni-collapse ref="collapseRef">
			<uni-collapse-item title-border="none" :border="false" :show-arrow="false" :open="true"
				v-for="item in woData">
				<template v-slot:title>
					<view class="cards-title">
						<view>
							<view class="iconfont icon-nongtian icon"></view>
							<view class="text" style="color: #333;">
								{{ item.landGroup }}{{ item.branchCanalCode }}
							</view>
						</view>
					</view>
				</template>
				<view class="content" v-if="item.children">
					<uni-forms ref="baseForm">
						<view class="cards-content">
							<view class="greybar-box" v-for="child in item.children">
								<view class="title">
									<view>出水口：<span>{{child.showName}}</span></view>
									<view v-if="child.deviceRelation">阀门：
										<span v-if="[2,3].includes(child.deviceRelation.deviceTypeId)">
											三通阀
										</span>
										<span v-if="[13].includes(child.deviceRelation.deviceTypeId)">
											五通阀
										</span>
									</view>
								</view>
								<uni-forms-item v-if="child.deviceRelation">
									<view class="check-box" v-if="[2,3].includes(child.deviceRelation.deviceTypeId)"
										v-for="vItem in valve">
										<u-button size="small" :text="vItem.text" @click="itemChange(child,vItem)"
											:type="(select[child.id]?.valveNo == vItem.valveNo || selected[`${child.id}_${vItem.valveNo}`]) ? 'success':'info'" />
										<uni-tag circle="true" type="warning"
											v-if="selected[`${child.id}_${vItem.valveNo}`]"
											:text="selected[`${child.id}_${vItem.valveNo}`].text" />
									</view>
									<view class="check-box" v-else-if="[13].includes(child.deviceRelation.deviceTypeId)"
										v-for="vItem in fiveValve">
										<u-button size="small" :text="vItem.text" @click="itemChange(child,vItem)"
											:type="(select[child.id]?.valveNo == vItem.valveNo || selected[`${child.id}_${vItem.valveNo}`]) ? 'success':'info'" />
										<uni-tag circle="true" type="warning"
											v-if="selected[`${child.id}_${vItem.valveNo}`]"
											:text="selected[`${child.id}_${vItem.valveNo}`].text" />
									</view>
								</uni-forms-item>
								<view class="no-data" v-else>
									<view class="iconfont icon-wbd"></view>未绑定阀门
								</view>
							</view>
						</view>
					</uni-forms>
				</view>
			</uni-collapse-item>
		</uni-collapse>
	</view>
	<view class="bottom-btn">
		<u-button type="success" size="large" text="保存" @click="confirm" v-if="showSave" />
		<u-button type="success" size="large" text="下一组" @click="nextGroup" v-else />
	</view>

	<!-- 左侧分组弹出层 -->
	<u-popup mode="left" :show="groupPop" @close="groupPopClose" :closeOnClickOverlay="false">
		<view style="width: 95vw;padding-bottom: 46px;">
			<view class="text-intel">
				<view>
					<span>轮灌组：</span>
					<span class="font-green">{{formData.groupNum}}</span>
				</view>
				<view>
					<span>总时长：</span>
					<span class="font-green">{{`${formData.irrigateTotalDuration} h`}}</span>
				</view>
			</view>
			<view class="card">
				<uni-collapse>
					<view v-for="(item,index) in formData.groups">
						<uni-collapse-item title-border="none" :border="false" :show-arrow="false" v-if="!item._isHide">
							<template v-slot:title>
								<view class="cards-title">
									<view>
										<view class="text">{{item.groupName}}</view>
										<view style="margin-left: 10px;" @click.stop="groupEditShow(index)">
											<span>时长：</span>
											<span class="font-orange"
												style="text-decoration: underline;">{{`${item.irrigateDuration} h`}}</span>
										</view>
										<view style="margin-left: 20px;">已选：{{item.wos.length}}</view>
									</view>
									<view class="title-r">
										<view @click.stop="selectGroup(index)">
											<u-button type="success" size="mini" text="选择" />
										</view>
										<view @click.stop="removeGroup(index)">
											<u-button class="bg-red" type="success" size="mini" text="删除" />
										</view>
									</view>
								</view>
							</template>
							<view class="content">
								<view class="cards-content" v-if="item.wos.length">
									<view class="greybar" v-for="wo in item.wos">
										<view>出水口：<span>{{wo.woName}}</span></view>
										<view v-if="wo.deviceTypeKey == 'valve'">三通阀
											<span>{{valveKey[wo.deviceTypeKey][wo.valveNo]}}</span>
										</view>
										<view v-else-if="wo.deviceTypeKey == 'fiveValve'">五通阀
											<span>{{valveKey[wo.deviceTypeKey][wo.valveNo]}}</span>
										</view>
									</view>
								</view>
							</view>
						</uni-collapse-item>
					</view>
				</uni-collapse>
			</view>
			<u-button type="success" size="normal" style="width: 30%;margin-top: 20px;" @click="addGroup"
				text="新增轮灌组" />
			<view style="position: absolute;bottom: 0; width: 100%;">
				<u-button type="success" size="large" text="关闭" @click="groupPopClose" />
			</view>
		</view>
	</u-popup>

	<!-- 轮灌组编辑 -->
	<u-modal :show="groupEdit.show" :title="groupEdit.item.groupName" :showCancelButton="true" :showConfirmButton="true"
		@confirm="groupEditConfirm(true)" @cancel="groupEditHide" @close="groupEditHide" :closeOnClickOverlay="true">
		<view class="slot-content" style="border: 1px solid red;width: 100%;">
			<u-form ref="formRef" :model="groupEdit.item">
				<u-form-item label="时长(h)" labelWidth="60px">
					<u-input v-model="groupEdit.item.irrigateDuration" placeholder="请输入时长" />
				</u-form-item>
			</u-form>
		</view>
	</u-modal>
</template>

<script>
	import store from '@/store'
	import plugins from "@/plugins";
	const user = store.state.user.user;
	import {
		woSort
	} from "@/utils/woSort"
	import {
		getWaterOutletPermissionList
	} from "@/api/system/landWaterOutletPermission";
	import * as isApi from '@/api/irrigate/irrigateScenario.js'

	export default {
		data() {
			return {
				formData: null,
				gIndex: 0, //当前编辑的索引
				selectIndex: false, //选择索引
				showSave: false, //保存按钮
				woData: [], //出水口列表
				// 三通阀
				valve: [{
						text: '①开',
						valveNo: 1,
						angleKey: "open1",
						deviceTypeKey: "valve",
					},
					{
						text: '②开',
						valveNo: 2,
						angleKey: "open2",
						deviceTypeKey: "valve",
					}
				],
				// 多通阀
				fiveValve: [{
						text: '①开',
						valveNo: 1,
						angleKey: "open",
						deviceTypeKey: "fiveValve",
					},
					{
						text: '②开',
						valveNo: 2,
						angleKey: "open",
						deviceTypeKey: "fiveValve",
					},
					{
						text: '③开',
						valveNo: 3,
						angleKey: "open",
						deviceTypeKey: "fiveValve",
					},
					{
						text: '④开',
						valveNo: 4,
						angleKey: "open",
						deviceTypeKey: "fiveValve",
					}
				],
				valveKey: {
					"valve": {
						"1": "①开",
						"2": "②开",
						"3": "全开 ",
						"4": "全关",
					},
					"fiveValve": {
						"1": "①开",
						"2": "②开",
						"3": "③开",
						"4": "④开",
					}
				},
				select: {}, //当前选择
				selected: {}, //往期选择
				groupPop: false, //组弹窗
				groupEdit: { //组编辑
					show: false,
					index: 0,
					item: {},
				}
			};
		},
		onLoad(par) {
			this.initData(par);

			uni.showLoading();
			// 初始化出水口数据
			getWaterOutletPermissionList(this.formData.landId).then(res => {
				uni.hideLoading()
				if (res.data) {
					this.woData = res.data;
				} else {
					this.woData = [];
				}
			});
		},
		onShow() {},
		mounted() {},
		methods: {
			async initData(par) {
				uni.showLoading()
				this.formData = JSON.parse(par.item);
				if (this.formData.id) {
					const res = await isApi.getIrrigateScenario(this.formData.id);
					if (res.data) {
						this.formData.groups = res.data.groups;
					}
				} else {
					let groupArr = [];
					for (var i = 1; i <= this.formData.groupNum; i++) {
						groupArr.push(this.createGroup(i));
					}
					this.formData.groups = groupArr;
					this.calcAVGDuration();
				}
				this.formData.groups.forEach((item, index) => {
					if (!item.wos.length) {
						return;
					}
					item.wos.forEach((_item, _index) => {
						if (index == 0) {
							if (_item.deviceTypeKey == "valve") {
								this.select[_item.woId] = this.valve[_item.valveNo - 1];
							} else if (_item.deviceTypeKey == "fiveValve") {
								this.select[_item.woId] = this.fiveValve[_item.valveNo - 1];
							}
						} else {
							this.selected[`${_item.woId}_${_item.valveNo}`] = {
								text: item.groupName, //页面显示
								gIndex: index, //轮灌组索引
							};
						}
					})
				});
				if (this.formData.groups.length == 1) {
					this.showSave = true;
				} else {
					this.showSave = false;
				}
				uni.hideLoading()
			},
			//创建轮灌组
			createGroup(index) {
				return {
					id: undefined,
					landId: this.formData.landId,
					userId: user.userId,
					shareUserIds: undefined,
					irrigateScenarioId: this.formData.id,
					groupName: `轮灌组${index}`,
					irrigateDuration: 0,
					sort: index,
					delFlag: "0",
					wos: [],
					_isHide: false
				}
			},
			//计算平均时长
			calcAVGDuration() {
				const avg = (Number(this.formData.irrigateTotalDuration) / Number(this.formData.groupNum)).toFixed(2);
				this.formData.groups.forEach(item => {
					if (item._isHide) {
						return;
					}
					item.irrigateDuration = avg;
				});
			},
			//关闭组选择
			groupPopClose() {
				if (this.selectIndex) {
					plugins.modal.msg("请选择操作的轮灌组")
					return;
				}
				this.groupPop = false;
			},
			// 选中数据
			itemChange(wo, vItem) {
				if (this.selected[`${wo.id}_${vItem.valveNo}`]) {
					plugins.modal.confirm("更换到当前轮灌组?").then(() => {
						//删除之前存储的组中的数据
						this.removeWo(this.selected[`${wo.id}_${vItem.valveNo}`].gIndex, wo.id, vItem.valveNo);
						delete this.selected[`${wo.id}_${vItem.valveNo}`];

						//添加新选中的
						this.setSelect(wo, vItem);
					}).catch(() => {});
					return;
				}
				//添加新选中的
				this.setSelect(wo, vItem);
			},
			//添加选中数据
			setSelect(wo, vItem) {
				vItem["item"] = wo;
				if (this.select[wo.id]) {
					this.removeWo(this.gIndex, wo.id, this.select[wo.id].valveNo);
					if (this.select[wo.id].valveNo == vItem.valveNo) {
						this.select[wo.id] = null;
						return;
					}
				}
				this.addWo(this.gIndex, vItem, wo)
				this.select[wo.id] = vItem;
			},
			//新增出水口
			addWo(index, vItem, wo) {
				const group = this.formData.groups[index];
				group.wos.push({
					landId: group.landId,
					irrigateScenarioId: group.irrigateScenarioId,
					irrigateGroupId: group.id,
					wogId: wo.landGroupId || -1,
					wogName: `${wo.landGroup || ''}${wo.branchCanalCode || ''}`,
					woId: wo.id,
					woName: wo.showName,
					deviceTypeKey: vItem.deviceTypeKey,
					valveNo: vItem.valveNo,
					angleKey: vItem.angleKey,
					sort: 1,
				});
				group.wos = group.wos.slice().sort((v1, v2) => woSort(v1, v2, "woName"));
				this.formData.groups[index] = group;
			},
			//删除出水口
			removeWo(index, woId, valveNo) {
				if (!this.formData.groups[index].wos.length) {
					return;
				}
				const _index = this.formData.groups[index].wos.findIndex(u => u.woId == woId && u.valveNo == valveNo);
				if (_index != -1) {
					this.formData.groups[index].wos.splice(_index, 1);
				}
			},
			//下一组
			nextGroup() {
				this.selectGroup(this.gIndex + 1);
			},
			//保存选择的数据
			savaSelectData() {
				let selected = {};
				for (var key in this.select) {
					if (this.select[key]) {
						const group = this.formData.groups[this.gIndex];
						selected[`${key}_${this.select[key].valveNo}`] = {
							text: group.groupName, //页面显示
							gIndex: this.gIndex, //轮灌组索引
						};
					}
				}
				this.selected = Object.assign({}, this.selected, selected)
			},
			//轮灌组编辑
			groupEditShow(index) {
				this.groupPop = false;
				this.groupEdit.show = true;
				this.groupEdit.index = index;
				this.groupEdit.item = this.formData.groups[index];
			},
			groupEditHide() {
				this.groupEdit.show = false;
				this.groupEdit.item = {};
				this.groupPop = true;
			},
			groupEditConfirm() {
				let irrigateDuration = this.groupEdit.item.irrigateDuration;
				// 清理非数字和非小数点字符
				let cleaned = irrigateDuration.replace(/[^0-9.]/g, '');
				// 确保只有一个小数点，并截取小数点后两位
				const [integerPart, decimalPart = ""] = cleaned.split('.').slice(0, 2);
				const formattedDecimal = decimalPart ? `${integerPart}.${decimalPart.slice(0, 2)}` : integerPart;
				this.groupEdit.item.irrigateDuration = formattedDecimal;

				//合计浇灌时长
				const sumId = this.formData.groups.reduce((accumulator, currentValue) => {
					return accumulator + Number(currentValue.irrigateDuration);
				}, 0);
				this.formData.irrigateTotalDuration = sumId;

				//关闭
				this.groupEditHide();
			},
			//选择轮灌组
			selectGroup(index) {
				if (this.groupPop) {
					this.groupPop = false;
					this.selectIndex = false;
				}
				if (this.formData.groups[index].sort == this.formData.groupNum) {
					this.showSave = true;
				} else {
					this.showSave = false;
				}
				this.savaSelectData();
				this.select = {};
				this.gIndex = index;


				for (var key in this.selected) {
					if (this.selected[key].gIndex == index) {
						delete this.selected[key];
					}
				}
				this.formData.groups[index].wos.forEach(item => {
					if (item.deviceTypeKey == "valve") {
						switch (item.valveNo) {
							case 1:
								this.select[item.woId] = this.valve[0];
								break;
							case 2:
								this.select[item.woId] = this.valve[1];
								break;
						}
					} else if (item.deviceTypeKey == "fiveValve") {
						this.select[item.woId] = this.fiveValve[item.valveNo - 1];
					}
				});
				this.$nextTick(() => {
					this.$refs.collapseRef.resize();
				})
			},
			//删除轮灌组
			removeGroup(index) {
				this.groupPop = false;
				const groupName = this.formData.groups[index].groupName;
				plugins.modal.confirm(`删除"${groupName}"?`).then(() => {
					//删除轮灌组
					this.formData.groups[index]._isHide = true;
					let i = 0;
					this.formData.groups.forEach(item => {
						if (item._isHide) {
							return;
						}
						i++;
						item.groupName = `轮灌组${i}`;
						item.sort = i;
					});
					this.formData.groupNum = i;
					this.calcAVGDuration();

					//删除存储的数据
					if (this.gIndex == index) { //删除的是当前的组
						this.select = {};
					} else { //不是当前组
						for (var key in this.selected) {
							let item = this.selected[key];
							if (item.gIndex == index) {
								delete this.selected[key];
							} else {
								this.selected[key].text = this.formData.groups[item.gIndex].groupName;
							}
						}
					}

					//新的编辑组索引
					this.selectIndex = true;
					plugins.modal.msg("删除成功，轮灌组重新排序")
				}).catch(() => {
					this.groupPop = true;
				});
			},
			//新增轮灌组
			addGroup() {
				let index = Number(this.formData.groupNum) + 1;
				this.formData.groupNum = index;
				this.formData.groups.push(this.createGroup(index));
				this.calcAVGDuration();
			},
			// 保存
			confirm() {
				let title = "";
				let formData = JSON.parse(JSON.stringify(this.formData));
				this.formData.groups.forEach((item, index) => {
					if (item._isHide) {
						formData.groups.splice(index, 1);
					} else {
						if (!item.wos.length) {
							if (title) {
								title = `${title},${item.groupName}`;
							} else {
								title = item.groupName;
							}
						}
					}
				})
				if (title) {
					plugins.modal.msg(`"${title}"未选择出水口`)
					return;
				}
				formData.groups.forEach((item, index) => {
					item.wos = item.wos.slice().sort((v1, v2) => woSort(v1, v2, "woName"));
					item.wos.forEach((_item, _index) => {
						_item.sort = (_index + 1)
					})
				})
				plugins.modal.confirm("保存轮灌方案?").then(() => {
					uni.showLoading();
					isApi.saveIrrigateScenario(formData).then(res => {
						uni.hideLoading();
						uni.switchTab({
							url: '/pages/irrigation/index'
						});
					});
				}).catch(() => {});
			},
		}
	}
</script>

<style lang="scss" scoped>
	uni-app,
	uni-page,
	uni-page-wrapper,
	uni-page-body {
		padding-bottom: 38px !important;
	}

	::v-deep.u-popup__content {
		background-color: #f3f3f3 !important;
	}

	.greybar>uni-view:first-child {
		color: #303133;
	}

	.greybar view>span {
		font-weight: normal;
	}

	// 按钮列表
	::v-deep .uni-forms-item__content {
		display: flex;
		flex: none;
		width: 100%;

		.check-box {
			padding: 10px 0;
			flex: 1;
			display: flex;
			align-items: center;
			flex-direction: column;

			.uni-tag {
				margin-top: 5px;
			}

			.u-button--small {
				width: 50px;
				height: 26px;

				.u-button__text {
					font-size: 14px !important;
				}
			}

			.u-button--info {
				border: 1px #DCDFE6 solid;
				background-color: #f5f5f5;
			}

		}
	}

	// 表单
	::v-deep .uni-forms {
		padding: 0 !important;
	}

	::v-deep .uni-forms-item__label {
		min-width: 0px !important;
	}

	.uni-forms-item {
		margin-bottom: 0;
	}

	::v-deep .uni-data-checklist .checklist-group {
		padding: 10px;
	}

	::v-deep .uni-data-checklist .checklist-group .checklist-box {
		flex: 1;
		margin-right: 0px;
	}

	::v-deep .uni-data-checklist .checklist-group .checklist-box.is--default.is-checked .checklist-text {
		color: #39ac4f;
	}

	::v-deep .uni-data-checklist .checklist-group .checklist-box.is--default.is-checked .checkbox__inner {
		border-color: #39ac4f;
		background-color: #39ac4f;
	}
</style>