<template>
	<view class="page-wrap">
		<uni-card margin="0" :is-shadow="true">
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="model" ref="wForm"
				:rules="rules">
				<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 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" disabled
						disabledColor="fff"></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" disabled
						disabledColor="fff"></u--input>
				</u-form-item>
				<u-form-item label="发起部门：" prop="Nav_InitiatingDepartment.NAME" borderBottom>
					<u--input v-if="model.Nav_InitiatingDepartment" v-model="model.Nav_InitiatingDepartment.NAME" border="none" slot="right"
						inputAlign="right" disabled disabledColor="fff"></u--input>
				</u-form-item>
				<u-form-item label="辨识要求：" prop="Nav_Request.NAME" borderBottom>
				</u-form-item>
				<u--textarea autoHeight v-model="model.Nav_Request.NAME" border="none" inputAlign="right" disabled
					disabledColor="#fff"></u--textarea>
				<u-form-item label="辨识对象：" prop="identifyings" borderBottom>
					<u--input autoHeight v-model="model.Identifyings" border="none" inputAlign="right" disabled
						disabledColor="#fff"></u--input>
				</u-form-item>
				<u-form-item label="辨识区域：" prop="Areas" borderBottom>
				</u-form-item>
				<u--textarea autoHeight v-html="model.Areas" border="none" inputAlign="right" disabled
					disabledColor="#fff"></u--textarea>
				<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 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">
					<u-collapse :border="false" accordion>
						<uni-card style="margin-bottom: 16px;" margin="0" spacing="0" :is-shadow="false"
							v-for="(item, index) in model.Nav_Details.filter(i => !i.IS_DELETED)">
							<u-collapse-item :title="index + 1 + '. ' + item.RISK_NAME">
								<view slot="value" class="row-action">
									<text @click="handleDelRowBeforeDetail(index,item)">
										<u--text type="error" text="删除"></u--text>
									</text>
								</view>
								<u-form-item label="区域：" prop="Nav_Area.NAME" 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 label="辨识对象：" prop="Nav_Identifying.NAME" borderBottom
									@click="handleChange('Nav_Identifying',item)">
									<u--input v-model="item.Nav_Identifying.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 label="风险类别：" prop="Nav_Type.NAME" borderBottom
									@click="handleChange('Nav_Type',item)">
									<u--input v-model="item.Nav_Type.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 label="风险名称：" prop="item.RISK_NAME" borderBottom
									@click="handleChange('Nav_RiskSource',item)">
									<u--input v-model="item.RISK_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 label="风险地点：" prop="RISK_PLACE" borderBottom>
									<u--input v-model="item.RISK_PLACE" border="none" inputAlign="right"></u--input>
								</u-form-item>
								<u-form-item label="岗位：" prop="Posts" borderBottom>
									<u--input :value="item.Posts" border="none" inputAlign="right" disabled
										disabledColor="#fff"></u--input>
								</u-form-item>
								<u-form-item label="设备设施：" prop="Equs" borderBottom>
									<u--input :value="item.Equs" border="none" inputAlign="right" disabled
										disabledColor="#fff"></u--input>
								</u-form-item>
								<u-form-item label="作业环节：" prop="Nav_OperationStep.NAME" borderBottom
									@click="handleChange('Nav_OperationStep',item)">
									<u--input v-if="item.Nav_OperationStep" v-model="item.Nav_OperationStep.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 label="责任部门：" prop="Nav_DepartmentLiable.NAME" borderBottom
									@click="handleChange('Nav_DepartmentLiable',item)">
									<u--input v-if="item.Nav_DepartmentLiable" v-model="item.Nav_DepartmentLiable.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 label="责任岗位：" prop="Nav_PostLiable.NAME" borderBottom
									@click="handleChange('Nav_PostLiable',item)">
									<u--input v-if="item.Nav_PostLiable" v-model="item.Nav_PostLiable.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 label="责任人：" prop="Nav_LiableUser.NAME" borderBottom>
									<u--input v-if="item.Nav_LiableUser" :value="item.Nav_LiableUser.NAME" border="none"
										inputAlign="right" disabled disabledColor="#fff"></u--input>
								</u-form-item>
							</u-collapse-item>
						</uni-card>
					</u-collapse>
				</u--form>
			</view>
		</view>
		<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" />
		<u-picker :defaultIndex="[0]" :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns"
			@confirm="onConfirmPicker" @close="closePicker" @cancel="closePicker" keyName="NAME"></u-picker>
		<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,
		getOperationStep
	} 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'
	import {
		getDepartmentLists
	} from '../../../../services/app'

	export default {
		data() {
			return {
				listPropUpload: ['RECORD_ID'],
				listPropValUpload: [],
				model: {
					Nav_Request: {
						NAME: ""
					},
					Nav_LiableUser: {
						NAME: "",
					},
					Nav_Details: [{
						Nav_User: {},
						Nav_Area: {
							NAME: ""
						},
						Nav_Identifying: {
							NAME: ""
						},
						Nav_Type: {
							NAME: ""
						},
					}],
					Nav_InitiatingDepartment: {
						NAME: "",
					},
					Identifyings: ""
				},
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					dataIndex: undefined,
					name: ''
				},
				rules: {
					'LEVEL': {
						type: 'string',
						required: false,
						trigger: ['blur', 'change']
					}
				},
				Lists: [],
				currSearchType: "",
				showPopup: false,
				TaskID: "",
				tableKey: '0',
				isLoadOK: false,
				AUDIT_OPINION: "",
				showDelModalIndex: undefined,
				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';
			this.loadData();
		},
		methods: {
			handleDelRowBeforeDetail(index, item) {
				if (item.AREA_ID == "" || item.AREA_ID == undefined) {
					this.model.Nav_Details.splice(this.showDelModalIndex, 1)
				} else {
					this.showDelModalIndex = index
				}
			},
			cancelDel() {
				this.showDelModalIndex = undefined
			},
			confirmDel() {
				this.model.Nav_Details[this.showDelModalIndex].IS_DELETED = true;
				this.showDelModalIndex = undefined
			},
			handleAddDetail() {
				this.model.Nav_Details.unshift({
					ID: guid(),
					RECORD_ID: this.model.ID,
					Nav_User: {
						NAME: ""
					},
					Nav_Area: {
						NAME: ""
					},
					Nav_Identifying: {
						NAME: ""
					},
					Nav_Type: {
						NAME: ""
					},
					Nav_OperationStep: {
						NAME: ""
					},
					Nav_DepartmentLiable: {
						NAME: ""
					},
					Nav_PostLiable: {
						NAME: ""
					},
					Nav_LiableUser: {
						NAME: ""
					},
					RISK_NAME: "",
					RISK_PLACE: "",
					ORG_ID: this.ORG_ID,
					IS_DELETED: false,
					MODIFY_TYPE: 2
				})
			},
			handleSearch(val) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME")
				json.Limit = 20
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				if (this.currSearchType == "Nav_Area") {
					const json = initFilter(orgId, "", "NAME")
					getAreaLists(json).then(res => {
						if (res.IsSuccessful) {
							this.Lists = res.Data.map(i => {
								return {
									...i,
									name: i.NAME,
								}
							})
						}
					})
				} 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
								}
							})
						}
					})
				} else if (this.currSearchType == "Nav_Identifying") {
					extendRule(json, 'RISK_TYPE', 1, 2);
					getIdentifying(json).then(res => {
						this.Lists = res.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				} else if (this.currSearchType == "Nav_Type") {
					getRequest(json, "/HM/RiskType/OrderPaged").then(res => {
						this.Lists = res.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				} else if (this.currSearchType == "Nav_RiskSource") {
					getRequest(json, "/HM/Risksource/OrderPaged").then(res => {
						this.Lists = res.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				} else if (this.currSearchType == "Nav_OperationStep") {
					getOperationStep(json).then(res => {
						this.Lists = res.Data.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				} else if (this.currSearchType == "Nav_DepartmentLiable") {
					getDepartmentLists(json).then(res => {
						if (res.IsSuccessful) {
							this.Lists = res.Data.map(i => {
								return {
									...i,
									name: i.NAME,
								}
							})
						}
					})
				} else if (this.currSearchType == "Nav_PostLiable") {
					getRequest(json, "/PF/ApprovalRole/OrderPaged").then(res => {
						this.Lists = res.map(i => {
							return {
								...i,
								name: i.NAME,
							}
						})
					})
				}
			},
			handleSelected(val) {
				this.showPopup = false;
				this.Lists = [];
				if (this.currSearchType == 'Nav_Area') {
					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;
				} else if (this.currSearchType == 'Nav_Identifying') {
					this.currentOperate.Nav_Identifying = val;
					this.currentOperate.IDENTIFYING_ID = val.ID;
				} else if (this.currSearchType == 'Nav_Type') {
					this.currentOperate.Nav_Type = val;
					this.currentOperate.TYPE_ID = val.ID;
				} else if (this.currSearchType == 'Nav_RiskSource') {
					this.currentOperate.RISK_NAME = val.NAME;
				} else if (this.currSearchType == 'Nav_OperationStep') {
					this.currentOperate.Nav_OperationStep = val;
					this.currentOperate.OPERATION_STEP_ID = val.ID;
				} else if (this.currSearchType == 'Nav_DepartmentLiable') {
					this.currentOperate.Nav_DepartmentLiable = val;
					this.currentOperate.DEPARTMENT_LIABLE_ID = val.ID;
				} else if (this.currSearchType == 'Nav_PostLiable') {
					this.currentOperate.Nav_PostLiable = val;
					this.currentOperate.POST_LIABLE_ID = val.ID;
				}

			},
			handleClosePopup() {
				this.showPopup = false
			},
			handleChange(title, item) {
				this.currentOperate = item;
				this.currSearchType = title;
				this.showPopup = true;
				this.handleSearch('init');
			},
			loadData() {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "CODE", 1)
				if (this.listPropValUpload.length == 0) {
					this.listPropValUpload.push(this.model.ID)
				}
				extendRule(json, 'ID', 1, this.model.ID);
				extendInclude(json, 'Nav_Request');
				extendInclude(json, 'Nav_Identifyings.Nav_Identifying');
				extendInclude(json, 'Nav_Files.Nav_ImgFile');

				extendInclude(json, 'Nav_LiableUser');
				extendInclude(json, 'Nav_Areas.Nav_Area');
				extendInclude(json, 'Nav_InitiatingDepartment');

				extendInclude(json, 'Nav_Details');
				extendInclude(json, 'Nav_Details.Nav_EvaluateRiskRecordEquipment.Nav_Equipment');
				extendInclude(json, 'Nav_Details.Nav_EvaluateRiskRecordWorkduty.Nav_Workduty');
				extendInclude(json, 'Nav_Details.Nav_Area');
				extendInclude(json, 'Nav_Details.Nav_Identifying');
				extendInclude(json, 'Nav_Details.Nav_Type');
				extendInclude(json, 'Nav_Details.Nav_OperationStep');
				extendInclude(json, 'Nav_Details.Nav_DepartmentLiable');
				extendInclude(json, 'Nav_Details.Nav_PostLiable');
				extendInclude(json, 'Nav_Details.Nav_LiableUser');
				extendInclude(json, 'Nav_Users.Nav_Area');
				getRequest(json, "/HM/HMRiskRecord/FullGet").then(res => {
					this.model = res
					if (res.STATUS == 9) {
						const orgId = uni.getStorageSync('orgId')
						const json = initFilter(orgId);
						json.ID = this.model.ID;
						getRiskRecordRefus(json).then(refusRes => {
							this.AUDIT_OPINION = refusRes;
						})
					}
					let strAreas = ''
					if (res.Nav_Users && res.Nav_Users.length > 0) {
						for (let i = 0; i < res.Nav_Users.length; i++) {
							strAreas += (strAreas.length > 0 ? " " : "") + res.Nav_Users[
								i].Nav_Area.NAME + "  --  " + res.Nav_Users[
								i].Nav_User.NAME + '</br>';
						}
					}
					let strIdentifyings = ''
					if (res.Nav_Identifyings && res.Nav_Identifyings.length > 0) {
						for (let i = 0; i < res.Nav_Identifyings.length; i++) {
							strIdentifyings += (strIdentifyings.length > 0 ? " " : "") + res.Nav_Identifyings[
								i].Nav_Identifying.NAME;
						}
					}
					if (res.Nav_Details && res.Nav_Details.length > 0) {
						for (let i = 0; i < res.Nav_Details.length; i++) {
							let strPosts = ''
							for (let j = 0; j < res.Nav_Details[i].Nav_EvaluateRiskRecordWorkduty.length; j++) {
								strPosts += (strPosts.length > 0 ? " " : "") + res.Nav_Details[i]
									.Nav_EvaluateRiskRecordWorkduty[
										j].Nav_Workduty.NAME;
							}
							this.model.Nav_Details[i].Posts = strPosts;
						}
					}
					if (res.Nav_Details && res.Nav_Details.length > 0) {
						for (let i = 0; i < res.Nav_Details.length; i++) {
							let strEqus = ''
							for (let j = 0; j < res.Nav_Details[i].Nav_EvaluateRiskRecordEquipment.length; j++) {
								strEqus += (strEqus.length > 0 ? " " : "") + res.Nav_Details[i]
									.Nav_EvaluateRiskRecordEquipment[
										j].Nav_Equipment.NAME;
							}
							this.model.Nav_Details[i].Equs = strEqus;
						}
					}
					if (this.model.Nav_Files && this.model.Nav_Files.length > 0) {
						for (let i = 0; i < this.model.Nav_Files.length; i++) {
							this.model.Nav_Files[i].url = config.uni_app_web_source_url + this.model.Nav_Files[
									i]
								.Nav_ImgFile.FILE_PATH;
							this.model.Nav_Files[i].name = this.model.Nav_Files[i].Nav_ImgFile.FILE_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.LEVEL_SHOW = this.renderLevel(this.model.LEVEL + "");
					this.model.Areas = strAreas;
					this.model.Identifyings = strIdentifyings;
					this.isLoadOK = true;
				})
			},
			renderLevel(level) {
				let str = '';
				if (level == undefined) {
					return str;
				}
				if (level.indexOf('0') >= 0) {
					str += '部门 ';
				}
				if (level.indexOf('1') >= 0) {
					str += '车间 ';
				}
				if (level.indexOf('2') >= 0) {
					str += '班组 ';
				}
				if (level.indexOf('3') >= 0) {
					str += '公司 ';
				}
				return str;
			},
			transLevel(level) {
				if (level == 0) {
					return '部门 ';
				}
				if (level == 1) {
					return '车间 ';
				}
				if (level == 2) {
					return '班组 ';
				}
				if (level == 3) {
					return '公司 ';
				}
			},
			onConfirmPicker(e) {
				const {
					name,
				} = this.comPickerInfo
				this.model.Nav_Detail[this.levelIndex][name] = e.value[0].ID
				this.model.Nav_Detail[this.levelIndex][name + '_SHOW'] = e.value[0].NAME
				this.comPickerInfo.showSheet = false
			},

			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
				}
			},
			async handleShowSheet(p, index) {
				let column = []
				this.levelIndex = index;
				if (p.name === 'LEVEL') {
					column = [{
							NAME: '部门',
							ID: 0
						},
						{
							NAME: '车间',
							ID: 1
						},
						{
							NAME: '班组',
							ID: 2
						},
						{
							NAME: '公司',
							ID: 3
						}
					]
				}
				if (column.length) {
					this.comPickerInfo = {
						showSheet: true,
						title: p.title,
						name: p.name,
						columns: [column]
					}
				} else {
					// 暂无数据
				}
			},
			submit() {
				this.model.PUBLISH = "SaveAndNotify";
				this.model.Nav_Request = null;
				this.model.Nav_Area = null;
				this.model.Nav_NoteTaker = null;
				this.model.Nav_InitiatingDepartment = null;
				this.model.TaskID = this.TaskID;
				if (this.model.ORG_ID == "") {
					this.model.ORG_ID = this.ORG_ID;
				}
				this.model.Nav_Files.forEach(item => {
					if (item.RECORD_ID == undefined) {
						item.RECORD_ID = this.model.ID;
					}
				});
				this.model.Nav_Files = null;
				this.model.Nav_Details.forEach(item => {
					item.Nav_Area = null;
					item.Nav_Identifying = null;
					item.Nav_Type = null;
					item.Nav_OperationStep = null;
					item.Nav_DepartmentLiable = null;
					item.Nav_PostLiable = null;
					item.Nav_LiableUser = null;
				});
				this.model.Nav_Users.forEach(item => {
					item.Nav_User = null;
					item.Nav_Area = null;
				});
				this.model.Nav_Identifyings.forEach(item => {
					item.Nav_Identifying = null;
				});

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

	}
</script>

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