<template>
	<view>
		<view class="content">
			<view class="content-form">
				<u--form :label-style="{'font-size':'26rpx'}" label-position="top" labelWidth="150" :model="formInfo"
					ref="form" :rules="rules">
					<u-form-item required label="标题" prop="title" borderBottom :customStyle="{
			  					'flex-direction': 'row !important'}">
						<u--input fontSize="24rpx" placeholderStyle="color: #999" inputAlign="right" border="none"
							v-model="formInfo.title" placeholder="请填写标题">
						</u--input>
					</u-form-item>
					<u-form-item required label="联系人" prop="linkman" borderBottom :customStyle="{
								'flex-direction': 'row !important',}">
						<u--input fontSize="24rpx" placeholderStyle="color: #999" inputAlign="right" border="none"
							v-model="formInfo.linkman" placeholder="请输入联系人姓名">
						</u--input>
					</u-form-item>
					<u-form-item required label="联系电话" prop="phone" borderBottom :customStyle="{
								'flex-direction': 'row !important',
							}">
						<u--input fontSize="24rpx" placeholderStyle="color: #999" inputAlign="right" border="none"
							v-model="formInfo.phone" placeholder="请输入联系人手机号">
						</u--input>
					</u-form-item>
					<u-form-item required label="维修时间" prop="repairTime" borderBottom :customStyle="{
								'flex-direction': 'row !important',
							}">
						<view class="input-box d-flex a-center" @click="showTime = true">
							<u-datetime-picker ref="datePicker" :formatter="formatter" v-model="formInfo.repairTime"
								:show="showTime" mode="date" @confirm="handleConfirmDate" @cancel="handleClose">
							</u-datetime-picker>
							<view class="time-text">{{formInfo.repairTime ? formInfo.repairTime : '请选择时间'}}</view>
							<!-- <input type="text" v-model="formInfo.repairTime" placeholder="请选择时间"> -->
							<u-icon name="arrow-down-fill" color="#000000" size="28"></u-icon>
						</view>
						</u--input>
					</u-form-item>
					<u-form-item required label="维修地址" prop="repairAddress" borderBottom :customStyle="{
								'flex-direction': 'row !important',
							}">
						<u--input fontSize="24rpx" placeholderStyle="color: #999" inputAlign="right" border="none"
							v-model="formInfo.repairAddress" placeholder="请填写维修地址">
						</u--input>
					</u-form-item>
					<u-form-item required label="预算金额" prop="budget" borderBottom :customStyle="{
								'flex-direction': 'row !important',
							}">
						<u--input fontSize="24rpx" placeholderStyle="color: #999" inputAlign="right" border="none"
							v-model="formInfo.budget" placeholder="请填写预算金额">
						</u--input>
					</u-form-item>
					<view>
						<view>
							<view class="d-flex j-sb a-center form-item-height-only">
								<view class="form-item-name">上传图片</view>
								<view class="form-tips">以下内容三选一必填</view>
							</view>
							<view class="">
								<comUpload v-model="formInfo.pictureList" @getVal="getPhotoList" @delVal="delPhotoItem"
									ref="photoRef"></comUpload>
							</view>
						</view>
						<view>
							<view class="d-flex j-sb a-center form-item-height-only">
								<view class="form-item-name">上传视频</view>
							</view>
							<view>

								<view class="video-box" style="" v-if="formInfo.videoList.length">
									<video id="myVideo" :src="formInfo.videoList[0].url" @error="videoErrorCallback"
										:danmu-list="danmuList" enable-danmu controls
										:show-fullscreen-btn='false'></video>

									<view class="position-icon" @click="delVideoList">
										<u-icon name="close-circle-fill" color="#D9001B" size="32"></u-icon>
									</view>

								</view>

								<comUpload v-else :afterWidth="350" @getVal="getVideoList" ref="videoRef"
									:acceptType="acceptType" :maxCount="1" :multiple="isMultiple">
								</comUpload>

							</view>
						</view>
						<view>
							<view class="d-flex j-sb a-center form-item-height-only">
								<view class="form-item-name">语音描述</view>
							</view>
							<view v-if="formInfo.voiceList.length" class="">
								<free-audio audioId='audio1' :url='formInfo.voiceList[0].url' @delete="handleDelete">
								</free-audio>
							</view>
							<view v-else class="paddding-x-three d-flex j-center " @click="showPopup = true">
								<view class="voice-box d-flex a-center j-center">
									<u-icon name="mic" color="#2979ff" size="32"></u-icon>
									<view>添加语音描述</view>
								</view>
							</view>
							<u-popup :show="showPopup" @close="handleClosePopup" @open="handleOpenPopup">
								<view class="padding-y-two">
									<recordCom @getVal="getVoiceList"></recordCom>
								</view>
							</u-popup>
						</view>

					</view>
					<u-form-item label="备注" prop="remark">
						<u--textarea maxlength="-1" :customStyle="{
			  						marginTop: '20rpx',
			  						background: '#F5F5F5',
			  						border: 'none'
			  					}" v-model="formInfo.remark" placeholder="备注说明" height="128rpx"></u--textarea>
					</u-form-item>
				</u--form>
			</view>
		</view>
		<view v-if="statusBtn == -1" class="submit-btn" @click="handlePublish">发布需求</view>
		<view class="submit-btn" v-else-if="statusBtn == 0" @click="handleUpdateForm">确认修改</view>
		<view class="submit-btn" v-else-if="statusBtn == 1" @click="handleUpdateForm">重新发布</view>
	</view>
</template>

<script>
	import {
		addOrderFunction
	} from '@/api/system/index.js'
	import freeAudio from '@/components/chengpeng-audio/free-audio.vue'
	import recordCom from '@/components/record/record.vue'
	export default {
		name: "form",
		components: {
			freeAudio,
			recordCom,
		},
		props: {
			statusBtn: Number,
			detailData: Object
		},

		data() {
			const mobile = (rule, value, callback) => {
				return /^1[3-9]\d{9}$/.test(value) ? callback() : callback(new Error('请输入正确的手机号码'))
			}

			return {
				showTime: false, //时间选择器是否显示
				acceptType: 'video',
				isMultiple: false, //视频上传数量(多张、单张)
				path: 'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-hello-uniapp/2cc220e0-c27a-11ea-9dfb-6da8e309e0d8.mp3',
				voicePath: '',
				showPopup: false,
				formInfo: {},
				rules: {
					title: {
						type: 'string',
						required: true,
						message: '请填写标题',
						trigger: ['blur', 'change']
					},
					linkman: {
						type: 'string',
						required: true,
						message: '请填写联系人',
						trigger: ['blur', 'change']
					},
					phone: [{
							type: 'string',
							required: true,
							message: '请输入正确的联系人手机号码',
							max: 11,
							min: 11,
							trigger: 'blur'
						},
						{
							// 自定义验证函数，见上说明
							validator: mobile,
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur'],
						}

					],
					repairAddress: {
						type: 'string',
						required: true,
						message: '请填写维修地址',
						trigger: ['blur', 'change']
					},
					budget: {
						type: 'number',
						required: true,
						message: '请填写预算金额',
						trigger: ['blur', 'change']
					},
				},


			};
		},
		//如果是自己封装的组件就是mounted() 
		//如果不是组件就是onReady()
		mounted() {
			this.$refs.form.setRules(this.rules);
		},
		watch: {
			detailData: {
				handler(newVal, oldVal) {
					let that = this
					if (newVal) {
						that.formInfo = that.detailData
					} else {
						that.resetForm()
					}
				},
				immediate: true,
				deep: true
			}
		},
		//暂停所有音频（一般用于页面切换时停止正在播放的音频）
		onUnload() { //普通页面在 onUnload 生命周期中执行
			uni.$emit('stop')
		},
		onHide() { //tabBar页面在onHide生命周期中执行
			uni.$emit('stop')
		},
		created() {
			let that = this
			// 时间格式化默认值
			if (!that.formInfo.repairTime) {
				that.formInfo.repairTime = uni.$u.timeFormat(Number(new Date()), 'yyyy-mm-dd');
			} else {
				that.formInfo.repairTime = uni.$u.timeFormat(that.formInfo.repairTime, 'yyyy-mm-dd')
			}
		},

		methods: {
			// 获取上传图片的值
			getPhotoList(data) {
				let that = this
				let photoList = []
				that.formInfo.pictureList.push({
					url: data.url,
					fileType: 'picture'
				})
				// that.formInfo.pictureList = photoList
			},
			//删除照片
			delPhotoItem(index) {
				this.formInfo.pictureList.splice(index, 1)
			},
			// 获取上传视频的值
			getVideoList(data) {
				let that = this
				let videoList = []
				videoList.push({
					url: data.url,
					fileType: 'video'
				})
				that.formInfo.videoList = videoList
			},
			delVideoList() {
				this.formInfo.videoList.splice(0, 1)
			},

			// 上传音频事件
			getVoiceList(data) {
				let that = this
				that.showPopup = false
				let voiceList = []
				voiceList.push({
					url: data.url,
					fileType: 'voice'
				})
				that.formInfo.voiceList = voiceList
			},
			//确认修改和重新发布按钮
			handleUpdateForm() {
				let that = this
				that.$refs.form.validate().then(res => {
					if (res) {
						if (that.formInfo.pictureList.length || that.formInfo.videoList.length || that.formInfo
							.voiceList.length) {
							that.$emit('submit', that.formInfo)
						} else {
							uni.$u.toast('图片、视频、音频选其一必填')
						}
					}
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
			},
			async handleAdd() {
				let that = this
				that.formInfo.repairTime = uni.$u.timeFormat(that.formInfo.repairTime, 'yyyy-mm-dd');
				const data_back = await addOrderFunction(that.formInfo)
				const {
					code
				} = data_back
				if (code == 200) {
					uni.showToast({
						title: '发布成功!',
						icon: 'none',
						duration: 2000,
						success() {
							let cleatTime = setTimeout(() => {
								clearTimeout(cleatTime)
								that.$uniGo.reLaunch({
									url: '/pages/demand/index'
								})
							}, 1000)

						}
					})
				}
			},
			//发布需求按钮
			handlePublish() {
				let that = this
				this.$refs.form.validate().then(res => {
					if (res) {
						if (that.formInfo.pictureList.length || that.formInfo.videoList.length || that.formInfo
							.voiceList.length) {
							that.handleAdd()
						} else {
							uni.$u.toast('图片、视频、音频选其一必填')
						}
					}
				}).catch(errors => {
					uni.$u.toast('校验失败')
				})
				// this.$emit('submit', this.formInfo)
			},
			// 时间选择器确认事件
			async handleConfirmDate(e) {
				// value:返回所选时间戳，mode:当前模式
				let that = this
				that.showTime = false
				// 时间格式化
				const timeFormat = uni.$u.timeFormat;
				let timeValue = await timeFormat(e.value, 'yyyy-mm-dd');
				that.formInfo.repairTime = timeValue
			},
			//时间选择器的关闭按钮事件
			handleClose() {
				this.showTime = false
			},
			//弹窗打开事件
			handleOpenPopup() {
				let that = this
				// console.log('open');
			},
			//弹窗关闭事件
			handleClosePopup() {
				let that = this
				that.showPopup = false
			},
			// 删除语音
			handleDelete() {
				console.log('删除')
				let that = this
				that.formInfo.voiceList.splice(0, 1)
				// const recorderManager = uni.getRecorderManager()
				// console.log(recorderManager,'大数据可能')
			},
			//时间选择器格式化
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			resetForm() {
				this.formInfo = {
					title: '', //标题
					linkman: '', //联系人
					phone: '', //联系电话
					repairTime: undefined, //维修时间
					repairAddress: '', //维修地址
					budget: '', //预算金额
					remark: '', //备注说明
					pictureList: [], //图片
					videoList: [], //视频
					voiceList: [], //音频
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		&-form {
			margin: 30rpx 20rpx;
			width: calc(100% - 20rpx * 2);

			/deep/ .u-form {
				width: calc(100% - 20rpx * 2);
				margin: 0rpx 20rpx;
			}
		}
	}

	.video-box {
		width: 373rpx;
		height: 210rpx;
		position: relative;

		video {
			width: 100%;
			height: 100%
		}
	}

	.position-icon {
		position: absolute;
		top: -10rpx;
		right: -10rpx;
	}
	.time-text{
		color:#666666;
		font-size:24rpx;
	}

	@import url("@/css/form.css");

	// ::v-deep .u-border {
	// 	border: 0 !important;
	// 	background: #F5F5F5 !important;
	// }

	// ::v-deep .u-upload__wrap__preview {
	// 	margin: 0 6rpx 10rpx 0 !important;
	// }
</style>
