<!-- WB013 外包工程危险作业申请编辑 -->
<template>
	<view class="todo-page">
		<view class="background"></view>
		<view class="card">
			<!-- <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">
				<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="Product_Unit" @click="handleChange('minetype')" borderBottom>
					<u--input v-model="model.Product_Unit" disabled disabledColor="#ffffff" 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="检查类型" prop="Nav_Project.NAME" borderBottom>
					<u--input disabled disabledColor="#ffffff" v-model="model.CHECKTYPENAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item label="巡检时间" prop="RECORD_DATE" borderBottom @click="showCheckDate()">
					<u--input disabled disabledColor="#fff" v-model="model.RECORD_DATE" 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_Users" @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.NavUsersName" disabled autoHeight placeholder="请选择巡检人员"></u-textarea>
				<u-form-item label="设备名称" prop="Nav_DeviceBase.NAME" borderBottom>
					<u--input v-if="model.Nav_DeviceBase" disabled disabledColor="#ffffff" v-model="model.Nav_DeviceBase.NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item label="规格" prop="Nav_Project.NAME" borderBottom>
					<u--input disabled disabledColor="#ffffff" v-model="model.SPEC" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item label="设备编号" prop="Nav_Project.NAME" borderBottom>
					<u--input disabled disabledColor="#ffffff" v-model="model.MACHINE_CODE" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>
				<u-form-item label="设备位置" prop="Nav_Project.NAME" borderBottom>
					<u--input disabled disabledColor="#ffffff" v-model="model.POSITION_NAME" border="none" inputAlign="right" fontSize="14px"></u--input>
				</u-form-item>

			</u--form>
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom" ref="sForm" class="sub-form" style="margin-top: 20px;" v-if="model.Nav_ListDetail">
				<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>

				<uni-collapse :border="false" accordion>
					<view v-for="(item, index) in model.Nav_ListDetail.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">
										{{item.ITEM1?index+1+'.'+item.ITEM1:index+1+'.'}}
									</view>
									<view @click.stop style="margin-right: 10px;">

										<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="padding: 0px 0px 0px 10px;">
								<u-form-item label="巡检部位" prop="POSITION" borderBottom>
									<u--input disabledColor="#ffffff" v-model="item.ITEM1" border="none" inputAlign="right" fontSize="14px" placeholder="请输入巡检部位">
									</u--input>
								</u-form-item>
								<u-form-item label="巡检内容" prop="POSITION" borderBottom>
									<u--input disabledColor="#ffffff" v-model="item.ITEM2" border="none" inputAlign="right" fontSize="14px" placeholder="请输入巡检内容">
									</u--input>
								</u-form-item>
								<u-form-item label="巡检标准" prop="POSITION" borderBottom>
									<u--input disabledColor="#ffffff" v-model="item.ITEM3" border="none" inputAlign="right" fontSize="14px" placeholder="请输入巡检标准">
									</u--input>
								</u-form-item>
								<u-form-item label="巡检结论" prop="Product_Unit" @click="handleChange('conclusion',item)" borderBottom>
									<u--input v-model="item.CHECK_VALUEShow" disabled disabledColor="#ffffff" 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="问题描述" prop="POSITION" borderBottom>
									<u--input disabledColor="#ffffff" v-model="item.DESCRIPTION" border="none" inputAlign="right" fontSize="14px" placeholder="请输入问题描述">
									</u--input>
								</u-form-item>
								<view class="upload-title">附件</view>
								<full-upload v-model="item.Nav_DetailFiles" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>


							</view>


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

			<!-- </uni-card> -->
		</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;" class="bottom-button">
			<u-button type="primary" @click="submit" color="#3d4b70" :disabled="isLoadOK">提交</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 {
		FMProductionUnit,
		CheckPeriods,
		CheckLevels,
		MineTypeIndex,
		MineTypeName
	} from '../../../../utils/enums.js'
	import {
		DMDeviceCheckGet,
		DMDeviceCheckFull,
		DMUser
	} from '../../../../services/apply/subPages/DM/dm';

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

	import config from '../../../../config/common'
	export default {
		data() {
			return {
				tableKey: '0',
				TaskID: '',
				ID: '',
				ORG_ID: uni.getStorageSync('orgId'),
				isLoadOK: true,
				stepsPageList: 0,
				listISORNOT: [], //是否涉及
				listType: [],
				listResult: [],
				listResultText: [],
				listISORNOTText: [],
				listPropUpload: ['PARENT_ID'],
				listPropValUpload: [],
				indexShow: 0,

				model: {
					Nav_Department: {
						NAME: ''
					},
					NavUsersName: '',
					Nav_User: {
						NAME: ""
					},
					Product_Unit: '',
					ID: '',
					ORG_ID: '',
					TaskID: null,
					Nav_ListDetail: []
				},
				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.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': "FMProductionUnit"
				}
				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()
					this.getEnumeration()
					this.getConclusion()
				})
			},
			getConclusion() {
				var dataParm = {
					'name': "CheckResult"
				}
				getEnum(dataParm).then(res => {
					this.listResult = res
					this.listResultText = []
					this.listResult.forEach(e => {
						e.name = e.NAME
						e.code = e.ID
						this.listResultText.push(e.NAME)
						
					})
				})
			},
			changeConfirm(item) {
				const validDetails = this.model.Nav_ListDetail.filter(i => !i.IS_DELETED);
				const index = validDetails.indexOf(item);
				const realIndex = this.model.Nav_ListDetail.findIndex(item => item === validDetails[index]);
				this.model.Nav_ListDetail[realIndex].ISOCONFIRM = true;
			},
			handleDelRowBefore(item) {
				item.IS_DELETED = true
				let indexNotDel = 1
				this.model.Nav_ListDetail.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() {
				let json = initFilter(this.ORG_ID);
				extendRule(json, 'ID', 1, this.ID);
				extendInclude(json, 'Nav_ListUser');
				extendInclude(json, 'Nav_ListUser.Nav_User');
				extendInclude(json, 'Nav_DeviceBase');
				extendInclude(json, 'Nav_Files.Nav_ImgFile');
				extendInclude(json, 'Nav_ListDetail');
				extendInclude(json, 'Nav_ListDetail.Nav_DetailFiles.Nav_ImgFile');

				DMDeviceCheckGet(json).then(ret => {
					this.isLoadOK = false
					this.model = ret
					this.model.ID = this.ID
					this.model.Product_Unit = this.listISORNOT.find(item => item.code === this.model.MineType).name
					let NavUsersName = ''
					if (this.model.Nav_ListUser && this.model.Nav_ListUser.length > 0) {
						this.model.Nav_ListUser.map(item => {
							if (item.Nav_User.NAME !== null) {
								NavUsersName += item.Nav_User.NAME + ' ';
							}
						})
					}
					this.model.NavUsersName = NavUsersName
					this.model.CHECKTYPENAME = this.listType.find(item => item.ID === this.model.CHECKTYPE).NAME
					this.listPropValUpload.push(this.ID)

					// uni.$updateData()

				});



				this.listPropValUpload.push(this.model.ID)
			},
			getEnumeration() {
				var dataParm = {
					'name': "CheckType"
				}
				getEnum(dataParm).then(res => {
					this.listType = res
				})
			},
			//显示时间控件
			showCheckDate() {
				this.dateTimePickerInfo.showCheckDate = true
				this.dateTimePickerInfo = {
					showCheckDate: true,
					defaultDateTime: this.model.RECORD_DATE
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {
				this.dateTimePickerInfo.showCheckDate = false
				this.model.RECORD_DATE = uni.$u.timeFormat(e.value,
					'yyyy-mm-dd hh:MM:ss')
			},
			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: ''
							};
						}

					}
				});
			},

			handleShowSheetForArea(item, todo) {
				const validDetails = this.model.Nav_ListDetail.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 = 'ID'
				this.selectorInfo.isMultiple = true
				json.SelectField = ["ID", "NAME", "NAME", "CODE"]
				// json.Sort = "NAME"
				// json.Order = 1
				if (p.name == 'UsersName') {
					dataSelect = await DMUser(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
					})
					if (this.model.Nav_ListUser.length > 0 && this.model.Nav_ListUser != null) {
						// this.selectorInfo.defaultChecked = []
						this.model.Nav_ListUser.filter(i => !i.IS_DELETED).forEach(e => {
							if (e.Nav_User != null && e.Nav_User.NAME != null)
								defaultChecked.push(e.Nav_User)
						})
					} 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
				if (this.selectorInfo.name == 'UsersName') { //被交底人
					let listUsers = []
					let UsersName = ''

					if (this.model.Nav_ListUser != null && this.model.Nav_ListUser.length > 0) {
						//如果有数据 数据删除
						this.model.Nav_ListUser.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(),
									CHECK_ID: this.model.ID,
									USER_ID: item.ID,
									ORG_ID: this.ORG_ID,
									Nav_User: {
										NAME: item.NAME,
										ID:item.ID
									},
									IS_DELETED: false,
								})
								UsersName += item.NAME
							}
						})
					}
					this.model.Nav_ListUser = listUsers
					this.model.NavUsersName = UsersName
				}



			},
			submit() {
				for (let item of this.model.Nav_ListDetail.filter(i => !i.IS_DELETED)) {
					if (item.CHECK_VALUEShow=='不正常'&&!item.DESCRIPTION) {
						uni.$showErrorInfo('请填写不正常结论的问题描述！')
						return
					}
					if (!item.CHECK_VALUEShow) {
						uni.$showErrorInfo('请选择巡检结论！')
						return
					}
					item.TaskID = this.TaskID
				}
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				
				delete this.modelEdit.Nav_DeviceBase
				this.modelEdit.Nav_ListDetail.map(item => {
					item.STATUS ='10'    //只针对巡检巡检，后端根据status判断
				})
				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.STATUS = '10' //只针对巡检巡检，后端根据status判断 
				DMDeviceCheckFull(this.modelEdit).then(res => {
					uni.$showMsgFunc('操作成功!', () => {
						uni.navigateBack()
					}, 'success', 1000)
				})

			},
			handleAdd() {
				if (this.model.Nav_ListDetail == null) {
					this.model.Nav_ListDetail = []
				}

				var ROW_NO = 1;
				if (this.model.Nav_ListDetail.length > 0) {
					this.model.Nav_ListDetail.forEach(e => {
						if (e.IS_DELETED == undefined || e.IS_DELETED == false)
							ROW_NO++
					})
				}
				var modelAdd = {
					ID: guid(),
					ORG_ID: this.ORG_ID,
					DEVICE_CHECK_ID: this.model.ID,
					ROW_NUM: ROW_NO,
					ITEM1:'',
					ITEM2:'',
					ITEM3:'',
					CHECK_VALUE:'',
					CHECK_VALUEShow:'',
					DESCRIPTION:'',
					Nav_DetailFiles:[],
					IS_DELETED: false,
				}
				this.model.Nav_ListDetail.push(modelAdd)
				this.indexShow = ROW_NO
			},

			handleChange(name, item) {
				if (name == 'minetype') {
					this.comPickerInfo = {
						showSheet: true,
						columns: [this.listISORNOTText],
						name: name
					}
				} else if (name == 'conclusion') {
					this.comPickerInfo = {
						showSheet: true,
						columns: [this.listResultText],
						dataItem: item,
						name: name
					}
				}

			},
			onConfirmPicker(e) {
				if (this.comPickerInfo.name == 'minetype') {
					this.comPickerInfo = {
						showSheet: false,
						columns: [],
						title: '',
						formIndex: undefined
					}
					this.model.Product_Unit = e.value[0]
					this.model.MineType = this.listISORNOT[e.indexs[0]].code
				} else if (this.comPickerInfo.name == 'conclusion') {
					this.comPickerInfo = {
						showSheet: false,
						dataItem: this.comPickerInfo.dataItem,
						columns: [],
						title: '',
						name: '',
						formIndex: undefined
					}
					this.comPickerInfo.dataItem.CHECK_VALUEShow = e.value[0]
					this.comPickerInfo.dataItem.CHECK_VALUE = this.listResult[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>