<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'})">
						<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'})">
						<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-item label="含下级组织成员" v-if="model.STATUS == undefined||model.STATUS == '0'">
						<u-switch v-model="model.IS_DOWN" @change="changeDown" slot="right"></u-switch>
					</u-form-item>

				</u--form>
				<u--form labelWidth="auto" :model="model" ref="wForm" class="sub-form">


					<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;margin-top: 20px;">参与人员</view>
					<uni-collapse :border="false" accordion>
						<view v-for="(item, index) in model.Nav_Demands.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_Department||{}).NAME+'-'+(item.Nav_User||{}).NAME}}
										</view>
										<view @click.stop>
											<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 label="组织" prop="Product_Unit" @click="handleShowSheet({title: '组织', name: 'Nav_Department',itemData:item})" borderBottom>
										<u--input v-model="(item.Nav_Department||{}).NAME" 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="Product_Unit" @click="handleShowSheet({title: '人员', name: 'Nav_User',itemData:item})" borderBottom>
										<u--input v-model="(item.Nav_User||{}).NAME" 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>


							</uni-collapse-item>
						</view>
					</uni-collapse>
					<view style="padding: 10px 16px;display: flex;flex-direction: row;">
						<u-button type="primary" @click="handleNew" color="#3d4b70" :plain="true" style="margin-right: 5px;">新增</u-button>
						<!-- <u-button type="primary" @click="handleNewCheckList" color="#3d4b70" style="margin-left: 5px;">检查清单</u-button> -->
					</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>
			<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>
		</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,
				isMultiple: false,
				defaultChecked: [],
				ORG_ID: uni.getStorageSync('orgId'),
				model: {
					Nav_JoinDepartment: [],
					Nav_Points: [],
					NAME: '',
					END_TIME: '',
					Nav_Demands: []

				},
				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'),
				stepsPage: 0,
				stepsPageList: 0,
				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
					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_Points.Nav_Point');
					extendInclude(json, 'Nav_LaunchDepartment');
					extendInclude(json, 'Nav_LaunchUser');
					extendInclude(json, 'Nav_JoinDepartment');
					extendInclude(json, 'Nav_Points');
					extendInclude(json, 'Nav_Demands');
					extendInclude(json, 'Nav_Demands.Nav_Department');
					extendInclude(json, 'Nav_Demands.Nav_User');

					extendIgnoreDataRule(json)
					// extendInclude(json, 'Nav_Details.Nav_DetailContents.Nav_Question');
					getRequest(json, "/SE/TrainSurvey/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
				}

			},
			changeDown(e) {
				this.getOperationList()
			},
			handleDelRowBefore(item) {
				item.IS_DELETED = true
				let indexNotDel = 1
				this.model.Nav_Demands.forEach((e, i) => {
					if (!e.IS_DELETED) {
						e.ROW_NO = indexNotDel
						indexNotDel++
					}
				})
				this.$forceUpdate()
			},

			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' || p.name == 'Nav_Department') {
					if (p.name == 'Nav_JoinDepartment') {
						this.selectorInfo.isMultiple = true
						extendRule(json, 'ENABLE_STATUS', 1, '0')
						json.Sort = 'ID'
						json.SelectField = ["ID", "NAME", "NAME"]
					}



					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
								res.Data[i].name = res.Data[i].NAME
							}
						} else {
							uni.showToast({
								title: '暂无信息',
								icon: 'none'
							})
						}
						return res.Data
					})
					if (p.name == 'Nav_JoinDepartment') {
						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
					json.Sort = "ID"


					extendRule(json, 'TYPE', 1, '2')

					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
					}
				}else if (p.name == 'Nav_User') {
					if (p.itemData.DEPARTMENT_ID) {
						extendRule(json, 'DEPARTMENT_ID', 1, p.itemData.DEPARTMENT_ID)
					}
					json.OrgRule = []
					dataSelect = await getRequestOrderPage(json, "/FM/FMUser/OrderPagedUseful").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 (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(),
									SURVEY_ID: this.model.ID,
									DEPARTMENT_ID: item.ID,
									ORG_ID: item.ORG_ID,
									Nav_Department: item
								})
							}
						})
					}
					this.model.Nav_JoinDepartment = listArea
					this.getOperationList()
					// 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(),
									SURVEY_ID: this.model.ID,
									POINT_ID: item.ID,
									ORG_ID: item.ORG_ID,
									Nav_Point: item
								})
							}
						})
					}
					this.model.Nav_Points = listArea
				} else if (this.selectorInfo.name == 'Nav_Department') {
					this.selectorInfo.itemData.Nav_Department = e
					this.selectorInfo.itemData.DEPARTMENT_ID = e.ID
				} else if (this.selectorInfo.name == 'Nav_User') {
					this.selectorInfo.itemData.Nav_User = e
					this.selectorInfo.itemData.USER_ID = e.ID
				}


			},
			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

			},
			handleNew() {
				this.model.Nav_Demands.push({
					Nav_Department: {
						NAME: ''
					},
					Nav_User: {
						NAME: ''
					},
					USER_ID: '',
					DEPARTMENT_ID: ''
				})
			},
			getOperationList() {
				let keyWord = ''
				if (this.model.Nav_JoinDepartment != null && this.model.Nav_JoinDepartment.length > 0) {
					this.model.Nav_JoinDepartment.forEach(e => {
						if (e.IS_DELETED == null || e.IS_DELETED == false)
							keyWord += e.DEPARTMENT_ID + '|'
					})
				}
				if (keyWord.length > 0) {
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, keyWord, null, null, null, (this.model.IS_DOWN == null ? 'false' : this.model.IS_DOWN), this.model.ID)
					extendRule(json, 'id', 1, this.model.ID);
					getRequestOrderPage(json, "/SE/SETrainSurvey/GetListDemand").then(res => {
						this.model.Nav_Demands = res.Data
					})
				}
			
			},
			submit() {
				this.modelEdit = JSON.parse(JSON.stringify(this.model))
				if (this.modelEdit.Nav_Demands && this.modelEdit.Nav_Demands.length > 0) {
					this.modelEdit.Nav_Demands.map(item => {
						delete item.Nav_Department
						delete item.Nav_User
					})
				}
				// if(this.modelEdit.Nav_JoinDepartment&&this.modelEdit.Nav_JoinDepartment.length>0){
				// 	this.modelEdit.Nav_JoinDepartment.map(item=>{
				// 		delete item.Nav_Department
				// 	})
				// }
				// if(this.modelEdit.Nav_Points&&this.modelEdit.Nav_Points.length>0){
				// 	this.modelEdit.Nav_Points.map(item=>{
				// 		delete item.Nav_Point
				// 	})
				// }



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


			}

		}



	}
</script>

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