<template>
	<view class="todo-page">
		<view class="background"></view>

		<view class="card">
			<u--form labelWidth="auto" :model="model" ref="wForm" class="demo-ruleForm">
				<view style="position: relative;">
					<view style="position: absolute;left: -10px;color: #3d4b70;top: -3px;">*</view>
				</view>

				<view style="font-size: 15px; font-weight: bold;color: #3d4b70;margin-bottom: 10px;">筛选条件</view>
				<u-form-item label="辨识部门" prop="RISK_AREA_NAME" borderBottom ref="item1" @click="handleShowSheet({title: '辨识部门'})">
					<u--input fontSize="14px" disabled disabledColor="#ffffff" v-model="(model.Nav_Department||{}).NAME" border="none" suffixIcon="arrow-right" customStyle="margin:0px;display:flex;padding:3px 9px"
						suffixIconStyle="font-size:12px"></u--input>
				</u-form-item>
				<u-form-item label="辨识岗位" prop="RISK_AREA_NAME" borderBottom ref="item1" @click="handleShowSheet({title: '辨识岗位'})">
					<u--input fontSize="14px" disabled disabledColor="#ffffff" v-model="(model.Nav_Post||{}).NAME" border="none" suffixIcon="arrow-right" customStyle="margin:0px;display:flex;padding:3px 9px"
						suffixIconStyle="font-size:12px"></u--input>
				</u-form-item>
				<u-button type="primary" text="查询" @click="filterData" :disabled="loading"></u-button>

			</u--form>
			<u--form labelWidth="auto" :model="model" ref="wForm" class="demo-ruleForm" style="margin-top: 20px;" v-if="filterDatas&&filterDatas.Nav_Librarys&&filterDatas.Nav_Librarys.length>0">
				<view style="position: relative;">
					<view style="position: absolute;left: -10px;color: #3d4b70;top: -3px;">*</view>
				</view>

				<view style="font-size: 15px; font-weight: bold;color: #3d4b70;margin-bottom: 10px;">岗位风险清单</view>
				<uni-collapse :border="false" accordion>
					<u-checkbox-group :value="checkedItems" placement="column" @change="handleCheckboxChange">
						<u-checkbox :customStyle="{marginBottom: '8px'}" label="全选" name="all">
						</u-checkbox>
						<view v-for="(item, index) in filterDatas.Nav_Librarys" :key="index" style="margin-top: 10px;">


							<uni-collapse-item title-border="none" :border="false">
								<template v-slot:title>
									<view class="uni-collapse-item__title-box">

										<u-checkbox :key="index" :name="item.ID">
										</u-checkbox>
										<view class="uni-collapse-item__title-text">
											{{item.RISK_NAME?index+1+'.风险名称：'+item.RISK_NAME:index+1+'.风险名称：'}}
										</view>
									</view>
								</template>
								<view class="content" style="padding: 0px 0px 0px 10px;">
									<u-form-item label="生产单元" prop="Nav_Contents.CHECKCONTENT" borderBottom>
										<u--input fontSize="14px" disabled disabledColor="#fff" v-model="item.MINE_NAME" border="none" inputAlign="right"></u--input>

									</u-form-item>
									<u-form-item label="辨识区域" prop="Nav_Contents.CHECKCONTENT" borderBottom>
										<u--input fontSize="14px" disabled disabledColor="#fff" v-model="(item.Nav_Area||{}).NAME" border="none" inputAlign="right"></u--input>

									</u-form-item>
									<!-- <u-form-item label="风险名称" prop="HIDDEN_PLACE" borderBottom>
										<u--input fontSize="14px" disabled disabledColor="#fff" v-model="item.RISK_NAME" border="none" inputAlign="right"></u--input>
									</u-form-item> -->
									<u-form-item label="风险描述" prop="HIDDEN_PLACE">
									</u-form-item>
									<u--textarea fontSize="14px" disabled disabledColor="#fff" v-model="item.RISK_DESCRIPTION" border="none" inputAlign="right" autoHeight></u--textarea>
									<u-form-item label="风险类别" prop="HIDDEN_PLACE" borderBottom>
										<u--input fontSize="14px" disabled disabledColor="#fff" v-model="(item.Nav_Type||{}).NAME" border="none" inputAlign="right"></u--input>
									</u-form-item>
									<u-form-item label="风险等级" prop="HIDDEN_PLACE" borderBottom>
										<u--input fontSize="14px" disabled disabledColor="#fff" v-model="item.EVALUATE_LEVELName" border="none" inputAlign="right"></u--input>
									</u-form-item>
								</view>


							</uni-collapse-item>

						</view>
					</u-checkbox-group>
				</uni-collapse>


			</u--form>

		</view>
		<view style="padding: 10px 16px;" class="bottom-button" v-if="filterDatas&&filterDatas.Nav_Librarys&&filterDatas.Nav_Librarys.length>0">
			<u-button type="primary" @click="submit" color="#3d4b70">生成岗位告知卡</u-button>
		</view>
		<query-selector :show="selectorInfo.showPopup" :defaultChecked="selectorInfo.defaultChecked" :title="selectorInfo.title" :lists="selectorInfo.dataLists" @search="handleSearch" @select="handleSelected"
			@close="selectorInfo.showPopup=false" :total="selectorInfo.totalCount" />
	</view>
</template>

<script>
	import {
		GetPostRiskList,
		DepartOrderPaged,
		GetPostOrderPaged
	} from '../../../../../services/apply/subPages/SK/SKServices.js'
	// import {
	// 	DepartOrderPaged,
	// 	PostOrderPaged,
	// 	getEnum
	// } from '../../services/common.js'
	import {
		getEnum,
		GetEnumAnyOrder
	} from '../../../../../services/common';
	import config from '../../../../../config/common'
	import {
		initFilter,
		extendRule,
		extendFilterGroupGroupRules,
		transformData
	} from '../../../../../utils/common'
	export default {
		data() {
			return {
				OrgId: uni.getStorageSync('orgId'),
				pageIndex: 0,
				pageSize: 20,
				total: 0,
				loading: true,
				baseUrl: config.uni_app_web_source_url,
				allData: [],
				// 新增选中项数组，存储选中item的唯一标识
				checkedItems: [],
				// 存储完整的选中对象（可选）
				selectedItems: [],
				filterDatas: {
					Nav_Librarys: []
				},
				model: {
					RISK_AREA_NAME: '请选择区域',
					RISK_AREA_ID: '',
					ISDOWN: '否',
					SchedulingType: '',
					COUNT_WORKER: '',
					COUNT_LEVEL: '',
					START_TIME: '',
					END_TIME: '',
					SchedulingNEXTTIME: '',
					LISTPERSON_SCHEDULING: [{
						NAME: ''
					}],
					LISTUSER_LEAVE: [{
						NAME: ''
					}],
					ListShow: []
				},
				radiolist: [{
					value: false,
					name: '否'
				}, {
					value: true,
					name: '是'
				}],
				selectorInfo: {
					showPopup: false,
					totalCount: 0,
					title: '班组名称',
					// itemData: {},
					index: 0,
					dataLists: [],
					defaultText: '',
					defaultValue: '',
					name: '',
					defaultChecked: []
				},
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {} // 存储枚举文本列表（用于下拉选择等场景）
			}
		},
		onLoad(option) {

			this.fetchEnums(['SKEvaluateLevelEnum', 'SKProductionUnit']);
		},
		// onReady() {
		// 	//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		// 	this.$refs.uForm.setRules(this.rules)
		// },
		methods: {
			fetchEnums(enumNames) {
				var dataParm = {
					'name': enumNames.join('|')
				}
				GetEnumAnyOrder(dataParm).then(res => {
					let newd = transformData(res, enumNames)
					this.enumsData = newd[0];
					// 生成文本列表（如需要）
					this.enumsText = newd[1]
					this.loadData();
				})
			},
			loadData() {
				const json = initFilter(this.OrgId, "", "")
				json.IgnoreDataRule = true
				GetPostRiskList(json).then(res => {
					this.loading = false
					this.allData = res.Data
					this.allData.map(item => {
						if (item.Nav_Librarys && item.Nav_Librarys.length > 0) {
							item.Nav_Librarys.map(item1 => {
								item1.EVALUATE_LEVELName = item1.EVALUATE_LEVEL !== undefined ? this.enumsData['SKEvaluateLevelEnum'].find(item => item.code === item1.EVALUATE_LEVEL).name : '';
								if (!item1.MINE_NAME) {
									item1.MINE_NAME = item1.MineType !== undefined ? this.enumsData['SKProductionUnit'].find(item => item.code === item1.MineType).name : '';
								}

							})
						}
					})
					// this.total = res.TotalCount



				})
			},
			handleCheckboxChange(e) {
				// 检查当前操作是否包含全选标识
				const hasAll = e.includes('all');
				// 获取所有可选项的ID列表
				const allIds = this.filterDatas.Nav_Librarys.map(item => item.ID);
				// 判断当前是否处于全选状态
				const isAllSelected = this.checkedItems.includes('all');

				if (this.checkedItems.length > e.length) {
					//取消选项
					if (hasAll) {
						//当前有全选
						if (isAllSelected) {
							//上一次有全选
							let arr = []
							const diff = this.checkedItems.filter(item => !e.includes(item));
							arr.push('all')
							arr.push(...diff)
							let arrs = []
							arrs = this.checkedItems.filter(item => !arr.includes(item));
							this.checkedItems = arrs
						} else {
							//lenth不对
						}

					} else {
						//当前没有全选
						if (isAllSelected) {
							//取消全选
							// const remainingIds = allIds.filter(id => e.includes(id));
							this.checkedItems = [];

						} else {
							const diff = this.checkedItems.filter(item => !e.includes(item));
							const newArr = this.checkedItems.filter(item => item !== diff[0]);
							this.checkedItems = newArr
						}
					}

				} else {
					//新增选项
					if (hasAll) {
						//当前有全选
						if (isAllSelected) {
							//上一次有全选 /选中其他选项 lenth不成立
						} else {
							//上一次没有全选
							// 点击全选：选中所有选项（包含全选自身）
							this.checkedItems = ['all', ...allIds];
						}

					} else {
						//当前没有全选
						if (isAllSelected) {
							//上一次有全选 lenth不成立

						} else {
							const diff = e.filter(item => !this.checkedItems.includes(item));
							this.checkedItems.unshift(...diff);
							if (e.length === allIds.length && allIds.length > 0) {
								this.checkedItems.unshift('all');
							}
						}
					}
				}
			},
			filterData() {
				if (!this.model.DEPARTMENT_ID || !this.model.POST_ID) {
					uni.showToast({
						icon: 'error',
						title: '请选择部门和岗位'
					})
					return
				}
				this.checkedItems = []
				this.allData.map(item => {
					if (item.DEPARTMENT_ID == this.model.DEPARTMENT_ID && item.POST_NAME == this.model.Nav_Post.NAME) {
						this.$set(this, 'filterDatas', item);
						this.$nextTick(() => { // 等待 DOM 渲染新数据后再全选
							const allIds = this.filterDatas.Nav_Librarys.map(item1 => item1.ID);
							this.checkedItems = ['all', ...allIds];
						});

					}
				})
				if (!this.filterDatas || !this.filterDatas.Nav_Librarys || this.filterDatas.Nav_Librarys.length == 0) {
					uni.showToast({
						icon: 'error',
						title: '暂无当前岗位数据',
					})
				}
			},
			submit() {
				let arr = []
				this.filterDatas.Nav_Librarys.map(item => {
					this.checkedItems.map(item1 => {
						if (item.ID == item1) {
							arr.push(item)
						}
					})
				})
				//MEASURES_NAME处理
				const groupedData = arr.reduce((acc, item) => {
					const riskName = item.RISK_NAME;
					// 提取当前项的所有措施，并去重（避免同一项内的重复措施）
					const currentMeasures = [...new Set(
						item.Nav_Details.map(detail => detail.MEASURES_NAME)
					)];

					if (!acc[riskName]) {
						// 若该风险名称首次出现，初始化数组
						acc[riskName] = currentMeasures;
					} else {
						// 若已存在，合并并去重（避免不同项的重复措施）
						acc[riskName] = [...new Set([...acc[riskName], ...currentMeasures])];
					}
					return acc;
				}, {});
				//
				// 1. 按 RISK_NAME 分组，收集所有对应的 RISK_DESCRIPTION

				const allPhotos = [];
				const photoNames = new Set(); // 用于记录已添加的图片name，实现去重

				arr.forEach(item => {
					// 确保当前对象存在 Nav_Photo 且是数组，避免报错
					if (Array.isArray(item.Nav_Photo)) {
						item.Nav_Photo.forEach(photo => {
							// 判断图片name是否已存在，不存在则添加
							if (!photoNames.has(photo.NAME)) {
								allPhotos.push(photo);
								photoNames.add(photo.NAME);
							}
						});
					}
				});
				// 此时 allPhotos 已包含所有 Nav_Photo 中的图片对象
				let newarr = {
					departName: this.filterDatas.Nav_Department ? this.filterDatas.Nav_Department.NAME : '',
					userName: this.filterDatas.USER_NAME,
					phone: this.filterDatas.PHONE,
					postName: this.filterDatas.POST_NAME,
					RISK_NAME: [...new Set(
						arr.map(item => item.RISK_NAME.trim())
					)].join(' ；'),
					EVALUATE_LEVELName: [...new Set(
						arr.map(item => item.EVALUATE_LEVELName.trim())
					)].join(' ；'),
					RISK_TYPE: [...new Set(
						arr.map(item => item.Nav_Type.NAME.trim())
					)].join(' ；'),
					RISK_DESCRIPTION: [...new Set(
						arr.map(item => item.RISK_DESCRIPTION.trim())
					)].join(' ；'),
					MEASURES_NAME: Object.entries(groupedData)
						.map(([riskName, measures], index) => {
							// 生成带序号的措施（1.xxx 2.yyy）
							const measuresList = measures
								.map((measure, mIndex) => `${mIndex + 1}.${measure}`)
								.join('\n  ');

							// 不同风险组之间用换行分隔（首组不加前缀换行）
							return index === 0 ?
								`${riskName}：\n  ${measuresList}` :
								`\n${riskName}：\n  ${measuresList}`;
						})
						.join(''),
					RISK_DESCRIPTION: this.handleData(arr, 'RISK_DESCRIPTION'),
					EMERGENCY: this.handleData(arr, 'EMERGENCY'),
					Nav_Photo: allPhotos
				}
				uni.setStorageSync('detailData', newarr);
				uni.navigateTo({
					url: 'jobRiskShow'
				})
			},
			handleData(arr, namekey) {
				const oneData = {};
				arr.forEach(item => {
					const name = item.RISK_NAME;
					const desc = item[namekey];
					// 若该名称已存在，追加描述；否则新建键值对
					if (oneData[name]) {
						oneData[name].add(desc);
					} else {
						oneData[name] = new Set([desc]);
					}
				});
				const resultArr = [];
				for (const [name, descList] of Object.entries(oneData)) {
					// Set 转数组，再拼接为 “名称：描述1；描述2” 格式
					const descStr = Array.from(descList).join('；');
					resultArr.push(`${name}：${descStr}`);
				}

				// 3. 所有名称的拼接结果用 “\n” 连接，得到最终字符串
				const finalResult = resultArr.join('\n');
				return finalResult
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},

			//显示组件
			handleChange() {
				this.selectorInfo.showPopup = true
				this.selectorInfo.title = '班组名称'
				this.handleSearch()
			},

			//数据加载
			handleSearch(val, pageIndex) {
				var p = {
					name: this.selectorInfo.name,
					title: this.selectorInfo.title,
					val: val,
					pageIndex: pageIndex
				}
				this.handleShowSheet(p)
			},
			async handleShowSheet(p) {
				uni.showLoading({
					title: '加载中...'
				})
				this.pageIndex = 0
				var defaultChecked = []
				let dataSelect = []
				const json = initFilter(this.OrgId, null, "NAME", 0, (p.pageIndex ?? 1));
				json.IgnoreDataRule = true
				json.Limit = 20
				if (p.val) {
					// extendFilterGroupGroupRules(json, 'NAME', 9, p.val)
					extendRule(json, "NAME", 9, p.val)
				}
				if (p.title == '辨识部门') {
					dataSelect = await DepartOrderPaged(json).then(res => {
						uni.hideLoading()
						this.selectorInfo.totalCount = res.TotalCount
						if (res != undefined && res.Data.length > 0) {
							for (let i = 0; i < res.Data.length; i++) {
								res.Data[i].name = res.Data[i].NAME
								res.Data[i].code = res.Data[i].CODE
							}
						}
						return res.Data
					})
				} else {
					if (this.model.DEPARTMENT_ID && this.model.DEPARTMENT_ID !== null) {
						// extendRule(json, "DEPARTMENT_ID", 1, this.model.DEPARTMENT_ID)
						json.Keyword = this.model.DEPARTMENT_ID
					}
					dataSelect = await GetPostOrderPaged(json).then(res => {
						uni.hideLoading()
						this.selectorInfo.totalCount = res.TotalCount
						if (res != undefined && res.Data.length > 0) {
							for (let i = 0; i < res.Data.length; i++) {
								res.Data[i].name = res.Data[i].NAME
								res.Data[i].code = res.Data[i].CODE
							}
						}
						return res.Data
					})
				}


				if (defaultChecked == null)
					defaultChecked = []
				if (dataSelect.length) {
					this.selectorInfo = {
						totalCount: this.selectorInfo.totalCount,
						showPopup: true,
						title: p.title,
						name: p.name,
						dataLists: dataSelect,
						defaultChecked: defaultChecked
					}
				} else {
					// 暂无数据
				}
			},
			handleSelected(e) {
				this.selectorInfo.showPopup = false
				if (this.selectorInfo.title == '辨识部门') {
					this.model.Nav_Department = e
					this.model.DEPARTMENT_ID = e.ID
				} else {
					this.model.Nav_Post = e
					this.model.POST_ID = e.ID
				}
				// this.WorkerScheduling()
			}
		},
	}
</script>

<style>
	@import url("../../../../../style/css/newTemplate.css");
</style>