<template>
	<view class="container">
		<navBar title="绘本生成" :back="true" @onBack="onBack" color="#333333" background="#FFFFFF" />
		<view class="mainBox">
			<view class="titleBox">
			</view>

			<view class="contentBox">
				<view class="bgTag" :style="{'background-image':`url(${picBase+'resBg.png'})`}">
					{{huibenRes.title&&!showLoading?huibenRes.title:'内容生成中...'}}
				</view>
				<view class="storeBox">
					<view class="loading" v-if="showLoading">
						<!-- <view class="loading" :style="{display:!showLoading?'none':''}"> -->
						<image class="loadingImg" mode="widthFix" :src="picBase+'loading.gif'">
						</image>



						<view class="progress" v-if="taskId!=-1">
							<!-- <view class="progress"> -->
							<u-line-progress :percentage="percentage" activeColor="#017AFF"></u-line-progress>

							<view class="tipTxt">
								生成大约需要2分钟，请不要离开....
							</view>
						</view>
					</view>


					<u-parse :content="content" @ready="loaded"></u-parse>
				</view>

			</view>
		</view>

		<view class="btnBox">
			<view class="btn b1" @click="downPdf">
				生成PDF
			</view>
			<view class="btn b2" @click="downPic">
				生成图片
			</view>
		</view>


		<u-modal showCancelButton @cancel="showLead=false" :show="showLead" title="PDF下载提示" confirmText="去预览" content=""
			@confirm="prePdf">
			<view class="slot-content">
				<view class="txt1">
					下载PDF,请先点击预览页面右上角...菜单按钮,如图1:
				</view>
				<image src="../../../static/other/caidan.jpg" mode="widthFix" class="caidan"></image>
				,再点击弹框中的保存到手机按钮，如图2：
				<image src="../../../static/other/caidan_s.jpg" mode="widthFix" class="caidan"></image>
			</view>
		</u-modal>
	</view>
</template>


<script>
	// import content from "../../../utils/pinyin.js"
	import {
		getGenRes,
		genPdf
	} from '@/api/index/index.js'
	// import navBar from '@/components/navBar/index.vue'
	export default {
		// components: {
		// 	navBar
		// },
		data() {
			return {
				picBase: this.$picBase2,
				taskId: -1,
				huibenRes: null,
				showLoading: true,
				timer: null,
				timer1: null,
				content: '',

				huibenDetail: null,

				percentage: 0,


				tempPdfile: '',
				showLead: false
			}
		},
		onLoad(o) {

			// console.log('content', content);
			// this.content = content.content
			if (o.taskId) {
				this.taskId = o.taskId
				this.showLoading = true
				console.log('this.taskId', this.taskId);

				this.timer = setInterval(() => {
					this.getGenRes()
				}, 1000)
			}

			if (getApp().huibenDetail) {
				this.timer1 = setInterval(() => {
					if (this.percentage <= 50) {
						this.percentage = this.percentage + 25

						console.log('this.percentage', this.percentage);
					}
				}, 1000)
				console.log('接收的绘本详情', getApp().huibenDetail);

				this.huibenRes = getApp().huibenDetail
				let firstImg = `<img src="${getApp().huibenDetail.image}"/>`

				this.content = firstImg + getApp().huibenDetail.pinyin_content
				getApp().huibenDetail = null

				// let pinyin_content = getApp().huibenDetail.pinyin_content
				// pinyin_content.replace(firstImg, '')
				// getApp().huibenDetail = null
				// huibenInfo.pinyin_content = firstImg + pinyin_content
				// this.huibenRes = huibenInfo

				console.log('this.content', this.content);

			}

		},
		methods: {
			prePdf() {
				this.showLead = false
				uni.openDocument({
					filePath: this.tempPdfile,
					showMenu: true, //是否可以分享
					success: (res) => {
						uni.hideLoading()
						console.log(res);
					},
					fail: (e) => {
						uni.showToast({
							title: '打开失败',
							icon: "error"
						})
					}
				})
			},

			downPic() {
				if (!uni.getStorageSync('token')) {
					return this.$toast('请登录后操作')
				}
				uni.showLoading({
					title: '生成中'
				});
				console.log('img-path', this.huibenRes.image_path);
				// this.pictureReview(this.huibenRes.image_path)
				this.download(this.huibenRes.image_path, 2)
			},

			pictureReview(arr) {
				uni.previewImage({
					urls: [arr],
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
						success: function(data) {
							console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
						},
						fail: function(err) {
							console.log(err.errMsg);
						}
					}
				});
			},
			loaded() {
				clearInterval(this.timer1)
				this.percentage = 100
				this.showLoading = false
				console.log('loaded()------');
			},
			async downPdf() {
				if (!uni.getStorageSync('token')) {
					return this.$toast('请登录后操作')
				}
				uni.showLoading({
					title: '生成中'
				});
				console.log('downPdf-------------', {
					id: this.taskId != -1 ? this.taskId : this.huibenRes.id
					// id: 4
				});
				let res1 = await genPdf({
					id: this.taskId != -1 ? this.taskId : this.huibenRes.id
					// id: 4
				})
				console.log('获取pdfurl返回值--------2', res1);

				if (res1.code == 0) {

					console.log('pdf地址：', res1.data.url);
					this.download(res1.data.url, 1)
				} else {
					uni.hideLoading()
					this.$toast(res1.message)
				}
			},

			download(file, type) {
				let _this = this

				//下载文件
				uni.downloadFile({ //只能是GET请求
					url: file, //请求地址(后台返回的码流地址)
					success: (res) => {
						//下载成功
						if (res.statusCode === 200) {
							//保存文件
							let tempFile = res.tempFilePath;

							if (type == 2) {
								uni.hideLoading()
								// return _this.pictureReview(tempFile)
								return uni.navigateTo({
									url: '/pages/index/filePre/index?url=' + tempFile
								})

							}

							//保存成功之后 打开文件
							uni.getFileSystemManager().saveFile({
								tempFilePath: tempFile,
								filePath: wx.env.USER_DATA_PATH + '/' + this.huibenRes.title +
									'.pdf', //自定义文件名
								success(res) {
									console.log(res)
									uni.hideLoading()

									_this.tempPdfile = res.savedFilePath
									_this.showLead = true
								}
							})
						}
					},
					fail: (e) => {
						uni.hideLoading()
						console.log(e, '文件下载失败')
						uni.showToast({
							title: '文件下载失败',
							icon: "error",
						})
					}
				});


			},

			onBack() {
				this.huibenRes = null

				// getApp().refreshRole = true

				console.log('onBack()-----------');
				if (this.timer) {
					clearInterval(this.timer)
				}
			},
			async getGenRes() {
				let res1 = await getGenRes({
					id: this.taskId
				})
				console.log('查询生成结果返回值--------2', res1);
				if (res1.code == 0) {
					if (res1.data.state == 0) {
						this.percentage = 10
					} else if (res1.data.state == 1) {
						this.percentage = 16
					} else if (res1.data.state == 2) {
						this.percentage = 32
					} else if (res1.data.state == 3) {
						this.percentage = 48
					} else if (res1.data.state == 4) {
						this.percentage = 64
					} else if (res1.data.state == 5) {
						this.percentage = 80
					} else if (res1.data.state == 6) {
						this.huibenRes = res1.data
						let firstImg = `<img src="${res1.data.image}"/>`
						this.content = firstImg + res1.data.pinyin_content
						this.percentage = 99
						// this.showLoading = false
						clearInterval(this.timer)
					}
					// this.chargeList=[]
				} else {
					this.$toast(res1.message)
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "./index.scss";
	@import "./util.scss";
</style>