<!-- WB013 外包工程危险作业申请编辑 -->
<template>
	<view class="todo-page">
		<view class="background"></view>
		<view class="card" v-if="stepsPageList === 0">
			<!-- <uni-card margin="0" :is-shadow="true"> -->
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model" :rules="rules" ref="wForm" errorType="border-bottom" class="demo-ruleForm">

				<!-- <u-form-item label="驳回理由" prop="AUDIT_OPINION" borderBottom>
						<u--input disabled disabledColor="#ffffff" v-model="model.AUDIT_OPINION" border="none"
							 inputAlign="right"></u--input>
					</u-form-item> -->
				<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 class="subRequired" required label="项目名称" prop="Nav_Project.NAME" borderBottom @click="handleShowSheet({title: '项目名称', name: 'ProjectName'})">
					<u--input disabledColor="#fff" v-model="(model.Nav_Project||{}).NAME" placeholder="请选择项目名称" border="none" inputAlign="right" fontSize="14px"></u--input>
					<u-icon style="margin-left: 4px;" name="arrow-down" size="12"></u-icon>
				</u-form-item>
				<u-form-item label="检查时间" required prop="CHECK_TIME" borderBottom @click="showCheckDate(1)">
					<u--input disabledColor="#fff" disabled v-model="model.CHECK_TIME" placeholder="请选择检查时间" border="none" inputAlign="right" fontSize="14px"></u--input>
					<u-icon style="margin-left: 4px;" name="arrow-down" size="12"></u-icon>
				</u-form-item>

				<u-form-item required label="检查类型" prop="Nav_CheckType" borderBottom @click="handleShowSheet({title: '检查类型', name: 'Nav_CheckType'})">
					<u--input disabledColor="#fff" placeholder="请选择检查类型" v-model="(model.Nav_CheckType||{}).NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
					<u-icon style="margin-left: 4px;" name="arrow-down" size="12"></u-icon>
				</u-form-item>
				<u-form-item label="生产单元：" prop="MineType">
				</u-form-item>
				<u-checkbox-group v-model="model.MineTypes" placement="row" @change="checkboxChange" style="display: flex;flex-wrap: wrap;">
					<u-checkbox :customStyle="{margin:'8px'}" v-for="(item, index) in checkboxList1" :key="index" :label="item.title" :name="item.value">
					</u-checkbox>
				</u-checkbox-group>
				<u-form-item required label="检查区域" prop="Nav_ListArea" borderBottom @click="handleShowSheet({title: '检查区域', name: 'Nav_ListArea'})">
					<u--input disabledColor="#fff" placeholder="请选择检查区域" v-model="model.Nav_ListAreas" border="none" inputAlign="right" fontSize="14px"></u--input>
					<u-icon style="margin-left: 4px;" name="arrow-down" size="12"></u-icon>
				</u-form-item>
			</u--form>

			<!-- </uni-card> -->
		</view>
		<view style="padding: 10px 16px;" v-if="stepsPageList === 0" class="bottom-button">
			<u-button type="primary" :disabled="isLoadOK" :loading="isLoading" @click="stepAdd" color="#3d4b70">下一步</u-button>
		</view>
		<view class="card" v-if="stepsPageList === 1">
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom" ref="sForm" class="sub-form">
				<uni-collapse :border="false" accordion>
					<view v-for="(item, index) in model.Nav_Details.filter(i => !i.IS_DELETED)" :key="index">
						<uni-collapse-item title-border="none" :border="false" :open="true">
							<template v-slot:title>
								<view class="uni-collapse-item__title-box">
									<view class="uni-collapse-item__title-text">
										{{index+1+'.'+item.Nav_Area.AREA+'-'+item.Nav_UsersName}}
									</view>
									<view @click.stop>
										<u-icon @click="handleDelRowBefore(item)" name="trash" color="#ff4d4f" size="21" style="margin-right: 10px;"></u-icon>
										<!-- <u-icon name="arrow-down" size="12"></u-icon> -->
									</view>
								</view>
							</template>
							<view class="content">
								<u-form-item label="检查人员:" prop="UsersName" @click="handleShowSheetForArea(item,{title: '检查人员', name: 'UsersName'})">
									<u-icon style="margin-left: 4px;" name="arrow-down" size="12" slot="right"></u-icon>
								</u-form-item>
								<u-textarea v-model="item.Nav_UsersName" disabled autoHeight placeholder="请选择检查人员"></u-textarea>
								<u-form-item required label="记录人员:" prop="DisCloseUser" borderBottom>
									<u--input disabledColor="#fff" disabled v-model="item.Nav_User.NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>
								<u-form-item label="生产单元：" prop="MineType" @click="handleChange(item)" borderBottom>
									<u--input disabledColor="#fff" disabled placeholder="请选择生产单元" v-model="item.MineTypes" border="none" inputAlign="right" fontSize="14px"></u--input>
									<u-icon style="margin-left: 4px;" name="arrow-down" size="12"></u-icon>
								</u-form-item>
								<u-form-item required label="检查区域" prop="Nav_ListArea" borderBottom @click="handleShowSheetForArea(item,{title: '检查区域', name: 'Sub_Nav_ListArea'})">
									<u--input disabledColor="#fff" placeholder="请选择检查区域" v-model="item.Nav_Area.AREA" border="none" inputAlign="right" fontSize="14px"></u--input>
									<u-icon style="margin-left: 4px;" name="arrow-down" size="12"></u-icon>
								</u-form-item>
								<u-form-item label="检查内容" borderBottom>
									<u--input disabledColor="#fff" v-model="item.CHECK_CONTENT" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>
								<u-form-item label="检查依据" borderBottom>
									<u--input disabledColor="#fff" v-model="item.CHECK_BASIS" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>
							</view>


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

				<u-button text="新增" type="primary" @click="handleAdd" color="#3d4b70" :plain="true" style="margin-bottom: 20px;margin-top: 20px;"></u-button>
				<u-button text="向下同步检查人员" type="primary" color="#3d4b70" @click="syncCheckersDownward"></u-button>

			</u--form>

		</view>



		<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-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" @cancel="cacelDel" :showCancelButton="true" title="是否确认执行？"></u-modal>
		<u-datetime-picker :show="dateTimePickerInfo.showCheckDate" v-model='dateTimePickerInfo.defaultDateTime' @confirm="handleCheckDate" @close="dateTimePickerInfo.showCheckDate = false"
			@cancel="dateTimePickerInfo.showCheckDate = false"></u-datetime-picker>
		<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" @close="comPickerInfo.showSheet=false" @cancel="comPickerInfo.showSheet=false" keyName="NAME"></u-picker>
		<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>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup,
		getProductionUnitValue,
		getDepartmentName
	} from '../../../../utils/common'
	import {
		FMProductionUnits,
	} from '../../../../utils/enums.js'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import {
		WBSCTFullUpdate,
		OrderEntitiesJobSafeMeasureEnum,
		ProjectInputDangerApply,
		WBSafeCheckTask,
		WBSafeCheckTaskGet,
		CheckTypeApply,
		CheckAreaEnumApply,
		CheckUseful
	} from '../../../../services/apply/subPages/scWB';

	import {
		getEnum
	} from '../../../../services/common';

	import config from '../../../../config/common'
	export default {
		data() {
			return {
				tableKey: '0',
				TaskID: '',
				ORG_ID: uni.getStorageSync('orgId'),
				isLoadOK: true,
				isLoading: false,
				showDelModalIndex: undefined,
				stepsPageList: 0,
				listISORNOT: [], //是否涉及
				listISORNOTText: [],
				listPropUpload: ['PARENT_ID'],
				listPropValUpload: [],
				checkboxValue1: [],
				checkboxList1: [{
						title: '全公司',
						value: '全公司'
					},
					{
						title: '选矿厂',
						value: '选矿厂'
					},
					{
						title: '尾矿库',
						value: '尾矿库'
					},
					{
						title: '露天矿',
						value: '露天矿'
					},

					{
						title: '地下矿',
						value: '地下矿'
					}
				],
				indexShow: 0,
				UnitLists: [],
				model: {
					ID: '',
					ORG_ID: '',
					TaskID: null,
					PROJECT_ID: '',
					CHECK_TIME: '',
					Nav_Project: {
						NAME: ''
					},
					Nav_CheckType: {
						NAME: ''
					},
					Nav_ListArea: [],
					Nav_ListArea: '',
					Nav_ListAreasID: '',
					MineTypes: [],
					Nav_Details: [{
						MineTypes: [],
						Nav_User: {
							NAME: ''
						},
						ID: '',
						ORG_ID: '',
					}]
				},
				rules: {
					'Nav_Project.NAME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change'],
						message: '请选择【项目名称】'
					},
					'CHECK_TIME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change'],
						message: '请选择【检查时间】'
					},
				},
				comPickerInfo: {
					showSheet: false,
					dataItem: {},
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},

				selectorInfo: {
					name: 'user',
					isMultiple: false,
					showPopup: false,
					totalCount: 0,
					title: '考核结果选择',
					dataItem: {},
					index: 0,
					columns: [],
					dataLists: [],
					defaultText: '',
					defaultChecked: []
				},

				dateTimePickerInfo: {
					showCheckDate: false,
					dataIndex: undefined,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					value: '',
					name: ''
				},
			}
		},
		onLoad(option) {
			// this.TaskID = option.taskID ? option.taskID : '';
			// this.model.ID = option.ID ? option.ID : '';
			// this.JOBID = option.ID ? option.ID : '';
			// this.tableKey = option.tableKey ? option.tableKey : '0'
			// this.loadData();

			this.model.ID = option.ID
			this.TaskID = option.taskID
			this.tableKey = option.tableKey
			if (option.taskID != null && option.taskID != '')
				this.model.TaskID = option.taskID
			// this.getEnums()
			this.loadData()
		},
		methods: {
			getEnums() {
				var dataParm = {
					'name': "ISORNOT"
				}
				getEnum(dataParm).then(res => {
					this.listISORNOT = res
					this.listISORNOTText = []
					this.listISORNOT.forEach(e => {
						e.name = e.NAME
						e.code = e.ID
						this.listISORNOTText.push(e.NAME)
					})
					this.loadData()
				})
			},
			checkboxChange(e, name, index) {
				let result = '';
				const map = {
					'全公司': '0',
					'选矿厂': '10',
					'尾矿库': '20',
					'露天矿': '30',
					'地下矿': '40'
				};
				e.forEach((item, index) => {
					if (index === 0) {
						result += `_${map[item]}_`;
					} else {
						result += `${map[item]}_`;
					}
				});
				if (name == 'sub') {
					this.model.Nav_Details[index].MineType = result
				} else {
					this.model.MineType = result
					this.getDetail()
				}
			},
			handleDelRowBefore(item) {
				item.IS_DELETED = true
				let indexNotDel = 1
				this.model.Nav_Details.forEach((e, i) => {
					if (!e.IS_DELETED) {
						e.ROW_NO = indexNotDel
						indexNotDel++
					}
				})
				this.$forceUpdate()
			},
			getDetail() {
				if (this.model.CHECK_TYPE_ID && this.model.Nav_ListAreasID && this.model.MineType) {
					const orgId = uni.getStorageSync('orgId')
					let json = initFilter(orgId, this.model.ID);
					json.FilterGroup.Rules.push({
						'Field': "Parameter1", // CHECK_PROJECT_CATEGORY_ID
						'Operate': 1,
						'Value': this.model.CHECK_TYPE_ID
					})
					json.FilterGroup.Rules.push({
						'Field': "Parameter2",
						'Operate': 1,
						'Value': this.model.Nav_ListAreasID
					})
					json.FilterGroup.Rules.push({
						'Field': "Parameter3",
						'Operate': 1,
						'Value': this.model.MineType
					})
					WBSafeCheckTask(json).then(res => {
						this.isLoadOK = false
						this.model.Nav_Details = res
						this.model.Nav_Details.map(item => {
							let arr = ''
							if (item.Nav_Users && item.Nav_Users.length > 0) {
								item.Nav_Users.map(item1 => {
									arr += item1.Nav_User.NAME
								})
							}
							item.Nav_User = {
								NAME: !item.Nav_User ? '' : item.Nav_User.NAME ? item.Nav_User.NAME : ''
							}
							item.Nav_UsersName = arr
							let MineTypeName = {
								0: '全公司',
								10: '选矿厂',
								20: '尾矿库',
								30: '露天矿',
								40: '地下矿',
							}
							item.MineTypes = MineTypeName[item.MineType]
						})

					})
				}

			},
			stepAdd() {
				this.isLoading = true
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					this.isLoading = false
					this.stepsPageList = this.stepsPageList + 1
				}).catch(err => {
					uni.$showErrorInfo(err[0].message + '！')
				})

			},
			stepReduce() {
				this.stepsPageList = this.stepsPageList - 1
			},
			loadData() {
				if (this.model.ID == undefined || this.model.ID == '') {
					this.isLoadOK = true
					this.model.Nav_Details = []
					if (this.model.ID == undefined || this.model.ID == '')
						this.model.ID = guid()
				} else {
					const json = initFilter(this.ORG_ID)
					extendRule(json, 'ID', 1, this.model.ID);
					extendInclude(json, 'Nav_Project')
					extendInclude(json, 'Nav_CheckType')
					extendInclude(json, 'Nav_ListArea.Nav_CheckArea')
					extendInclude(json, 'Nav_ListArea')
					extendInclude(json, 'Nav_Details')
					extendInclude(json, 'Nav_Details.Nav_User')
					extendInclude(json, 'Nav_Details.Nav_Users.Nav_User')
					extendInclude(json, 'Nav_Details.Nav_Area')
					WBSafeCheckTaskGet(json).then(res => {
						this.model = res
						this.model.MineTypes = [getDepartmentName(res.MineType)].flatMap(item =>
							item.split('、').map(part => part.trim())
						);

						let arr = ''
						let areaShowID = ''
						res.Nav_ListArea.map(item => {

							if (item.Nav_CheckArea && item.Nav_CheckArea.AREA) {
								arr += item.Nav_CheckArea.AREA
								areaShowID += item.CHECK_AREA_ID + ','
							}

						})
						this.model.Nav_ListAreas = arr
						this.model.Nav_ListAreasID = areaShowID
						this.model.Nav_Details.map(item => {
							let arr = ''
							if (item.Nav_Users && item.Nav_Users.length > 0) {
								item.Nav_Users.map(item1 => {
									arr += item1.Nav_User.NAME
								})
							}
							item.Nav_User = {
								NAME: !item.Nav_User ? '' : item.Nav_User.NAME ? item.Nav_User.NAME : ''
							}
							item.Nav_Area = {
								AREA: !item.Nav_Area ? '' : item.Nav_Area.AREA ? item.Nav_Area.AREA : ''
							}
							item.Nav_UsersName = arr
							let MineTypeName = {
								0: '全公司',
								10: '选矿厂',
								20: '尾矿库',
								30: '露天矿',
								40: '地下矿',
							}
							item.MineTypes = MineTypeName[item.MineType]
						})
						// if (this.model.STATUS == 30) {
						// 	this.isSign = true;
						// 	this.isAudit = false;
						// } else if (this.model.STATUS == 20) {
						// 	this.isSign = false;
						// 	this.isAudit = true;
						// }
						this.isLoadOK = false
					})
				}
				this.listPropValUpload.push(this.model.ID)
			},

			//显示时间控件
			showCheckDate(dataIndex) {
				this.dateTimePickerInfo.showCheckDate = true
				if (this.model.CHECK_TIME == null)
					this.model.CHECK_TIME = uni.$u.timeFormat(new Date(),
						'yyyy-mm-dd hh:MM:ss')

				this.dateTimePickerInfo = {
					showCheckDate: true,
					dataIndex: dataIndex,
					defaultDateTime: this.model.CHECK_TIME
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {
				// let v = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				// const {
				// 	name,
				// 	dataIndex
				// } = this.dateTimePickerInfo

				this.dateTimePickerInfo.showCheckDate = false
				this.model.CHECK_TIME = uni.$u.timeFormat(e.value,
					'yyyy-mm-dd hh:MM:ss')
			},

			handleShowSheetForArea(item, todo) {
				const validDetails = this.model.Nav_Details.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


				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'
				// json.Sort = "NAME"
				// json.Order = 1
				if (p.name == 'ProjectName') { //项目名称

					dataSelect = await ProjectInputDangerApply(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
								res.Data[i].code = res.Data[i].UNIT_NAME
							}
						}
						return res.Data
					})
				} else if (p.name == 'Nav_CheckType') {

					dataSelect = await CheckTypeApply(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_ListArea' || p.name == 'Sub_Nav_ListArea') {

					if (p.name == 'Nav_ListArea') {
						json.Sort = 'ID'
						json.SelectField = ['ID', 'AREA', 'AREA']
						this.selectorInfo.isMultiple = true
					}
					dataSelect = await CheckAreaEnumApply(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].AREA
								res.Data[i].NAME = res.Data[i].AREA
							}
						}
						return res.Data
					})

					if (this.model.Nav_ListArea && this.model.Nav_ListArea.length > 0) {
						this.model.Nav_ListArea.map(item => {

							let newId = item.Nav_CheckArea.ID;
							// 创建一个新对象，ID 为 item.LAW_ID，其他属性和 item 相同
							let newItem = {
								...item,
								ID: newId
							};
							// 将新对象添加到 this.defaultChecked 数组中
							defaultChecked.push(newItem);
						})
					} else {
						defaultChecked = []
					}

				} else if (p.name == 'UsersName') {
					this.selectorInfo.isMultiple = true
					json.Sort = 'ID'
					json.SelectField = ['ID', 'NAME', 'NAME', 'CODE']
					json.OrgRule = []
					json.OrgType = 0
					dataSelect = await CheckUseful(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
								res.Data[i].code = res.Data[i].CODE
							}
						}
						return res.Data
					})
					let arrs = this.model.Nav_Details.filter(i => !i.IS_DELETED)
					if (arrs[p.index].Nav_Users && arrs[p.index].Nav_Users.length > 0) {
						arrs[p.index].Nav_Users.map(item => {
							let newId = item.USER_ID;
							// 创建一个新对象，ID 为 item.LAW_ID，其他属性和 item 相同
							let newItem = {
								...item,
								ID: newId
							};
							// 将新对象添加到 this.defaultChecked 数组中
							defaultChecked.push(newItem);
						})
					} else {
						defaultChecked = []
					}
				}
				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_Details.filter(i => !i.IS_DELETED);
				if (this.selectorInfo.name == 'ProjectName') { //项目名称
					this.model.PROJECT_ID = e.ID
					this.model.Nav_Project = e
				} else if (this.selectorInfo.name == 'Nav_CheckType') {
					this.model.CHECK_TYPE_ID = e.ID
					this.model.Nav_CheckType = e
					this.getDetail()
				} else if (this.selectorInfo.name == 'Nav_ListArea') {
					let listArea = []
					let areaShow = ''
					let areaShowID = ''
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (i > 0) {
								areaShow += ' '
								areaShowID += ''
							}
							let newId = item.ID;
							// 创建一个新对象，ID 为 item.LAW_ID，其他属性和 item 相同
							let newItem = {
								Nav_CheckArea: {
									AREA: item.Nav_CheckArea ? item.Nav_CheckArea.AREA : item.AREA,
									ID: newId
								},
								CHECK_TASK_ID: this.model.ID,
								CHECK_AREA_ID: newId,
								ORG_ID: this.ORG_ID
							};
							listArea.push(newItem)
							areaShow += item.Nav_CheckArea ? item.Nav_CheckArea.AREA : item.AREA
							areaShowID += item.ID + ','
						})
					}
					this.model.Nav_ListArea = listArea
					// this.model.Nav_ListArea.CHECK_AREA_ID = 
					this.model.Nav_ListAreas = areaShow
					this.model.Nav_ListAreasID = areaShowID
					this.getDetail()
				} else if (this.selectorInfo.name == 'Sub_Nav_ListArea') {
					const index = this.selectorInfo.index;
					const realIndex = this.model.Nav_Details.findIndex(item => item === validDetails[index]);
					this.model.Nav_Details[realIndex].Nav_Area = e;
					this.model.Nav_Details[realIndex].AREA_ID = e.ID;
				} else if (this.selectorInfo.name == 'UsersName') {
					const index = this.selectorInfo.index;
					const realIndex = this.model.Nav_Details.findIndex(item => item === validDetails[index]);
					let listArea = []
					let areaShow = ''
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (i > 0) {
								areaShow += ' '
							}
							let newId = item.ID;
							// 创建一个新对象，ID 为 item.LAW_ID，其他属性和 item 相同
							let newItem = {
								// ...item,
								USER_ID: newId,
								NAME: item.NAME,
								ORG_ID: this.ORG_ID,
								


							};
							listArea.push(newItem)
							areaShow += item.NAME
						})
						this.model.Nav_Details[realIndex].Nav_Users = listArea;
						this.model.Nav_Details[realIndex].Nav_UsersName = areaShow;
						this.model.Nav_Details[realIndex].Nav_User = listArea[0];
						this.model.Nav_Details[realIndex].USER_ID = listArea[0].USER_ID ? listArea[0].USER_ID : '';
					} else {
						this.model.Nav_Details[realIndex].Nav_Users = [];
						this.model.Nav_Details[realIndex].Nav_UsersName = '';
						this.model.Nav_Details[realIndex].Nav_User = {
							NAME: ''
						};
						this.model.Nav_Details[realIndex].USER_ID = '';
					}


				}
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},
			syncCheckersDownward() {
				this.showDelModalIndex = 1

			},
			confirmDel() {
				this.syncCheckersDownwards()
				this.showDelModalIndex = undefined
			},
			cacelDel() {
				this.showDelModalIndex = undefined
			},
			syncCheckersDownwards() {
				const validDetails = this.model.Nav_Details.filter(i => !i.IS_DELETED);
				let sourceIndex = -1;

				for (let i = 0; i < validDetails.length; i++) {
					if (validDetails[i].Nav_Users && validDetails[i].Nav_Users.length > 0) {
						sourceIndex = i;
						const sourceItem = validDetails[sourceIndex];

						// 从当前有检查人员的行开始，向下同步
						for (let j = i + 1; j < validDetails.length; j++) {
							const targetItem = validDetails[j];
							if (targetItem.Nav_Users && targetItem.Nav_Users.length > 0) {
								// 遇到下一个有检查人员的行，更新 sourceIndex 并跳出内层循环
								sourceIndex = j;
								break;
							} else {
								targetItem.Nav_Users = [...sourceItem.Nav_Users];
								targetItem.Nav_UsersName = sourceItem.Nav_UsersName;
								targetItem.Nav_User = {
									...sourceItem.Nav_User
								};
								targetItem.USER_ID = sourceItem.USER_ID;
							}
						}
					}
				}

				// 如果没有找到有检查人员的行，则提示用户
				if (sourceIndex === -1) {
					uni.$showMsgFunc('没有找到有检查人员的行!', null, 'none', 1500);
					return;
				}

				this.$forceUpdate();
			},

			submit() {
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				delete this.modelEdit.Nav_Project
				delete this.modelEdit.Nav_CheckType
				// this.modelEdit.MineTypes = null
				delete this.modelEdit.MineTypes;
				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.Nav_Details.forEach(e => {
					if (Array.isArray(e.Nav_Users)) {
						// 遍历 Nav_Users 数组，为每个元素的 ID 赋新值
						e.Nav_Users.forEach(navUser => {
							navUser.ID = guid(),
							navUser.RECORD_ID=e.ID
						});
					}
					if (e.Nav_Area != null)
						delete e.Nav_Area
					if (e.Nav_Main != null)
						delete e.Nav_Main
					if (e.Nav_User != null)
						delete e.Nav_User
					if (e.MineTypes != null)
						delete e.MineTypes
				})
				this.modelEdit.PUBLISH = 'SaveAndNotify'
				WBSCTFullUpdate(this.modelEdit).then(res => {
					uni.$showMsgFunc('操作成功!', () => {
						uni.navigateBack()
					}, 'success', 1000)
				})
			},
			handleAdd() {
				if (this.model.Nav_Details == null) {
					this.model.Nav_Details = []
				}

				var ROW_NO = 1;
				if (this.model.Nav_Details.length > 0) {
					this.model.Nav_Details.forEach(e => {
						if (e.IS_DELETED == undefined || e.IS_DELETED == false)
							ROW_NO++
					})
				}
				var modelAdd = {
					ID: guid(),
					ORG_ID: this.ORG_ID,
					PARENT_ID: this.model.ID,
					Nav_Users: [],
					Nav_UsersName: '',
					Nav_User: {
						NAME: ''
					},
					MineType: '',
					MineTypes: '',
					Nav_Area: {
						AREA: ''
					},
					CHECK_CONTENT: '',
					CHECK_BASIS: '',
					IS_DELETED: false,
				}
				this.model.Nav_Details.push(modelAdd)
				this.indexShow = ROW_NO
			},

			handleChange(item) {
				this.comPickerInfo = {
					showSheet: true,
					columns: [FMProductionUnits],
					dataItem: item
				}
			},
			onConfirmPicker(e) {
				const codeMapping = {
					'全公司': 0,
					'选矿厂': 10,
					'尾矿库': 20,
					'露天矿': 30,
					'地下矿': 40
				};
				this.comPickerInfo = {
					showSheet: false,
					dataItem: this.comPickerInfo.dataItem,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
				this.comPickerInfo.dataItem.MineType = codeMapping[e.value]
				this.comPickerInfo.dataItem.MineTypes = String(e.value)
				// this.model.Nav_Details[this.comPickerInfo.dataItem.index].MineType = codeMapping[e.value]
				// this.model.Nav_Details[this.comPickerInfo.dataItem.index].MineTypes = String(e.value)
			}
		}
	}
</script>

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

	/* .todo-page {
		padding: 16px 16px 70px;
	} */
</style>