<template>
	<view class="container">
		<!-- <tn-nav-bar :isBack="false" backgroundColor="#fff" :bottomShadow="false">数字人</tn-nav-bar> -->
		<!-- <view class="pos">
		</view> -->

		<view class="addPd">
			<view class="createPro" @click="handleCreatePro">
				<view class="centerAdd">
					<view class="addIcon">
						<image src="/static/add_icon.png" mode=""></image>
						<!-- <text class="iconfont icon-chuangjian" style="color: white;"></text> -->
					</view>

					<view class="addTxt">
						创建项目
					</view>
				</view>
			</view>
		</view>

		<view class="context">
			<view class="" style="padding-left: 30rpx;padding-right: 30rpx;">
				<view class="swiperBox" v-if="isLogin">
					<view class="draftLabel">
						<image src="/static/caogao_icon.png" mode="" class="labelIcon"></image>
						草稿
					</view>
					<empty v-if="draftList.length==0" tipTxt="暂无草稿" style="margin-top: -50rpx;"></empty>
					<view class="swiperCard" v-else>
						<view class="itemBox" :style="{backgroundImage:`url(${item.backs.url})`}"
							v-for="(item,index) in draftList" @click="toCreateDetail(item)">
							<image class="role" :src="item.roles.url" mode=""></image>
							<div class="barBox">
								<div class="name">
									{{item.name}}
								</div>
								<text @click.stop="delDraft(item,index)" style="color:white;font-size: 28rpx;"
									class="iconfont icon-shanchu"></text>
							</div>
						</view>
					</view>

					<div class="dotBox" v-if="draftList.length!==0">
						<div class="i1"></div>
						<div class="i2"></div>
						<div class="i3"></div>
						<div class="i4"></div>
						<div class="i5"></div>
					</div>
				</view>
			</view>


			<view class="draft">
				<view class="draftLabel" style="padding-left: 30rpx;padding-right: 30rpx;">
					<image style="width: 34rpx;height: 34rpx;" src="/static/zuopin_icon.png" mode="" class="labelIcon">
					</image>
					{{isLogin?'数字人作品':'精选案例'}}
				</view>
				<view style="padding-left: 15rpx;padding-right: 15rpx;">
					<empty v-if="workList.length==0" :tipTxt="isLogin?'暂无作品':'暂无案例'"></empty>
					<view class="draftList" v-else>
						<view class="itemBox" v-for="(item,index) in workList" @click="goWorkDetail(item)">
							<!-- <view class="top" :style="{minHeight:isPc?'184rpx':'184rpx'}"> -->
							<view class="top">
								<image :src="item.cover" mode="aspectFit" v-if="item.state">
								</image>

								<view class="tipBox" v-else>
									<view class="preloader_1 loadingBox" style="">
										<view></view>
										<view></view>
										<view></view>
										<view></view>
										<view></view>
									</view>
									<!-- <view class="progress">
										<u-line-progress :percentage="'percentage'+item.id" :showText="true"
											activeColor="#9b59b6" height="12"></u-line-progress>
									</view> -->
									<view class="tip" style="color:#237FED">
										生成中...
									</view>
								</view>

							</view>
							<view class="bottom" v-if="isLogin">
								<view class="left">
									{{item.name}}
								</view>
								<!-- <view class="left">
									{{item.state==1?"已生成":'生成中'}}
								</view> -->
								<view class="delIcon" @click.stop="handleShowMoreMenu(item,index)">
									<!-- <image src="/static/images/head.jpg" mode=""></image> -->
									<text class="iconfont icon-gengduo-shuxiang" style="font-size:32rpx;"></text>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<wike-tabbar2 :currTabIndex='3' v-if="appInfo.page_template == 3" :is_aipainting="appInfo.is_aipainting"
				:onTabbar="true" :isShowAnimate="true" :appInfos="appInfo.page_template"></wike-tabbar2>
			<wike-tabbar :currTabIndex='3' v-else :onTabbar="true" :is_aipainting="appInfo.is_aipainting"
				:isShowAnimate="true" :appInfos="appInfo.page_template"></wike-tabbar>




			<u-popup :show="show" @close="close" @open="open" mode="center">
				<view
					style="background: rgba(0, 0, 0, 0);width: 300rpx;height: 300rpx;display: flex;align-items: center;flex-direction: column;justify-content: center;color:#26b3a0;">
					<l-circularProgress :isBgShow="true" :lineWidth="10" boxWidth="100" boxHeight="100"
						progressColor="##237FED" fontColor="##237FED" gradualColor="##237FED"
						:percent="progress"></l-circularProgress>
					<view class="">
						视频下载中...
					</view>
				</view>
			</u-popup>

			<u-picker ref="picker" defaultIndex='' :closeOnClickOverlay="true" :showIcon="true" :show="showMoreMenu"
				:columns="columns" title="更多" confirmColor="" @cancel="showMoreMenu=false" @confirm="handleConfirm"
				@close="handleClosePicker"></u-picker>
			<!-- <wike-tabbar :onTabbar="true" :isShowAnimate="true"></wike-tabbar> -->

			<!-- 数字人初始引导界面 -->
			<div class="leadBg" v-if="showInitLead">
				<div class="leadBox1" v-if="showLead1">
					<div class="nextBtn" @click="nextLead">
					</div>
				</div>
				<div class="leadBox2" v-if="showLead2">
					<div class="nextBtn" @click="finishLead">
					</div>
				</div>
			</div>


			<view class="pos2">
			</view>
		</view>
	</view>
</template>

<script>
	import empty from '@/components/empty/empty.vue'
	import {
		demoList,
		workList,
		delWork,
		draftList
	} from '@/api/robot/index.js'
	import {
		downLoad3
	} from '@/utils/download3.js'
	import {
		mapMutations,
		mapActions,
		mapState,
		mapGetters
	} from 'vuex';
	export default {
		data() {
			return {
				showInitLead: false,
				showLead2: false,
				showLead1: true,

				demoList: [],

				show: false,


				showMoreMenu: false,
				columns: [
					['删除', '下载视频', '复制链接']
				],
				draftList: [],
				workList: [],

				delItem: {},
				delIndex: -1,

				is_wx: false,
				isPc: false,
				timer: null,
				// percentage: 0,
				reqTimes: 0,

				progress: 0,

				isDowload: false
			};
		},
		computed: {
			...mapGetters(['appInfo', 'userInfo', 'userData', 'isLogin']),
			isLogin() {
				if (uni.getStorageSync('token')) {
					return true
				} else {
					return false
				}
			}
		},

		onReady() {

		},
		onUnload() {

		},
		onLoad(o) {
			this.showInitLead = !uni.getStorageSync('showInitLead_szr')
			console.log("uni.getStorageSync('showInitLead')", uni.getStorageSync('showInitLead_szr'));
		},
		beforeDestroy() {
			console.log('beforeDestroy()---------------------');
			clearInterval(this.timer)
		},
		onHide() {
			console.log('onHide()---------------------');
			// 清除定时器
			clearInterval(this.timer)
		},
		onShow() {
			if (this.timer) {
				this.timer = null
			}

			// console.log('当前时间戳：', Date.now() + 180000);
			let _this = this
			// if (getApp().from == 'create') {
			// }
			this.getWorkList()
			this.getIndexData()
			const userAgent = navigator.userAgent.toLowerCase();
			if (/ipad|iphone|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/.test(userAgent)) {
				// 移动端
				console.log('移动端')
				this.isPc = false
			} else {
				// pc端
				this.isPc = true
				console.log('PC端')
			}
			// console.log('1213', download);
			this.is_wx = this.is_weixin()
			console.log('this.is_wx', this.is_wx);
		},
		onShareAppMessage: function(res) {

		},
		// async onPullDownRefresh() {
		// 	this.getIndexData()
		// },
		methods: {
			nextLead() {
				// this.showLead1 = false
				// this.showLead2 = true

				this.showInitLead = false
				this.showLead1 = false
				uni.setStorageSync('showInitLead_szr', true)
			},
			finishLead() {
				this.showInitLead = false
				this.showLead2 = false
				uni.setStorageSync('showInitLead_szr', true)
			},
			open() {
				// console.log('open');
			},
			close() {
				this.show = false
				// console.log('close');
			},
			handleClosePicker() {
				this.showMoreMenu = false

				// this.columns = [
				// 	['删除', '下载视频', '复制链接']
				// ]
			},
			toCreateDetail(item) {
				getApp().draftDetail = item
				uni.navigateTo({
					url: '/pages/digitalMen/generate/index'
				})
			},
			delDraft(item, index) {
				let _this = this
				uni.showModal({
					title: '提示',
					confirmColor: '#207CF7',
					content: '是否确认删除：' + item.name + '?',
					success: async (res1) => {
						if (res1.confirm) {
							// let res = await delWork({
							// 	id: item.id
							// })

							let res = await this.$http('digitalMen.delWork', {
								id: item.id
							})
							if (res.code == 0) {
								_this.draftList.splice(index, 1)

								console.log('删除数字人草稿返回值：', res);
								uni.showToast({
									title: '数字人：' + item.name + '草稿删除成功！',
									icon: 'success'
								})
							} else {
								uni.showToast({
									title: res.msg,
									icon: 'none'
								})
							}

						} else if (res1.cancel) {

						}
					}
				});
			},
			downLoad(url) {
				uni.downloadFile({
					url: url,
					header: {
						// 'Authorization':this.$utils.localData.getToken(), 
					},
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('res.tempFilePath', res.tempFilePath);
							return
							//res.tempFilePath; //此参数为本地的缓存地址
							var link = document.createElement('a');
							link.href = url; //url 为获取的本地缓存地址或者直接是url地址
							link.download = name + '.file'; //name为自定义的文件名称  .file为文件后缀名
							document.body.appendChild(link)
							link.click()
							//移除
							setTimeout(() => document.body.removeChild(link), 1000)

						}
					},
					fail: (e) => {
						uni.showToast({
							title: '数据处理错误，请刷新重试',
							icon: 'none',
							duration: 2000
						});
					}
				})
			},
			downLoad2(url) {
				var link = document.createElement('a');
				link.href = url; //url 为获取的本地缓存地址或者直接是url地址
				link.download = '数字人视频' + '.mp4'; //name为自定义的文件名称  .file为文件后缀名
				document.body.appendChild(link)
				link.click()
				//移除
				setTimeout(() => document.body.removeChild(link), 1000)
			},
			// 判断是否是微信浏览器 
			is_weixin() {
				var ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/MicroMessenger/i) == 'micromessenger') {
					console.log('微信浏览器');
					return true;
				} else {
					console.log("不是微信浏览器");
					return false;
				}
			},


			async getWorkList() {
				let _this = this
				let res = await this.$http('digitalMen.workList', {})
				if (res.code == 0) {
					// uni.stopPullDownRefresh()
					this.workList = res.data

					let allSuc = res.data.every((item, index) => {
						return item.state == 1
					})

					if (allSuc || res.data.length == 0) {
						clearInterval(_this.timer)
						return
					}

					console.log('onshow------------------_this.timer', _this.timer);
					if (_this.timer) {
						return
					}
					_this.timer = setInterval(() => {
						_this.getWorkList()
					}, 5000)

					console.log('数字人作品列表返回值：', res);
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			},
			async getIndexData() {
				if (!uni.getStorageSync('token')) {
					return
				}
				let res1 = await this.$http('digitalMen.draftList', {})
				if (res1.code == 0) {
					// uni.stopPullDownRefresh()
					this.draftList = res1.data
					console.log('数字人草稿列表返回值：', res1);
				} else {
					uni.showToast({
						title: res1.msg,
						icon: 'none'
					})
				}
				if (res1.code == 0 && res.code == 0) {
					uni.stopPullDownRefresh()
				}

			},
			goWorkDetail(item) {
				if (item.state == 0) {
					uni.showToast({
						title: '数字人正在生成中，请稍后查看',
						icon: 'none'
					})
					return
				}
				getApp().url = item.url
				uni.navigateTo({
					url: '/pages/digitalMen/workDetail/index'
				})
			},
			handleCreatePro() {
				if (!uni.getStorageSync('token')) {

					uni.showToast({
						title: '请登录后创建项目',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/user/signin'
						})
					}, 1500)
					return
				} else {
					uni.navigateTo({
						url: '/pages/digitalMen/generate/index?type=create'
					})
				}
			},
			handleShowMoreMenu(item, index) {
				this.$refs.picker.setIndexs([0])
				this.delIndex = index
				this.delItem = item
				this.showMoreMenu = true


			},
			async handleConfirm(e) {
				let _this = this
				this.showMoreMenu = false
				if (e.value[0] == '删除') {
					// if (this.delItem.state == 0) {
					// 	uni.showToast({
					// 		title: '数字人正在生成中，请稍后操作',
					// 		icon: 'none'
					// 	})
					// 	return
					// }
					uni.showModal({
						title: '提示',
						confirmColor: '#207CF7',
						content: '是否确认删除：' + _this.delItem.name + '?',
						success: async (res1) => {
							if (res1.confirm) {
								// let res = await delWork({
								// 	id: _this.delItem.id
								// })

								let res = await _this.$http('digitalMen.delWork', {
									id: _this.delItem.id
								})
								if (res.code == 0) {
									_this.workList.splice(this.delIndex, 1)

									if (_this.workList.length == 0) {
										clearInterval(_this.timer)
									}

									console.log('删除数字人返回值：', res);
									uni.showToast({
										title: '数字人：' + _this.delItem.name + '删除成功！',
										icon: 'success'
									})
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none'
									})
								}

							} else if (res1.cancel) {

							}
						}
					});

				} else if (e.value[0] == '复制链接') {
					if (this.delItem.state == 0) {
						uni.showToast({
							title: '数字人正在生成中，请稍后复制链接',
							icon: 'none'
						})
						return
					}

					uni.setClipboardData({
						data: this.delItem.url,
						success: function() {
							uni.showToast({
								title: '链接复制成功！',
								duration: 1500
							});
						}
					});
				} else if (e.value[0] == '下载视频') {
					if (this.delItem.state == 0) {
						uni.showToast({
							title: '数字人正在生成中，请稍后下载视频',
							icon: 'none'
						})
						return
					}


					const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i
						.test(
							navigator.userAgent) ? false : true;
					if (this.is_wx) {
						// 微信内置浏览器
						// this.downLoad2(this.delItem.url)
						let _that = this
						uni.showModal({
							title: '温馨提示',
							content: '微信内置浏览器不支持视频文件下载，请复制视频链接至手机浏览器打开',
							confirmText: '复制',
							confirmColor: '#207CF7',
							success: function(res) {
								if (res.confirm) {
									uni.setClipboardData({
										data: _that.delItem.url,
										success: function() {
											uni.showToast({
												title: "复制成功",
												icon: 'success',
											})
										}
									});
								} else if (res.cancel) {}
							}
						})
						return
					} else {
						if (detectDeviceType()) {
							let _this = this

							if (_this.isDowload) {
								uni.showToast({
									icon: 'none',
									title: '请等待上一个视频下载完成后，再下载',
								});
							}
							// PC端
							// this.delItem.url = 'http://www.liwantao.top/test.mp4'

							const downloadTask = uni.downloadFile({
								url: _this.delItem.url, //文件链接
								timeout: 99999999,
								success: (res) => {
									if (res.statusCode === 200) {
										var oA = document.createElement("a");
										oA.download = _this.delItem.name; // 设置下载的文件名，默认是'下载'	
										oA.href = res.tempFilePath; //临时路径再保存到本地
										document.body.appendChild(oA);
										oA.click();
										oA.remove(); // 下载之后把创建的元素删除
									}
								},
								fail: (err) => {
									_this.show = false;
									_this.isDowload = false
									_this.progress = 0

									// console.log(_this.show, _this.isDowload, _this.progress, err);
									uni.showToast({
										icon: 'none',
										mask: true,
										title: '失败请重新下载',
									});
								},
							})

							downloadTask.onProgressUpdate((res) => {
								if (res.progress > 0) {
									_this.show = true;
									_this.isDowload = true
								}
								_this.progress = res.progress;
								if (res.progress == 100) {
									_this.show = false;
									_this.isDowload = false
									_this.progress = 0

									uni.showToast({
										icon: 'success',
										title: _this.delItem.name + ',下载成功！',
									});
								}
							})
						} else {
							// 其他移动端浏览器
							// window.open(this.delItem.url)

							let _this = this
							// this.delItem.url = 'http://www.liwantao.top/test.mp4'

							var oA = document.createElement("a");
							oA.download = _this.delItem.name;
							oA.href = _this.delItem.url;
							document.body.appendChild(oA);
							oA.click();
							oA.remove();
						}
					}
				}

			}
		}
	};
</script>

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