<template>
	<view class="todo-page">
		<step-title :stepPage="stepsPage" :stepText="stepsText"></step-title>
		<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 required label="生产单元：" prop="Product_Unit" @click="handleChange('minetype')">
						<u--input v-model="(model.Nav_ProductionUnit||{}).NAME" disabled disabledColor="#ffffff" placeholder="请选择生产单元" border="none" inputAlign="right" fontSize="14px">
						</u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down" size="12">
						</u-icon>
					</u-form-item>
					<u-form-item required label="检查区域:" @click="handleShowSheet({title: '检查区域', name: 'Nav_RiskArea'})">
						<u--input v-model="model.Nav_RiskArea.NAME" placeholder="请选择检查区域" suffixIcon="arrow-down" suffixIconStyle="font-size: 12px" disabled disabledColor="#ffffff" border="none" inputAlign="right"
							fontSize="14px">
						</u--input>
					</u-form-item>
					<u-form-item label="隐患地点:" prop="HIDDEN_PLACE">
						<u--input v-model="model.HIDDEN_PLACE" placeholder="请填写隐患地点" disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input>
					</u-form-item>
					<u-form-item label="隐患描述:" prop="HIDDEN_DESCRIPTION">
						<u--input v-model="model.HIDDEN_DESCRIPTION" placeholder="请填写隐患描述" disabledColor="#ffffff" inputAlign="right" fontSize="14px" border="none">
						</u--input>
					</u-form-item>
					<view class="upload-title">隐患照片：</view>
					<full-upload v-model="model.Nav_ReportFiles" :isShowBtn='true' :listProp='listPropUpload' :listPropVal='listPropValUpload'></full-upload>

				</u--form>
			</view>
			<view style="padding: 10px 16px;" class="bottom-button">
				<u-button type="primary" @click="submit" color="#3d4b70">提交</u-button>
			</view>
			<people-selector :defaultChecked="peopleSelectOption.defaultChecked" :show="peopleSelectOption.showSelector" @select="handleSelectorPeople" @close="peopleSelectOption.showSelector = false">
			</people-selector>
			<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker" @close="comPickerInfo.showSheet=false" @cancel="comPickerInfo.showSheet=false" keyName="NAME"></u-picker>
			<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,
		transformData
	} from '../../../../utils/common'
	import {
		FMProductionUnit,
		CheckPeriods,
		CheckLevels,
		MineTypeIndex,
		MineTypeName
	} from '../../../../utils/enums.js'
	import {
		GetRiskHandleReport,
		GetNewRiskAreaInfo,
		HiddenDangerReportFullUpdate
	} from '../../../../services/apply/subPages/SK/SKServices.js'
	import {
		getRequest,
	} from '../../../../services/apply/FOServices/FOServices';
	import config from '../../../../config/common.js'
	import stepTitle from '@/components/custom/step-title.vue'
	import {
		getEnum,
		GetEnumAnyOrder
	} from '../../../../services/common';
	export default {
		components: {
			stepTitle,
		},
		data() {
			return {
				isOnline: true,
				sourceUrl: config.uni_app_web_source_url,
				listPropUpload: ['NOTIFY_ID'],
				listPropValUpload: [],
				ORG_ID: uni.getStorageSync('orgId'),
				model: {
					ORG_ID: uni.getStorageSync('orgId'),
					Nav_ReportFiles: [],
					Nav_RiskArea: {
						NAME: ''
					},
					Nav_ProductionUnit:{
						NAME: ''
					},
					PRODUCTION_UNIT_ID:'',
					HIDDEN_PLACE: '',
					HIDDEN_DESCRIPTION: '',
				},
				peopleSelectOption: {
					showSelector: false,
					value: null,
					index: 0,
					defaultChecked: []
				},
				selectorInfo: {
					name: 'user',
					isMultiple: false,
					showPopup: false,
					totalCount: 0,
					title: '考核结果选择',
					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'),
				dateRecitifyTime: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
				stepsText: ['发起', '归档'],
				stepsPage: 0,
				stepsPageList: 0,
				TaskID: '',
				ID: '',
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {}, // 存储枚举文本列表（用于下拉选择等场景）
				RiskUpInfo: [],
				thisRiskUp: {},


			}
		},
		onLoad(option) {
			if (option.isOnline && option.isOnline == 'false') {
				this.isOnline = false
				this.RiskUpInfo = uni.getStorageSync('riskUpInfo')
				this.thisRiskUp = this.RiskUpInfo.filter(e => e.imgFileID == option.IMG_FILE_ID)
				this.model.Nav_ReportFiles = [{
					ID: guid(),
					ORG_ID: this.ORG_ID,
					IMG_FILE_ID: option.IMG_FILE_ID,
					name: this.thisRiskUp[0].tempFiles[0].name || '附件',
					path: this.thisRiskUp[0].tempFiles[0].path,
					size: this.thisRiskUp[0].tempFiles[0].size,
					remoteId: option.IMG_FILE_ID,
					remotePath: this.thisRiskUp[0].filePath,
					responseText: {
						imgFileID: option.IMG_FILE_ID,
						imgFilePath: this.thisRiskUp[0].filePath
					}
				}]

			} else {
				this.TaskID = option.taskID ? option.taskID : '';
				this.ID = option.ID ? option.ID : '';
				this.fetchEnums(['SKProductionUnit']);
				// this.model.Nav_ReportFiles
				this.model.Nav_ReportFiles = this.$store.state.imageLists.map(i => {
					return {
						IMG_FILE_ID: i.IMG_FILE_ID,
						ID: guid(),
						ORG_ID: this.ORG_ID,
						name: i.tempFiles[0].name || '附件',
						path: i.tempFiles[0].path,
						size: i.tempFiles[0].size,
						remoteId: i.IMG_FILE_ID,
						remotePath: i.IMG_FILE_PATH,

						responseText: {
							imgFileID: i.IMG_FILE_ID,
							imgFilePath: i.IMG_FILE_PATH
						}
					}
				})
			}
		},
		methods: {
			fetchEnums(enumNames) {
				var dataParm = {
					'name': enumNames.join('|')
				}
				GetEnumAnyOrder(dataParm).then(res => {
					let newd = transformData(res, enumNames)
					this.enumsData = newd[0];
					// 生成文本列表（如需要）
					this.enumsText = newd[1]
					this.loadData();
				})
			},
			loadData() {
				if (this.ID == undefined || this.ID == '') {
					this.model.ID = guid()
					this.isNew = true
					this.isLoadOK = false
					this.$forceUpdate()
				} else {
					this.isNew = false
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, "", "")
					extendIgnoreDataRule(json)
					GetRiskHandleReport(json).then(res => {
						this.model = res;
						this.model.ID = this.ID
						this.stepsPage = res.STATUS == 0 ? 0 : 1

					})


				}
				// const json = {}


			},

			handleChange(name) {
				if (!this.isOnline) {
					var mineTypeStorage = uni.getStorageSync('mineTypeStorage')
					if (mineTypeStorage != '' && mineTypeStorage) {
						this.comPickerInfo = {
							showSheet: true,
							columns: [mineTypeStorage],
							name: name
						}
					}
				} else {
					const json = initFilter(this.ORG_ID)
					getRequest(json, "/FM/UserProductionUnitSet/OrderPaged").then(res => {
						this.comPickerInfo = {
							showSheet: true,
							columns: [res],
							name: name
						}
					})
				}



			},
			onConfirmPicker(e) {
				if (!this.isOnline) {
					var mineTypeStorage = uni.getStorageSync('mineTypeStorage')
					this.model.Nav_ProductionUnit = e.value[0]
					this.model.MineType = e.value[0].ID
				} else {
					this.model.Nav_ProductionUnit = e.value[0]
					this.model.PRODUCTION_UNIT_ID = e.value[0].ID
				}

				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					formIndex: undefined
				}
			},

			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 = []
				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", "CODE"]
				// json.Sort = "NAME"
				// json.Order = 1
				if (p.name == 'Nav_RiskArea') {
					if (!this.isOnline) {
						var listAreasInfo = uni.getStorageSync('listAreas')
						if (listAreasInfo != '' && listAreasInfo.Data) {
							for (let i = 0; i < listAreasInfo.Data.length; i++) {
								listAreasInfo.Data[i].name = listAreasInfo.Data[i].NAME
							}
							dataSelect = listAreasInfo.Data
							this.selectorInfo.totalCount = listAreasInfo.TotalCount
						}
					} else {
						if(this.model.PRODUCTION_UNIT_ID){
							extendRule(json, 'PRODUCTION_UNIT_ID', 1, this.model.PRODUCTION_UNIT_ID);
						}
						dataSelect = await GetNewRiskAreaInfo(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
						})
					}
					// extendRule(json, 'DEVICE_STATUS', 1, '1');

				}

				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,
						index: p.index
					}
				} 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
				this.model.Nav_RiskArea = e;
				this.model.RISK_AREA_ID = e.ID;
			},

			submit() {

				if (!this.model.PRODUCTION_UNIT_ID) {
					uni.showToast({
						title: '请选择生产单元',
						icon: 'none'
					})
					return
				}
				if (!this.model.Nav_RiskArea.NAME) {
					uni.showToast({
						title: '请选择检查区域',
						icon: 'none'
					})
					return
				}
				if (this.isOnline) {
					this.modelEdit = JSON.parse(JSON.stringify(this.model))
					delete this.modelEdit.Nav_RiskArea
					delete this.modelEdit.Nav_ProductionUnit
					if (this.model.ORG_ID == '' || !this.model.ORG_ID) {
						this.model.ORG_ID = this.ORG_ID
					}
					if (this.TaskID == null || this.TaskID == '') {
						this.modelEdit.TaskID = '00000000-0000-0000-0000-000000000000'
					} else {
						this.modelEdit.TaskID = this.TaskID
					}
					this.modelEdit.PUBLISH = "SaveAndNotify";
					HiddenDangerReportFullUpdate(this.modelEdit).then(res => {
						if (res) {
							uni.$showMsgFunc('操作成功!', () => {
								uni.navigateBack()
							}, 'success', 1000)
						}
					})
				} else {
					var riskUp = this.thisRiskUp[0]
					riskUp.RISK_AREA_ID = this.model.RISK_AREA_ID //作为判断依据
					riskUp.HIDDEN_PLACE = this.model.HIDDEN_PLACE
					riskUp.HIDDEN_DESCRIPTION = this.model.HIDDEN_DESCRIPTION
					riskUp.MineType = this.model.MineType
					riskUp.APPLY_USER_ID = uni.getStorageSync('appInfo').User.ID
					riskUp.APPLY_DEPARTMENT_ID = uni.getStorageSync('appInfo').User.DEPARTMENT_ID
					riskUp.CREATE_TIME = new Date()
					this.RiskUpInfo.forEach(e => {
						if (e.imgFileID == riskUp.imgFileID) {
							e = riskUp
						}
					})
					uni.setStorageSync('riskUpInfo', this.RiskUpInfo)
					uni.$showMsgFunc('缓存成功，待有网络会自动同步', () => {
						uni.navigateBack()
					}, '', 1000)
				}


			}

		}



	}
</script>

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

	.todo-page>>>.u-steps-item__line {
		width: 187.6px !important;
	}
</style>