<!-- 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 label="项目名称" prop="Nav_Project.NAME" borderBottom>
					<u--input 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 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 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="作业开始时间" borderBottom>
					<u--input disabled v-model="model.START_TIME" border="none" inputAlign="right" fontSize="14px"></u--input>

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

				</u-form-item>

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

				<u-form-item label="现场监护人" borderBottom>
					<u--input disabled v-model="model.Nav_User.NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>

				<view class="upload-title">附件</view>
				<full-upload v-model="model.Nav_Files" :isShowBtn='false' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>

			</u--form>

			<!-- </uni-card> -->
		</view>
		<view style="padding: 10px 16px;" v-if="stepsPageList === 0" class="bottom-button">
			<u-button type="primary" :disabled="isLoadOK" @click="stepAdd" color="#3d4b70">下一步</u-button>
		</view>
		<view class="card" v-if="stepsPageList === 1">
			<u--form labelPosition="left" labelWidth="auto" :model="model" :rules="rules" labelAlign="center" errorType="border-bottom" ref="sForm" class="sub-form">
				<uni-collapse :border="false" accordion>
					<view v-for="(item, index) in model.Nav_MointerRecordDetails.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.Nav_MointerDepartment.NAME+'-'+item.Nav_MointerUser.NAME}}
									</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" style="margin: 0px 10px;">
								<u-form-item label="开始时间" required :prop="`Nav_MointerRecordDetails.${index}.START_TIME`" borderBottom @click="showCheckDate(1,item)">
									<u--input disabledColor="#fff" disabled v-model="item.START_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 label="结束时间" required :prop="`Nav_MointerRecordDetails.${index}.END_TIME`" borderBottom @click="showCheckDate(2,item)">
									<u--input disabledColor="#fff" disabled v-model="item.END_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_MointerRecordDetails.${index}.Nav_MointerDepartment.NAME`" borderBottom
									@click="handleShowSheet({title: '监查部门', name: 'Nav_MointerDepartment'},item)">
									<u--input disabledColor="#fff" disabled placeholder="请选择监查部门" v-model="item.Nav_MointerDepartment.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 required label="监查人:" :prop="`Nav_MointerRecordDetails.${index}.Nav_MointerUser.NAME`" borderBottom @click="handleShowSheet({title: '监查人', name: 'UserName'},item)">
									<u--input disabledColor="#fff" disabled placeholder="请选择监查人" v-model="item.Nav_MointerUser.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 required label="监查情况说明" :prop="`Nav_MointerRecordDetails.${index}.REMARK`" borderBottom>
									<u--input disabledColor="#fff" v-model="item.REMARK" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>
								<view class="upload-title">监查照片</view>
								<full-upload v-model="item.Nav_Files" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>



							</view>


						</uni-collapse-item>
					</view>
				</uni-collapse>
				<u-button text="新增" type="primary" @click="handleAdd" color="#3d4b70" style="margin-top: 20px;"></u-button>
			</u--form>

		</view>
		<u-datetime-picker :show="dateTimePickerInfo.showCheckDate" v-model='dateTimePickerInfo.defaultDateTime' @confirm="handleCheckDate" @close="dateTimePickerInfo.showCheckDate = false"
			@cancel="dateTimePickerInfo.showCheckDate = false" mode="datetime"></u-datetime-picker>
		<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 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 style="padding: 10px 16px;" v-if='isLoadOK' class="bottom-button">
			<u-button type="primary" @click="submit" color="#3d4b70">提交</u-button>
		</view> -->
		<!-- 		<view class="bottom-button">
			<button type="primary" v-if='isLoadOK' @click="submit">提交</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 {
		WBMointerFull,
		JobTypeDangerApply,
		OrderEntitiesJobSafeMeasureEnum,
		ProjectInputDangerApply,
		WBUserOrderPaged,
		GetDangerousJob,
		CheckUseful,
		WBDepartment
	} 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_Users: [{
						Nav_User: {
							NAME: ''
						}
					}],
					USER_ID: '',
					Nav_User: {
						NAME: ''
					},
					Nav_Files: [],
					Nav_MointerRecordDetails: [{
						ID: '',
						ORG_ID: '',
						START_TIME: '',
						END_TIME: '',
						Nav_MointerDepartment: {
							NAME: ''
						},
						Nav_MointerUser: {
							NAME: ''
						},
						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.loadData()
		},
		methods: {
			//显示时间控件
			showCheckDate(dataIndex, item) {
				this.dateTimePickerInfo.showCheckDate = true
				// if (dataIndex == 1) {
				// 	if (this.model.START_TIME == null)
				// 		this.model.START_TIME = uni.$u.timeFormat(new Date(),
				// 			'yyyy-mm-dd')
				// } else {
				// 	if (this.model.END_TIME == null)
				// 		this.model.END_TIME = uni.$u.timeFormat(new Date(),
				// 			'yyyy-mm-dd')
				// }
				const validDetails = this.model.Nav_MointerRecordDetails.filter(i => !i.IS_DELETED);
				const index = validDetails.indexOf(item);
				const realIndex = this.model.Nav_MointerRecordDetails.findIndex(item => item === validDetails[index]);
				this.dateTimePickerInfo = {
					showCheckDate: true,
					dataIndex: dataIndex,
					defaultDateTime: dataIndex == 1 ? this.model.START_TIME : this.model.END_TIME,
					realIndex: realIndex
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {
				// let v = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				// const {
				// 	name,
				// 	dataIndex
				// } = this.dateTimePickerInfo

				this.dateTimePickerInfo.showCheckDate = false
				if (this.dateTimePickerInfo.dataIndex == 1) {
					this.model.Nav_MointerRecordDetails[this.dateTimePickerInfo.realIndex].START_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				} else {
					this.model.Nav_MointerRecordDetails[this.dateTimePickerInfo.realIndex].END_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				}
			},
			handleDelRowBefore(item) {
				item.IS_DELETED = true
				let indexNotDel = 1
				this.model.Nav_MointerRecordDetails.forEach((e, i) => {
					if (!e.IS_DELETED) {
						e.ROW_NO = indexNotDel
						indexNotDel++
					}
				})
				this.$forceUpdate()
			},
			stepAdd() {
				this.stepsPageList = this.stepsPageList + 1

			},
			stepReduce() {
				this.stepsPageList = this.stepsPageList - 1
			},
			loadData() {
				if (this.model.ID == undefined || this.model.ID == '') {
					this.isLoadOK = false
					this.model.Nav_MointerRecordDetails = []
					if (this.model.ID == undefined || this.model.ID == '')
						this.model.ID = guid()
				} else {
					let json = initFilter(this.ORG_ID);
					extendRule(json, 'ID', 1, this.model.ID);
					extendInclude(json, 'Nav_Files.Nav_ImgFile')
					extendInclude(json, 'Nav_Project')
					extendInclude(json, 'Nav_Type')
					extendInclude(json, 'Nav_User')
					extendInclude(json, 'Nav_Users')
					extendInclude(json, 'Nav_Users.Nav_User')
					extendInclude(json, 'Nav_MointerRecordDetails')
					extendInclude(json, 'Nav_MointerRecordDetails.Nav_MointerDepartment')
					extendInclude(json, 'Nav_MointerRecordDetails.Nav_MointerUser')
					json.IgnoreDataRule = true;
					GetDangerousJob(json).then(ret => {
						this.isLoadOK = false
						this.model = ret
						let UsersName = ''
						if (this.model.Nav_Users&&this.model.Nav_Users.length > 0) {
							this.model.Nav_Users.forEach((item, i) => {
								if (item.Nav_User.NAME != null) {
									if (i > 0) {
										UsersName += ' '
									}
									UsersName += item.Nav_User.NAME
								}
							})
						}
						this.model.UsersName = UsersName
						this.initializeMissingFields();
						this.listPropValUpload.push(this.model.ID)

						// uni.$updateData()

					});


				}
				this.listPropValUpload.push(this.model.ID)
			},
			initializeMissingFields() {
				const fields = ['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: ''
							};
						}

					}
				});
			},
			async handleShowSheet(p, item) {

				const validDetails = this.model.Nav_MointerRecordDetails.filter(i => !i.IS_DELETED);
				const index = validDetails.indexOf(item);
				const realIndex = this.model.Nav_MointerRecordDetails.findIndex(item => item === validDetails[index]);
				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.Sort = "NAME"
				json.Order = 1
				json.Limit = 20
				if (p.pageIndex) {
					json.Start = (p.pageIndex - 1) * json.Limit;
				}
				if (p.name == 'Nav_MointerDepartment') {
					extendRule(json, 'ENABLE_STATUS', 1, '0');
					dataSelect = await WBDepartment(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
					})
				} else if (p.name == 'UserName') {
					const depId = this.model.Nav_MointerRecordDetails[realIndex].MOINTER_DEPARTMENT_ID
					if (depId != undefined && depId != '')
						extendRule(json, 'DEPARTMENT_ID', 1, depId);
					extendRule(json, 'ENABLE_STATUS', 1, '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
					})
				}


				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,
					realIndex: realIndex,
					item: item
				}
			},
			//数据加载
			handleSearch(val, pageIndex) {
				var p = {
					name: this.selectorInfo.name,
					title: this.selectorInfo.title,
					val: val,
					pageIndex: pageIndex
				}
				this.handleShowSheet(p, this.selectorInfo.item)
			},

			handleSelected(e) {
				this.selectorInfo.showPopup = false
				if (this.selectorInfo.name == 'UserName') { //交底人
					this.model.Nav_MointerRecordDetails[this.selectorInfo.realIndex].Nav_MointerUser = e
					this.model.Nav_MointerRecordDetails[this.selectorInfo.realIndex].MOINTER_USER_ID = e.ID
				} else if (this.selectorInfo.name == 'Nav_MointerDepartment') {
					this.model.Nav_MointerRecordDetails[this.selectorInfo.realIndex].Nav_MointerDepartment = e
					this.model.Nav_MointerRecordDetails[this.selectorInfo.realIndex].MOINTER_DEPARTMENT_ID = e.ID
				}
			},

			submit() {
				if (this.model.Nav_MointerRecordDetails.length > 0) {
					for (let item of this.model.Nav_MointerRecordDetails.filter(i => !i.IS_DELETED)) {
						if (!item.START_TIME) {
							uni.$showErrorInfo('请填写开始时间！')
							return
						}
						if (!item.END_TIME) {
							uni.$showErrorInfo('请填写结束时间！')
							return
						}
						if (!item.Nav_MointerDepartment.NAME) {
							uni.$showErrorInfo('请填写监查部门！')
							return
						}
						if (!item.Nav_MointerUser.NAME) {
							uni.$showErrorInfo('请填写监查人！')
							return
						}
						if (!item.REMARK) {
							uni.$showErrorInfo('请填写监查情况说明！')
							return
						}
					}

					this.modelEdit = JSON.parse(JSON.stringify(this.model))
					delete this.modelEdit.Nav_Project
					delete this.modelEdit.Nav_Type
					delete this.modelEdit.Nav_User
					this.modelEdit.Nav_MointerRecordDetails.map(item => {
						item.TaskID = this.TaskID
						item.PUBLISH = 'SaveAndNotify'
						delete item.Nav_MointerDepartment
						delete item.Nav_MointerUser
					})
					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'
					WBMointerFull(this.modelEdit).then(res => {
						uni.$showMsgFunc('操作成功!', () => {
							uni.navigateBack()
						}, 'success', 1000)
					})
				} else {
					uni.$showErrorInfo('请新增监查信息！')


				}

			},
			handleAdd() {
				if (this.model.Nav_MointerRecordDetails == null) {
					this.model.Nav_MointerRecordDetails = []
				}
				var modelAdd = {
					ID: guid(),
					ORG_ID: this.ORG_ID,
					PARENT_ID: this.model.ID,
					START_TIME: '',
					END_TIME: '',
					Nav_MointerDepartment: {
						NAME: ''
					},
					Nav_MointerUser: {
						NAME: ''
					},
					REMARK: '',
					Nav_Files: [],
					IS_DELETED: false,
				}
				this.model.Nav_MointerRecordDetails.push(modelAdd)
			},
		}
	}
</script>

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

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