<template>
	<view class="camera-page">
		<uni-card class="card-style" margin="0" :is-shadow="true">
			<u--form labelPosition="left" labelWidth="auto" labelAlign="center" :model="dataModel" :rules="rules"
				ref="wForm" errorType="border-bottom">
				<u-form-item label="检查类型" prop="checkType" borderBottom
					@click="handleShowSheet({title: '检查类型', name: 'checkType'})">
					<u--input :value="dataModel.checkType.name" disabled disabledColor="#fff" 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="检查层级" prop="checkLevel" borderBottom
					@click="handleShowSheet({title: '检查层级', name: 'checkLevel'})">
					<u--input :value="dataModel.checkLevel.name" placeholder="请选择检查层级" disabled disabledColor="#fff"
						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="检查时间" prop="checkDate" borderBottom @click="showCheckDate = true;">
					<u--input disabled disabledColor="#fff" :value="dataModel.checkDate.value" border="none"
						inputAlign="right"></u--input>
				</u-form-item>
				<view class="label-title">照片</view>
				<u-form-item borderBottom>
					<u-upload :fileList="pictureLists" @afterRead="afterRead" @delete="deletePic" multiple :maxCount="3"
						style="margin-bottom: 0;" :previewFullImage="true" uploadIcon="plus"></u-upload>
				</u-form-item>
				<view>
					<view class="label-title">检查内容</view>
					<u-form-item borderBottom>
						<u--textarea :value="dataModel.checkContent.value" @input="onInput" placeholder="请输入检查内容"
							border="surround"></u--textarea>
					</u-form-item>
				</view>
			</u--form>
			<u-datetime-picker :show="showCheckDate" mode="datetime" :value="dataModel.checkDate.value"
				@confirm="handleCheckDate" @close="showCheckDate = false;"
				@cancel="showCheckDate = false;"></u-datetime-picker>
			<u-picker :show="comPickerInfo.showSheet" :columns="comPickerInfo.columns" @confirm="onConfirmPicker"
				@close="closePicker" @cancel="closePicker" keyName="name"></u-picker>
		</uni-card>
		<button type="primary" @click="handleSubmit">提交</button>
	</view>
</template>

<script>
	import store from '@/store/index.js'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		extendInclude,
		extendOrder,
		extendRule,
		guid,
		initFilter
	} from '../../utils/common'
	import {
		getCheckArea,
		getCheckContent,
		getCheckLevel,
		getCheckProblem,
		getCheckType,
		saveRiskReport
	} from '../../services/safe'
	import config from '../../config/common'
	// import UImage from '../../uni_modules/uview-ui/components/u--image/u--image.vue'

	export default {
		// components: { UImage },
		data() {
			return {
				pictureLists: [],
				dataModel: {
					checkType: {
						name: '',
						value: ''
					},
					checkLevel: {
						name: '',
						value: ''
					},
					checkDate: {
						name: '',
						value: uni.$u.timeFormat(new Date(), 'yyyy-mm-dd hh:MM')
					},
					checkContent: {
						name: '',
						value: ''
					}
				},
				rules: {},
				showCheckDate: false,
				comPickerInfo: {
					showSheet: false,
					columns: [],
					title: '',
					formIndex: undefined,
					name: ''
				}
			}
		},
		onLoad() {
			this.pictureLists = this.$store.state.imageLists.map(i => {
				return {
					url: i
				}
			})
		},
		methods: {
			onConfirmPicker(e) {
				const {
					name,
					formIndex
				} = this.comPickerInfo
				this.dataModel[name].value = e.value[0].id
				this.dataModel[name].name = e.value[0].name
				this.comPickerInfo.showSheet = false
			},
			async handleShowSheet(p) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "", 0)
				let column = []
				if (p.name === 'checkType') {
					extendOrder(json, "NUM", "0")
					column = await getCheckType(json).then(res => {
						return res.map(i => {
							return {
								...i,
								name: i.NAME,
								id: i.ID
							}
						})
					})
				}
				// if (p.name === 'checkType') {
				// 	column = [
				// 		{name: '巡回检查', value: 1},
				// 		{name: '隐患上报', value: 2}
				// 	]
				// }
				if (p.name === 'checkLevel') {
					extendRule(json, 'CHECK_TYPE_ID', 1, this.dataModel.checkType.value)
					extendInclude(json, "Nav_Enums")
					column = await getCheckLevel(json).then(res => {
						return res.map(i => {
							return {
								...i,
								name: i.Nav_Enums?.NAME,
								id: i.Nav_Enums?.ID
							}
						})
					})
				}
				// if (p.name === 'checkLevel') {
				// 	// extendInclude(json, "Nav_Enums")
				// 	// column = await getCheckLevel(json).then(res => {return res})
				// 	column = [
				// 		{name: '高', id: 1},
				// 		{name: '中', id: 2},
				// 		{name: '低', id: 3},
				// 	]
				// }
				if (column.length) {
					this.comPickerInfo = {
						showSheet: true,
						title: p.title,
						name: p.name,
						formIndex: p.formIndex,
						columns: [column]
					}
				} else {
					// 暂无数据
				}
			},
			handleCheckDate(e) {
				this.showCheckDate = false
				this.dataModel.checkDate.value = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
			},
			onInput(e) {
				this.dataModel.checkContent.value = e
			},
			handleSubmit() {
				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
					} = this.dataModel
					const submitId = guid()
					// TODO: 确认对应字段是否填写正确
					const params = {
						ID: submitId,
						ORG_ID: orgId,
						FORM_ID: guid(), // ?
						ENTITY_ORG_TPYE: 0, // ?
						ENABLE_STATUS: 0, // ?
						CHECKTIME: checkDate.value,
						CHECK_TYPE_ID: checkType.value,
						NAME: checkType.name,
						CHECK_TYPE_LEVEL_ID: checkLevel.value,
						SUBMIT_STATUS: '5', // ?
						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 => {
						// 	return {
						// 		ID: guid(),
						// 		ORG_ID: orgId,
						// 		ENTITY_ORG_TPYE: 0, // ?
						// 		RISK_SUBMIT_ID: submitId,
						// 		ROW_NO: 1, // ?
						// 		ADDRESS: '',
						// 		CHECK_CONTENTS_ID: o.checkContent,
						// 		CHECKCONTENT: o.checkContent_name,
						// 		CHECK_QUESTION_ID: o.checkProblem,
						// 		DESCREPTION: '', // ?
						// 		DEMAND: '', // ?
						// 		QUESTION_LEVEL: 50, // ?
						// 		RISK_AREA_ID: o.checkArea,
						// 		USER_ID: appInfoData.User.ID, // ?
						// 		DEPARTMENT_ID: appInfoData.User.DEPARTMENT_ID, // ?
						// 		SUBMIT_STATUS: 5 // ?
						// 	}
						// })
					}

					saveRiskReport(params).then(res => {
						if (res) {
							uni.showToast({
								title: '提交成功'
							})
						}
					})
				}).catch(err => {
					console.log('校验失败', err)
				})
			},
			closePicker() {
				this.comPickerInfo = {
					showSheet: false,
					columns: [],
					title: '',
					name: '',
					formIndex: undefined
				}
			},
			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)
								}
							}
						}
					})
				})
			},
		}
	}
</script>

<style scoped>
	/* @import url("@/style/css/editTemplate.css"); */
	.camera-page {
		padding: 16px;
	}

	.label-title {
		color: #303133;
		font-size: 15px;
		line-height: 22px;
		padding-top: 8px;
	}
</style>