<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">
					<u-form-item label="检查区域" required style="margin-left: 10px;" prop="Nav_RiskArea.NAME" borderBottom
						@click="handleShowSheet({title: '检查区域', name: 'riskArea'})">
						<u--input disabled disabledColor="#fff" placeholder="请选择检查区域" border="none" inputAlign="right"
							v-model="model.Nav_RiskArea.NAME"></u--input>
						<u-icon style="margin-left: 4px;" slot="right" name="arrow-down"></u-icon>
					</u-form-item>
					<u-form-item label="隐患地点" required style="margin-left: 10px;" prop="ADDRESS" borderBottom>
						<u--input disabledColor="#fff" v-model="model.ADDRESS" placeholder="请填写隐患地点" border="none"
							inputAlign="right"></u--input>
					</u-form-item>
					<view class="label-title">问题点描述</view>
					<u-form-item prop="CHECKCONTENT" borderBottom>
						<u--textarea v-model="model.DESCRIBE" placeholder="请填写问题点描述" border="surround"></u--textarea>
					</u-form-item>
				</u--form>
				<w-view-require class="label-title" title='附件'></w-view-require>
				<u-upload :fileList="pictureLists" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="3"
					style="margin-bottom: 0;" :previewFullImage="true" uploadIcon="plus"></u-upload>
			</uni-card>
		</view>
		<query-selector :show="comPickerInfo.showSheet" :total="curTotal" :lists="comPickerInfo.columns"
			@close="closePicker" @search="handleSearch" @select="onSelect" />
		<view class="bottom-button">
			<button type="primary" @click="submit">提交</button>
		</view>
	</view>
</template>

<script>
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		extendFilterGroup,
		extendGroupRule,
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter,
		initFilterGroup
	} from '../../../utils/common'
	import {
		getRiskDataById,
		getCheckType,
		getCheckLevel,
		getCheckArea,
		getCheckContent,
		getCheckProblem,
		saveRiskReport,
		getUserLists,
		GetRiskAreaMaster
	} from '../../../services/safe'


	import {
		FullUpdateUserNew
	} from '../../../services/apply/subPages/BS/riskSubmit'

	import config from '../../../config/common'
	import wViewRequire from '@/components/custom/w-view-require.vue'
	export default {
		components: {
			wViewRequire
		},
		data() {
			return {
				sourceUrl: config.uni_app_web_source_url,
				pictureLists: [],
				isOnline: true,
				RiskUpInfo: [],
				thisRiskUp: {},
				model: {
					ID: '',
					TaskID: '00000000-0000-0000-0000-000000000000',
					ORG_ID: '',
					RISK_AREA_ID: '',
					Nav_RiskArea: {
						NAME: ''
					},
					ADDRESS: '',
					DESCRIBE: '',
					Nav_Files: [],
				},

				dataModel: {
					checkDate: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM'),
					checkContent: {
						name: '',
						value: ''
					}
				},
				curTotal: 0,
				subDataModel: [{
					title: '隐患1',
					checkArea: '',
					checkContent: '',
					checkProblem: '',
					problemLevel: '',
					riskPosition: '',
					demand: '',
					userID: '',
					departmentID: ''
				}],
				options: [{
					text: '删除',
					style: {
						backgroundColor: '#f56c6c'
					}
				}],
				rules: {
					'RISK_AREA_ID': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
					'ADDRESS': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					},
					'DESCRIBE': {
						type: 'string',
						required: true,
						trigger: ['blur', 'change']
					}
				},
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					formIndex: undefined,
					name: ''
				},
				showCheckDate: false,
			}
		},
		onLoad(opt) {
			if (opt.isOnline && opt.isOnline == 'false') {
				this.isOnline = false
				this.RiskUpInfo = uni.getStorageSync('riskUpInfo')
				this.thisRiskUp = this.RiskUpInfo.filter(e => e.imgFileID == opt.IMG_FILE_ID)
				this.pictureLists = [{
					url: this.thisRiskUp[0].filePath,
					id: opt.IMG_FILE_ID,
					IMG_FILE_PATH: this.thisRiskUp[0].filePath,
					IMG_FILE_ID: opt.IMG_FILE_ID,
				}]

			} else {
				this.pictureLists = this.$store.state.imageLists.map(i => {
					return {
						url: this.sourceUrl + i.IMG_FILE_PATH,
						id: i.IMG_FILE_ID,
						IMG_FILE_PATH: this.sourceUrl + i.IMG_FILE_PATH,
						IMG_FILE_ID: i.IMG_FILE_ID,
					}
				})

				const orgId = uni.getStorageSync('orgId')
				if (opt.id) {
					const json = initFilter(orgId, "", "", 0)
					extendRule(json, 'ID', 1, opt.id)
					extendInclude(json, "Nav_CheckType")
					extendInclude(json, "Nav_CheckTypeLevel.Nav_Enums")
					extendInclude(json, "Nav_Files.Nav_ImgFile")
					extendInclude(json, "Nav_ListRiskSubmitContent")
					extendInclude(json, "Nav_ListRiskSubmitContent.Nav_RiskArea")
					extendInclude(json, "Nav_ListRiskSubmitContent.Nav_User")
					extendInclude(json, "Nav_ListRiskSubmitContent.Nav_Department")
					getRiskDataById(json).then(res => {
						this.dataModel = {
							checkType: res.CHECK_TYPE_ID,
							checkType_name: res.NAME,
							checkLevel: res.CHECK_TYPE_LEVEL_ID,
							checkLevel_name: res.CHECK_TYPE_LEVEL, // error
						}
						this.subDataModel = res.Nav_ListRiskSubmitContent.map(item => {
							return {
								...item,
								checkArea: item.RISK_AREA_ID,
								checkArea_name: item.Nav_RiskArea.NAME,
								checkContent: item.CHECK_CONTENTS_ID,
								checkContent_name: item.CHECKCONTENT,
								checkProblem: item.CHECK_QUESTION_ID,
								checkProblem_name: item.DESCREPTION,
								problemLevel: item.QUESTION_LEVEL,
								problemLevel_name: item.QUESTION_LEVEL,
								riskPosition: item.ADDRESS,
							}
						})
						this.pictureLists = res.Nav_Files.map(item => {
							return {
								...item,
								url: item.Nav_ImgFile.FILE_PATH
							}
						})
					})

				}
			}
		},
		methods: {
			onSelect(val) {
				const {
					name,
					formIndex
				} = this.comPickerInfo

				this.model.RISK_AREA_ID = val.ID
				this.model.Nav_RiskArea = val
				this.comPickerInfo.showSheet = false
			},

			async getRiskAreaMaster(AreaID, subData) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, AreaID)
				await GetRiskAreaMaster(json).then(res => {
					subData['userID'] = res.ID
					subData['departmentID'] = res.DEPARTMENT_ID

				})
			},


			onConfirmPicker(e) {
				const {
					name,
					formIndex
				} = this.comPickerInfo
				if (formIndex >= 0) {
					if (this.subDataModel[formIndex]) {
						this.subDataModel[formIndex][name] = e.value[0].ID
						this.subDataModel[formIndex][name + '_name'] = e.value[0].NAME
					} else {
						this.subDataModel[formIndex] = {}
						this.subDataModel[formIndex][name] = e.value[0].ID
						this.subDataModel[formIndex][name + '_name'] = e.value[0].NAME
					}
				} else {
					this.dataModel[name] = e.value[0].ID
					this.dataModel[name + '_name'] = e.value[0].NAME
				}
				this.comPickerInfo.showSheet = false
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},
			handleDelAction(i) {
				uni.showModal({
					title: '是否删除隐患' + (i + 1) + '？',
					success: (res) => {
						if (res.confirm) {
							this.subDataModel.splice(i, 1)
							this.subDataModel.forEach((value, index) => {
								value.title = '隐患' + (index + 1)
							})
						}
					}
				})
			},
			async handleSearch(val, pi) {
				const result = await this.handleGet(this.comPickerInfo, val, pi)
				this.comPickerInfo.columns = result.map(i => {
					return {
						...i,
						name: i.NAME,
						NAME: i.NAME,
						id: i.ID
					}
				})
			},
			async handleShowSheet(p) {
				let column = await this.handleGet(p)

				if (column && column.length) {
					this.comPickerInfo = {
						showSheet: true,
						title: p.title,
						name: p.name,
						formIndex: p.formIndex,
						columns: column
					}
				} else {
					// 暂无数据
				}
			},
			async handleGet(p, value, pageIndex) {
				var listAreasInfo = uni.getStorageSync('listAreas')
				if (listAreasInfo != '' && listAreasInfo.data) {
					var resultT = []
					listAreasInfo.data.map(item => {
						if (value) {
							if (item.NAME.indexOf(value) > -1) {
								resultT.push({
									...item,
									name: item?.NAME,
									id: item?.ID
								})
							}
						} else {
							resultT.push({
								...item,
								name: item?.NAME,
								id: item?.ID
							})
						}
					})
					return resultT
				} else {
					const orgId = uni.getStorageSync('orgId')
					const json = initFilter(orgId, '', "", 0, pageIndex || 1)
					json.Limit = 20
					if (pageIndex) {
						json.Start = (pageIndex - 1) * 20;
					}
					let result = null
					if (value) {
						extendRule(json, 'NAME', 9, value)
					}
					if (p.name === 'riskArea') {
						json.Sort = "NAME"
						const raw = await getCheckArea(json).then(res => {
							this.curTotal = res.TotalCount
							return res.Data
						})
						result = raw.map(item => {
							return {
								...item,
								name: item?.NAME,
								id: item?.ID
							}
						})
					}
					return result
				}
			},
			handleCheckDate(e) {
				this.showCheckDate = false
				this.dataModel.checkDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
			},
			submit() {
				if (this.isOnline) {
					const ele = this.$refs
					ele['wForm'].validate().then(res => {
						const orgId = uni.getStorageSync('orgId')
						this.model.ID = guid()
						this.model.ORG_ID = orgId
						this.model.Nav_Files = this.pictureLists.map(i => {
							return {
								// ID: guid(),
								IMG_FILE_ID: i.IMG_FILE_ID,
								ORG_ID: orgId,
								RISK_SUBMIT_CONTENT_ID: this.model.ID,
								RISK_SUBMIT_ID: '00000000-0000-0000-0000-000000000000'
							}
						})

						this.model.Nav_RiskArea = null
						this.model.RiskContentState = 15
						FullUpdateUserNew(this.model).then(res => {
							if (res) {
								uni.$showMsgFunc('提交成功', () => {
									uni.switchTab({
										url: '/pages/index/index2'
									})
								}, '', 1000)
							}
						})
					}).catch(err => {
						console.log('校验失败', err)
					})
				} else {

					if (this.model.RISK_AREA_ID == '' || this.model.RISK_AREA_ID.length < 1) {
						uni.$showErrorInfo('请选择检查区域')
						return false
					}
					if (this.model.ADDRESS == '' || this.model.ADDRESS.length < 1) {
						uni.$showErrorInfo('请填写隐患地点')
						return false
					}
					if (this.model.DESCRIBE == '' || this.model.DESCRIBE.length < 1) {
						uni.$showErrorInfo('请填写问题点描述')
						return false
					} else if (this.model.DESCRIBE.length > 450) {
						uni.$showErrorInfo('问题点描述不能超过450字')
						return false
					}

					//离线做数据缓存到手机 尽量减少非必要的信息
					// riskUp.RiskContentState = 15
					var riskUp = this.thisRiskUp[0]
					riskUp.RISK_AREA_ID = this.model.RISK_AREA_ID //作为判断依据
					riskUp.ADDRESS = this.model.ADDRESS
					riskUp.DESCRIBE = this.model.DESCRIBE
					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)
				}
			},
			// 删除图片
			deletePic(event) {
				this[`pictureLists`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`pictureLists`].length
				lists.map((item) => {
					this[`pictureLists`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`pictureLists`][fileListLen]
					this[`pictureLists`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						IMG_FILE_ID: result.imgFileID
						// url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				const appInfoData = uni.getStorageSync('appInfo')
				const userId = appInfoData?.User?.ID || ''
				const orgId = uni.getStorageSync('orgId')
				const tenant = uni.getStorageSync('Tenant') || ''
				const remoteUrl = config.serviceHost('/PF/File/UploadFile')
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: remoteUrl,
						filePath: url,
						fileList: url,
						name: 'file',
						formData: {
							OrgId: orgId
						},
						header: {
							Tenant: tenant,
							userid: userId
						},
						success: (res) => {
							if (res.statusCode === 200) {
								const uploadResult = JSON.parse(res.data)
								if (uploadResult.IsSuccessful) {
									resolve(uploadResult.Data)
								}
							}
						}
					});
				})
			},
			onInputContent(e) {
				this.dataModel.checkContent.value = e
			},
			levelEnum(s) {
				const Enum = [{
						"NAME": "重大",
						"ID": 10
					},
					{
						"NAME": "A",
						"ID": 20
					},
					{
						"NAME": "B",
						"ID": 30
					},
					{
						"NAME": "C",
						"ID": 40
					},
					{
						"NAME": "D",
						"ID": 50
					}
				]
				return Enum.filter(e => e.ID === s)[0]
			}
		},
		onNavigationBarButtonTap(e) {
			this.subDataModel.push({
				title: '隐患' + (this.subDataModel.length + 1),
				checkArea: '',
				checkContent: '',
				checkProblem: '',
				problemLevel: '',
				riskPosition: ''
			})
		}
	}
</script>

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

	.page-wrap {
		padding: 16px 16px 50px;
	}

	.card {
		margin-bottom: 18px;
	}

	.sub-form {
		margin-bottom: 16px;
	}

	.upload-title {
		color: #303133;
		font-size: 15px;
		line-height: 22px;
		padding: 8px 0;
	}

	.page-wrap>>>.u-upload__button {
		margin-bottom: 0;
	}
</style>