<template>
	<view class="todo-page">
		<step-title :stepPage="stepsPage" :stepText="stepsText"></step-title>
		<view class="allview">
			<view class="card">
				<u--form labelWidth="auto" :model="dataModel" 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="YEAR">
						<u--input v-model="dataModel.YEAR" disabledColor="#ffffff" placeholder="请填写年度" border="none" inputAlign="right" fontSize="14px">
						</u--input>
					</u-form-item>

					<u-form-item label="辨识开始时间" @click="handleChangeRecitify('start')">
						<u--input v-model="dataModel.START_DATE" placeholder="请选择时间" disabled disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
						</u-icon>
					</u-form-item>
					<u-form-item label="辨识结束时间" @click="handleChangeRecitify('end')">
						<u--input v-model="dataModel.END_DATE" placeholder="请选择时间" disabled disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
						</u-icon>
					</u-form-item>
					<u-form-item label="评估结束时间" @click="handleChangeRecitify('evaluate')">
						<u--input v-model="dataModel.EVALUATION_END_DATE" placeholder="请选择时间" disabled disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
						</u-icon>
					</u-form-item>
					<u-form-item label="辨识与评估内容:">
						<!-- <u--input v-model="dataModel.CONTENTS" placeholder="请填写内容" disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input> -->
					</u-form-item>
					<u--textarea v-model="dataModel.CONTENTS" placeholder="请输入内容" autoHeight></u--textarea>
					<u-form-item label="辨识要求" borderBottom @click="handleShowSheet({title: '辨识要求', name: 'Nav_Requires'})">
						<u-icon style="margin-left: 4px;" name="arrow-down" size="12" slot="right"></u-icon>
					</u-form-item>
					<u-textarea v-model="dataModel.Nav_RequiresName" disabled autoHeight placeholder="请选择辨识要求"></u-textarea>
					<u-form-item label="评估要求" borderBottom @click="handleShowSheet({title: '评估要求', name: 'Nav_Evaluations'})">
						<u-icon style="margin-left: 4px;" name="arrow-down" size="12" slot="right"></u-icon>
					</u-form-item>
					<u-textarea v-model="dataModel.Nav_EvaluationsName" disabled autoHeight placeholder="请选择评估要求"></u-textarea>
					<view class="upload-title">附件：</view>
					<full-upload v-model="dataModel.Nav_Files" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>

				</u--form>
				<u--form labelWidth="auto" :model="dataModel" ref="wForm" class="demo-ruleForm" style="margin-top: 20px;border-top: #ceccca 1px solid;">
					<!-- <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> -->
					<view v-for="(item,index) in dataModel.Nav_Details.filter(i => !i.IS_DELETED)" :key="index" style="border-bottom: #ceccca 1px dashed;padding-bottom: 10px;">
						<u-form-item>
							<view style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;flex: 1;">
								<view @click="handleShowSheet({title: '部门', name: 'Nav_Department',itemData:item})" style="flex: 1;display: flex;flex-direction: row;align-items: center;">
									<view>
										{{'部门 : ' +item.Nav_Department.NAME}}
									</view>
									<u-icon style="margin-left: 5px;" name="arrow-down" size="12">
									</u-icon>
								</view>
								<view class="action" style="display: flex;flex-direction: row;align-items: center;justify-content: space-around;">
									<u-icon @click="handleDelRowBefore(item)" name="trash" color="#ff4d4f" size="21"></u-icon>
								</view>
							</view>
						</u-form-item>
						<u-form-item label="辨识人员" @click="handleShowUserSelector(item)">
							<u-icon name="man-add" size="24" color="#3d9cff" slot="right"></u-icon>
						</u-form-item>
						<view v-show="!!item.Nav_DetailUsers.length" class="tag-view">
							<u-textarea v-model="item.userlist" disabled></u-textarea>
						</view>
					</view>

				</u--form>
			</view>
			<view style="padding: 10px 16px;display: flex;flex-direction: row;" class="bottom-button">
				<u-button text="新增" type="primary" color="#3d4b70" :plain="true" style="margin-right: 5px;" @click="handleNewCheckContent"></u-button>
				<u-button type="primary" @click="submit" color="#3d4b70" style="margin-left: 5px;">提交</u-button>
			</view>

			<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" @cancel="cacelDel" :showCancelButton="true" title="确认删除？"></u-modal>
			<u-datetime-picker :show="showPopupRecitifyDate" v-model="dateRecitifyTime" mode="date" @confirm="confirmRecitifyDate" @cancel="cancelRecitifyDate"></u-datetime-picker>
			<people-selector-dep :defaultChecked="peopleSelectOption.defaultChecked" :depId="peopleSelectOption.depId" :show="peopleSelectOption.showSelector" @select="handleSelectorPeople"
				@close="peopleSelectOption.showSelector = false">
			</people-selector-dep>
			<!-- <query-selector :show="showPopupStep" :total="curTotalStep" :lists="stepLists" :defaultValue="currentOperateStep.NAME" @close="handleClosePopupStep" @search="handleSearchStep" @select="handleSelectedStep" /> -->
			<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" />
		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		extendIgnoreDataRule,
		guid,
		initFilter,
		initFilterGroup,
		handleOriginalArray
	} from '../../../../utils/common'
	import {
		FMProductionUnit,
		CheckPeriods,
		CheckLevels
	} from '../../../../utils/enums.js'
	import {
		EvaluationPlanGet,
		EvaluationPlanFullUpdate,
		getUserLists,
		GetDepartmentInfo
	} from '../../../../services/apply/subPages/SK/SKServices.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';
	export default {
		components: {
			stepTitle,
		},
		data() {
			return {
				showDelModalIndex: undefined,
				showPopupDate: false,
				showPopupRecitifyDate: false,
				listPropUpload: ['NOTIFY_ID'],
				listPropValUpload: [],
				ORG_ID: uni.getStorageSync('orgId'),
				currentOperateStep: {},
				showPopupStep: false,
				stepLists: [],
				curTotalStep: 0,
				selectorInfo: {
					name: 'user',
					isMultiple: false,
					showPopup: false,
					totalCount: 0,
					title: '考核结果选择',
					dataItem: {},
					index: 0,
					columns: [],
					dataLists: [],
					defaultText: '',
					defaultChecked: []
				},
				dataModel: {
					YEAR: '',
					START_DATE: '',
					END_DATE: '',
					EVALUATION_END_DATE: '',
					CONTENTS: '',
					Nav_Files: [],

					Nav_Details: [{
						Nav_Department: {
							NAME: ''
						},
						Nav_DetailUsers: [{
							Nav_User: {
								NAME: ''
							}
						}],
						userlist: '',
					}]
				},
				model: {
					ORG_ID: '',
					YEAR: '',
					START_DATE: '',
					END_DATE: '',
					EVALUATION_END_DATE: '',
					CONTENTS: '',
					Nav_Files: [],
					Nav_Details: [{
						Nav_Department: {
							NAME: ''
						},
						Nav_DetailUsers: [{
							Nav_User: {
								NAME: ''
							}
						}]
					}]

				},
				peopleSelectOption: {
					showSelector: false,
					value: null,
					index: 0,
					depId: '',
					defaultChecked: []
				},
				dateRecitifyTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
				stepsText: ['发起', '审批', '归档'],
				stepsPage: 0,
				stepsPageList: 0,
				TaskID: '',
				nowName: '',
				nowIndex: 0,

			}
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			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()
					if (this.TaskID == undefined || this.TaskID == '')
						this.TaskID = '00000000-0000-0000-0000-000000000000'

				} else {
					// const json = {}
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, "", "")
					extendRule(json, 'ID', 1, this.ID);
					extendInclude(json, 'Nav_Requires');
					extendInclude(json, 'Nav_Requires.Nav_Require');
					extendInclude(json, 'Nav_Evaluations');
					extendInclude(json, 'Nav_Evaluations.Nav_Evaluation');
					extendInclude(json, 'Nav_Files.Nav_ImgFile');
					extendInclude(json, 'Nav_Details');
					extendInclude(json, 'Nav_Details.Nav_Department');
					extendInclude(json, 'Nav_Details.Nav_DetailUsers.Nav_User');
					extendIgnoreDataRule(json)
					// extendRule(json, 'TASK_ID', 1, this.TaskID);
					EvaluationPlanGet(json).then(res => {
						this.dataModel = res;
						this.stepsPage = res.STATUS == 0 ? 0 : res.STATUS == 20 ? 1 : 2
						this.dataModel.START_DATE = uni.$u.timeFormat(res.START_DATE, 'yyyy-mm-dd')
						this.dataModel.END_DATE = uni.$u.timeFormat(res.END_DATE, 'yyyy-mm-dd')
						this.dataModel.EVALUATION_END_DATE = uni.$u.timeFormat(res.EVALUATION_END_DATE, 'yyyy-mm-dd')
						let Nav_RequiresName = ''
						if (this.dataModel.Nav_Requires && this.dataModel.Nav_Requires.length > 0) {
							this.dataModel.Nav_Requires.map(item => {
								if (item.Nav_Require && item.Nav_Require.NAME !== null) {
									Nav_RequiresName += item.Nav_Require.NAME + ' ';
								}
							})
						}
						this.dataModel.Nav_RequiresName = Nav_RequiresName
						let Nav_EvaluationsName = ''
						if (this.dataModel.Nav_Evaluations && this.dataModel.Nav_Evaluations.length > 0) {
							this.dataModel.Nav_Evaluations.map(item => {
								if (item.Nav_Evaluation && item.Nav_Evaluation.NAME !== null) {
									Nav_EvaluationsName += item.Nav_Evaluation.NAME + ' ';
								}
							})
						}
						this.dataModel.Nav_EvaluationsName = Nav_EvaluationsName
						this.dataModel.Nav_Details.map((item, index) => {
							let arr = item.Nav_DetailUsers.map((item1, index1) => {
								if (item1.Nav_User && !item1.Nav_User.IS_DELETED) {
									return '  ' + item1.Nav_User.NAME
								}

							})
							item['userlist'] = String(arr)
						})

					})
				}
			},
			handleNewCheckContent() {
				this.dataModel.Nav_Details.unshift({
					IS_DELETED: false,
					ID: guid(),
					IDENTIFY_EVALUATION_PLAN_ID: this.ID,
					Nav_Department: {
						NAME: ''
					},
					Nav_DetailUsers: [{
						Nav_User: {
							NAME: ''
						}
					}]
				})

				this.dataModel.Nav_Details = [...this.dataModel.Nav_Details]
			},
			handleDelRowBefore(item) {
				item.IS_DELETED = true
				this.$forceUpdate()
			},
			cancelRecitifyDate() {
				this.showPopupRecitifyDate = false
			},
			handleChangeRecitify(name) {
				this.nowName = name
				this.showPopupRecitifyDate = true
			},
			confirmRecitifyDate(e) {
				if (this.nowName == 'start') {
					this.dataModel.START_DATE = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd ')

				} else if (this.nowName == 'end') {
					this.dataModel.END_DATE = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd ')
				} else {
					this.dataModel.EVALUATION_END_DATE = uni.$u.timeFormat(e.value,
						'yyyy-mm-dd ')
				}
				this.dateRecitifyTime = uni.$u.timeFormat(e.value,
					'yyyy-mm-dd ')

				this.showPopupRecitifyDate = false
			},
			handleChangeStep(item) {
				this.currentOperateStep = {}
				this.showPopupStep = true
				this.nowIndex = item
				this.handleSearchStep('init')
			},
			handleClosePopupStep() {
				this.showPopupStep = false
				// this.showPopupCertificate = false
			},
			handleSearchStep(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0, pageIndex ?? 1)
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * json.Limit;
				}
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				// json.Limit = 100
				GetDepartmentInfo(json).then(res => {
					// if (res.IsSuccessful) {
					this.stepLists = (res.Data || res).map(i => {
						return {
							...i,
							id: i.ID,
							name: i.NAME,
						}
					})
					this.curTotalStep = res.TotalCount
					// }
				})
			},
			handleSelectedStep(val) {
				this.nowIndex.DEPARTMENT_ID = val.ID
				this.nowIndex.Nav_Department.NAME = val.NAME
				this.showPopupStep = false

			},
			handleSelectorPeople(e) {
				this.peopleSelectOption.value.Nav_DetailUsers = e.map(i => {
					return {
						USER_ID: i.USER_ID,
						IS_DELETED: i.IS_DELETED,
						NAME: i.NAME,
						Nav_User: {
							NAME: i.NAME,
							ID: i.USER_ID,
							IS_DELETED: i.IS_DELETED
						}
					}
				})
				let arr = ''
				this.peopleSelectOption.value.Nav_DetailUsers.map(item => {
					if (!item.IS_DELETED) {
						arr += ' ' + item.Nav_User.NAME
					}
				})
				this.peopleSelectOption.value.userlist = String(arr)
			},
			handleShowUserSelector(item) {
				this.peopleSelectOption = {
					showSelector: true,
					value: item,
					depId: item.DEPARTMENT_ID,
					defaultChecked: item.Nav_DetailUsers.map(i => {
						return {
							...i,
							NAME: i.Nav_User.NAME,
							USER_ID: i.Nav_User.ID,
						}

					})
				}
			},
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0, p.pageIndex ?? 1)
				let dataSelect = []
				// this.selectorInfo.defaultChecked = []
				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"]
				if (p.name == "Nav_Requires") {
					this.selectorInfo.isMultiple = true
					dataSelect = await getRequestOrderPage(json, "/SK/Request/OrderPaged").then(res => {
						this.selectorInfo.totalCount = res.TotalCount
						if (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
					})
					if (this.dataModel.Nav_Requires && this.dataModel.Nav_Requires.length > 0) {
						// this.selectorInfo.defaultChecked = []
						this.dataModel.Nav_Requires.filter(i => !i.IS_DELETED).forEach(e => {
							if (e.Nav_Require != null && e.Nav_Require.NAME != null)
								defaultChecked.push(e.Nav_Require)
						})
					} else {
						defaultChecked = null
					}
				} else if (p.name == "Nav_Evaluations") {
					this.selectorInfo.isMultiple = true
					dataSelect = await getRequestOrderPage(json, "/SK/Evaluation/OrderPaged").then(res => {
						if (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
					})
					if (this.dataModel.Nav_Evaluations && this.dataModel.Nav_Evaluations.length > 0) {
						// this.selectorInfo.defaultChecked = []
						this.dataModel.Nav_Evaluations.filter(i => !i.IS_DELETED).forEach(e => {
							if (e.Nav_Evaluation != null && e.Nav_Evaluation.NAME != null)
								defaultChecked.push(e.Nav_Evaluation)
						})
					} else {
						defaultChecked = null
					}
				} else if (p.name == 'Nav_Department') {
					dataSelect = await GetDepartmentInfo(json).then(res => {
						if (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
					})
				}
				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
					}
				} 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_Requires') {
					let listArea = []
					let areaShow = ''
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (item.name != null || item.NAME != null) {
								if (i > 0) {
									areaShow += ' '
								}
								listArea.push({
									ID: guid(),
									IDENTIFY_EVALUATION_PLAN_ID: this.ID,
									REQUIRE_ID: item.ID,
									ORG_ID: item.ORG_ID,
									Nav_Require: item
								})
								areaShow += item.NAME
							}
						})
					}
					this.dataModel.Nav_Requires = listArea
					this.dataModel.Nav_RequiresName = areaShow
				} else if (this.selectorInfo.name == 'Nav_Evaluations') {
					let listArea = []
					let areaShow = ''
					if (e.length > 0) {
						e.forEach((item, i) => {
							if (item.name != null || item.NAME != null) {
								if (i > 0) {
									areaShow += ' '
								}
								listArea.push({
									ID: guid(),
									IDENTIFY_EVALUATION_PLAN_ID: this.ID,
									EVALUATION_ID: item.ID,
									ORG_ID: item.ORG_ID,
									Nav_Evaluation: item
								})
								areaShow += item.NAME
							}
						})
					}
					this.dataModel.Nav_Evaluations = listArea
					this.dataModel.Nav_EvaluationsName = areaShow
				} else if (this.selectorInfo.name == 'Nav_Department') {
					this.selectorInfo.itemData.Nav_Department = e
					this.selectorInfo.itemData.DEPARTMENT_ID = e.ID
				}


			},

			submit() {
				if (!this.dataModel.CONTENTS) {
					uni.showToast({
						title: '请填写辨识与评估内容',
						icon: 'none'
					})
					return
				}
				for (let item of this.dataModel.Nav_Details.filter(i => !i.IS_DELETED)) {
					if (!item.Nav_Department.NAME) {
						uni.showToast({
							title: '部门不能为空',
							icon: 'none'
						})
						return
					}
					if (item.Nav_DetailUsers.length == 0) {
						uni.showToast({
							title: '辨识人员不能为空',
							icon: 'none'
						})
						return
					}
				}
				this.model =JSON.parse(JSON.stringify(this.dataModel))
				if (this.model.Nav_Details && this.model.Nav_Details.length > 0) {
					this.model.Nav_Details.map(item => {
						delete item.Nav_Department
					})
				}
				this.model.ID = this.ID
				this.model.TaskID = this.TaskID
				this.model.PUBLISH = "SaveAndNotify";
				EvaluationPlanFullUpdate(this.model).then(res => {
					if (res) {
						uni.$showMsgFunc('操作成功!', () => {
							uni.navigateBack()
						}, 'success', 1000)
					}
				})


			}

		}



	}
</script>

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