<!-- 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">


				<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="CHECK_TIME" borderBottom>
					<u--input disabledColor="#fff" disabled v-model="model.CHECK_TIME" 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_Project.UNIT_NAME" borderBottom @click="handleShowSheet({title: '整改责任单位', name: 'ProjectName'})">
					<u--input v-if="model.Nav_Project" placeholder="请选择整改责任单位" disabledColor="#fff" disabled v-model="model.Nav_Project.UNIT_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="隐患提报人" required prop="Nav_User.NAME" borderBottom @click="handleShowSheet({title: '隐患提报人', name: 'UserName'})">
					<u--input disabledColor="#fff" placeholder="请选择隐患提报人" disabled v-model="model.Nav_User.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>
				<view class="upload-title">附件</view>
				<full-upload v-model="model.Nav_Files" :isShowBtn='true' :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" 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}}
									</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="生产单元：" prop="MineType" @click="handleChange(item,'minetype')" 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="检查区域" 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" placeholder="请填写检查内容" 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" placeholder="请填写检查依据" v-model="item.CHECK_BASIS" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>

								<u-form-item label="问题描述" borderBottom>
									<u--input disabledColor="#fff" placeholder="请填写问题描述" v-model="item.REMARK" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>
								<u-form-item label="隐患地点" borderBottom>
									<u--input disabledColor="#fff" placeholder="请填写隐患地点" v-model="item.ADRESS" border="none" inputAlign="right" fontSize="14px"></u--input>
								</u-form-item>

								<u-form-item label="整改期限" prop="CHECK_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>
								<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"></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" mode="date"></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,
		getRealIndex,
		getDepartmentName
	} from '../../../../utils/common'
	import {
		FMProductionUnits,
	} from '../../../../utils/enums.js'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import {
		WBHDFull,
		ProjectInputDangerApply,
		WBUserOrderPagedNew,
		CheckAreaEnumApply
	} 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: [],
				checkboxValue1: [],
				checkboxList1: [{
						title: '全公司',
						value: '全公司'
					},
					{
						title: '选矿厂',
						value: '选矿厂'
					},
					{
						title: '尾矿库',
						value: '尾矿库'
					},
					{
						title: '露天矿',
						value: '露天矿'
					},

					{
						title: '地下矿',
						value: '地下矿'
					}
				],
				indexShow: 0,
				UnitLists: [],
				model: {
					ID: '',
					ORG_ID: '',
					TaskID: null,
					PROJECT_ID: '',
					Nav_Project: {
						NAME: ''
					},
					Nav_User: {
						NAME: ''
					},
					MineTypes: [],
					Nav_Details: [{
						MineTypes: '',
						Nav_Area: {
							AREA: ''
						},
						ID: '',
						ORG_ID: '',
					}]
				},
				rules: {
					'Nav_Project.UNIT_NAME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change'],
						message: '请选择【整改责任单位】'
					},
					'Nav_User.NAME': {
						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'),
					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
				}
			},
			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()
			},
			stepAdd() {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					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 = false
					this.model.Nav_Details = []
					this.model.CHECK_TIME = uni.$u.timeFormat(new Date(),
						'yyyy-mm-dd')
					this.model.USER_ID = uni.getStorageSync('appInfo')?.User?.ID
					this.model.Nav_User.NAME = uni.getStorageSync('appInfo')?.User?.NAME
					if (this.model.ID == undefined || this.model.ID == '')
						this.model.ID = guid()
				}
				this.listPropValUpload.push(this.model.ID)

			},

			//显示时间控件
			showCheckDate(dataIndex, item) {
				this.dateTimePickerInfo.showCheckDate = true

				this.dateTimePickerInfo = {
					showCheckDate: true,
					dataIndex: dataIndex,
					item: item
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {
				// let v = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				// const {
				// 	name,
				// 	dataIndex
				// } = this.dateTimePickerInfo
				if (this.dateTimePickerInfo.dataIndex == 1) {
					this.model.CHECK_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd')
				} else {
					const realIndex = getRealIndex(this.dateTimePickerInfo.item, this.model.Nav_Details)
					this.model.Nav_Details[realIndex].END_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd')
				}
				this.dateTimePickerInfo.showCheckDate = false
			},

			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 == 'UserName') {
					dataSelect = await WBUserOrderPagedNew(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
					})
				} else if (p.name == 'Sub_Nav_ListArea') {
					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 (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);
				const index = this.selectorInfo.index;
				const realIndex = this.model.Nav_Details.findIndex(item => item === validDetails[index]);
				if (this.selectorInfo.name == 'ProjectName') { //项目名称
					this.model.Nav_Project = e;
					this.model.PROJECT_ID = e.ID;
				} else if (this.selectorInfo.name == 'UserName') {
					this.model.Nav_User = e;
					this.model.USER_ID = e.ID;
				} else if (this.selectorInfo.name == 'Sub_Nav_ListArea') {
					this.model.Nav_Details[realIndex].Nav_Area = e;
					this.model.Nav_Details[realIndex].AREA_ID = e.ID;
				}
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},

			submit() {
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				delete this.modelEdit.Nav_User
				delete this.modelEdit.Nav_Project
				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 (e.Nav_Area != null)
						delete e.Nav_Area
				})
				this.modelEdit.PUBLISH = 'SaveAndNotify'
				WBHDFull(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,
					MineType: 0,
					MineTypes: '',
					Nav_Area: {
						AREA: ''
					},
					CHECK_CONTENT: '',
					CHECK_BASIS: '',
					REMARK: '',
					ADRESS: '',
					END_TIME: '',
					Nav_Files: [],
					IS_DELETED: false,
				}
				this.model.Nav_Details.push(modelAdd)
				this.indexShow = ROW_NO
			},

			handleChange(item, name) {
				let arr = name == 'minetype' ? FMProductionUnits : this.listISORNOTText
				this.comPickerInfo = {
					showSheet: true,
					columns: [arr],
					dataItem: item,
					name: name
				}
			},
			onConfirmPicker(e) {
				const codeMapping = {
					'全公司': 0,
					'选矿厂': 10,
					'尾矿库': 20,
					'露天矿': 30,
					'地下矿': 40
				};
				this.comPickerInfo = {
					showSheet: false,
					dataItem: this.comPickerInfo.dataItem,
					columns: [],
					title: '',
					name: this.comPickerInfo.name,
					formIndex: undefined
				}
				if (this.comPickerInfo.name == 'minetype') {
					this.comPickerInfo.dataItem.MineType = codeMapping[e.value]
					this.comPickerInfo.dataItem.MineTypes = String(e.value)
				} else {

					this.comPickerInfo.dataItem.ISORNOTShow = e.value[0]
					this.comPickerInfo.dataItem.ISORNOT = this.listISORNOT[e.indexs[0]].code
				}

				// 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>