<template>
	<view class="detail-container">
		<u--form labelPosition="left" :model="detailsPatrol" :rules="rules" ref="patrolForm" label-width="100px">
			<uni-section title="巡检内容" type="line">
				<view style="background: white;padding:0px 20px 0px 20px;">
					<u-form-item label="任务编号:" prop="" borderBottom>
						{{detailsPatrol.taskNum}}
					</u-form-item>
					<u-form-item label="任务创建时间:" prop="" borderBottom>
						{{detailsPatrol.createTime}}
					</u-form-item>
					<u-form-item label="计划完成时间:" prop="" borderBottom>
						{{detailsPatrol.planTime}}
					</u-form-item>
					<u-form-item label="所属部门:" prop="" borderBottom>
						{{detailsPatrol.dept}}
					</u-form-item>
					<u-form-item label="巡检计划内容:" prop="" borderBottom>
						<view><mp-html :content="detailsPatrol.patrolContent" /></view>
					</u-form-item>
					<u-form-item label="巡检计划备注:" prop="" borderBottom>
						{{detailsPatrol.remark}}
					</u-form-item>
				</view>
			</uni-section>
			<uni-section title="巡检报告" type="line">
				<view style="background: white;padding:0px 20px 20px 20px;">
					<u-form-item label="巡检结果:" prop="reportResult" borderBottom>
						<u--input v-model="detailsPatrol.reportResult" border="none" placeholder="请输入巡检结果"></u--input>
					</u-form-item>
					<u-form-item label="巡检报告内容:" prop="reportContent" borderBottom>
						<u--textarea v-model="detailsPatrol.reportContent" placeholder="请输入巡检报告内容"></u--textarea>
					</u-form-item>
					<u-form-item label="图片:" prop="" borderBottom>
						<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
							:maxCount="5"></u-upload>
					</u-form-item>
					<u-form-item label="视频:" prop="" borderBottom>
						<u-upload accept="video" :fileList="fileList2" @afterRead="afterRead" @delete="deletePic"
							name="2" :maxCount="1"></u-upload>
					</u-form-item>
					<u-form-item label="录音:" prop="" borderBottom>
						<view>
							<nb-voice-record :btnDefaultText="btnDefaultText" :popupFixBottom="popupFixBottom"
								@startRecord="startTranscribe" @endRecord="endTranscribe"></nb-voice-record>
							<u-button @click="submitTranscribe" v-if="voicePath != ''" style="margin-top: 10px;"
								type="primary" text="上传录音"></u-button>
						</view>
					</u-form-item>
					<u-form-item label="备注:" prop="detailsPatrol.patrolremark" borderBottom>
						<u--textarea v-model="detailsPatrol.patrolremark" placeholder="请输入备注"></u--textarea>
					</u-form-item>
					<u-button type="primary" text="提交" @click="submitPatrol"></u-button>
				</view>
			</uni-section>
		</u--form>
	</view>
</template>

<script>
	import config from '@/config'
	const baseUrl = config.baseUrl
	
	import {
		getPatrolDetailsById,
		addTaskReport
	} from "@/api/patrol/patrol.js"

	import {
		getToken
	} from '@/utils/auth'

	const recorderManager = uni.getRecorderManager();
	const innerAudioContext = uni.createInnerAudioContext();

	innerAudioContext.autoplay = true;

	export default {
		data() {
			return {
				id: null,
				detailsPatrol: {
					reportResult: null,
					reportContent: null
				},
				rules: {
					reportResult: {
						type: 'string',
						required: true,
						message: '请填写巡检结果',
						trigger: ['blur', 'change']
					},
					reportContent: {
						type: 'string',
						required: true,
						message: '请填写巡检报告内容',
						trigger: ['blur', 'change']
					},
				},
				fileName: null,
				fileList1: [],
				photoPathList: [],
				fileList2: [],
				vedioPathList: [],
				//录音临时地址
				voicePath: "",
				//录音按钮文字
				btnDefaultText: "长按开始录音",
				//弹窗展开后距底部高度
				popupFixBottom: 0,
				//录音服务器存储地址
				transcribeSavePath: ""
			}
		},
		onLoad(opts) {
			this.id = opts.id;
			this.getPatrolById();
		},
		methods: {
			//提交巡检报告
			submitPatrol() {
				if (this.voicePath !== "" && this.transcribeSavePath === "") {
					uni.$u.toast('已录音但未上传');
				} else {
					this.$refs.patrolForm.validate().then(res => {
						const data = {
							taskId: this.id,
							photoPath: this.photoPathList.toString(),
							vedioPath: this.vedioPathList.toString(),
							audioPath: this.transcribeSavePath,
							reportContent: this.detailsPatrol.reportContent,
							reportResult: this.detailsPatrol.reportResult,
							remark: this.detailsPatrol.patrolremark
						}
						addTaskReport(data).then(() => {
							uni.$u.toast('提交成功')
							uni.navigateBack({
								//关闭当前页面，返回上一页面或多级页面。
								delta: 1
							});
							this.cleanParams();
						});
					})
				}
			},
			cleanParams() {
				this.fileList1 = [];
				this.photoPathList = [];
				this.fileList2 = [];
				this.vedioPathList = [];
				this.voicePath = "";
				this.transcribeSavePath = "";
			},
			//上传录音
			submitTranscribe() {
				if (this.transcribeSavePath === "") {
					const self = this;
					uni.saveFile({
						tempFilePath: this.voicePath,
						success: function(res) {
							console.log("savedFilePath:" + res.savedFilePath)
							self.uploadFilePromise(res.savedFilePath, "3");
							uni.$u.toast('上传成功')
						},
					});
				} else {
					uni.$u.toast('录音已上传，请勿重复上传')
				}
			},
			//开始录音
			startTranscribe() {
				this.voicePath = "";
				this.transcribeSavePath = ""
				this.btnDefaultText = "长按重新录音";
			},
			//结束录音
			endTranscribe(event) {
				// 结束录音并处理得到的录音文件
				// event中，app端仅有tempFilePath字段，微信小程序还有duration和fileSize两个字段
				this.voicePath = event.tempFilePath;
			},
			playVoice() {
				if (this.voicePath) {
					innerAudioContext.src = this.voicePath;
					innerAudioContext.play();
				}
			},
			//this[`fileList${event.name}`]  其实就是  this.fileList1 
			//这样写的话 这个参数就是动态的,比如一个文件中有多个上传图片功能,你可以写多个html,但只需要写一个js
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				if ("1" === event.name) {
					this.photoPathList = this.photoPathList.filter((item) => item !== event.file.fileName);
				} else if ("2" === event.name) {
					this.vedioPathList = this.vedioPathList.filter((item) => item !== event.file.fileName);
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url, event.name)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						fileName: this.fileName
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url, flag) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: baseUrl + '/common/upload',
						filePath: url,
						name: 'file',
						formData: {},
						header: {
							Authorization: "Bearer " + getToken()
						},
						success: (res) => {
							this.fileName = JSON.parse(res.data).fileName;
							if ("1" === flag) {
								this.photoPathList.push(JSON.parse(res.data).fileName)
							} else if ("2" === flag) {
								this.vedioPathList.push(JSON.parse(res.data).fileName)
							} else if ("3" === flag) {
								this.transcribeSavePath = JSON.parse(res.data).fileName
							}
							resolve(res.data.fileName)
						}
					});
				})
			},
			getPatrolById() {
				getPatrolDetailsById(this.id).then((res) => {
					this.detailsPatrol = res.data;
				})
			},
		}
	}
</script>

<style>

</style>