<!-- 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 required label="维保开始时间" prop="CHECKDATETIME" borderBottom @click="showCheckDate(1)">
					<u--input disabled disabledColor="#fff" v-model="model.CHECKDATETIME" 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="ENDTIME" borderBottom @click="showCheckDate(2)">
					<u--input disabled disabledColor="#fff" v-model="model.ENDTIME" 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_Department.NAME" borderBottom @click="handleShowSheet({title: '维保部门', name: 'Nav_Department'})">
					<u--input disabled disabledColor="#ffffff" placeholder="请选择维保部门" v-model="model.Nav_Department.NAME" border="none" fontSize="14px" inputAlign="right" v-if="model.Nav_Department"></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="Nav_User.NAME" borderBottom @click="handleShowSheet({title: '维保人员', name: 'Nav_ListUser'})">
					<u-icon style="margin-left: 4px;" name="arrow-down" size="12" slot="right"></u-icon>
				</u-form-item>
				<u-textarea v-model="model.Nav_ListUserName" disabled autoHeight placeholder="请选择维保人员"></u-textarea>

				<view class="upload-title">维保工作方案</view>
				<full-upload v-model="model.Nav_Files" :isShowBtn="true" :listProp="listPropUpload" :listPropVal="listPropValUpload"></full-upload>

			</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.MACHINE_NAME?index+1+'.'+item.MACHINE_NAME: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>
									</view> -->
								</view>
							</template>
							<view class="content" style="padding: 0px 0px 0px 10px;">
								<u-form-item class="subRequired" label="设备名称" prop="Nav_Device.NAME" borderBottom>
									<u--input disabled fontSize="14px" disabledColor="#fff" v-model="item.MACHINE_NAME" border="none" inputAlign="right"></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 disabled disabledColor="#ffffff" v-model="item.SPEC" border="none" inputAlign="right" fontSize="14px">
									</u--input>
								</u-form-item>
								<u-form-item label="数量" prop="POSITION" borderBottom>
									<u--input disabled disabledColor="#ffffff" v-model="item.COUNT" border="none" inputAlign="right" fontSize="14px">
									</u--input>
								</u-form-item>
								<u-form-item label="位置" prop="POSITION" borderBottom>
									<u--input disabled disabledColor="#ffffff" v-model="item.POSITION" border="none" inputAlign="right" fontSize="14px">
									</u--input>
								</u-form-item>

								<u-form-item label="维保内容" prop="POSITION" borderBottom>
									<u--input disabledColor="#ffffff" v-model="item.CONTENT" border="none" inputAlign="right" fontSize="14px" placeholder="请输入维保内容">
									</u--input>
								</u-form-item>
								<u-form-item label="维保周期" prop="Product_Unit" @click="handleChange('MaintenanceResult',item)" borderBottom>
									<u--input v-model="item.ResultShow" 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>


								<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>
				<!-- <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" :mode="dateTimePickerInfo.mode"></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,
		getRealIndex
	} from '../../../../utils/common'
	import {
		FMProductionUnit,
		CheckPeriods,
		CheckLevels,
		MineTypeIndex,
		MineTypeName
	} from '../../../../utils/enums.js'
	import {
		DMMaintenanceGet,
		DMMaintenanceFull,
		FMUserUseful,
		DMDepartment
	} 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: '',
					mode: ''
				},
			}
		},
		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.getConclusion()
			// 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': "MaintenanceResult"
				}
				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)

					})
					this.loadData()
				})
			},
			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_Department');
				extendInclude(json, 'Nav_ListUser');
				extendInclude(json, 'Nav_ListUser.Nav_User');
				extendInclude(json, 'Nav_ListDetail');
				extendInclude(json, 'Nav_Files.Nav_ImgFile');
				extendInclude(json, 'Nav_ListDetail.Nav_Files.Nav_ImgFile');

				DMMaintenanceGet(json).then(ret => {
					this.isLoadOK = false
					this.model = ret
					this.model.ID = this.ID
					this.listPropValUpload.push(this.ID)
					if (this.model.Nav_ListDetail && this.model.Nav_ListDetail.length > 0) {
						this.model.Nav_ListDetail.map(item => {
							if (item.Result) {
								item.ResultShow = this.listResult.find(item1 => item1.code === item.Result).name
							}
						})
					}

					// uni.$updateData()

				});



				this.listPropValUpload.push(this.model.ID)
			},
			// getEnumeration() {
			// 	var dataParm = {
			// 		'name': "CheckType"
			// 	}
			// 	getEnum(dataParm).then(res => {
			// 		this.listType = res
			// 	})
			// },
			//显示时间控件
			showCheckDate(dataIndex, item) {
				// let date = new Date()
				// this.dateTimePickerInfo.showCheckDate = true
				this.dateTimePickerInfo = {
					showCheckDate: true,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					dataIndex: dataIndex,
					item: item,
					mode: 'datetime'
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {

				if (this.dateTimePickerInfo.dataIndex == 1) {
					this.model.CHECKDATETIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				} else if (this.dateTimePickerInfo.dataIndex == 2) {
					this.model.ENDTIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				}
				this.dateTimePickerInfo.showCheckDate = false

			},
			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 = 'NAME'
				// json.SelectField = ["ID", "NAME", "NAME", "CODE"]
				// json.Sort = "NAME"
				// json.Order = 1
				if (p.name == 'Nav_Department') {
					// extendRule(json, 'DEVICE_STATUS', 1, '1');
					dataSelect = await DMDepartment(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_ListUser') {
					this.selectorInfo.isMultiple = true
					json.SelectField = ["ID", "NAME", "NAME"]
					json.Sort = 'ID'
					json.OrgRule = []
					json.OrgType = 0
					dataSelect = await FMUserUseful(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,
						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
				if (this.selectorInfo.name == 'Nav_Department') {
					this.model.Nav_Department = e;
					this.model.DEPARTMENT_ID = e.ID;
				} else if (this.selectorInfo.name == 'Nav_ListUser') {
					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.Nav_ListUserName = UsersName
				}


			},
			submit() {
				if (!this.model.CHECKDATETIME) {
					uni.$showErrorInfo('请选择维保开始时间！')
					return
				}
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				delete this.modelEdit.Nav_Department
				this.modelEdit.Nav_ListDetail.map(item => {
					if (!item.IS_DELETED) {
						item.STATUS_APPROVE = '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_APPROVE = '10' //只针对点检巡检，后端根据status判断 
				DMMaintenanceFull(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_MAINTENANCE_PLAN_ID: this.model.ID,
					ROW_NUM: ROW_NO,
					Nav_DeviceBase: {
						NAME: '',
						MACHINE_CODE: ''
					},
					SPEC: '',
					POSITION: '',
					RUNSETTIME: '',
					ENDTIME: '',
					CONTENTS: '',
					PLANCHECKFREQUENCY: '',
					PLANCHECKFREQUENCYShow: '',
					Nav_User: {
						NAME: '',
					},
					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 == 'MaintenanceResult') {
					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 == 'MaintenanceResult') {
					this.comPickerInfo = {
						showSheet: false,
						dataItem: this.comPickerInfo.dataItem,
						columns: [],
						title: '',
						name: '',
						formIndex: undefined
					}
					this.comPickerInfo.dataItem.ResultShow = e.value[0]
					this.comPickerInfo.dataItem.Result = 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>