<template>
	<view class="todo-page">
		<view class="background"></view>
		<view class="allview">
			<view class="card" >
				<u--form labelWidth="auto" :model="model" ref="wForm" 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="LOCATION" borderBottom>
						<u--input disabledColor="#ffffff" v-model="model.NAME" border="none" inputAlign="right" fontSize="14px" placeholder="请输入调查名称"></u--input>
					</u-form-item>
					
					<u-form-item required label="截止时间" prop="ENDTIME" borderBottom @click="showCheckDate(1)">
						<u--input disabled disabledColor="#fff" v-model="model.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="参与部门" @click="handleShowSheet({title: '参与部门', name: 'Nav_JoinDepartment'})" borderBottom>
						<u-icon name="arrow-down" size="12" slot="right"></u-icon>
					</u-form-item>
					<view class="tag-view" v-if="model.Nav_JoinDepartment">
						<uni-tag class="tag" v-for="(i, k) in model.Nav_JoinDepartment.filter(i => !i.IS_DELETED)" :key="k" :inverted="true" :text="i.Nav_Department.NAME" type="primary" />
					</view>
					<u-form-item required label="调查内容" @click="handleShowSheet({title: '调查内容', name: 'Nav_Points'})" borderBottom>
						<u-icon name="arrow-down" size="12" slot="right"></u-icon>
					</u-form-item>
					<view class="tag-view" v-if="model.Nav_Points">
						<uni-tag class="tag" v-for="(i, k) in model.Nav_Points.filter(i => !i.IS_DELETED)" :key="k" :inverted="true" :text="i.Nav_Point.NAME" type="primary" />
					</view>

				</u--form>
			</view>
			<view style="padding: 10px 16px;"  class="bottom-button">
				<u-button type="primary" @click="submit" color="#3d4b70" :loading="stepLoad">提交</u-button>
			</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-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" @close="comPickerInfo.showSheet=false" @cancel="comPickerInfo.showSheet=false" keyName="NAME"></u-picker>
			<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" @cancel="cacelDel" :showCancelButton="true" title="确认删除？"></u-modal>
			<people-selector :defaultChecked="peopleSelectOption.defaultChecked" :show="peopleSelectOption.showSelector" @select="handleSelectorPeople" @close="peopleSelectOption.showSelector = false">
			</people-selector>
			<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>
			<query-selector :show="showPopupMonitor" :total="curTotalMonitor" :lists="monitorLists" :defaultValue="currentOperateMonitor.NAME" @close="handleClosePopupMonitor" @search="handleSearchMonitor"
				@select="handleSelectedMonitor" />
		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		extendIgnoreDataRule,
		guid,
		initFilter,
		initFilterGroup
	} from '../../../../utils/common'
	import {
		FMProductionUnit,
		CheckPeriods,
		CheckLevels,
		MineTypeIndex,
		MineTypeName
	} from '../../../../utils/enums.js'
	import {
		getRequest,
		getRequestOrderPage
	} from '../../../../services/apply/FOServices/FOServices';
	import stepTitle from '@/components/custom/step-title.vue'
	import swipeActionItem from '../../../../uni_modules/uview-ui/libs/config/props/swipeActionItem';
	import {
		getEnum
	} from '../../../../services/common';
	export default {
		components: {
			stepTitle,
		},
		data() {
			return {
				showDelModalIndex: undefined,
				showDelModalIndex1: undefined,
				subsectionList: ['无隐患', '有隐患', '不涉及'],
				isMultiple: false,
				defaultChecked: [],
				RiskLevel: ['一般', '重大'],
				showPopupUnit: false,
				UnitDefaultIndex: [0],
				RiskLevelDefaultIndex: [0],
				UnitLists: [],
				showPopupRiskLevel: false,
				TypeLists: [],
				showPopupType: false,
				TypeDefaultIndex: [0],
				PeriodLists: [],
				showPopupPeriod: false,
				PeriodDefaultIndex: [0],
				LevelLists: [],
				showPopupStep: false,
				showPopupLevel: false,
				curTotalStep: 0,
				stepLists: [],
				LevelDefaultIndex: [0],
				showPopupDate: false,
				listPropUpload: ['NOTIFY_ID'],
				listPropValUpload: [],
				ORG_ID: uni.getStorageSync('orgId'),
				checkListData: {},
				monitorLists: [],
				currentOperateMonitor: {},
				showPopupMonitor: false,
				curTotalMonitor: 0,
				model: {
					Nav_ApplyUser: {
						NAME: ''
					},
					Nav_ApplyDepartment: {
						NAME: ''
					},
					Nav_ProductionUnit: {
						NAME: ''
					},
					Nav_OperationStep: {
						NAME: ''
					},
					Nav_FireDepartment: {
						NAME: ''
					},
					Nav_FireUser: {
						NAME: ''
					},
					Nav_SafeUser: {
						NAME: ''
					},
					Nav_Area: {
						NAME: ''
					},
					Nav_Type: {
						NAME: ''
					},
					IS_HOLIDAY: false,
					IS_HOLIDAYName: '否',
					EVALUATE_LEVEL: '',
					EVALUATE_LEVELName: '',
					JOB_LOCATION: '',
					JOB_CONTENT: '',
					JOB_DATE: '',
					JOB_END_DATE: '',
					Nav_Users: [],
					Nav_Risks: [],
					Nav_Details: [],
					Nav_Files: []
				},
				peopleSelectOption: {
					showSelector: false,
					value: null,
					index: 0,
					defaultChecked: []
				},
				dateTimePickerInfo: {
					showCheckDate: false,
					dataIndex: undefined,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					value: '',
					name: '',
					mode: ''
				},
				selectorInfo: {
					name: 'user',
					isMultiple: false,
					showPopup: false,
					totalCount: 0,
					title: '考核结果选择',
					itemData: {},
					dataItem: {},
					index: 0,
					columns: [],
					dataLists: [],
					defaultText: '',
					defaultChecked: []
				},
				comPickerInfo: {
					showSheet: false,
					dataItem: {},
					columns: [],
					title: '',
					dataIndex: undefined,
					formIndex: undefined,
					name: ''
				},
				dateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
				stepsText: ['发起', '归档'],
				stepsPage: 0,
				stepsPageList: 0,
				Pu: '',
				Check_Type_ID: '',
				TypeListres: {},
				TaskID: '',
				poparr: '',
				currentOperateStep: {},
				chooseCheckContent: '',
				chooseCheckArea: '',
				currentOperateArea: {},
				areaLists: [],
				curTotalArea: 0,
				showPopupArea: false,
				nowIndex: {},
				nowName: '',
				newCheckList: false,
				stepLoad: true,
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {} // 存储枚举文本列表（用于下拉选择等场景）

			}
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			this.model.ID = option.ID ? option.ID : '';
			this.ID = option.ID ? option.ID : '';
			this.loadData();
		},
		methods: {
			loadData() {
				if (this.ID == undefined || this.ID == '') {
					this.stepLoad = false
					this.model.Nav_Details = []
					if (this.ID == undefined || this.ID == '')
						this.ID = guid()
					this.model.ID = this.ID
				} else {
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, "", "")
					extendRule(json, 'ID', 1, this.ID);
					extendInclude(json, 'Nav_JoinDepartment.Nav_Department');
					extendInclude(json, 'Nav_JoinDepartment');
					extendInclude(json, 'Nav_Points');
					extendInclude(json, 'Nav_Points.Nav_Point');
					extendInclude(json, 'Nav_LaunchUser');

					extendIgnoreDataRule(json)
					// extendInclude(json, 'Nav_Details.Nav_DetailContents.Nav_Question');
					getRequest(json, "/SE/SafeSurvey/Get").then(res => {
						this.stepLoad = false
						this.model = res;
						this.model.ID = this.ID
					})
				}
			},
			stepAdd() {
				const isBlank = (value) => {
					return typeof value !== 'string' || value.trim() === '';
				};
				if (isBlank(this.model.Nav_OperationStep.NAME) ||
					isBlank(this.model.Nav_FireDepartment.NAME) ||
					isBlank(this.model.Nav_FireUser.NAME) ||
					isBlank(this.model.Nav_SafeUser.NAME) ||
					isBlank(this.model.JOB_DATE) ||
					isBlank(this.model.JOB_END_DATE)) {
					uni.$showErrorInfo('请检查必填项，必填项不能为空')
				} else {
					this.stepsPageList = this.stepsPageList + 1
				}

			},

			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'
				if (p.name == 'Nav_JoinDepartment') {
					
					this.selectorInfo.isMultiple = true


					extendRule(json, 'ENABLE_STATUS', 1, '0')

					dataSelect = await getRequestOrderPage(json, "/FM/Department/OrderPaged").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
							}
						} else {
							uni.showToast({
								title: '暂无信息',
								icon: 'none'
							})
						}
						return res.Data
					})
					if (this.model.Nav_JoinDepartment && this.model.Nav_JoinDepartment.length > 0 && this.model.Nav_JoinDepartment[0]
						.Nav_Department != null) {
						// this.selectorInfo.defaultChecked = []
						this.model.Nav_JoinDepartment.forEach(e => {
							defaultChecked.push(e.Nav_Department)
						})
					} else {
						defaultChecked = null
					}
				} else if (p.name == 'Nav_Points') {
					
					this.selectorInfo.isMultiple = true
					
					extendRule(json, 'TYPE', 1, '1')
					
					dataSelect = await getRequestOrderPage(json, "/SE/TestEnumPoint/OrderPaged").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
							}
						} else {
							uni.showToast({
								title: '暂无信息',
								icon: 'none'
							})
						}
						return res.Data
					})
					if (this.model.Nav_Points && this.model.Nav_Points.length > 0 && this.model.Nav_Points[0]
						.Nav_Point != null) {
						// this.selectorInfo.defaultChecked = []
						this.model.Nav_Points.forEach(e => {
							defaultChecked.push(e.Nav_Point)
						})
					} 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,
					itemData: this.selectorInfo.itemData
				}
				this.handleShowSheet(p)
			},

			handleSelected(e) {
				this.selectorInfo.showPopup = false
				if (this.selectorInfo.name == 'Nav_JoinDepartment') {
					let listArea = []
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (item.name != null || item.NAME != null) {
								listArea.push({
									ID: guid(),
									SAFE_ID: this.model.ID,
									DEPARTMENT_ID: item.ID,
									ORG_ID: item.ORG_ID,
									Nav_Department: item
								})
							}
						})
					}
					this.model.Nav_JoinDepartment = listArea
					// this.model.RiskAreaNAME = areaShow
				} else if (this.selectorInfo.name == 'Nav_Points') {
					let listArea = []
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (item.name != null || item.NAME != null) {
								listArea.push({
									ID: guid(),
									SAFE_ID: this.model.ID,
									POINT_ID: item.ID,
									ORG_ID: item.ORG_ID,
									Nav_Point: item
								})
							}
						})
					}
					this.model.Nav_Points = listArea
				} 


			},
			showCheckDate(dataIndex, item) {
				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.END_TIME = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd hh:MM:ss')
				}
				this.dateTimePickerInfo.showCheckDate = false

			},
			submit() {
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				delete this.modelEdit.Nav_ApplyDepartment
				delete this.modelEdit.Nav_ApplyUser
				delete this.modelEdit.Nav_Area
				delete this.modelEdit.Nav_FireDepartment
				delete this.modelEdit.Nav_FireUser
				delete this.modelEdit.Nav_OperationStep
				delete this.modelEdit.Nav_ProductionUnit
				delete this.modelEdit.Nav_SafeUser
				delete this.modelEdit.Nav_Type
				if(this.model.Nav_Risks&&this.model.Nav_Risks.length>0){
					this.model.Nav_Risks.map(item=>{
						delete item.Nav_Risk
					})
				}
				if (this.modelEdit.Nav_Users && this.modelEdit.Nav_Users.length > 0) {
					this.modelEdit.Nav_Users.map(item => {
						item.PUBLISH = 'SaveAndNotify'
						delete item.Nav_Train
						delete item.Nav_User
						delete item.Nav_UserType
						if (item.Nav_UserFiles && item.Nav_UserFiles.length > 0) {
							item.Nav_UserFiles.map(item1 => {
								item1.FIRE_JOB_USER_ID = item.ID
							})
						}
					})
				}

				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'
				getRequest(this.modelEdit, "/SE/SESafeSurvey/FullUpdate").then(res => {
					if (res) {
						uni.$showMsgFunc('操作成功!', () => {
							uni.navigateBack()
						}, 'success', 1000)
					}
				})


			}

		}



	}
</script>

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