<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>

				<!-- <u-datetime-picker :show="showCheckDate" mode="datetime" :value="dataModel.checkDate"
					@confirm="handleCheckDate" @close="showCheckDate = false;"
					@cancel="showCheckDate = false;"></u-datetime-picker> -->
			</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: [],
				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) {
			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.Nav_File")
				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,
							// TODO: 加上路径
							url: item.Nav_ImgFile.Nav_File.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) {
				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() {
				const ele = this.$refs
				ele['wForm'].validate().then(res => {
					const orgId = uni.getStorageSync('orgId')
					// const appInfoData = uni.getStorageSync('appInfo')
					// const {
					// 	checkDate,
					// 	checkType,
					// 	checkType_name,
					// 	checkLevel,
					// 	checkLevel_name,
					// } = this.dataModel
					// const submitId = guid()
					// // TODO: 确认对应字段是否填写正确
					// const params = {
					// 	ID: submitId,
					// 	ORG_ID: orgId,
					// 	// FORM_ID: guid(), // ?   wyw
					// 	ENTITY_ORG_TPYE: 0, // ?
					// 	// ENABLE_STATUS: 0, // ?  wyw
					// 	CHECKTIME: checkDate,
					// 	CHECK_TYPE_ID: checkType,
					// 	NAME: "手动上报" + checkLevel_name + checkType_name,
					// 	CHECK_TYPE_LEVEL_ID: checkLevel,
					// 	SUBMIT_STATUS: '15', // wyw
					// 	OrgRule: [], // ?
					// 	Nav_Files: this.pictureLists.map(i => {
					// 		return {
					// 			// ID: guid(),
					// 			IMG_FILE_ID: i.IMG_FILE_ID,
					// 			ORG_ID: orgId,
					// 			RISK_SUBMIT_ID: submitId
					// 		}
					// 	}),
					// 	Nav_ListRiskSubmitContent: this.subDataModel.map((o, index) => {
					// 		return {
					// 			ID: guid(),
					// 			ORG_ID: orgId,
					// 			ENTITY_ORG_TPYE: 0, // ?
					// 			RISK_SUBMIT_ID: submitId,
					// 			ROW_NO: (index + 1), // wyw 1, // ?
					// 			ADDRESS: o.riskPosition,
					// 			CHECK_CONTENTS_ID: o.checkContent,
					// 			CHECKCONTENT: o.checkContent_name,
					// 			CHECK_QUESTION_ID: o.checkProblem,
					// 			DESCREPTION: o.checkProblem_name, //wyw '', // ?
					// 			DEMAND: o.demand, //wyw  '', // ?
					// 			QUESTION_LEVEL: o.problemLevel, //wyw 50, // ?
					// 			RISK_AREA_ID: o.checkArea,
					// 			USER_ID: o.userID, //wyw  appInfoData.User.ID, // ?
					// 			DEPARTMENT_ID: o
					// 				.departmentID, //wyw  appInfoData.User.DEPARTMENT_ID, // ?
					// 			// SUBMIT_STATUS: 5 // ?   wyw设个属性没有啊？
					// 		}
					// 	})
					// }
					// params.SUBMIT_STATUS = 15 //wyw
					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)
				})
			},
			// 删除图片
			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: ''
			})
			// this.subDataModel.push({})
		}
	}
</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>