<!-- 检查任务制定 -->
<template>
	<view class="page-wrap">
		<view class="card">
			<uni-card margin="0" :is-shadow="true">
				<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model" :rules="rules"
					ref="wForm" errorType="border-bottom">

					<view v-if='AUDIT_OPINION' class="label-title-red">驳回信息</view>
					<u-form-item v-if='AUDIT_OPINION' borderBottom>
						<u--textarea disabled autoHeight style="color: red !important;" :value="AUDIT_OPINION"
							placeholder="驳回信息" border="surround"></u--textarea>
					</u-form-item>

					<u-form-item label="检查范围" prop="CHECKOBJECT_DESCRIPTION" borderBottom>
						<u--input disabled disabledColor="#fff" v-model="model.CHECKOBJECT_DESCRIPTION" border="none"
							slot="right" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="检查类型" prop="Nav_CheckType.NAME" borderBottom>
						<u--input disabled disabledColor="#fff" v-model="model.Nav_CheckType.NAME" border="none"
							slot="right" inputAlign="right"></u--input>
					</u-form-item>
					<u-form-item label="检查层级" prop="Nav_CheckTypeLevel.Nav_Enums.NAME" borderBottom>
						<u--input disabled disabledColor="#fff" v-model="model.Nav_CheckTypeLevel.Nav_Enums.NAME"
							border="none" slot="right" inputAlign="right"></u--input>
					</u-form-item>

					<view class="label-title">检查区域</view>
					<u-form-item prop="RiskAreaNAME" borderBottom>
						<u--textarea disabled autoHeight v-model="model.RiskAreaNAME" placeholder="检查项目"
							border="surround"></u--textarea>
					</u-form-item>

					<view class="label-title">检查项目</view>
					<u-form-item prop="CheckProjectNAME" borderBottom>
						<u--textarea disabled autoHeight v-model="model.CheckProjectNAME" placeholder="检查项目"
							border="surround"></u--textarea>
					</u-form-item>
					<view class="label-title">检查项目分类</view>
					<u-form-item prop="CheckProjectCategoryNAME" borderBottom>
						<u--textarea disabled autoHeight v-model="model.CheckProjectCategoryNAME" placeholder="检查项目分类"
							border="surround"></u--textarea>
					</u-form-item>

					<u-form-item label="检查时间" required prop="CHECKTIME" borderBottom @click="showCheckDate(index)">
						<u--input disabledColor="#fff" v-model="model.CHECKTIME" placeholder="请选择检查时间" border="none"
							inputAlign="right"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</u-form-item>

					<u-form-item label="检查人员" required borderBottom prop="listCheckUserSign" @click="handleChange()">
						<u--input disabledColor="#fff" v-model="model.listCheckUserSign" border="none"
							inputAlign="right"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</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>
		</view>
		<!-- <view class="sub-form-btns">
						<view class="sub-form-btn" @click="handleAdd">
							<u--text type="primary" text="删除"></u--text>
						</view>
					</view> -->

		<u-sticky offset-top="20">
			<view class="sub-form">
				<view class="sub-form-wrap">
					<u--form labelPosition="left" labelWidth="auto" labelAlign="center"
						:model="model.Nav_ListSafeCheckDetail" errorType="border-bottom" ref="sForm">
						<u-collapse :border="false" accordion>
							<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
								v-if="!item.IS_DELETED" v-for="(item, index) in model.Nav_ListSafeCheckDetail">
								<u-collapse-item :title="item.ROW_NO + '. ' + item.CHECKCONTENT" name="1">
									<view slot="value" class="row-action">
										<text v-if='isLoadOK && tableKey === "1"' @click.stop="DetailDel(item)"
											class="enableTrue">
											<u--text type="primary" class="btnCheck" text="删除"></u--text>
										</text>
									</view>
									<u-form-item label="检查区域" prop="Nav_CheckArea.NAME" borderBottom>
										<u--input disabled disabledColor="#fff" v-model="item['Nav_CheckArea'].NAME"
											border="none" inputAlign="right"></u--input>
									</u-form-item>
									<u-form-item label="检查项目" prop="Nav_CheckProject.NAME" borderBottom>
										<u--input disabled disabledColor="#fff" v-model="item.Nav_CheckProject.NAME"
											border="none" inputAlign="right"></u--input>
									</u-form-item>
									<u-form-item label="检查项目分类" prop="Nav_CheckProjectCategory.NAME" borderBottom>
										<u--input disabled disabledColor="#fff"
											v-model="item.Nav_CheckProjectCategory.NAME" border="none"
											inputAlign="right"></u--input>
									</u-form-item>
									<view class="label-title">检查内容</view>
									<u-form-item prop="CHECKCONTENT" borderBottom>
										<u--textarea disabled autoHeight v-model="item.CHECKCONTENT" placeholder="检查内容"
											border="surround"></u--textarea>
									</u-form-item>
									<view class="label-title">检查依据</view>
									<u-form-item prop="CHECKPROOF" borderBottom>
										<u--textarea disabled autoHeight v-model="item.CHECKPROOF" placeholder="检查依据"
											border="surround"></u--textarea>
									</u-form-item>


									<!-- <u-form-item>
										<button class="btnSubDel" type="primary" @click="DetailDel(item)">删除</button>
									</u-form-item> -->

								</u-collapse-item>
							</uni-card>
						</u-collapse>
					</u--form>
				</view>
			</view>
		</u-sticky>
		<u-modal :show="showDelModalIndex >= 0" @confirm="confirmDel" title="确认删除？"></u-modal>

		<u-datetime-picker :show="dateTimePickerInfo.showCheckDate" v-model='dateTimePickerInfo.defaultDateTime'
			@confirm="handleCheckDate" @close="dateTimePickerInfo.showCheckDate = false"
			@cancel="dateTimePickerInfo.showCheckDate = false"></u-datetime-picker>

		<!--<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker"
			@close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker> -->

		<query-selector multiple :show="selectorInfo.showPopup" :defaultChecked="selectorInfo.defaultChecked"
			:title="selectorInfo.title" :lists="selectorInfo.dataLists" @search="handleSearch" @select="handleSelected"
			@close="selectorInfo.showPopup=false" />


		<view class="bottom-button">
			<button type="primary" v-if='isLoadOK && tableKey === "1"' @click="FullCheckUpdate">提交</button>
		</view>

	</view>
</template>

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

	import {
		GetInfo,
		FullUpdateBS032,
		orderPagedRiskReason
	} from '../../../../services/apply/subPages/BS/safeCheck'

	import {
		OrderPagedUseful2,
		auditOptionShow
	} from '../../../../services/common'

	export default {
		data() {
			return {
				tableKey: '0',
				TaskID: '',
				listPropUpload: ['SAFE_CHECK_ID'],
				listPropValUpload: [],
				AUDIT_OPINION: '',
				model: {
					ID: '',
					TaskID: '',
					Nav_CheckType: {
						NAME: ''
					},
					Nav_CheckTypeLevel: {
						Nav_Enums: {}
					},
					CHECKOBJECT: '',
					CHECKTIME: '',
					Nav_Files: [],

					listCheckUserSign: '',
					Nav_ListCheckUser: [{
						SAFE_CHECK_ID: '',
						SUSER_ID: '',
						Nav_User: {
							NAME: ''
						},
						IMG_FILE_ID: ''
					}],
					RiskAreaNAME: '',
					CheckProjectNAME: '',
					CheckProjectCategoryNAME: '',
					Nav_ListSafeCheckDetail: [{
						ROW_NO: '',
						Nav_CheckArea: {
							NAME: ''
						},
						Nav_CheckProject: {
							NAME: ''
						},
						Nav_CheckProjectCategory: {
							NAME: ''
						},
						CHECKCONTENT: '',
						CHECKPROOF: '',
						Nav_ListCheckDetailUser: []
					}] //子表
				},
				isAudit: true,
				isLoadOK: false,
				lists: [],
				dateTimePickerInfo: {
					showCheckDate: false,
					dataIndex: undefined,
					defaultDateTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM:ss'),
					value: ''
				},
				selectorInfo: {
					showPopup: false,
					title: '检查人员',
					itemData: {},
					index: 0,
					dataLists: [],
					defaultText: '',
					defaultValue: '',
					name: '',
					defaultChecked: []
				},

				showPopup: false,
				showDelModalIndex: undefined,
				rules: {
					'CHECKTIME': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
					'listCheckUserSign': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					}
				},
			}

		},
		onLoad(option) {
			this.model.ID = option.ID
			this.model.TaskID = option.taskID
			this.TaskID = option.taskID
			this.tableKey = option.tableKey
			this.loadData()

		},
		methods: {
			// handleOkRow() {
			// 	console.log('ok row')
			// },
			// handleDelRowBefore(index) {
			// 	this.showDelModalIndex = index
			// },

			//手动删除信息 编号修改
			DetailDel(item) {
				//不要直接删除 比如已经保存过，直接删除提交的时候不操作数据库
				item.IS_DELETED = true
				let indexNotDel = 1
				// this.ListApplyDetail = []
				this.model.Nav_ListSafeCheckDetail.forEach((e, i) => {
					if (!e.IS_DELETED) {
						e.ROW_NO = indexNotDel
						// this.ListApplyDetail.push(e)
						indexNotDel++
					}
				})
				this.isLoadOK = true
			},
			//显示时间控件
			showCheckDate(dataIndex) {
				if (this.model.NAME == '') {
					uni.$showErrorInfo('请先选择隐患通知！')
					return false
				}

				if (this.model.CHECKTIME == null) {
					this.model.CHECKTIME = uni.$u.timeFormat(new Date(),
						'yyyy-mm-dd hh:MM:ss')
				}
				this.dateTimePickerInfo = {
					showCheckDate: true,
					dataIndex: dataIndex,
					defaultDateTime: this.model.CHECKTIME
				}
			},
			//隐藏控件 显示时间
			handleCheckDate(e) {
				let v = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM:ss')
				const {
					name,
					dataIndex
				} = this.dateTimePickerInfo
				this.dateTimePickerInfo.showCheckDate = false
				this.model.CHECKTIME = uni.$u.timeFormat(e.value,
					'yyyy-mm-dd hh:MM:ss')
			},

			confirmDel() {
				this.model.Nav_ListSafeCheckDetail.splice(this.showDelModalIndex, 1)
				this.showDelModalIndex = undefined
			},
			handleTab(t) {
				this.currentTab = t
			},
			FullCheckUpdate() {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					const orgId = uni.getStorageSync('orgId')
					this.model.STATUSPLAN = 5
					this.model.TaskID = this.TaskID
					if (this.model.Nav_ListSafeCheckDetail != null && this.model.Nav_ListSafeCheckDetail.length >
						0) {
						this.model.Nav_ListSafeCheckDetail.forEach(e => {
							if (e.Nav_ListCheckDetailReason != null && e.Nav_ListCheckDetailReason.length >
								0) {
								e.Nav_ListCheckDetailReason.forEach(er => {
									if (er.Nav_RiskReason != null)
										er.Nav_RiskReason = null
								})
							}
						})
					}

					// 行数据处理 把选择人 分别插入 每行的人员信息
					this.model.Nav_ListSafeCheckDetail.forEach(e => {
						e.Nav_ListCheckDetailUser = []
						this.model.Nav_ListCheckUser.forEach((u, i) => {
							let userSign = {
								ID: guid(),
								ORG_ID: orgId,
								SAFE_CHECK_DETAIL_ID: e.ID,
								// SAFE_CHECK_ID: u.SAFE_CHECK_ID,
								USER_ID: u.SUSER_ID,
								ISMAINCHECK: i == 0 ? 1 : 0
							}
							e.Nav_ListCheckDetailUser.push(userSign)
						})

						e.Nav_CheckArea = null
						e.Nav_CheckProject = null
						e.Nav_CheckProjectCategory = null
					})

					FullUpdateBS032(this.model).then(res => {
						uni.$showMsgFunc('操作成功!', () => {
							if (this.tableKey == null || this.tableKey == 0) {
								uni.navigateTo({
									url: 'safeCheckIndex'
								})
							} else {
								uni.navigateBack()
							}
						}, 'success', 1000)
					})
				}).catch(err => {
					uni.$showErrorInfo('校验失败');
				})
			},

			async loadData() {
				const orgId = uni.getStorageSync('orgId')
				if (this.listPropValUpload.length == 0) {
					this.listPropValUpload.push(this.model.ID)
				}

				const json = initFilter(orgId, "", "CODE", 1)
				extendRule(json, 'ID', 1, this.model.ID);
				extendInclude(json, "Nav_CheckType");
				extendInclude(json, "Nav_CheckTypeLevel.Nav_Enums");
				extendInclude(json, "Nav_ListCheckRiskArea");
				extendInclude(json, "Nav_ListCheckRiskArea.Nav_RiskArea");
				extendInclude(json, "Nav_ListCheckProject");
				extendInclude(json, "Nav_ListCheckProject.Nav_CheckProject");
				extendInclude(json, "Nav_ListCheckProjectCategory");
				extendInclude(json, "Nav_ListCheckProjectCategory.Nav_CheckProjectCategory");
				extendInclude(json, "Nav_Files.Nav_ImgFile");
				extendInclude(json, "Nav_ListSafeCheckDetail");
				extendInclude(json, "Nav_ListSafeCheckDetail.Nav_CheckArea");
				extendInclude(json, "Nav_ListSafeCheckDetail.Nav_CheckProject");
				extendInclude(json, "Nav_ListSafeCheckDetail.Nav_CheckQuestion");
				extendInclude(json, "Nav_ListSafeCheckDetail.Nav_ListCheckDetailQuestion.Nav_Question");
				extendInclude(json, "Nav_ListSafeCheckDetail.Nav_ListCheckDetailReason.Nav_RiskReason");
				extendInclude(json, "Nav_ListSafeCheckDetail.Nav_Files.Nav_ImgFile");

				json.IgnoreDataRule = true
				GetInfo(json).then(res => {
					if (res.Nav_ListSafeCheckDetail == null || res.Nav_ListSafeCheckDetail.length < 1) {
						// uni.$showErrorInfo('未获取到检查明细，完整操作请移至电脑端！');
						// uni.navigateBack()
						// uni.$showMsgFunc = function(title, func, icon, duration)

						uni.$showMsgFunc('未获取到检查明细，完整操作请移至电脑端!', () => {
							if (this.tableKey == null || this.tableKey == 0) {
								uni.navigateTo({
									url: 'safeCheckIndex'
								})
							} else {
								uni.navigateBack()
							}
						}, 'error', 1500)

					}
					this.model = res

					// auditOptionShow(this.model.STATECHECK, 40, this.model.APPROVE_CHECKAUDIT_ID).then(res => {
					// 	this.AUDIT_OPINION = res
					// })

					this.Nav_Files = res.Nav_Files

					//数据组装
					let strRiskAreaNAME = ''
					let idCheck = []
					if (res.Nav_ListCheckRiskArea && res.Nav_ListCheckRiskArea.length > 0) {
						for (let i = 0; i < res.Nav_ListCheckRiskArea.length; i++) {
							if (idCheck.indexOf(res.Nav_ListCheckRiskArea[i].RISK_AREA_ID) == -1) {
								idCheck.push(res.Nav_ListCheckRiskArea[i].RISK_AREA_ID)
								strRiskAreaNAME += (strRiskAreaNAME.length > 0 ? "," : "") + res
									.Nav_ListCheckRiskArea[
										i].Nav_RiskArea.NAME;
							}
						}
					}

					let CheckProjectCategoryNAME = ''
					if (res.Nav_ListCheckProjectCategory && res.Nav_ListCheckProjectCategory.length > 0) {
						for (let i = 0; i < res.Nav_ListCheckProjectCategory.length; i++) {
							if (idCheck.indexOf(res.Nav_ListCheckProjectCategory[i]
									.CHECK_PROJECT_CATEGORY_ID) == -
								1) {
								idCheck.push(res.Nav_ListCheckProjectCategory[i].CHECK_PROJECT_CATEGORY_ID)
								CheckProjectCategoryNAME += (CheckProjectCategoryNAME.length > 0 ? "," : "") +
									res
									.Nav_ListCheckProjectCategory[i].Nav_CheckProjectCategory.NAME;
							}
						}
					}

					let CheckProjectNAME = ''
					if (res.Nav_ListCheckProject && res.Nav_ListCheckProject.length > 0) {
						for (let i = 0; i < res.Nav_ListCheckProject.length; i++) {
							if (idCheck.indexOf(res.Nav_ListCheckProject[i].CHECK_PROJECT_ID) == -1) {
								idCheck.push(res.Nav_ListCheckProject[i].CHECK_PROJECT_ID)
								CheckProjectNAME += (CheckProjectNAME.length > 0 ? "," : "") + res
									.Nav_ListCheckProject[i].Nav_CheckProject.NAME;
							}
						}
					}
					this.model.RiskAreaNAME = strRiskAreaNAME
					this.model.CheckProjectCategoryNAME = CheckProjectCategoryNAME
					this.model.CheckProjectNAME = CheckProjectNAME
					this.isLoadOK = true
				})
			},

			//下拉数据加载
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0)
				let dataSelect = []
				if (p.name === 'listCheckDetailReason') {
					// extendOrder(json, "NUM", "0")
					// NAME
					dataSelect = await orderPagedRiskReason(json).then(res => {
						return res
					})
				} else if (p.name == 'listCheckDetailQuestion') {

					let theItems = p.subData
					extendInclude(json, "Nav_Main")
					extendFilterGroupGroupRules(json, 'SAFE_CHECK_ID', 1, p.subData.SAFE_CHECK_ID)
					extendFilterGroupGroupRules(json, 'CHECKCONTENT', 1, p.subData.CHECKCONTENT)
					extendFilterGroupGroupRules(json, 'DEPARTMENT_ID', 1, p.data.DEPARTMENTID)
					extendFilterGroupGroupRules(json, 'CHECK_PROJECT_ID', 1, p.subData.CHECK_PROJECT_ID)
					extendFilterGroupGroupRules(json, 'RISK_AREA_ID', 1, p.subData.RISK_AREA_ID)
					extendFilterGroupGroupRules(json, 'CHECK_PROJECT_CATEGORY_ID', 1, p.subData
						.CHECK_PROJECT_CATEGORY_ID)
					dataSelect = await GetCheckDetailDESCREPTION(json).then(res => {
						//数据组装
						if (res != undefined && res.length > 0) {
							for (let i = 0; i < res.length; i++) {
								res[i].NAME = res[i].DESCREPTION
							}
						}
						return res
					})
				}

				if (dataSelect.length) {
					this.comPickerInfo = {
						showSheet: true,
						title: p.title,
						name: p.name,
						formIndex: p.formIndex,
						columns: [dataSelect]
					}
				} else {
					// 暂无数据
				}
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},

			//显示组件
			handleChange() {
				this.selectorInfo.showPopup = true
				this.selectorInfo.title = '检查人员'
				// this.selectorInfo.name = name
				// this.selectorInfo.index = val

				this.selectorInfo.itemData = this.model.Nav_ListCheckUser

				// let defCheck = []
				// if (itemData.Nav_ListCheckDetailReason != null && itemData.Nav_ListCheckDetailReason.length > 0) {
				// 	for (let i = 0; i < itemData.Nav_ListCheckDetailReason.length; i++) {
				// 		defCheck.push(itemData.Nav_ListCheckDetailReason[i].Nav_RiskReason)
				// 	}
				// }
				// this.selectorInfo.defaultChecked = defCheck

				this.handleSearch()
			},

			//数据加载
			handleSearch(val) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0)
				if (val) {
					extendRule(json, 'NAME', 9, val);
				}
				OrderPagedUseful2(json).then(res => {
					this.selectorInfo.dataLists = res.Data.map(i => {
						return {
							...i,
							name: i.NAME,
							code: i.CODE
						}
					})
				})
			},

			handleSelected(e) {
				this.selectorInfo.showPopup = false
				let listUsers = []
				let userShow = ''
				if (e.length > 0) {
					e.forEach((item, i) => {
						if (i > 0) {
							userShow += ' '
						}

						listUsers.push({
							ID: guid(),
							SAFE_CHECK_ID: this.model.ID,
							SUSER_ID: item.ID,
							ORG_ID: item.ORG_ID,
							Nav_User: e[i]
						})
						userShow += item.NAME
					})
				}

				this.model.Nav_ListCheckUser = listUsers
				this.model.listCheckUserSign = userShow
			}
		},
		computed: {},
		// onNavigationBarButtonTap(e) {
		// 	this.subForms.push({
		// 		title: '检查详情' + (this.subForms.length + 1),
		// 		Nav_ListCheckDetailReason: '',
		// 	})
		// }
	}
</script>


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