<template>
	<view class="todo-page">
		<step-title :stepPage="stepsPage" :stepText="stepsText"></step-title>
		<view class="allview">
			<view class="card" v-if="stepsPageList === 0">
				<u--form labelWidth="auto" :model="dataModel" 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="YEAR">
						<u--input v-model="dataModel.YEAR" disabled Color="#ffffff" placeholder="请填写年度" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>
					<!-- <u-form-item label="辨识与评估内容:">
					</u-form-item>
					<u--textarea v-model="dataModel.CONTENTS" placeholder="请输入内容" autoHeight></u--textarea> -->
					<u-form-item label="辨识开始时间:" @click="handleChangeRecitify('start')">
						<u--input v-model="dataModel.START_DATE" placeholder="请选择时间" disabled Color="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input>
						<!-- <u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
						</u-icon> -->
					</u-form-item>
					<u-form-item label="辨识结束时间:" @click="handleChangeRecitify('end')">
						<u--input v-model="dataModel.END_DATE" placeholder="请选择时间" disabled Color="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input>
						<!-- <u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
						</u-icon> -->
					</u-form-item>
					<u-form-item label="辨识要求:">
					</u-form-item>
					<u--textarea v-model="dataModel.Nav_RequiresName" disabled autoHeight></u--textarea>
					<view class="upload-title">附件：</view>
					<full-upload v-model="dataModel.Nav_Files" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>

				</u--form>
			</view>
			<view style="padding: 10px 16px;" v-if="stepsPageList === 0" class="bottom-button">
				<u-button type="primary" :loading="stepLoad" @click="stepAdd" color="#3d4b70">下一步</u-button>
			</view>
			<view class="card" v-if="stepsPageList === 1">
				<u--form labelWidth="auto" :model="dataModel" ref="wForm" class="sub-form">


					<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;margin-top: 20px;">辨识内容</view>
					<view v-for="(item,index) in dataModel.Nav_Details.filter(i => !i.IS_DELETED)" :key="index" style="border-bottom: #ceccca 1px solid;margin-bottom: 10px;padding-bottom: 10px;">
						<u-form-item prop="Nav_Contents">

							<view style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;flex: 1;">
								<view style="flex: 1;" @click="handleShowSheet({title: '辨识区域', name: 'Nav_Area',itemData:item})">
									{{index+1+'.辨识区域：'+item.Nav_Area.NAME}}
								</view>
								<view class="action" style="display: flex;flex-direction: row;align-items: center;justify-content: space-around;">
									<u-icon @click="handleDelRowBefore(item)" name="trash" color="#ff4d4f" size="21" style="margin-right: 20px;"></u-icon>
									<u-icon name="arrow-up" size="12" v-if="item.showPack" @click="handlePack(item)"></u-icon>
									<u-icon name="arrow-down" size="12" v-if="!item.showPack" @click="handlePack(item)"></u-icon>
								</view>
							</view>
						</u-form-item>
						<view v-if="item.showPack==true">
							<u-form-item label="生产单元：" @click="handleChangeUnit(item,'MinType')" border-bottom>
								<u--input v-model="(item.Nav_ProductionUnit||{}).NAME" disabled disabledColor="#ffffff" placeholder="请选择生产单元" border="none" inputAlign="right" fontSize="14px">
								</u--input>
								<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
								</u-icon>
							</u-form-item>
							<u-form-item label="风险名称" prop="CHECKSTANDARD" border-bottom>
								<u--input v-model="item.RISK_NAME" placeholder="请填写风险名称" disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
								</u--input>
							</u-form-item>
							<u-form-item label="风险描述" prop="HIDDEN_DESCRIPTION">
							</u-form-item>
							<u--textarea v-model="item.RISK_DESCRIPTION" placeholder="请填写风险描述" autoHeight maxlength="-1"></u--textarea>
							<u-form-item label="风险类别" prop="HIDDEN_LEVEL" @click="handleShowSheet({title: '风险类别', name: 'Nav_Type',itemData:item})" border-bottom>
								<u--input v-model="item.Nav_Type.NAME" placeholder="请选择风险类别" disabled suffixIcon="arrow-down" suffixIconStyle="font-size: 12px" disabledColor="#ffffff" inputAlign="right" fontSize="14px"
									border="none">
								</u--input>
							</u-form-item>
							<uni-collapse class="collapse" ref="collapse">

								<uni-collapse-item title="管控措施" name="Variety components">
									<u-button type="primary" @click="handleNewMeasures(item)" color="#3d4b70">新增管控措施</u-button>
									<view v-if="item.Nav_DetailMeasures&&item.Nav_DetailMeasures.length!==0">
										<view v-for="item1 in item.Nav_DetailMeasures.filter(i => !i.IS_DELETED)" style="margin: 5px 5px;padding: 0px 10px;">
											<u-form-item label="序号" prop="HIDDEN_DESCRIPTION" border-bottom>
												<view slot="right" style="display: flex;flex-direction: row;align-items: center;">
													<u-number-box v-model="item1.NUM" integer></u-number-box>
													<u-icon @click="handleDelRowMeasures(item,item1)" name="trash" color="#ff4d4f" size="21" style="margin-right: 20px;margin-left: 20px;"></u-icon>
												</view>

											</u-form-item>
											<u-form-item label="措施" prop="HIDDEN_DESCRIPTION">

											</u-form-item>
											<u--textarea v-model="item1.MEASURE" placeholder="请填写管控措施" autoHeight></u--textarea>
										</view>
									</view>
								</uni-collapse-item>
								<uni-collapse-item title="辨识岗位" name="Docs guide">
									<u-button type="primary" @click="handleNewPost(item)" color="#3d4b70">新增辨识层级</u-button>
									<view v-if="item.Nav_DetailPosts&&item.Nav_DetailPosts.length>0">

										<view v-for="(item1,index1) in item.Nav_DetailPosts.filter(i => !i.IS_DELETED)" style="padding: 10px;">
											<u-form-item :label="(index1+1)+' . '" prop="HIDDEN_PLACE" border-bottom>
												<!-- 	<u--input v-model="index1+1" disabled  disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
											</u--input> -->
												<u-icon @click="handleDelRowPost(item,item1)" name="trash" color="#ff4d4f" size="21" style="margin-right: 20px;margin-left: 20px;" slot="right"></u-icon>
											</u-form-item>
											<u-form-item label="辨识层级" prop="HIDDEN_PLACE" border-bottom @click="handleChangeUnit(item1,'SKDepartmentTypeEnum')">
												<u--input v-model="item1.DEPARTMENT_TYPE_NAME" disabled placeholder="请选择辨识层级" disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
												</u--input>
												<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
												</u-icon>
											</u-form-item>
											<u-form-item label="辨识部门" prop="HIDDEN_PLACE" border-bottom @click="handleShowSheet({title: '辨识部门', name: 'Nav_Department',itemData:item1})">
												<u--input v-model="(item1.Nav_Department||{}).NAME" disabled placeholder="请选择辨识部门" disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
												</u--input>
												<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
												</u-icon>
											</u-form-item>
											<u-form-item label="辨识岗位" prop="HIDDEN_PLACE" border-bottom @click="handleShowSheet({title: '辨识岗位', name: 'Nav_ResultPostDets',itemData:item1})">
												<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
												</u-icon>
											</u-form-item>
											<u-textarea v-model="item1.Nav_ResultPostDetsName" disabled autoHeight placeholder="请选择辨识岗位"></u-textarea>
										</view>
									</view>
								</uni-collapse-item>
							</uni-collapse>
							<u-form-item label="应急处置" prop="HIDDEN_PLACE" border-bottom>
							</u-form-item>
							<u--textarea v-model="item.EMERGENCY" placeholder="请填写应急处置" autoHeight maxlength="-1"></u--textarea>
							<u-form-item label="新增标识" prop="HIDDEN_PLACE" border-bottom>
								<u--input v-model="item.MARK_NAME" disabled disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
								</u--input>
							</u-form-item>
							<u-form-item label="操作" prop="HIDDEN_PLACE">
								<u-icon style="margin-left: 4px;" slot="right" name="eye" size="16" @click="showDetail(item.ID)">
								</u-icon>
							</u-form-item>
						</view>
					</view>
					<view style="padding: 10px 16px;display: flex;flex-direction: row;">
						<u-button type="primary" @click="handleNewCheckContent" color="#3d4b70">新增检查区域</u-button>
						<u-button type="primary" @click="handleNewCheckList" color="#3d4b70" style="margin-left: 5px;">导入企业库内容</u-button>
					</view>
				</u--form>
			</view>
			<view style="padding: 10px 16px;display: flex;flex-direction: row;" v-if="stepsPageList === 1" class="bottom-button">
				<u-button type="primary" @click="stepReduce" color="#3d4b70" :plain="true" style="margin-right: 5px;">上一步</u-button>
				<u-button type="primary" @click="submit" color="#3d4b70" style="margin-left: 5px;">提交</u-button>
			</view>
			<u-picker :show="showPopupUnit" :columns="UnitLists" @confirm="confirmUnit" @cancel="cancelUnit" :defaultIndex="UnitDefaultIndex" keyName="NAME"></u-picker>
			<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" @cancel="cacelDel" :showCancelButton="true" title="确认删除？"></u-modal>
			<u-datetime-picker :show="showPopupRecitifyDate" v-model="dateRecitifyTime" mode="date" @confirm="confirmRecitifyDate" @cancel="cancelRecitifyDate"></u-datetime-picker>
			<query-selector :show="showPopupStep" :total="curTotalStep" :lists="stepLists" :defaultValue="currentOperateStep.NAME" @close="handleClosePopupStep" @search="handleSearchStep" @select="handleSelectedStep" />
			<query-selector :multiple="selectorInfo.isMultiple" :show="selectorInfo.showPopup" :title="selectorInfo.title" :lists="selectorInfo.dataLists" :defaultChecked="selectorInfo.defaultChecked"
				@search="handleSearch" @select="handleSelected" @close="selectorInfo.showPopup=false" :total="selectorInfo.totalCount" />
		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		extendIgnoreDataRule,
		guid,
		initFilter,
		initFilterGroup,
		handleOriginalArray,
		transformData
	} from '../../../../utils/common'
	import {
		FMProductionUnit,
		SKEffective,
		SKMarkEnum,
		CheckPeriods,
		CheckLevels,
		MineTypeIndex,
		MineTypeName
	} from '../../../../utils/enums.js'
	import {
		getEnum,
		GetEnumAnyOrder
	} from '../../../../services/common';
	import {
		EvaIdentifyResGet,
		IdentifyResFullUpdate,
		getUserLists,
		GetSKRequestInfo,
		GetRiskAreaInfo,
		GetDepartmentInfo,
		GetPostOrderPaged,
		GetRiskTypeInfo,
		GetRiskNameInfo
	} from '../../../../services/apply/subPages/SK/SKServices.js'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import stepTitle from '@/components/custom/step-title.vue'
	import swipeActionItem from '../../../../uni_modules/uview-ui/libs/config/props/swipeActionItem';
	export default {
		components: {
			stepTitle,
		},
		data() {
			return {
				showDelModalIndex: undefined,
				showPopupDate: false,
				showPopupRecitifyDate: false,
				listPropUpload: ['NOTIFY_ID'],
				listPropValUpload: [],
				ORG_ID: uni.getStorageSync('orgId'),
				currentOperateStep: {},
				showPopupStep: false,
				stepLists: [],
				curTotalStep: 0,
				showPopupUnit: false,
				stepLoad: true,
				UnitLists: [],
				UnitDefaultIndex: [0],
				selectorInfo: {
					name: 'user',
					isMultiple: false,
					showPopup: false,
					totalCount: 0,
					title: '考核结果选择',
					dataItem: {},
					index: 0,
					columns: [],
					dataLists: [],
					defaultText: '',
					defaultChecked: []
				},
				dataModel: {
					YEAR: '',
					START_DATE: '',
					END_DATE: '',
					Nav_Require: {
						NAME: ''
					},
					RequireName: '',
					IDENTIFY_EVALUATION_PLAN_ID: null,
					IDENTIFY_ID: null,
					Nav_Files: [],
					Nav_Details: [{
						showPack: false,
						MineType: '',
						Nav_Area: {
							NAME: ''
						},
						RISK_NAME: '',
						RISK_DESCRIPTION: '',
						Nav_Type: {
							NAME: ''
						},
						DEPARTMENT_TYPE: '',
						IDENTIFY_DEPARTMENT: '',
						IDENTIFY_POST: '',
						MEASURE: '',
						EMERGENCY: '',
						MARK: '',
					}]
				},
				model: {
					ORG_ID: '',
					YEAR: '',
					START_DATE: '',
					END_DATE: '',
					Nav_Require: {
						NAME: ''
					},
					RequireName: '',
					IDENTIFY_EVALUATION_PLAN_ID: null,
					IDENTIFY_ID: null,
					Nav_Files: [],
					Nav_Details: [{
						MineType: '',
						Nav_Area: {
							NAME: ''
						},
						RISK_NAME: '',
						RISK_DESCRIPTION: '',
						Nav_Type: {
							NAME: ''
						},
						DEPARTMENT_TYPE: '',
						IDENTIFY_DEPARTMENT: '',
						IDENTIFY_POST: '',
						MEASURE: '',
						EMERGENCY: '',
					}]

				},
				dateRecitifyTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
				stepsText: ['发起', '审批', '归档'],
				stepsPage: 0,
				stepsPageList: 0,
				TaskID: '',
				nowName: '',
				nowItem: '',
				nowIndex: 0,
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {} // 存储枚举文本列表（用于下拉选择等场景）

			}
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			this.ID = option.ID ? option.ID : '';
			this.fetchEnums(['SKMarkEnum', 'SKEnableStatusEnum', 'SKDepartmentTypeEnum']);
		},
		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 = {}
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "")
				extendRule(json, 'ID', 1, this.ID);
				extendInclude(json, 'Nav_Require');
				extendInclude(json, 'Nav_Requires');
				extendInclude(json, 'Nav_Requires.Nav_Require');
				extendInclude(json, 'Nav_Files.Nav_ImgFile');
				extendInclude(json, 'Nav_Details');
				extendInclude(json, 'Nav_Details.Nav_Area');
				extendInclude(json, 'Nav_Details.Nav_ProductionUnit');
				extendInclude(json, 'Nav_Details.Nav_Type');
				extendInclude(json, 'Nav_Details.Nav_RiskName');
				extendInclude(json, 'Nav_Details.Nav_DetailMeasures');
				extendIgnoreDataRule(json)
				// extendRule(json, 'TASK_ID', 1, this.TaskID);
				EvaIdentifyResGet(json).then(res => {
					this.dataModel = res;
					this.stepsPage = res.STATUS == 0 ? 0 : res.STATUS == 20 ? 1 : 2
					this.dataModel.START_DATE = uni.$u.timeFormat(res.START_DATE, 'yyyy-mm-dd')
					this.dataModel.END_DATE = uni.$u.timeFormat(res.END_DATE, 'yyyy-mm-dd')
					let Nav_RequiresName = ''
					if (this.dataModel.Nav_Requires && this.dataModel.Nav_Requires.length > 0) {
						this.dataModel.Nav_Requires.map(item => {
							if (item.Nav_Require && item.Nav_Require.NAME !== null) {
								Nav_RequiresName += item.Nav_Require.NAME + ' ';
							}
						})
					}
					this.dataModel.Nav_RequiresName = Nav_RequiresName
					this.dataModel.Nav_Details.map(item => {
						item['showPack'] = false
						item.MARK_NAME = item.MARK !== undefined ? this.enumsData['SKMarkEnum'].find(item1 => item1.code === item.MARK).name : '';

						if (item.Nav_DetailPosts && item.Nav_DetailPosts.length > 0) {
							item.Nav_DetailPosts.map(item1 => {
								item1.DEPARTMENT_TYPE_NAME = item1.DEPARTMENT_TYPE !== undefined ? this.enumsData['SKDepartmentTypeEnum'].find(item2 => item2.code === item1.DEPARTMENT_TYPE).name :
									'';
								if (item1.Nav_ResultPostDets && item1.Nav_ResultPostDets.length > 0) {
									let Nav_ResultPostDetsName = ''
									if (item1.Nav_ResultPostDets && item1.Nav_ResultPostDets.length > 0) {
										item1.Nav_ResultPostDets.map(item2 => {
											if (item2.Nav_Post && item2.Nav_Post.NAME !== null) {
												Nav_ResultPostDetsName += item2.Nav_Post.NAME + ' ';
											}
										})
									}
									item1.Nav_ResultPostDetsName = Nav_ResultPostDetsName
								}
							})

						}
					})
					this.stepLoad = false

				})
			},
			handleDelRowMeasures(item, item1) {
				item1.IS_DELETED = true
				this.$forceUpdate()
			},
			handleDelRowPost(item, item1) {
				item1.IS_DELETED = true
				this.$forceUpdate()
			},
			handleNewMeasures(item) {
				item.Nav_DetailMeasures.unshift({
					NUM: 1,
					ID: guid(),
					RISK_IDENTIFY_DETAIL_ID: item.ID,
					MEASURE: '',
					IS_DELETED: false,
				})
			},
			handleNewPost(item) {
				item.Nav_DetailPosts.unshift({
					DEPARTMENT_TYPE: '',
					ID: guid(),
					RISK_IDENTIFY_DETAIL_ID: item.ID,
					Nav_Department: {
						NAME: ''
					},
					DEPARTMENT_ID: '',
					Nav_ResultPostDets: [],
					IS_DELETED: false,
				})
			},
			showDetail(id) {
				uni.navigateTo({
					url: 'SK003Show?ID=' + id + '&taskID=' + this.TaskID
				})
			},
			handlePack(item) {
				item.showPack = item.showPack == false ? true : false
				this.$forceUpdate()

			},
			cancelUnit() {
				this.showPopupUnit = false
			},
			handleChangeUnit(item, name) {
				this.nowName = name
				this.nowItem = item
				if (name == 'MinType') {
					const json = initFilter(this.ORG_ID)
					getRequest(json, "/FM/UserProductionUnitSet/OrderPaged").then(res => {
						this.UnitLists = [res]
					})
				} else {
					this.UnitLists = [this.enumsData[name]]
				}
				this.showPopupUnit = true
			},
			confirmUnit(e) {
				console.log(e, '999')
				if (this.nowName == 'MinType') {
					this.nowItem.Nav_ProductionUnit = e.value[0]
					this.nowItem.PRODUCTION_UNIT_ID = e.value[0].ID
				} else {
					this.nowItem.DEPARTMENT_TYPE = e.value[0].code
					this.nowItem.DEPARTMENT_TYPE_NAME = e.value[0].name
				}
				this.showPopupUnit = false
			},
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0, p.pageIndex ?? 1)
				let dataSelect = []
				// this.selectorInfo.defaultChecked = []
				var defaultChecked = []
				this.selectorInfo.isMultiple = false
				if (p.val) {
					extendRule(json, 'NAME', 9, p.val);
				}
				json.Limit = 20
				if (p.pageIndex) {
					json.Start = (p.pageIndex - 1) * json.Limit;
				}
				json.Sort = "NAME"
				if (p.name == "Nav_Area") {
					dataSelect = await GetRiskAreaInfo(json).then(res => {
						console.log(res, '99')
						this.selectorInfo.totalCount = res.TotalCount
						if (res.Data != undefined && res.Data.length > 0) {
							for (let i = 0; i < res.Data.length; i++) {
								res.Data[i].name = res.Data[i].NAME
							}
						}
						return res.Data
					})
				} else if (p.name == "Nav_Type") {
					dataSelect = await GetRiskTypeInfo(json).then(res => {
						if (res.Data != undefined && res.Data.length > 0) {
							for (let i = 0; i < res.Data.length; i++) {
								res.Data[i].name = res.Data[i].NAME
							}
						}
						return res.Data
					})
				} else if (p.name == "Nav_Department") {
					dataSelect = await GetDepartmentInfo(json).then(res => {
						if (res.Data != undefined && res.Data.length > 0) {
							for (let i = 0; i < res.Data.length; i++) {
								res.Data[i].name = res.Data[i].NAME
							}
						}
						return res.Data
					})
				} else if (p.name == "Nav_ResultPostDets") {
					this.selectorInfo.isMultiple = true
					if (p.itemData.DEPARTMENT_ID) {
						extendRule(json, 'DEPARTMENT_ID', 1, p.itemData.DEPARTMENT_ID);
					}
					json.SelectField = ["ID", "NAME", "NAME"]
					dataSelect = await GetPostOrderPaged(json).then(res => {
						if (res.Data != undefined && res.Data.length > 0) {
							for (let i = 0; i < res.length; i++) {
								res[i].name = res.Data[i].NAME
								res[i].code = res.Data[i].CODE
							}
						}
						return res.Data
					})
					if (p.itemData.Nav_ResultPostDets && p.itemData.Nav_ResultPostDets.length > 0) {
						// this.selectorInfo.defaultChecked = []

						p.itemData.Nav_ResultPostDets.filter(i => !i.IS_DELETED).forEach(e => {
							if (e.Nav_Post != null && e.Nav_Post.NAME != null)
								defaultChecked.push(e.Nav_Post)
						})
					} else {
						defaultChecked = null
					}
				}
				if (defaultChecked == null)
					defaultChecked = []
				if (dataSelect.length) {
					this.selectorInfo = {
						itemData: p.itemData != undefined ? p.itemData : this.selectorInfo
							.itemData, //itemData: p.itemData,  搜索的时候  p.itemData为空  赋值修改 为 她自己本身 this.selectorInfo.itemData
						isMultiple: this.selectorInfo.isMultiple,
						totalCount: this.selectorInfo.totalCount,
						showPopup: true,
						title: p.title,
						name: p.name,
						dataLists: dataSelect,
						defaultChecked: defaultChecked
					}
				} else {
					// 暂无数据
				}
			},
			//数据加载
			handleSearch(val, pageIndex) {
				var p = {
					name: this.selectorInfo.name,
					title: this.selectorInfo.title,
					val: val,
					pageIndex: pageIndex,
					index: this.selectorInfo.index
				}
				this.handleShowSheet(p)
			},

			handleSelected(e) {
				this.selectorInfo.showPopup = false
				console.log(e, '999')
				if (this.selectorInfo.name == 'Nav_Area') {

					this.selectorInfo.itemData.Nav_Area = e
					this.selectorInfo.itemData.AREA_ID = e.ID
				} else if (this.selectorInfo.name == 'Nav_Type') {
					this.selectorInfo.itemData.Nav_Type = e
					this.selectorInfo.itemData.TYPE_ID = e.ID
				} else if (this.selectorInfo.name == 'Nav_Department') {
					this.selectorInfo.itemData.Nav_Department = e
					this.selectorInfo.itemData.DEPARTMENT_ID = e.ID
				} else if (this.selectorInfo.name == 'Nav_ResultPostDets') {
					let listArea = []
					let areaShow = ''
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (item.name != null || item.NAME != null) {
								if (i > 0) {
									areaShow += ' '
								}
								listArea.push({
									ID: guid(),
									RISK_IDENTIFY_DETAIL_RESULT_POST_ID: this.selectorInfo.itemData.ID,
									POST_ID: item.ID,
									ORG_ID: item.ORG_ID,
									Nav_Post: item
								})
								areaShow += item.NAME
							}
						})
					}
					this.selectorInfo.itemData.Nav_ResultPostDets = listArea
					this.selectorInfo.itemData.Nav_ResultPostDetsName = areaShow
				}


			},
			stepAdd() {
				if (!this.dataModel.YEAR) {
					uni.showToast({
						title: '年度不能为空',
						icon: 'none'
					})
					return
				}
				if (!this.dataModel.START_DATE) {
					uni.showToast({
						title: '辨识开始时间不能为空',
						icon: 'none'
					})
					return
				}
				if (!this.dataModel.END_DATE) {
					uni.showToast({
						title: '辨识结束时间不能为空',
						icon: 'none'
					})
					return
				}
				if (!this.dataModel.Nav_Require.NAME) {
					uni.showToast({
						title: '辨识要求不能为空',
						icon: 'none'
					})
					return
				}

				this.stepsPageList = this.stepsPageList + 1
			},
			stepReduce() {
				this.stepsPageList = this.stepsPageList - 1
			},
			handleNewCheckContent() {
				this.dataModel.Nav_Details.push({
					showPack: false,
					Nav_ProductionUnit: {
						NAME: ''
					},
					PRODUCTION_UNIT_ID: '',
					Nav_Area: {
						NAME: ''
					},
					ORG_ID: this.ORG_ID,
					RISK_NAME: '',
					RISK_DESCRIPTION: '',
					Nav_Type: {
						NAME: ''
					},
					DEPARTMENT_TYPE: '',
					IDENTIFY_DEPARTMENT: '',
					IDENTIFY_POST: '',
					MEASURE: '',
					EMERGENCY: '',
					Nav_DetailMeasures: [],
					Nav_DetailPosts: [],
					MARK: this.enumsData['SKMarkEnum'].find(item1 => item1.name === '新增').code,
					MARK_NAME: this.enumsData['SKMarkEnum'].find(item1 => item1.name === '新增').name,
					ID: guid()

				})

				this.dataModel.Nav_Details = [...this.dataModel.Nav_Details]
			},
			handleNewCheckList() {
				// 将现有数据传递给选择页面用于去重判断
				const existingData = this.dataModel.Nav_Details.map(item => ({
					PRODUCTION_UNIT_ID: item.PRODUCTION_UNIT_ID,
					AREA_ID: item.AREA_ID,
					RISK_NAME: item.RISK_NAME
				}))

				uni.navigateTo({
					url: `/pages/apply/subPages/SK/enterprise/enterpriseLibarary?existingData=${encodeURIComponent(JSON.stringify(existingData))}`,
					events: {
						// 监听页面返回的数据
						confirm: (data) => {
							this.handleEnterpriseSelection(data.selectedItems)
						}
					}
				})

			},
			// 新增处理企业库选择结果的方法
			handleEnterpriseSelection(selectedItems) {
				if (!selectedItems || selectedItems.length === 0) return

				const newDetails = []
				const duplicateItems = []

				selectedItems.forEach(enterpriseItem => {
					// 检查是否与现有数据重复
					const isDuplicate = this.dataModel.Nav_Details.filter(i => !i.IS_DELETED).some(existingItem =>
						existingItem.AREA_ID === (enterpriseItem.AREA_ID || '') &&
						existingItem.PRODUCTION_UNIT_ID === (enterpriseItem.PRODUCTION_UNIT_ID || '') &&
						existingItem.RISK_NAME === (enterpriseItem.RISK_NAME || '')
					)

					if (isDuplicate) {
						duplicateItems.push({
							生产单元: enterpriseItem.Nav_ProductionUnit?.NAME || '',
							辨识区域: enterpriseItem.Nav_Area?.NAME || '',
							风险名称: enterpriseItem.RISK_NAME || ''
						})
						return
					}
					const convertedMeasures = (enterpriseItem.Nav_Details || [])
						.map((item, index) => ({
							...item,
							MEASURE: item.MEASURES_NAME, // 措施名称
						}))

					const convertedItem = {
						showPack: false,
						PRODUCTION_UNIT_ID: enterpriseItem.PRODUCTION_UNIT_ID || '',
						Nav_ProductionUnit: enterpriseItem.Nav_ProductionUnit || {
							NAME: ''
						},
						AREA_ID: enterpriseItem.AREA_ID || '',
						Nav_Area: enterpriseItem.Nav_Area || {
							NAME: ''
						},
						RISK_NAME: enterpriseItem.RISK_NAME || '',
						Nav_DetailMeasures: convertedMeasures,
						Nav_DetailPosts: [],
						RISK_DESCRIPTION: enterpriseItem.RISK_DESCRIPTION || '',
						TYPE_ID: enterpriseItem.TYPE_ID || '',
						Nav_Type: enterpriseItem.Nav_Type || {
							NAME: ''
						},
						MEASURE: enterpriseItem.MEASURE || '',

						EMERGENCY: enterpriseItem.EMERGENCY || '',
						MARK: this.enumsData['SKMarkEnum'].find(item1 => item1.name === '新增').code,
						MARK_NAME: this.enumsData['SKMarkEnum'].find(item1 => item1.name === '新增').name,
						ORG_ID: this.ORG_ID,
						ID: guid()
					}
					newDetails.push(convertedItem)
				})
				// 处理重复项提示
				if (duplicateItems.length > 0) {
					const duplicateCount = duplicateItems.length
					let message = ''
					if (duplicateCount === 1) {
						const dup = duplicateItems[0]
						message = `以下数据已存在，无法重复导入：\n生产单元：${dup.生产单元}\n辨识区域：${dup.辨识区域}\n风险名称：${dup.风险名称}`
					} else {
						message = `有 ${duplicateCount} 条数据已存在，无法重复导入：\n`
						duplicateItems.slice(0, 3).forEach((dup, i) => {
							message += `${i+1}. ${dup.生产单元} / ${dup.辨识区域} / ${dup.风险名称}\n`
						})
						if (duplicateCount > 3) {
							message += `...等共 ${duplicateCount} 条`
						}
					}
					setTimeout(() => {
						uni.showModal({
							title: '重复数据提示',
							content: message,
							showCancel: false,
							confirmText: '知道了'
						})
					}, 100) // 延迟100毫秒
				}

				if (newDetails.length > 0) {
					this.dataModel.Nav_Details.push(...newDetails)
					setTimeout(() => {
						uni.showToast({
							title: `成功导入 ${newDetails.length} 条数据${duplicateItems.length > 0 ? `，跳过 ${duplicateItems.length} 条重复数据` : ''}`,
							icon: 'success',
							duration: 2000
						})
					}, 100)

				} else if (duplicateItems.length > 0) {
					setTimeout(() => {
						uni.showToast({
							title: `所选数据均重复，未导入任何内容`,
							icon: 'none',
							duration: 2000
						})
					}, 100)
				}
			},

			handleDelRowBefore(item) {
				item.IS_DELETED = true
				this.$forceUpdate()



			},
			confirmDel() {
				this.dataModel.Nav_Details.splice(this.nowIndex, 1)
				this.showDelModalIndex = undefined

			},
			cacelDel() {
				this.showDelModalIndex = undefined
			},
			cancelRecitifyDate() {
				this.showPopupRecitifyDate = false
			},
			handleChangeRecitify(name) {
				this.nowName = name
				this.showPopupRecitifyDate = true
			},
			confirmRecitifyDate(e) {
				if (this.nowName == 'start') {
					this.dataModel.START_DATE = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd')

				} else {
					this.dataModel.END_DATE = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd')
				}
				this.dateRecitifyTime = uni.$u.timeFormat(e.value,
					'yyyy-mm-dd')

				this.showPopupRecitifyDate = false
			},
			handleChangeStep(item, name) {
				this.currentOperateStep = {}
				this.showPopupStep = true
				this.nowName = name
				this.nowItem = item
				this.handleSearchStep('init')
			},
			handleClosePopupStep() {
				this.showPopupStep = false
				// this.showPopupCertificate = false
			},
			handleSearchStep(val, pageIndex) {
				let requestInfo = this.nowName == 'Area' ? GetRiskAreaInfo : this.nowName == 'RiskName' ? GetRiskNameInfo : this.nowName == 'Category' ? GetRiskTypeInfo : this.nowName == 'Nav_ResultPostDets' ?
					GetPostOrderPaged : GetDepartmentInfo
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0, pageIndex ?? 1)
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * json.Limit;
				}
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}

				requestInfo(json).then(res => {
					// if (res.IsSuccessful) {
					this.stepLists = (res.Data || res).map(i => {
						return {
							...i,
							id: i.ID,
							name: i.NAME,
						}
					})
					this.curTotalStep = res.TotalCount
					// }
				})


			},
			handleSelectedStep(val) {
				if (this.nowName == 'demand') {
					this.dataModel.Nav_Require.NAME = val.NAME
					this.dataModel.REQUIRE_ID = val.ID
					this.dataModel.RequireName = val.NAME
				} else if (this.nowName == 'Area') {
					this.dataModel.Nav_Details[this.nowIndex[0]].Nav_Area.NAME = val.NAME
					this.dataModel.Nav_Details[this.nowIndex[0]].AREA_ID = val.ID
				} else if (this.nowName == 'RiskName') {
					this.dataModel.Nav_Details[this.nowIndex[0]].Nav_RiskName.NAME = val.NAME
					this.dataModel.Nav_Details[this.nowIndex[0]].RISK_NAME_ID = val.ID
				} else {
					this.dataModel.Nav_Details[this.nowIndex[0]].Nav_Type.NAME = val.NAME
					this.dataModel.Nav_Details[this.nowIndex[0]].TYPE_ID = val.ID
				}
				this.showPopupStep = false

			},

			submit() {
				let i = 1
				for (let item of this.dataModel.Nav_Details.filter(i => !i.IS_DELETED)) {
					if (!item.PRODUCTION_UNIT_ID) {
						uni.showToast({
							title: '顺序' + i + '生产单元不能为空',
							icon: 'none'
						})
						return
					}
					if (!item.Nav_Area.NAME) {
						uni.showToast({
							title: '顺序' + i + '辨识区域不能为空',
							icon: 'none'
						})
						return
					}
					if (!item.RISK_NAME) {
						uni.showToast({
							title: '顺序' + i + '风险名称不能为空',
							icon: 'none'
						})
						return
					}
					// if (!item.Nav_RiskName.NAME) {
					// 	uni.showToast({
					// 		title: '顺序'+i+'风险名称不能为空',
					// 		icon: 'none'
					// 	})
					// 	return
					// }
					if (!item.RISK_DESCRIPTION) {
						uni.showToast({
							title: '顺序' + i + '风险描述不能为空',
							icon: 'none'
						})
						return
					}
					if (!item.Nav_Type.NAME) {
						uni.showToast({
							title: '顺序' + i + '风险类别不能为空',
							icon: 'none'
						})
						return
					}
					i++
				}

				this.model =JSON.parse(JSON.stringify(this.dataModel))

				this.model.ORG_ID = this.ORG_ID
				delete this.model.Nav_ApplyDepartment
				delete this.model.Nav_ApplyUser
				delete this.model.Nav_Require
				delete this.model.Nav_RequiresName

				// let arr = []

				this.model.Nav_Details.map(item => {
					delete item.Nav_Area
					delete item.Nav_ProductionUnit
					delete item.Nav_Type
					delete item.MARK_NAME
					delete item.showPack
					if (item.Nav_DetailPosts && item.Nav_DetailPosts.length > 0) {
						item.Nav_DetailPosts.map(item1 => {
							delete item1.Nav_Department
							delete item1.DEPARTMENT_TYPE_NAME
							delete item1.Nav_ResultPostDetsName
							if (item1.Nav_ResultPostDets && item1.Nav_ResultPostDets.length > 0) {
								item1.Nav_ResultPostDets.map(item2 => {
									delete item2.Nav_Post
								})
							}
						})
					}
				})
				// this.model = {
				// 	ORG_ID: this.ORG_ID,
				// 	YEAR: this.dataModel.YEAR,
				// 	START_DATE: this.dataModel.START_DATE,
				// 	END_DATE: this.dataModel.END_DATE,
				// 	REQUIRE_ID: this.dataModel.REQUIRE_ID,
				// 	RequireName: this.dataModel.RequireName,
				// 	IDENTIFY_EVALUATION_PLAN_ID: this.dataModel.IDENTIFY_EVALUATION_PLAN_ID,
				// 	IDENTIFY_ID: this.dataModel.IDENTIFY_ID,
				// 	Nav_Files: this.dataModel.Nav_Files,
				// 	Nav_Details: arr
				// }
				this.model.ID = this.ID
				this.model.TaskID = this.TaskID
				this.model.PUBLISH = "SaveAndNotify";
				IdentifyResFullUpdate(this.model).then(res => {
					if (res) {
						uni.$showMsgFunc('操作成功!', () => {
							uni.navigateBack()
						}, 'success', 1000)
					}
				})


			}

		}



	}
</script>

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