<template>
	<view class="todo-page">
		<view class="background"></view>
		<!-- <step-title :stepPage="stepsPage" :stepText="stepsText"></step-title> -->
		<view class="allview">
			<view class="card" v-if="stepsPageList === 0">
				<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 required label="生产单元：" prop="Product_Unit" >
						<u--input v-model="model.Product_Unit" disabled disabledColor="#ffffff"  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 required label="检查内容:">
					</u-form-item>
					<u-textarea v-model="model.CHECKCONTENT"  disabled>
					</u-textarea>
				</u--form>
				<u--form labelWidth="auto" :model="model" 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>
					<uni-collapse :border="false" accordion>
						<view v-for="(item, index) in model.Nav_ListCheckQuestion" :key="index">
							<uni-collapse-item title-border="none" :border="false">
								<template v-slot:title>
									<view class="uni-collapse-item__title-box">
										<view class="uni-collapse-item__title-text">
											{{item.DESCREPTION?index+1+'.'+item.DESCREPTION:index+1+'.'}}
										</view>
										<view @click.stop>
											<u-icon @click="handleDelRowBefore(index)" name="trash" color="#ff4d4f" size="21" style="margin-right: 10px;"></u-icon>
										</view>
									</view>
								</template>
								<view class="content" style="padding-left: 10px;">
									<u-form-item label='顺序' prop="NUM" borderBottom>
										<u-number-box integer v-model="item.NUM" :min="-10000" :max="10000" slot="right"></u-number-box>
									</u-form-item>

									<u-form-item required label="隐患描述：" prop="CHECK_TIME">
									</u-form-item>
									<u-textarea v-model="item.DESCREPTION" placeholder="请填写隐患描述">
									</u-textarea>
									<!-- <u--textarea v-model="item.Nav_Question.DESCREPTION" disabled placeholder="请选择隐患描述" maxlength="-1"></u--textarea> -->
									<u-form-item required label="隐患等级" prop="QUESTION_LEVEL" @click="handleChange('SKHiddenLevel',item)" border-bottom>
										<u--input v-model="item.QUESTION_LEVELName" disabled placeholder="请选择隐患等级" suffixIcon="arrow-down" suffixIconStyle="font-size: 12px" disabledColor="#ffffff" inputAlign="right"
											fontSize="14px" border="none">
										</u--input>
									</u-form-item>
									<u-form-item required label="整改措施" prop="HIDDEN_PLACE" border-bottom>
										<u--input v-model="item.DEMAND" placeholder="请填写整改措施" disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
										</u--input>
									</u-form-item>

								</view>


							</uni-collapse-item>
						</view>
					</uni-collapse>

					<view style="padding: 10px 16px;display: flex;flex-direction: row;">
						<u-button type="primary" @click="handleNewCheckArea" 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;" class="bottom-button">
				<u-button type="primary" @click="submit" color="#3d4b70" :loading="stepLoad">保存</u-button>
			</view>

			<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" @cancel="cacelDel" :showCancelButton="true" title="确认删除？"></u-modal>
			<u-datetime-picker :show="showPopupDate" v-model="dateTime" mode="datetime" @confirm="confirmDate" @cancel="cancelDate"></u-datetime-picker>
			<people-selector :defaultChecked="peopleSelectOption.defaultChecked" :show="peopleSelectOption.showSelector" @select="handleSelectorPeople" @close="peopleSelectOption.showSelector = false">
			</people-selector>
			<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" />
			<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" @close="comPickerInfo.showSheet=false" @cancel="comPickerInfo.showSheet=false" keyName="NAME"></u-picker>

		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		extendIgnoreDataRule,
		guid,
		initFilter,
		initFilterGroup
	} from '../../../../utils/common'
	import {
		FMProductionUnit,
		CheckPeriods,
		CheckLevels,
		MineTypeIndex,
		MineTypeName
	} from '../../../../utils/enums.js'
	import {
		GetCheckContentsInfo,
		SKCheckContentsFullUpdate,
		GetHiddenScripList,
		GetNewRiskAreaInfo,
		GetCheckContentsNew
	} 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';
	import {
		getEnum
	} from '../../../../services/common';
	export default {
		components: {
			stepTitle,
		},
		data() {
			return {
				showDelModalIndex: undefined,
				showDelModalIndex1: undefined,
				subsectionList: ['无隐患', '有隐患', '不涉及'],
				curNow: 1,
				RiskLevel: ['一般', '重大'],
				showPopupUnit: false,
				UnitDefaultIndex: [0],
				showPopupRiskLevel: false,
				RiskLevelDefaultIndex: [0],
				UnitLists: [],
				TypeLists: [],
				showPopupType: false,
				isMultiple: false,
				defaultChecked: [],
				TypeDefaultIndex: [0],
				PeriodLists: [],
				showPopupPeriod: false,
				PeriodDefaultIndex: [0],
				LevelLists: [],
				showPopupStep: false,
				showPopupArea: false,
				showPopupLevel: false,
				stepLoad: true,
				curTotalStep: 0,
				curTotalArea: 0,
				stepLists: [],
				areaLists: [],
				LevelDefaultIndex: [0],
				showPopupDate: false,
				listPropUpload: ['NOTIFY_ID'],
				listPropValUpload: [],
				ORG_ID: uni.getStorageSync('orgId'),
				model: {
					Nav_Files: [],
					Check_Type: '',
					Check_Period: '',
					Check_Level: '',
					SECURITY_INSPECTION_RECORD_ID: null,
					CHECK_TIME: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					Nav_ListCheckQuestion: [],
					CHECK_CONTENTS_ID: ''
				},
				selectorInfo: {
					name: 'user',
					isMultiple: false,
					showPopup: false,
					totalCount: 0,
					title: '考核结果选择',
					dataItem: {},
					index: 0,
					columns: [],
					dataLists: [],
					defaultText: '',
					defaultChecked: []
				},
				peopleSelectOption: {
					showSelector: false,
					value: null,
					index: 0,
					defaultChecked: []
				},
				comPickerInfo: {
					showSheet: false,
					dataItem: {},
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				dateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
				stepsText: ['发起', '确认', '归档'],
				stepsPage: 0,
				stepsPageList: 0,
				Pu: '',
				Check_Type_ID: '',
				TypeListres: {},
				TaskID: '',
				ID: '',
				poparr: '',
				currentOperateStep: {},
				currentOperateArea: {},
				chooseCheckContent: '',
				chooseCheckArea: '',
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {} // 存储枚举文本列表（用于下拉选择等场景）

			}
		},
		onLoad(option) {
			this.model.CHECK_CONTENTS_ID = option.CHECK_CONTENTS_ID ? option.CHECK_CONTENTS_ID : ''
			this.TaskID = option.taskID ? option.taskID : '';
			this.ID = option.ID ? option.ID : '';
			this.fetchEnums(['SKProductionUnit', 'SKHiddenLevel']);

		},
		methods: {
			async fetchEnums(enumNames) {
				try {
					// 存储所有枚举请求的Promise
					const enumPromises = enumNames.map(name => {
						return getEnum({
							name
						}).then(res => {
							// 统一处理枚举格式：添加name/code字段，便于后续映射
							return {
								enumName: name,
								data: res.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'
					});
				}
			},
			getNotNew() {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "")
				extendRule(json, 'ID', 1, this.model.CHECK_CONTENTS_ID)
				extendInclude(json, 'Nav_Area');
				extendInclude(json, 'Nav_ContentsBasics');
				extendInclude(json, 'Nav_ContentsBasics.Nav_Law');
				extendInclude(json, 'Nav_ListCheckQuestion');
				extendIgnoreDataRule(json)
				GetCheckContentsNew(json).then(res => {
					this.stepLoad = false
					this.model = res
					this.model.Product_Unit = res.MineType !== undefined ? this.enumsData['SKProductionUnit'].find(item => item.code === res.MineType).name : '';
					if (this.model.Nav_ListCheckQuestion && this.model.Nav_ListCheckQuestion.length > 0) {
						this.model.Nav_ListCheckQuestion = this.model.Nav_ListCheckQuestion.sort((a, b) => a.NUM - b.NUM);
						this.model.Nav_ListCheckQuestion.map(item => {
							item.QUESTION_LEVELName = item.QUESTION_LEVEL !== undefined ? this.enumsData['SKHiddenLevel'].find(item1 => item1.code === item.QUESTION_LEVEL).name : '';
						})
					}

				})
			},

			loadData() {
				if (this.model.CHECK_CONTENTS_ID) {
					this.getNotNew()
				} else {
					this.model.ID = guid()
					this.isLoadOK = false
					this.stepLoad = false
					this.$forceUpdate()
				}

			},

			stepAdd() {
				if (!this.model.Product_Unit) {
					uni.showToast({
						title: '请选择生产单元',
						icon: 'none'
					})
					return
				}
				if (!this.model.CHECKCONTENT) {
					uni.showToast({
						title: '请填写检查内容',
						icon: 'none'
					})
					return
				}
				this.stepsPageList = this.stepsPageList + 1
			},
			stepReduce() {
				this.stepsPageList = this.stepsPageList - 1
			},

			confirmDate(e) {
				this.model.CHECK_TIME = uni.$u.timeFormat(e.value,
					'yyyy-mm-dd hh:MM:ss')
				this.dateTime = this.model.CHECK_TIME
				this.showPopupDate = false
			},
			handleChangeDate() {
				this.showPopupDate = true
			},
			cancelDate() {
				this.showPopupDate = false
			},
			handleSelectorPeople(e) {
				const {
					index: key
				} = this.peopleSelectOption
				this.model.Nav_ListCheckQuestion[key].Nav_CheckRecordDetailUsers = e.map(i => {
					return {
						USER_ID: i.USER_ID,
						IS_DELETED: i.IS_DELETED,
						NAME: i.NAME,
						Nav_User: {
							NAME: i.NAME,
							ID: i.USER_ID
						}
					}
				})
			},
			handleShowUserSelector(item, index) {
				this.peopleSelectOption = {
					showSelector: true,
					value: item,
					index,
					defaultChecked: item.Nav_CheckRecordDetailUsers.map(i => {
						return {
							...i,
							NAME: i.Nav_User.NAME,
							USER_ID: i.Nav_User.ID,
						}
					})
				}
			},
			handleChange(name, item) {
				if (name == 'SKProductionUnit') {
					this.comPickerInfo = {
						showSheet: true,
						columns: [this.enumsText['SKProductionUnit']],
						name: name
					}
				} else if (name == 'SKHiddenLevel') {
					this.comPickerInfo = {
						showSheet: true,
						columns: [this.enumsText['SKHiddenLevel']],
						dataItem: item,
						name: name
					}
				}

			},
			onConfirmPicker(e) {
				if (this.comPickerInfo.name == 'SKProductionUnit') {
					this.model.Product_Unit = e.value[0]
					this.model.MineType = this.enumsData['SKProductionUnit'][e.indexs[0]].code
					this.comPickerInfo = {
						showSheet: false,
						columns: [],
						title: '',
						formIndex: undefined
					}


				} else if (this.comPickerInfo.name == 'SKHiddenLevel') {
					this.comPickerInfo.dataItem.QUESTION_LEVELName = e.value[0]
					this.comPickerInfo.dataItem.QUESTION_LEVEL = this.enumsData['SKHiddenLevel'][e.indexs[0]].code
					this.comPickerInfo = {
						showSheet: false,
						dataItem: this.comPickerInfo.dataItem,
						columns: [],
						title: '',
						name: '',
						formIndex: undefined
					}

				}


			},

			handleShowSheetForArea(item, todo) {
				const validDetails = this.model.Nav_ListCheckQuestion.filter(i => !i.IS_DELETED);
				const index = validDetails.indexOf(item);
				this.handleShowSheet({
					title: todo.title,
					name: todo.name,
					index: index
				});
			},
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0, p.pageIndex ?? 1)
				// const json = initFilter(this.ORG_ID, "", "", 0, p.pageIndex ?? 1)
				let dataSelect = []
				var defaultChecked = []
				this.selectorInfo.isMultiple = false





				json.Limit = 20
				if (p.pageIndex) {
					json.Start = (p.pageIndex - 1) * json.Limit;
				}
				json.Sort = 'NAME'
				// json.SelectField = ["ID", "NAME", "NAME", "CODE"]
				// json.Sort = "NAME"
				// json.Order = 1
				if (p.name == 'Nav_RiskArea') {
					if (p.val) {
						extendRule(json, 'NAME', 9, p.val);
					}
					// extendRule(json, 'DEVICE_STATUS', 1, '1');
					dataSelect = await GetNewRiskAreaInfo(json).then(res => {
						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
							}
						}
						return res.Data
					})
				} else if (p.name == 'Nav_Contents') {
					if (p.val) {
						extendRule(json, 'CHECKCONTENT', 9, p.val);
					}
					json.Sort = 'CHECKCONTENT'
					dataSelect = await GetCheckContentsInfo(json).then(res => {
						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].CHECKCONTENT
							}
						}
						return res.Data
					})
				} else if (p.name == 'Nav_Question') {
					if (p.val) {
						extendRule(json, 'DESCREPTION', 9, p.val);
					}
					let data = this.model.Nav_ListCheckQuestion[p.index]
					if (data.CHECK_CONTENTS_ID && data.CHECK_CONTENTS_ID !== '') {
						extendRule(json, 'CHECK_CONTENTS_ID', 1, data.CHECK_CONTENTS_ID);
					}
					json.Sort = 'DESCREPTION'
					dataSelect = await GetHiddenScripList(json).then(res => {
						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].DESCREPTION
							}
						}
						return res.Data
					})
				}

				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,
						index: p.index
					}
				} 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
				const validDetails = this.model.Nav_ListCheckQuestion.filter(i => !i.IS_DELETED);
				const index = this.selectorInfo.index;
				const realIndex = this.model.Nav_ListCheckQuestion.findIndex(item => item === validDetails[index]);
				if (this.selectorInfo.name == 'Nav_RiskArea') {
					this.model.Nav_ListCheckQuestion[realIndex].Nav_RiskArea = e;
					this.model.Nav_ListCheckQuestion[realIndex].RISK_AREA_ID = e.ID;
				} else if (this.selectorInfo.name == 'Nav_Contents') {
					this.model.Nav_ListCheckQuestion[realIndex].Nav_Contents = e;
					this.model.Nav_ListCheckQuestion[realIndex].CHECK_CONTENTS_ID = e.ID;
				} else if (this.selectorInfo.name == 'Nav_Question') {
					this.model.Nav_ListCheckQuestion[realIndex].Nav_Question = e;
					this.model.Nav_ListCheckQuestion[realIndex].CHECK_QUESTION_ID = e.ID;
				}


			},
			handleNewCheckArea() {
				this.model.Nav_ListCheckQuestion.push({
					ID: guid(),
					ORG_ID: this.ORG_ID,
					CHECK_CONTENTS_ID: this.model.ID,
					DESCREPTION: '',
					QUESTION_LEVEL: null,
					QUESTION_LEVELName: '',
					DEMAND: '',
					NUM: 0

				})
			},
			handleDelRowBefore(index) {
				this.nowIndex = index
				this.showDelModalIndex = index

			},
			confirmDel() {
				this.model.Nav_ListCheckQuestion.splice(this.nowIndex, 1)
				this.showDelModalIndex = undefined
			},
			cacelDel() {
				this.showDelModalIndex = undefined
			},
			submit() {
				if (!this.model.Nav_ListCheckQuestion || this.model.Nav_ListCheckQuestion.length == 0) {
					uni.$showErrorInfo('请至少添加一条隐患内容！')
					return
				}
				for (let item of this.model.Nav_ListCheckQuestion) {
					if (!item.DESCREPTION) {
						uni.$showErrorInfo('请填写隐患描述！')

						return
					}
					if (!item.QUESTION_LEVELName) {
						uni.$showErrorInfo('请选择隐患等级！')

						return
					}
					if (!item.DEMAND) {
						uni.$showErrorInfo('请填写整改措施！')

						return
					}
				}
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				// delete this.modelEdit.Nav_ApplyDepartment
				// delete this.modelEdit.Nav_ApplyUser
				// delete this.modelEdit.Nav_CheckType

				this.modelEdit.Nav_ListCheckQuestion.map(item => {
					item.PUBLISH = 'SaveAndNotify'
					// delete item.Nav_Contents
					// delete item.Nav_RiskArea
					// delete item.Nav_Question
				})
				if (this.TaskID == null || this.TaskID == '') {
					this.modelEdit.TaskID = '00000000-0000-0000-0000-000000000000'
				} else {
					this.modelEdit.TaskID = this.TaskID
				}
				if (this.modelEdit.ORG_ID == null || this.modelEdit.ORG_ID == '')
					this.modelEdit.ORG_ID = this.ORG_ID

				this.modelEdit.PUBLISH = 'SaveAndNotify'
				// console.log(this.modelEdit,'this.modelEdit')
				SKCheckContentsFullUpdate(this.modelEdit).then(res => {
					if (res) {
						uni.$showMsgFunc('操作成功!', () => {
							uni.navigateBack()
						}, 'success', 1000)
					}
				})


			}

		}



	}
</script>

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