<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="recipient.name" borderBottom
					@click="handleShowPersonQuery">
					<u--input :value="dataModel.recipient.name" readonly 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&#45;&#45;input :value="dataModel.checkLevel.name" placeholder="请选择检查层级" disabled disabledColor="#fff"-->
<!--						border="none" inputAlign="right"></u&#45;&#45;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&#45;&#45;input disabled disabledColor="#fff" :value="dataModel.checkDate.value" border="none"-->
<!--						inputAlign="right"></u&#45;&#45;input>-->
<!--				</u-form-item>-->
				<view class="label-title">照片</view>
				<u-form-item borderBottom prop="pictureLists">
					<u-upload :fileList="dataModel.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>
<!--			<people-selector :show="showSelectorPerson" @select="handleSelectorPeople"-->
<!--											 @close="showSelectorPerson = false">-->
<!--			</people-selector>-->
			<query-selector :show="showQueryPerson" :lists="userLists" :total="curTotal"
											@close="handleClosePopup" @search="handleSearchUser" @select="handleSelectedUser" />
<!--			<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 {
	extendFilterGroup,
	extendGroupRule,
	extendInclude,
	extendOrder,
	extendRule,
	guid,
	initFilter, initFilterGroup
} from '../../utils/common'
// import {
// 	getUserLists
// } from '../../services/safe'
// import {
// 	saveSnapShot
// } from '../../services/app'
	import config from '../../config/common'

	export default {
		data() {
			return {
				sourceUrl: config.uni_app_web_source_url,
				userLists: [],
				curTotal: 0,
				showSelectorPerson: false,
				showQueryPerson: false,
				dataModel: {
					recipient: {
						name: '',
						value: ''
					},
					checkContent: {
						value: ''
					},
					pictureLists: [],
				},
				rules: {
					'recipient.name': {
						type: 'string',
						required: true,
						message: '请选择接收人',
						trigger: ['blur', 'change']
					},
					'pictureLists': {
						type: 'array',
						required: true,
						message: '请上传照片',
						trigger: ['blur', 'change']
					}
				}
			}
		},
		onLoad() {
			// this.dataModel.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,
			// 	}
			// })
		},
		methods: {
			handleShowPersonQuery() {
				this.showQueryPerson = true
				this.handleSearchUser('init')
			},
			handleClosePopup() {
				this.showQueryPerson = false
			},
			// handleSelectorPeople(e) {
			// 	console.log(e)
			// },
			handleSearchUser(val, pageIndex) {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "NAME", '', pageIndex)
				extendInclude(json, "Nav_Person.Nav_Post")
				extendRule(json, 'ENABLE_STATUS', 1, '0')
				if (val !== 'init') {
					const tempGroup = initFilterGroup(false);
					extendGroupRule(tempGroup, 'NAME', 9, val)
					extendFilterGroup(json, tempGroup);
				}
				json.Limit = 20
				if (pageIndex) {
					json.Start = (pageIndex - 1) * 20;
				}

				// getUserLists(json).then(res => {
				// 	if (res.IsSuccessful) {
				// 		this.userLists = res.Data.map(i => {
				// 			return {
				// 				...i,
				// 				name: i.NAME,
				// 				code: i.CODE
				// 			}
				// 		})
				// 		this.curTotal = res.TotalCount
				// 	}
				// })
			},
			handleSelectedUser(val) {
				this.showQueryPerson = false
				this.lists = []
				this.dataModel.recipient = val
			},
			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 {
						recipient,
						checkContent,
						pictureLists
					} = this.dataModel
					// const submitId = guid()
					const params = {
						ACCEPT_ID: recipient.ID,
						DESCRIPTION: checkContent.value,
						Nav_Files: pictureLists.map(i => {
							return {
								ID: guid(),
								IMG_FILE_ID: i.IMG_FILE_ID,
								ORG_ID: orgId,
							}
						}),
					}
					// saveSnapShot(params).then(res => {
					// 	if (res) {
					// 		uni.$showMsgFunc('提交成功', () => {
					// 			uni.switchTab({
					// 				url: '/pages/index/index2'
					// 			})
					// 		}, '', 1000)
					// 	}
					// })
				}).catch(err => {
					console.log('校验失败', err)
				})
			},
			deletePic(event) {
				this.dataModel.pictureLists.splice(event.index, 1)
			},
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this.dataModel.pictureLists.length
				lists.map((item) => {
					this.dataModel.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.dataModel.pictureLists[fileListLen]
					this.dataModel.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>
