<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 label="交底时间" prop="CHECKDATETIME" borderBottom @click="showCheckDate(1)">
						<u--input disabled disabledColor="#fff" v-model="model.DISCLOSURE_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 label="交底地点" prop="LOCATION" borderBottom>
						<u--input disabledColor="#ffffff" v-model="model.JOB_LOCATION" border="none" inputAlign="right" fontSize="14px" placeholder="请输入交底地点"></u--input>
					</u-form-item>
					<u-form-item label="交底人：" prop="Nav_User.NAME" @click="handleChangeMonitor('Nav_User')" borderBottom>
						<u--input disabledColor="#fff" v-model="(model.Nav_User||{}).NAME" disabled placeholder="请选择交底人" suffixIcon="arrow-down" suffixIconStyle="font-size:12px" fontSize="14px"
							customStyle="margin:0px;display:flex;padding:3px 0px" border="none" inputAlign="right">
						</u--input>
					</u-form-item>
					<u-form-item label="交底人部门：" prop="Nav_User.NAME" @click="handleChangeMonitor('Nav_Department')" borderBottom>
						<u--input disabledColor="#fff" v-model="(model.Nav_Department||{}).NAME" disabled placeholder="请选择交底人部门" suffixIcon="arrow-down" suffixIconStyle="font-size:12px" fontSize="14px"
							customStyle="margin:0px;display:flex;padding:3px 0px" border="none" inputAlign="right">
						</u--input>
					</u-form-item>
					<u-form-item label="交底内容" prop="LOCATION">

					</u-form-item>
					<u--textarea v-model="model.DisclosureContent" placeholder="请输入交底内容" border="surround"></u--textarea>
					<view class="upload-title">附件：</view>
					<full-upload v-model="model.Nav_Files"></full-upload>
					<u-form-item label="人员" @click="handleShowSheet({title: '人员', name: 'Nav_Person'})">
						<u-icon name="man-add" size="24" color="#3d9cff" slot="right"></u-icon>
					</u-form-item>
					<view class="tag-view" v-if="model.Nav_Person">
						<uni-tag class="tag" v-for="(i, k) in model.Nav_Person.filter(i => !i.IS_DELETED)" :key="k" :inverted="true" :text="i.Nav_User.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 {
		getUserLists,
		getDepartmentLists,
	} from '../../../../services/safe';
	import {
		getUser,
		getTechDisclosureSafe,
		fullFOTechDisclosureSafe,
		getRiskArea
	} from '../../../../services/apply/FOServices/FOServices.js'
	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_User: {
						NAME: ''
					},
					Nav_Department: {
						NAME: ''
					},
					Nav_Person: [],
				},
				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
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, "", "")
					let userid = uni.getStorageSync('appInfo').User.ID
					extendRule(json, 'ID', 1, userid);
					extendInclude(json, 'Nav_Department');
					extendIgnoreDataRule(json)
					// extendInclude(json, 'Nav_Details.Nav_DetailContents.Nav_Question');
					getUser(json).then(res => {
						this.stepLoad = false
						this.model.Nav_User.NAME = res.NAME
						this.model.USER_ID = res.ID
						this.model.Nav_Department.NAME = res.Nav_Department.NAME
						this.model.DEPARTMENT_ID = res.DEPARTMENT_ID
					})
				} else {
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, "", "")
					extendRule(json, 'ID', 1, this.ID);
					extendInclude(json, 'Nav_User');
					extendInclude(json, 'Nav_Department');
					extendInclude(json, 'Nav_Files.Nav_ImgFile');
					extendInclude(json, 'Nav_Person');
					extendInclude(json, 'Nav_Person.Nav_User');

					extendIgnoreDataRule(json)
					// extendInclude(json, 'Nav_Details.Nav_DetailContents.Nav_Question');
					getTechDisclosureSafe(json).then(res => {
						this.stepLoad = false
						this.model = res;
						this.model.ID = this.ID

					})
				}
			},
			handleAddPerson() {
				this.model.Nav_Person.unshift({
					TECH_DISCLOSURE_FROM_ID: this.model.ID,
					ID: guid(),
					ORG_ID: this.ORG_ID,
					Nav_User: {
						NAME: "",
						CODE: ""
					},
					USER_ID: "",
					IS_DELETED: false,
					DEAL_STATUS: 0,
				})
			},
			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 = []


				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
				this.selectorInfo.isMultiple = true


				// extendRule(json, 'DEVICE_STATUS', 1, '1');
				dataSelect = await getUserLists(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_Person && this.model.Nav_Person.length > 0 && this.model.Nav_Person[0]
					.Nav_User != null) {
					// this.selectorInfo.defaultChecked = []
					this.model.Nav_Person.forEach(e => {
						defaultChecked.push(e.Nav_User)
					})
				} else {
					defaultChecked = null
				}
				if (defaultChecked == null)
					defaultChecked = []
				if (dataSelect.length) {
					this.selectorInfo = {
						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,
				}
				this.handleShowSheet(p)
			},

			handleSelected(e) {
				this.selectorInfo.showPopup = false
				let listArea = []
				if (e.length > 0) {
					e.forEach((item, i) => {
						if (item.name != null || item.NAME != null) {
							listArea.push({
								ID: guid(),
								TECH_DISCLOSURE_FROM_ID: this.model.ID,
								USER_ID: item.ID,
								ORG_ID: item.ORG_ID,
								Nav_User: item
							})
						}
					})
				}
				this.model.Nav_Person = listArea

			},
			handleClosePopupMonitor() {
				this.showPopupMonitor = false
			},
			handleChangeMonitor(name) {
				this.currentOperateMonitor = name
				this.showPopupMonitor = true
				this.handleSearchMonitor('init')
			},
			handleSearchMonitor(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)

				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * 20;
				}

				if (this.currentOperateMonitor == 'Nav_User') {
					extendRule(json, 'ENABLE_STATUS', 1, '0')
					extendInclude(json, 'Nav_Department');
					getUserLists(json).then(res => {
						if (res.IsSuccessful) {
							this.monitorLists = res.Data.map(i => {
								return {
									...i,
									name: i.NAME,
									code: i.CODE
								}
							})
							this.curTotalMonitor = res.TotalCount
						}
					})
				} else if (this.currentOperateMonitor == 'Nav_Department') {
					extendRule(json, 'ENABLE_STATUS', 1, '0')
					getDepartmentLists(json).then(res => {
						if (res.IsSuccessful) {
							this.monitorLists = res.Data.map(i => {
								return {
									...i,
									name: i.NAME,
									code: i.CODE
								}
							})
							this.curTotalMonitor = res.TotalCount
						}
					})
				}

			},
			handleSelectedMonitor(val) {
				this.showPopupMonitor = false
				if (this.currentOperateMonitor == 'Nav_User') {
					this.model.Nav_User = val
					this.model.USER_ID = val.ID
					this.model.Nav_Department = val.Nav_Department
					this.model.DEPARTMENT_ID = val.Nav_Department.ID
				} else if (this.currentOperateMonitor == 'Nav_Department') {
					this.model.Nav_Department = val
					this.model.DEPARTMENT_ID = val.ID
				}
				this.currentOperateMonitor = val
			},
			handleDelRowBefore(item) {
				this.nowIndex = item
				this.showDelModalIndex = 1

			},
			confirmDel() {

				this.nowIndex.IS_DELETED = true
				this.showDelModalIndex = undefined
			},
			cacelDel() {
				this.showDelModalIndex = undefined
			},
			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) {
				this.model.DISCLOSURE_DATE = 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_Department
				delete this.modelEdit.Nav_User

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


			}

		}



	}
</script>

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