<template>
	<view class="todo-page">
		<uni-card margin="0" :is-shadow="true">
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model">
				<u-form-item label="审核意见：" prop="AUDIT_OPINION" borderBottom v-if="model.STATUS==9">
				</u-form-item>
				<u--textarea v-html="AUDIT_OPINION" border="surround" v-if="model.STATUS==9" disabled></u--textarea>
				<u-form-item v-if="isAdd!=1" label="层级：" prop="LEVEL_SHOW" borderBottom>
					<u--input v-model="model.LEVEL_SHOW" border="none" slot="right" inputAlign="right" disabled
						disabledColor="#fff"></u--input>
				</u-form-item>
				<u-form-item label="开始时间：" prop="START_TIME" borderBottom>
					<u--input v-model="model.START_TIME" border="none" slot="right" inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item label="结束时间：" prop="END_TIME" borderBottom>
					<u--input v-model="model.END_TIME" border="none" slot="right" inputAlign="right"></u--input>
				</u-form-item>
				<u-form-item v-if="isAdd!=1" label="辨识区域：" prop="Areas" borderBottom>
				</u-form-item>
				<u--textarea v-if="isAdd!=1" autoHeight v-model="model.Areas" border="none" inputAlign="right"
					disabled></u--textarea>
				<u-form-item required class="custom-form-item" label="职业危害名称" prop="DetailPost" :borderBottom="false">
					<view slot="right" class="custom-form-item-right">
						<view class="multi">
							<u--text v-for="(i, k) in model.Nav_Identifyings" :key="k" class="item"
								:text="k + 1 + '. ' + i.Nav_Identifying.NAME"></u--text>
						</view>
					</view>
				</u-form-item>
				<view class="upload-title">附件：</view>
				<full-upload v-model="model.Nav_Files" :isShowBtn='true' :listProp='listPropUpload'
					:listPropVal='listPropValUpload'></full-upload>
			</u--form>
		</uni-card>
		<u-sticky offset-top="20">
			<view class="sub-form">
				<view class="sub-form-wrap">
					<view class="sub-form-btns">
						<view class="sub-form-btn" @click="handleAddDetail">
							<u-icon class="icon" name="plus-circle" color="#3c9cff" size="21"></u-icon>
							<u--text type="primary" text="新增辨识任务"></u--text>
						</view>
					</view>
					<u--form labelPosition="left" labelWidth="auto" labelAlign="center" errorType="border-bottom"
						ref="sForm">
						<uni-collapse>
							<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
								v-for="(item, index) in model.Nav_Detail.filter(i => !i.IS_DELETED)">
								<uni-collapse-item title-border="none" :show-arrow="false" :border="false" :open="true">
									<view slot="title" class="custom-collapse-title">
										<view class="down">
											<uni-icons type="bottom"></uni-icons>
										</view>
										<view class="text">{{index + 1 + '. ' +item.Nav_Area.NAME}}</view>
										<view class="action" @click.stop>
											<u-icon @click="handleDelRowBefore(index, item)" class="icon" name="trash"
												color="#ff4d4f" size="21"></u-icon>
										</view>
									</view>
									<u-form-item label="区域：" prop="Nav_Area" borderBottom
										@click="handleChange('Nav_Area',item)">
										<u--input v-model="item.Nav_Area.NAME" placeholder="请选择区域" border="none"
											inputAlign="right" disabled disabledColor="#fff"></u--input>
										<u-icon style="margin-left: 4px;" slot="right" name="arrow-down">
										</u-icon>
									</u-form-item>
									<u-form-item required class="custom-form-item" label="职业危害名称" prop="DetailPost"
										:borderBottom="false"
										@click="handleQuerySelect({ formIndex: 'Nav_Identifyings', isMultiple: true, dataIndex: index})">
										<view slot="right" class="custom-form-item-right">
											<view class="multi">
												<u--text v-for="(i, k) in item.Nav_Identifyings" :key="k" class="item"
													:text="k + 1 + '. ' + i.Nav_Identifying.NAME"></u--text>
											</view>
											<u-icon class="icon" name="arrow-down">
											</u-icon>
										</view>
									</u-form-item>
									<u-form-item label="辨识人员：">
										<u-icon name="man-add" @click="handleShowUserSelector(item, index)" size="24"
											color="#3d9cff" slot="right"></u-icon>
									</u-form-item>
									<view v-show="!!item.Nav_Users.length" class="tag-view">
										<uni-tag class="tag" v-for="(i, k) in item.Nav_Users.filter(i => !i.IS_DELETED)"
											:key="k" :inverted="true" :text="i.NAME" type="primary" />
									</view>
									<u-form-item label="记录人员：" prop="Nav_User">
										<u--input v-if="item.Nav_User" v-model="item.Nav_User.NAME"
											placeholder="请选择记录人员" border="none" inputAlign="right" disabled
											disabledColor="#fff"></u--input>
									</u-form-item>
								</uni-collapse-item>
							</uni-card>
						</uni-collapse>
					</u--form>
				</view>
			</view>
		</u-sticky>
		<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" @cancel="cancelDel" showCancelButton
			title="确认删除？"></u-modal>
		<query-selector :show="showPopup" :lists="Lists" @close="handleClosePopup" @search="handleSearch"
			@select="handleSelected" />
		<people-selector :defaultChecked="peopleSelectOption.defaultChecked" :show="peopleSelectOption.showSelector"
			@select="handleSelectorPeople" @close="peopleSelectOption.showSelector = false">
		</people-selector>
		<query-selector :multiple="qsCom.isMultiple" :total="curTotal" :show="qsCom.show" :lists="qsCom.lists"
			@close="onCloseQS" @search="onSearchQS" @select="onSelectedQS" />
		<view class="bottom-button">
			<button type="primary" @click="submit">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup
	} from '../../../../utils/common'

	import {
		getAreaLists,
		getRiskRecordRefus,
		getIdentifying
	} from '../../../../services/apply/HMServices/HMServices'
	import {
		getRequest,
		getUserLists,
	} from '../../../../services/apply/FOServices/FOServices.js'
	import '../../../../utils/showMsg.js'
	import color from '../../../../uni_modules/uview-ui/libs/config/color'
	import config from '../../../../config/common'

	export default {
		data() {
			return {
				listPropUpload: ['TASK_ID'],
				listPropValUpload: [],
				model: {
					Nav_Detail: [],
					Nav_Areas: [],
					Nav_Files: [],
					Nav_Identifyings: [],
					START_TIME: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
					END_TIME: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd'),
					ORG_ID: uni.getStorageSync('orgId'),
				},
				curTotal: 0,
				qsCom: {
					show: false,
					lists: [],
					formIndex: undefined,
					isMultiple: false,
					dataIndex:undefined,
				},
				Lists: [],
				currSearchType: "",
				showPopup: false,
				TaskID: "",
				tableKey: '0',
				isLoadOK: false,
				showDelModalIndex: undefined,
				AUDIT_OPINION: "",
				isAdd: 0,
				peopleSelectOption: {
					showSelector: false,
					value: null,
					index: 0,
					defaultChecked: []
				},
				checked: true,
				ORG_ID: uni.getStorageSync('orgId')
			}
		},
		onLoad(option) {
			this.TaskID = option.taskID ? option.taskID : '';
			this.model.ID = option.ID ? option.ID : '';
			this.tableKey = option.tableKey ? option.tableKey : '0';
			if (option.isAdd != 1) {
				this.loadData();
			} else {
				this.isAdd = 1;
				let currUser = uni.getStorageSync('appInfo').User;
				this.model.LIABLE_USER_ID = currUser.ID;
				this.model.ID = guid();
				const json = initFilter(this.ORG_ID, "", "NAME", 1);
				json.SelectField = [
					"NAME",
					"ID",
				]
			}
		},
		methods: {
			handleSelectorPeople(e) {
				const {
					index: key
				} = this.peopleSelectOption
				this.model.Nav_Detail[key].Nav_Users = e.map(i => {
					return {
						USER_ID: i.USER_ID,
						ID: i.ID || guid(),
						TASK_DETAIL_ID: this.model.Nav_Detail[key].ID,
						ORG_ID: this.ORG_ID,
						IS_DELETED: i.IS_DELETED,
						NAME: i.NAME,
						Nav_User: {
							NAME: i.NAME,
							ID: i.USER_ID
						}
					}
				})
				this.model.Nav_Detail[key].Nav_User.NAME = e.filter(i => !i.IS_DELETED)[0].NAME;
				this.model.Nav_Detail[key].RECORD_USER_ID = e.filter(i => !i.IS_DELETED)[0].USER_ID;
			},
			handleShowUserSelector(item, index) {
				this.peopleSelectOption = {
					showSelector: true,
					value: item,
					index,
					defaultChecked: item.Nav_Users.map(i => {
						return {
							...i,
							NAME: i.Nav_User.NAME,
							USER_ID: i.Nav_User.ID,
						}
					})
				}
			},
			handleDelRowBefore(index, item) {
				if (item.AREA_ID == "" || item.AREA_ID == undefined) {
					this.model.Nav_Detail.splice(this.showDelModalIndex, 1)
				} else {
					this.showDelModalIndex = index
				}
			},
			cancelDel() {
				this.showDelModalIndex = undefined
			},
			confirmDel() {
				this.model.Nav_Detail[this.showDelModalIndex].IS_DELETED = true;
				this.model.Nav_Detail[this.showDelModalIndex].Nav_Users.forEach(item => {
					item.IS_DELETED = true;
				});
				this.showDelModalIndex = undefined
			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleAddDetail() {
				this.model.Nav_Detail.unshift({
					ID: guid(),
					TASK_ID: this.model.ID,
					ORG_ID: this.ORG_ID,
					Nav_User: {},
					Nav_Area: {
						NAME: ""
					},
					Nav_Users: [],
					IS_DELETED: false
				})
			},
			handleChange(title, item) {
				this.currentOperate = item;
				this.currSearchType = title;
				this.showPopup = true;
				this.handleSearch('init');
			},
			handleSearch(val) {
				const json = initFilter(this.ORG_ID, "", "NAME")
				json.Limit = 20
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				if (this.currSearchType == "Nav_Area") {
					if (this.model.Nav_Areas.length > 0) {
						extendRule(json, 'TASK_ID', 1, this.model.ID);
						extendInclude(json, 'Nav_Area');
						getRequest(json, "/HM/HazardTaskArea/Entities").then(res => {
							this.Lists = res.map(i => {
								return {
									...i,
									name: i.Nav_Area.NAME,
									type: 0
								}
							})
						})
					} else {
						getAreaLists(json).then(res => {
							if (res.IsSuccessful) {
								this.Lists = res.Data.map(i => {
									return {
										...i,
										name: i.NAME,
										type: 1
									}
								})
							}
						})
					}
				} else if (this.currSearchType == "Nav_User") {
					extendInclude(json, "Nav_Department")
					extendRule(json, 'ENABLE_STATUS', 1, '0')
					getUserLists(json).then(res => {
						if (res.IsSuccessful) {
							this.Lists = res.Data.map(i => {
								return {
									...i,
									name: i.NAME,
									code: i.CODE
								}
							})
						}
					})
				}
			},
			handleSelected(val) {
				this.showPopup = false
				this.Lists = []
				if (this.currSearchType == "Nav_Area") {
					if (val.type == 0) {
						this.currentOperate = val;
					} else {
						this.currentOperate.Nav_Area = val;
						this.currentOperate.AREA_ID = val.ID;
					}

				} else if (this.currSearchType == "Nav_User") {
					this.currentOperate.Nav_User = val;
					this.currentOperate.RECORD_USER_ID = val.ID;
				}
			},
			loadData() {
				const json = initFilter(this.ORG_ID, "", "CODE", 1)
				if (this.listPropValUpload.length == 0) {
					this.listPropValUpload.push(this.model.ID)
				}
				extendRule(json, 'ID', 1, this.model.ID);
				extendInclude(json, 'Nav_Identifyings.Nav_Identifying');
				extendInclude(json, 'Nav_Areas.Nav_Area');
				extendInclude(json, 'Nav_Files.Nav_ImgFile');

				extendInclude(json, 'Nav_Detail.Nav_Identifyings.Nav_Identifying');
				extendInclude(json, 'Nav_Detail.Nav_Users.Nav_User');
				extendInclude(json, 'Nav_Detail.Nav_User');
				extendInclude(json, 'Nav_Detail.Nav_Area');
				getRequest(json, "/HM/HazardTask/Get").then(res => {
					this.model = res
					if (res.STATUS == 9) {
						const json = initFilter(this.ORG_ID);
						json.ID = this.model.ID;
						getRiskRecordRefus(json).then(refusRes => {
							this.AUDIT_OPINION = refusRes;
						})
					}
					//数据组装
					let strAreas = ''
					if (res.Nav_Areas && res.Nav_Areas.length > 0) {
						for (let i = 0; i < res.Nav_Areas.length; i++) {
							strAreas += (strAreas.length > 0 ? " " : "") + res.Nav_Areas[
								i].Nav_Area.NAME;
						}
					}
					this.model.Nav_Detail.forEach(i => {
						i.Nav_Users.forEach(o => {
							o.NAME = o.Nav_User.NAME
						})
					})
					this.model.START_TIME = uni.$u.timeFormat(this.model.START_TIME, 'yyyy-mm-dd');
					this.model.END_TIME = uni.$u.timeFormat(this.model.END_TIME, 'yyyy-mm-dd');
					this.model.Areas = strAreas;
					this.isLoadOK = true;
				})
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},
			async handleQuerySelect(opt) {
				let column = await this.handleGet(opt, 'init')
				if (column && column.length) {
					this.qsCom = {
						show: true,
						name: opt.NAME,
						dataIndex:opt.dataIndex,
						formIndex: opt.formIndex,
						isMultiple: opt.isMultiple,
						lists: column
					}
				} else {
					// 暂无数据
				}
			},
			async onSearchQS(val, pi) {
				const result = await this.handleGet(this.qsCom, val, pi)
				this.qsCom.lists = result.map(i => {
					return {
						...i,
						name: i.NAME,
						NAME: i.NAME,
						id: i.ID
					}
				})
			},
			async handleGet(opt, value, pageIndex) {
				const json = initFilter(this.ORG_ID, '', "", 0, pageIndex || 1)
				if (value !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, value)
					extendFilterGroup(json, tempGroup);
				}
				let result = [];
				var raw = [];
				if (this.model.Nav_Identifyings.length > 0) {
					extendRule(json, 'TASK_ID', 1, this.model.ID);
					extendInclude(json, 'Nav_Identifying');
					 raw = await getRequest(json, "/HM/HazardTaskIdentifying/Entities").then(res => {
						this.curTotal = res.TotalCount
						return res
					})
				}else{
					extendRule(json, 'RISK_TYPE', 1, 2);
					 raw = await getIdentifying(json).then(res => {
						this.curTotal = res.TotalCount
						return res
					})
				}
				
				result = raw.map(item => {
					return {
						...item,
						NAME: item?.Nav_Identifying.NAME,
						IDENTIFYING_ID: item?.Nav_Identifying.ID
					}
				})
				return result
			},
			onSelectedQS(val) {
				const { formIndex, dataIndex } = this.qsCom
				var detailId=this.model.Nav_Detail[dataIndex].ID;
				this.model.Nav_Detail[dataIndex].Nav_Identifyings = [];
				val.forEach(item => {
					let obj = {
						IDENTIFYING_ID: item.IDENTIFYING_ID,
						Nav_Identifying: {
							NAME: item.NAME
						},
						ID: guid(),
						TASK_DETAIL_ID: detailId,
						ORG_ID: this.ORG_ID,
					}
					this.model.Nav_Detail[dataIndex].Nav_Identifyings.push(obj);
				})
				this.qsCom.show = false
			},
			onCloseQS() {
				this.qsCom = {
					show: false,
					lists: [],
					formIndex: undefined,
					isMultiple: false,
					dataIndex: undefined
				}
			},
			submit() {
				this.model.PUBLISH = "SaveAndNotify";
				if (this.TaskID != "") {
					this.model.TaskID = this.TaskID;
				}
				if (this.model.NOTE_AKER_ID == "") {
					this.model.NOTE_AKER_ID = uni.getStorageSync('appInfo').User.ID;
				}
				this.model.Nav_Detail.forEach(item => {
					item.Nav_User = null;
					item.Nav_Area = null;
					item.Nav_Users.forEach(item2 => {
						item2.Nav_User = null;
					});
					item.Nav_Identifyings.forEach(item2 => {
						item2.Nav_Identifying = null;
					});
				});
				this.model.Nav_Files.forEach(item => {
					if (item.TASK_ID == undefined) {
						item.TASK_ID = this.model.ID;
					}
					item.Nav_ImgFile = null;
				});

				this.model.Nav_Identifyings.forEach(item => {
					item.TASK_ID = this.model.ID;
					item.Nav_Identifying = null;
				});

				this.model.Nav_Areas.forEach(item => {
					item.TASK_ID = this.model.ID;
					item.Nav_Area = null;
				});
				//const ele = this.$refs
				// ele['wForm'].validate().then(res => {
				getRequest(this.model, "/HM/HMHazardTask/FullUpdate").then(res => {
					if (res) {
						uni.$showMsgFunc('操作成功!', () => {
							uni.navigateBack()
						}, 'success', 1000)
					}
				})
				// }).catch(err => {
				// 	uni.$showErrorInfo('请检查必填项，必填项不能为空')
				// })
			},
		},

	}
</script>

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

	.todo-page {
		padding: 16px 16px 70px;
	}
</style>