<template>
	<view class="container">
		<uni-card v-if="formData && formData.status == 1">
			<uni-section title="驳回原因" type="line">
				<text class="msg">{{ formData.rejectReason }}</text>
			</uni-section>
		</uni-card>
		<uni-forms ref="baseForm" :modelValue="formData" :rules="rules" :label-width="80">
			<uni-forms-item v-for="item in fileds" :label="item.title" :name="item.name"  :key="item.name" required>
				<uni-easyinput v-if="!item.formatter && !item.type" type="text" v-model="formData[item.name]" :placeholder="`请输入${item.title}`" />
				<uni-data-checkbox v-model="formData[item.name]" v-if="item.formatter && item.type == 'checkbox'" :multiple="item.multiple || false" :localdata="item.dict" />
				<uni-data-select v-model="formData[item.name]" v-if="item.formatter && item.type == 'select'" :localdata="item.dict"></uni-data-select>
				<view class="upVideo" v-if="item.type == 'video' && !formData[item.name]" @click="upVideo">
					<uni-icons color="#cacaca" class="videoIcon" type="videocam" size="30"></uni-icons>
				</view>
				<uni-data-select v-model="formData[item.name]" v-if="item.type == 'picker'" :localdata="item.dict" placeholder="请选择社区"></uni-data-select>

				<video controls v-if="item.type == 'video' && formData[item.name]" class="uploadVideo" :src="filesUrl + formData[item.name]"></video>
			</uni-forms-item>
		</uni-forms>
		<button :disabled="formData.status == 0 || formData.status == 2" class="btn" type="primary" @click="submitForm">{{ btnText }}</button>
	</view>
</template>

<script>
	import request from '../../api/report.js';
	import { BASE_URL } from '../../env.js';
	export default {
		data() {
			return {
				pickerList: [],
				pickerValue: '',
				pickerName: '',
				indicatorStyle: `height: 50px`,
				visible: false,
				btnText: '提交',
				baseUrl: BASE_URL.url,
				filesUrl: BASE_URL.fileUrl,
				formData: {},
				fileds: [
					{ name: 'name', title: '姓名' },
					{ name: 'sex', title: '性别', formatter: 'dict:user_sex_type', type: 'checkbox' },
					{ name: 'phone', title: '联系电话' },
					{ name: 'workUnit', title: '工作单位' },
					{ name: 'deptId', title: '报到社区', type: 'picker' },
					{ name: 'reportLocation', title: '报到位置' },
					{ name: 'reportType', title: '报到类别', formatter: 'dict:baodao_type', type: 'select' },
					{ name: 'residence', title: '居住地' },
					{ name: 'content', title: '报到内容' },
				],
				rules: {
					name: {
						rules:[{ required: true, errorMessage: '请填写姓名' }]
					},
					sex: {
						rules:[{ required: true, errorMessage: '请选择性别' }]
					},
					phone: {
						rules:[{ required: true, errorMessage: '请填写联系电话' }]
					},
					workUnit: {
						rules:[{ required: true, errorMessage: '请填写工作单位' }]
					},
					reportLocation: {
						rules:[{ required: true, errorMessage: '请填写报到位置' }]
					},
					reportType: {
						rules:[{ required: true, errorMessage: '请选择报到类别' }]
					},
					residence: {
						rules:[{ required: true, errorMessage: '请填写居住地' }]
					},
					content: {
						rules:[{ required: true, errorMessage: '请填写报到内容' }]
					},
					deptId: {
						rules:[{ required: true, errorMessage: '请选择报到社区' }]
					},
					// videoPath: {
					// 	rules:[{ required: true, errorMessage: '请上传影片' }]
					// }
				}
			}
		},
		async mounted() {
			const getCommunity = await request.getCommunity();
			this.pickerList = getCommunity.rows;
			const res = await request.getDyStatus();
			if (res.data) {
				this.formData = { ...res.data, sex: String(res.data.sex), reportType: String(res.data.reportType) };;
				if (res.data.status == 0) this.btnText = '审核中';
				// if (res.data.status == 1) this.btnText = '已驳回';
				if (res.data.status == 2) this.btnText = '已报到';
			}
			await this.setDict();
		},
		onShow() {},
		methods: {
			// 社区选择改变
			bindChange(e) {
				console.log(e, '社区选择改变')
			},
			// 选择社区
			pickerClick() {
				console.log('选择社区')
				this.visible = true;
			},
			async setDict() {
				this.fileds = await Promise.all(this.fileds.map(async e => {
					if (e.name == 'deptId') e.dict = this.pickerList.map(e => ({ ...e, text: e.deptName, value: e.deptId }));
					if (e.formatter && e.formatter.includes('dict')) {
						const dictType = e.formatter.split(':')[1];
						const res = await request.getDict(dictType);
						if (res.code == 200) e.dict = res.data.map(l => ({ ...l, value: l.dictValue, text: l.dictLabel }));
					}
					return e;
				}));
			},
			async upVideo() {
				const _this = this;
				wx.chooseMedia({
					  count: 1,  //上传视频的个数
					  mediaType:['video'],  //限制上传的类型为video
					  sourceType:['album', 'camera'], //视频选择来源
					  maxDuration: 30, //拍摄限制时间
					  camera: 'back',  //采用后置摄像头
					  success:function(res){
						const token = uni.getStorageSync('token');
						//获取临时存放的视频资源
						let tempFilePath=res.tempFiles[0].tempFilePath
						// 上传视频
						uni.uploadFile({
							url: _this.baseUrl + '/activity/photo',
							name: 'file',
							header: {
								'Authorization': `Bearer ${token}`
							},
							filePath: tempFilePath,
							success: (uploadFileRes) => {
								const obj = JSON.parse(uploadFileRes.data);
								_this.$set(_this.formData, 'videoPath', obj.imgUrl);
							},
							fail() {
								wx.showToast({
									title: '上传失败'
								})
							},
							complete() {
								wx.hideLoading();
							}
						});
					  },
					})
			},
			submitForm() {
				this.$refs.baseForm.validate().then(async valid=>{
					let res;
					if (this.formData.dangyuanId) {
						res = await request.updatedy(this.formData);
					} else {
						res = await request.submitdy(this.formData);
					}
					if (res.code == 200) {
						uni.showToast({
							title: '提交成功',
							icon: 'success',
							duration: 2000,
						});
						setTimeout(() => {
							uni.navigateBack();
						}, 1000)
					}
				}).catch(err =>{
					console.log('表单错误信息：', err);
				})
			}
		},
		// 页面生命周期中onReachBottom（页面滚动到底部的事件）
		onReachBottom() {}
	}
</script>

<style>
	.uni-forms {
		width: 90%;
		margin: 10px auto;
	}
	.btn {
		width: 90%;
		margin: 0 auto;
	}
	.upVideo {
		width: 100px;
		height: 100px;
		border: 1px solid #cacaca;
		border-radius: 12px;
	}
	.videoIcon {
		display: block;
		text-align: center;
		line-height: 100px;
	}
	.uploadVideo {
		width: 100px;
		height: 100px;
	}
	.pickerItem {
		text-indent: 0.5em;
		border: 1px solid #e8e8e8;
		line-height: 2.5em;
	}
	.msg {
		color: red;
		font-size: 12px;
	}
</style>
