<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"></u-button>

			</u--form>
			<u--form labelWidth="auto" :model="model" ref="wForm" class="demo-ruleForm" style="margin-top: 20px;">
				<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-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;">


						<u-checkbox :customStyle="{marginBottom: '8px'}" :key="index" :label="index+1+'.生产单元：'+item.MINE_NAME" :name="item.ID">
						</u-checkbox>

						<u-form-item label="辨识区域" prop="Nav_Contents.CHECKCONTENT" borderBottom>
							<u--input fontSize="14px" disabled disabledColor="#fff" v-model="item.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" borderBottom>
						</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.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>
				</u-checkbox-group>


			</u--form>

		</view>
		<view style="padding: 10px 16px;" class="bottom-button">
			<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,
		PagedRisk
	} from '../../services/apply'
	import {
		DepartOrderPaged,
		PostOrderPaged,
		getEnum
	} from '../../services/common.js'
	import config from '../../config/common'
	import {
		initFilter,
		extendRule,
		extendFilterGroupGroupRules
	} from '../../utils/common'
	export default {
		data() {
			return {
				OrgId: '',
				pageIndex: 0,
				pageSize: 20,
				total: 0,
				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.OrgId = option.OrgId // 'B043B28B-BBC3-C452-6052-4FBA1457ABFA'
			// const orgId = uni.getStorageSync('orgId')
			this.fetchEnums(['SKEvaluateLevelEnum']);
		},
		// onReady() {
		// 	//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
		// 	this.$refs.uForm.setRules(this.rules)
		// },
		methods: {
			async fetchEnums(enumNames) {
				try {
					// 存储所有枚举请求的Promise
					const enumPromises = enumNames.map(name => {
						return getEnum({
							name
						}).then(res => {
							// 统一处理枚举格式：添加name/code字段，便于后续映射
							return {
								enumName: name,
								data: res.Data.map(item => ({
									...item,
									name: item.NAME, // 统一显示名称字段
									code: item.ID // 统一值字段
								}))
							};
						});
					});

					// 等待所有枚举请求完成
					const results = await Promise.all(enumPromises);
					// 存储枚举结果到data中（键为枚举名称，值为处理后的数据）
					results.forEach(({
						enumName,
						data
					}) => {
						this.enumsData[enumName] = data;
						// 生成文本列表（如需要）
						this.enumsText[enumName] = data.map(item => item.name);
					});
					// 所有枚举获取完成后，执行loadData
					this.loadData();
				} catch (error) {
					console.error('枚举请求失败:', error);
					uni.showToast({
						title: '枚举数据加载失败',
						icon: 'none'
					});
				}
			},
			loadData() {
				const json = initFilter(this.OrgId, "", "")
				json.IgnoreDataRule = true
				GetPostRiskList(json).then(res => {
					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 : '';
							})
						}
					})
					// 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');
							}
							// const diff = this.checkedItems.filter(item => !e.includes(item));

							// // 取消其他选项
							// this.checkedItems = e.filter(item => item !== 'all');

							// // 检查是否所有选项都被选中，如果是则自动勾选全选
							// if (this.checkedItems.length === allIds.length && allIds.length > 0) {
							// 	this.checkedItems.unshift('all');
							// }
						}
					}
				}
			},
			filterData() {
				this.allData.map(item => {
					if (item.DEPARTMENT_ID == this.model.DEPARTMENT_ID && item.POST_NAME == this.model.Nav_Post.NAME) {
						this.filterDatas = item
						console.log(this.filterDatas, 'this.filterData')
					}
				})
			},
			checkChange(e) {
				console.log(e, '888')
			},
			submit() {
				console.log(this.checkedItems, '9999')
				console.log(this.filterDatas, '9999')
				let arr = []
				this.filterDatas.Nav_Librarys.map(item => {
					this.checkedItems.map(item1 => {
						if (item.ID == item1) {
							arr.push(item)
						}
					})
				})
				console.log(arr, 'arr')
				//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
				
				
				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')
				}

				console.log(newarr, 'nnnnnnnnnnnnn')



				uni.setStorageSync('detailData', newarr);
				uni.navigateTo({
					url: '/pages/apply/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 PostOrderPaged(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>