<!-- WB013 外包工程危险作业申请编辑 -->
<template>
	<view class="todo-page">
		<view class="background"></view>
		<view class="card" v-if="stepsPageList === 0">
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model" :rules="rules" ref="wForm" errorType="border-bottom" 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="Nav_Project.NAME" borderBottom>
					<u--input v-if="model.Nav_Project" disabled v-model="model.Nav_Project.NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>

				<u-form-item label="外包单位名称" prop="Nav_Project.UNIT_NAME" borderBottom>
					<u--input v-if="model.Nav_Project" disabled v-model="model.Nav_Project.UNIT_NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>

				<u-form-item label="作业类别" prop="Nav_Type.NAME" borderBottom>
					<u--input v-if="model.Nav_Type" disabled v-model="model.Nav_Type.NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>

				<u-form-item label="危险作业名称" prop="DANGEROUS_JOB_NAME" borderBottom>
					<u--input disabled v-model="model.DANGEROUS_JOB_NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item label="危险作业具体事项" prop="DANGEROUS_JOB_ITEM" borderBottom>
					<u--input disabled v-model="model.DANGEROUS_JOB_ITEM" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item label="作业风险辨识" prop="JOB_RISK_IDENTIFY" borderBottom>
					<u--input disabled v-model="model.JOB_RISK_IDENTIFY" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>

				<u-form-item label="作业开始时间" prop="START_TIME" borderBottom>
					<u--input disabled v-model="model.START_TIME" border="none" inputAlign="right" fontSize="14px"></u--input>

				</u-form-item>
				<u-form-item label="作业结束时间" prop="END_TIME" borderBottom>
					<u--input disabled v-model="model.END_TIME" border="none" inputAlign="right" fontSize="14px"></u--input>

				</u-form-item>

				<u-form-item label="作业地点" prop="JOB_ADDRESS" borderBottom>
					<u--input disabled v-model="model.JOB_ADDRESS" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>


				<u-form-item label="现场监护人" prop="USER_ID" borderBottom>
					<u--input v-if="model.Nav_User" disabled v-model="model.Nav_User.NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item label="交底时间" prop="DISCLOSE_TIME" borderBottom @click="showCheckDate(1)">
					<u--input disabledColor="#fff" disabled v-model="model.DISCLOSE_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="DisCloseUser" borderBottom @click="handleShowSheet({title: '交底人', name: 'UserName'})">
					<u--input v-if="model.Nav_DisCloseUser" disabledColor="#fff" disabled placeholder="请选择交底人" v-model="model.Nav_DisCloseUser.NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
					<u-icon style="margin-left: 4px;" name="arrow-down" size="12" slot="right"></u-icon>
				</u-form-item>
				<u-form-item label="被交底人:" prop="UsersName" @click="handleShowSheet({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="model.UsersName" disabled autoHeight placeholder="请选择被交底人"></u-textarea>

				<view class="upload-title">附件</view>
				<full-upload v-model="model.Nav_DisCloseFiles" :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="isLoadOK" @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_DisCloseDetails.filter(i => !i.IS_DELETED)" :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">
										{{index+1+'.'+item.MEASURE}}
									</view>
									<view @click.stop>
										<u-icon @click="handleDelRowBefore(item)" name="trash" color="#ff4d4f" size="21" style="margin-right: 10px;"></u-icon>
									</view>
								</view>
							</template>
							<view class="content">
								<u-form-item label="序号" prop="ROW_NUM" borderBottom>
									<u--input disabledColor="#fff" v-model="item.ROW_NUM" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>
								<u-form-item label="安全措施" class="subRequired" required prop="MEASURE" borderBottom>
									<u--input disabledColor="#fff" v-model="item.MEASURE" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>
								<!-- <u-form-item label="是否涉及" class="subRequired" required prop="ISORNOTShow" borderBottom @click="handleChange( item)">
									<u--input disabled disabledColor="#fff" v-model="item.ISORNOTShow" 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="REMARK" borderBottom>
									<u--input disabledColor="#fff" v-model="item.REMARK" 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"></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-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
	} from '../../../../utils/common'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import {
		GetDangerousJob,
		WBDJFullUpdate,
		OrderEntitiesJobSafeMeasureEnum,
		WBUserOrderPaged
	} 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,
				stepsPageList: 0,
				listISORNOT: [], //是否涉及
				listISORNOTText: [],
				listPropUpload: ['PARENT_ID'],
				listPropValUpload: [],
				indexShow: 0,
				model: {
					ID: '',
					ORG_ID: '',
					TaskID: null,
					Nav_Files: [],
					AUDIT_OPINION: '',
					PROJECT_ID: '',
					Nav_Project: {
						NAME: ''
					},
					UNIT_NAME: '',
					TYPE_ID: '',
					Nav_Type: {
						NAME: ''
					},
					DANGEROUS_JOB_NAME: '',
					DANGEROUS_JOB_ITEM: '',
					JOB_RISK_IDENTIFY: '',
					START_TIME: '',
					END_TIME: '',
					JOB_ADDRESS: '',
					UsersName: '',
					Nav_DisCloseUsers: [{
						Nav_User: {
							NAME: ''
						}
					}],
					PARENT_ID: '',
					Nav_DisCloseUser: {
						NAME: ''
					},
					DISCLOSE_USER_ID: '',
					USER_ID: '',
					Nav_User: {
						NAME: ''
					},
					DISCLOSE_TIME: '',
					Nav_DisCloseFiles: [],
					Nav_DisCloseDetails: [{
						ID: '',
						ORG_ID: '',
						PARENT_ID: '',
						ROW_NUM: '',
						MEASURE: '安全措施',
						ISORNOT: '',
						ISORNOTShow: '',
						REMARK: '',
					}]
				},
				rules: {},
				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()
				})
			},
			handleDelRowBefore(item) {
				item.IS_DELETED = true
				let indexNotDel = 1
				this.model.Nav_DisCloseDetails.forEach((e, i) => {
					if (!e.IS_DELETED) {
						e.ROW_NO = indexNotDel
						indexNotDel++
					}
				})
				this.$forceUpdate()
			},
			stepAdd() {
				// const ele = this.$refs
				// ele['wForm'].validate().then(res => {
				// 	this.stepsPageList = this.stepsPageList + 1
				// }).catch(err => {
				// 	uni.$showErrorInfo(err[0].message + '！')
				// })
				if (!this.model.Nav_DisCloseUser.NAME) {
					uni.$showErrorInfo('请选择交底人！')
				} else {
					this.stepsPageList = this.stepsPageList + 1
				}

			},
			stepReduce() {
				this.stepsPageList = this.stepsPageList - 1
			},
			loadData() {
				let json = initFilter(this.ORG_ID);
				extendRule(json, 'ID', 1, this.model.ID);
				extendInclude(json, 'Nav_DisCloseUsers.Nav_User')
				extendInclude(json, 'Nav_DisCloseFiles.Nav_ImgFile')
				extendInclude(json, 'Nav_Project')
				extendInclude(json, 'Nav_Type')
				extendInclude(json, 'Nav_User')
				extendInclude(json, 'Nav_DisCloseUser')
				extendInclude(json, 'Nav_DisCloseUsers')
				extendInclude(json, 'Nav_DisCloseDetails')
				json.IgnoreDataRule = true;

				GetDangerousJob(json).then(ret => {
					this.model = ret
					// this.initializeMissingFields();
					this.listPropValUpload.push(this.model.ID)
					let listUsers = []
					let UsersName = ''
					if (this.model.Nav_DisCloseUsers.length > 0) {
						this.model.Nav_DisCloseUsers.forEach((item, i) => {
							if (item.Nav_User.NAME != null) {
								if (i > 0) {
									UsersName += ' '
								}
								UsersName += item.Nav_User.NAME
							}
						})
					}
					this.model.UsersName = UsersName
					if (this.model.Nav_DisCloseDetails.length > 0) {
						this.model.Nav_DisCloseDetails.map(item => {
							item.ISORNOTShow = item.ISORNOT == 1 ? '是' : '否'
							item.MEASURE = item.MEASURE ? item.MEASURE : ''
						})
					}
					// uni.$updateData()
					this.isLoadOK = false
				});
				this.listPropValUpload.push(this.model.ID)
			},
			initializeMissingFields() {
				const fields = ['Nav_DisCloseUser', 'Nav_Project', 'Nav_Type', 'Nav_User'];
				fields.forEach(field => {
					if (!this.model[field]) {
						if (field == 'Nav_Project') {
							this.model[field] = {
								NAME: '',
								UNIT_NAME: ''
							};
						} else {
							this.model[field] = {
								NAME: ''
							};
						}

					}
				});
			},

			//显示时间控件
			showCheckDate(dataIndex) {
				this.dateTimePickerInfo.showCheckDate = true
				if (this.model.DISCLOSE_TIME == null)
					this.model.DISCLOSE_TIME = uni.$u.timeFormat(new Date(),
						'yyyy-mm-dd hh:MM:ss')
				this.dateTimePickerInfo = {
					showCheckDate: true,
					dataIndex: dataIndex,
					defaultDateTime: this.model.DISCLOSE_TIME
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {
				this.model.DISCLOSE_TIME = uni.$u.timeFormat(e.value,
					'yyyy-mm-dd hh:MM:ss')
				this.dateTimePickerInfo.showCheckDate = false
			},


			async handleShowSheet(p) {
				const json = initFilter(this.ORG_ID, "", "", 0, p.pageIndex ?? 1)
				let dataSelect = []
				var defaultChecked = []
				this.selectorInfo.isMultiple = false
				json.Sort = "NAME"
				json.Order = 1
				if (this.model.PROJECT_ID == undefined || this.model.PROJECT_ID == '') {
					uni.$showErrorInfo('请先选择项目名称')
					return false
				}
				if (p.val) {
					extendRule(json, 'NAME', 9, p.val);
				}

				json.Limit = 20
				if (p.name == 'UsersName') //作业人员
					this.selectorInfo.isMultiple = true
				if (this.model.PROJECT_ID != undefined && this.model.PROJECT_ID != '')
					extendRule(json, 'PROJECT_ID', 1, this.model.PROJECT_ID);
				dataSelect = await WBUserOrderPaged(json).then(res => {
					this.selectorInfo.totalCount = res.TotalCount
					if (res != undefined && res.Data != 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 (this.model.Nav_DisCloseUsers && this.model.Nav_DisCloseUsers.length > 0) {

					this.model.Nav_DisCloseUsers.filter(i => !i.IS_DELETED).map(item => {
						let newItem = {
							...item,
							ID: item.Nav_User.ID
						};
						// 将新对象添加到 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
					}
				} else {
					// 暂无数据
				}
			},
			//数据加载
			handleSearch(val, pageIndex) {
				var p = {
					name: this.selectorInfo.name,
					title: this.selectorInfo.title,
					val: val,
					pageIndex: pageIndex
				}
				this.handleShowSheet(p)
			},

			handleSelected(e) {
				this.selectorInfo.showPopup = false
				if (this.selectorInfo.name == 'UsersName') { //被交底人
					let listUsers = []
					let UsersName = ''
					if (this.model.Nav_DisCloseUsers != null && this.model.Nav_DisCloseUsers.length > 0) {
						//如果有数据 数据删除
						this.model.Nav_DisCloseUsers.forEach(e => {
							e.IS_DELETED = true
							listUsers.push(e)
						})
					}
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (item.NAME != null) {
								if (i > 0) {
									UsersName += ' '
								}
								listUsers.push({
									ID: guid(),
									PARENT_ID: this.model.ID,
									NAME:item.NAME,
									USER_ID: item.ID,
									ORG_ID: this.ORG_ID,
									Nav_User: e[i],
									IS_DELETED: false,
								})
								UsersName += item.NAME
							}
						})
					}
					this.model.Nav_DisCloseUsers = listUsers
					this.model.UsersName = UsersName


				} else if (this.selectorInfo.name == 'UserName') { //交底人
					this.model.Nav_DisCloseUser = e
					this.model.DISCLOSE_USER_ID = e.ID
				}



				// if (this.selectorInfo.name == "ProjectName") {
				// 	this.model.CHECKOBJECT_DESCRIPTION = e.NAME
				// 	this.model.CHECKOBJECT = e.ID
				// } else if (this.selectorInfo.name == 'TypeName') {
				// 	this.model.CHECK_TYPE_ID = e.ID
				// 	this.model.Nav_CheckType.NAME = e.NAME
				// } else if (this.selectorInfo.name == 'UsersName') {
				// 	this.model.CHECK_TYPE_LEVEL_ID = e.ID
				// 	this.model.Nav_CheckTypeLevel.Nav_Enums = e.Nav_Enums
				// 	// this.model.Nav_CheckTypeLevel.Nav_Enums.NAME = e.NAME
				// } else if (this.selectorInfo.name == 'UserName') {
				// 	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(),
				// 					SAFE_CHECK_ID: this.model.ID,
				// 					RISK_AREA_ID: item.ID,
				// 					ORG_ID: item.ORG_ID,
				// 					Nav_RiskArea: item
				// 				})
				// 				areaShow += item.NAME
				// 			}
				// 		})
				// 	}
				// 	this.model.Nav_ListCheckRiskArea = listArea
				// 	this.model.RiskAreaNAME = areaShow
				// }
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},

			submit() {
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				this.modelEdit.Nav_Project = null
				this.modelEdit.Nav_Type = null
				this.modelEdit.Nav_User = null
				if (this.TaskID == null || this.TaskID == '') {
					this.modelEdit.TaskID = '00000000-0000-0000-0000-000000000000'
				} else {
					this.modelEdit.TaskID = this.TaskID
				}
				this.modelEdit.Nav_DisCloseDetails.map(item => {
					item.TaskID = this.TaskID
					item.PUBLISH = 'SaveAndNotify'
				})

				if (this.modelEdit.ORG_ID == null || this.modelEdit.ORG_ID == '')
					this.modelEdit.ORG_ID = this.ORG_ID

				this.modelEdit.Nav_DisCloseUsers.forEach(e => {
					if (e.Nav_User != null)
						e.Nav_User = null
				})
				this.modelEdit.PUBLISH = 'SaveAndNotify'
				WBDJFullUpdate(this.modelEdit).then(res => {
					uni.$showMsgFunc('操作成功!', () => {
						uni.navigateBack()
					}, 'success', 1000)
				})
			},
			handleAdd() {
				if (this.model.Nav_DisCloseDetails == null) {
					this.model.Nav_DisCloseDetails = []
				}

				var ROW_NO = 1;
				if (this.model.Nav_DisCloseDetails.length > 0) {
					this.model.Nav_DisCloseDetails.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,
					ROW_NUM: ROW_NO,
					MEASURE: '',
					ISORNOT: 1,
					ISORNOTShow: '是',
					REMARK: '',
					IS_DELETED: false,
				}
				this.model.Nav_DisCloseDetails.push(modelAdd)
				this.indexShow = ROW_NO
			},

			handleChange(item) {
				this.comPickerInfo = {
					showSheet: true,
					columns: [this.listISORNOTText],
					dataItem: item
				}
			},
			onConfirmPicker(e) {
				this.comPickerInfo = {
					showSheet: false,
					dataItem: this.comPickerInfo.dataItem,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
				this.comPickerInfo.dataItem.ISORNOTShow = e.value[0]
				this.comPickerInfo.dataItem.ISORNOT = this.listISORNOT[e.indexs[0]].code
			}
		}
	}
</script>

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

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