<template>
	<view class="page-container">
		<view class="status-bar"></view>
		<view class="video" :style="{ height: video_height + 'px' }">
			<artplayer
				ref="artplayer"
				@openAD="openAD"
				@toBack="toBack"
				@openShare="openShare"
				@changePlay="selectEpisodes"
				@playNext="selectNextEpisodes"
				@showPlayAdv="showPlayAdv"
				@playpip="playpip"
				@addDanmu="addDanmu"
				@openairplay="scanairplay"
				:currentTime.sync="currentTime"
			/>
			<!-- <view class="video-box">
      </view> -->
			<!-- <u-loading-icon v-if="lookLoading"></u-loading-icon>
      <view v-show="panelShow" class="panel" @click="switchLine(false)">
        <view class="line-panel">
          <scroll-view scroll-y="true">
            <view class="line-panel-content">
              <uni-text v-for="(item, index) in data.vod_play_url" :key="index" class="line-panel-item"
                :class="index == playIndex && 'selected'" @click="changePlay(index)">{{ item.name }}</uni-text>
            </view>
          </scroll-view>
        </view>
      </view>
      <view v-show="controllerShow" class="controller">
        <view class="controller-header">
          <uni-icons type="back" color="#ffffff" size="30" @click="toBack"></uni-icons>
          <text v-if="data.vod_play_url && data.vod_play_url.length > 1" class="switch-line"
            @click="switchLine(true)">切换线路</text>
        </view>
      </view>
	  -->
			<view v-if="tvShow" class="play-tv">
				<image src="/static/images/oxplayer_dlna_bg.png" />
				<text class="time">正在投屏</text>
			</view>
			<view v-if="adShow" class="play-adv" @click="openAD(advList.play_adv.adv_link)">
				<vod-image :src="advList.play_adv.adv_image"></vod-image>
				<u-count-down ref="advTime" :time="advList.play_adv.adv_show_time * 1000" format="ss" autoStart @change="timeChange" @finish="adClose">
					<text class="time">{{ adTime.seconds }}s后关闭，升级VIP可跳过</text>
				</u-count-down>
			</view>
			<!-- <view v-if="playAdvShow" class="play-adv">
				<image :src="playAdv.adv_image" @click="openAD(playAdv.adv_link)" />
				<text @click="setplayAdv">关闭</text>
			</view> -->
		</view>

		<view class="video-info">
			<view class="video-info-header" v-if="!introShow">
				<view class="header-bg">
					<view class="header-bg-upper"></view>
				</view>
				<view class="video-tabs justify-between">
					<view class="video-tabs-title">
						<text :class="videoTabsIndex == 0 && 'selected'" @click="tabsClick(0)">详情</text>
						<text :class="videoTabsIndex == 1 && 'selected'" @click="tabsClick(1)">评论</text>
					</view>
					<view class="video-msg" @click="openUrl('/pages/video/video-guide')">无法全屏？</view>
					<view class="video-bar" v-if="false">
						<template v-if="introShow">
							<uni-icons type="closeempty" size="20" @click="closeIntro"></uni-icons>
						</template>
						<!-- <template v-else>
							<uni-icons type="compose" size="22"
								@click="openUrl('/pages/feedback/feedback?type=1&vod_id=' + data.vod_id + '&vod_name=' + data.vod_name)"></uni-icons>
							<uni-icons :type="data.is_fav === 1 ? 'star-filled' : 'star'" size="22"
								:color="data.is_fav === 1 ? '#f0ad4e' : ''" @click="favVod"></uni-icons>
							<uni-icons type="download" size="22" @click="download"></uni-icons>
							<uni-icons custom-prefix="xicon" type="x-icon-share" size="22"
								@click="openShare"></uni-icons>
						</template> -->
					</view>
				</view>
			</view>
			<!-- <view class="video-info-swiper">
				<swiper :current="videoTabsIndex" @change="swiperChange" class="swiper-container">
					<swiper-item>
						<video-info :intro-show.sync="introShow" :play-index.sync="playIndex" :is_fav="data.is_fav"
							:video-episodes.sync="videoEpisodes" @episodes="triggerEpisodes" @Share="openShare"
							:data="data" :adv="advList" @dig="digVod" @favVod="favVod"
							@download="download"></video-info>
					</swiper-item>
					<swiper-item>
						<video-comment ref="comment" :id="id" @reward="toReward"></video-comment>
					</swiper-item>
				</swiper>
			</view> -->
			<view class="video-info-swiper">
				<scroll-view ref="scrollView" class="swiper-container" :scroll-top="scrollTop" scroll-y="true" @scrolltolower="commentData" @scroll="handleScroll">
					<view v-if="advList.banner_adv1" class="ad-banner" @click="openAD(advList.banner_adv1.adv_link)">
						<image :src="advList.banner_adv1.adv_image" mode="widthFix" />
					</view>
					<video-info
						:intro-show.sync="introShow"
						:video-tabs-index.sync="videoTabsIndex"
						:play-index.sync="playIndex"
						:video-episodes.sync="videoEpisodes"
						@episodes="triggerEpisodes"
						:data="data"
						:adv="advList"
						@Share="openShare"
						@download="download"
						@favVod="favVod"
						:is_fav="data.is_fav"
						@dig="digVod"
					></video-info>
					<video-comment ref="comment" :id="id" @reward="toReward" :showinput="1"></video-comment>
				</scroll-view>
			</view>
		</view>
		<u-popup :show="episodesShow" :round="10" @close="triggerEpisodes(false)">
			<view class="video-episodes-popup">
				<scroll-view :scroll-top="episodesScroll" scroll-y>
					<view v-if="data.vod_play_url.length > 0" class="episodes-popup-grid">
						<view
							v-for="(item, index) in data.vod_play_url[playIndex].list"
							:key="index"
							class="grid-item"
							:class="index == videoEpisodes && 'selected'"
							@click="selectEpisodes(index)"
						>
							<text class="grid-text">{{ item.name }}</text>
							<u-badge v-if="item.badge" :value="item.badge.value"></u-badge>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
		<share ref="share"></share>
		<u-loading-page :loading="loading" bgColor="none" fontSize="16"></u-loading-page>
		<reward ref="reward" />
		<full-adv ref="fullAdv" @close="closeFullAdv" />
	</view>
</template>

<script>
const lyzmlDLNA = uni.requireNativePlugin('lyzml-DLNA');
import artplayer from '../../components/artplayer-app.vue';
import videoInfo from './video-info';
import videoComment from './video-comment';
import vodImage from '@/components/vod-image.vue';
import share from '@/components/share';
import { loadImage } from '@/utils/utils';
import reward from '@/components/reward';
import fullAdv from '@/components/full-adv';
import fileManager from '@/utils/fileManager.js';
import { app, user } from '@/utils/api';
// #ifdef APP-PLUS
import DB from '@/utils/sqlite.js';
// #endif
export default {
	components: {
		artplayer,
		vodImage,
		videoInfo,
		videoComment,
		share,
		reward,
		fullAdv
	},
	data() {
		return {
			id: 0,
			data: {
				vod_play_url: [],
				is_fav: 0
			},
			advList: {},
			playerUrl: '',
			// playerReady: false,
			// playerDestroy: false,
			// controllerShow: true,
			// panelShow: false,
			introShow: false,
			episodesShow: false,
			videoTabsIndex: 0,
			videoEpisodes: 0,
			episodesScroll: 0,
			loading: true,
			lookLoading: false,
			playIndex: 0,
			adShow: false,
			adTime: {},
			adLookNum: 0,
			looked: [],
			playTime: 0,
			timer: null,
			faved: false,
			trySee: false,
			//artplayer
			// adData:{},
			video_height: (uni.getSystemInfoSync().screenWidth / 16) * 9 + 50,
			playAdv: null,
			playAdvShow: false,
			isios: false,
			tvList: [],
			tvlistShow: false,
			tvShow: false,
			tvitem: {},
			pipstate: false,
			danmulist: [],
			scrollTop: 0,
			showinput: false,
			videoCachePath: '',
			isStartDownload: false,
			lookcode: 0,
			lookedUrl: '',
			urlarr: [],
			p2p: 0,
			currentTime: 0
		};
	},
	watch: {
		playIndex: {
			handler(val) {
				// let url = this.data.vod_play_url[val]['list'][this.videoEpisodes].url
				// this.playerUrl = this.getVideoUrl(url)
				this.$refs.artplayer.pause();
				this.playerLoadData();
			}
		},
		videoEpisodes: {
			handler(val) {
				if (this.loading === false) {
					if (this.data.adv_list.play_adv.length && this.data.adv_list.play_adv.length > 0) {
						this.advList.play_adv = this.data.adv_list.play_adv[Math.floor(Math.random() * this.data.adv_list.play_adv.length)];
					}
					this.playAdvShow = false;
					this.lookVod();
				}
			}
		}
	},
	onLoad(option) {
		this.openSQL();
		if (option.id) {
			this.id = parseInt(option.id);
		}
		if (option.play_index) {
			this.videoEpisodes = parseInt(option.play_index);
		}
		if (uni.getSystemInfoSync().platform == 'ios') {
			this.isios = true;
		} else {
			this.isios = false;
		}

		fileManager.readAppDir().then((res) => {
			this.videoCachePath = res;
			this.getData();
		});
		this.$nextTick(() => {
			this.commentData();
		});
	},
	onShow() {
		this.$nextTick(() => {
			this.timer = setInterval(() => {
				let play = false;
				if (this.$refs.artplayer) {
					play = this.$refs.artplayer.playStatus();
				}
				// this.$refs.artplayer.currentTime();
				if (play) {
					this.playTime++;
				}
				if (this.playTime == 1800) {
					this.toTask();
				}
				if (this.trySee && this.data.vod_trysee > 0 && this.playTime >= this.data.vod_trysee) {
					this.$refs.artplayer.destroy();
					this.trySee = false;
					if (this.data.vod_mode == 2) {
						this.toVip();
					} else {
						this.toPay();
					}
				}
				if (this.playTime > 1800) {
					clearInterval(this.timer);
				}
			}, 1000);
		});
	},
	onHide() {
		this.adShow = false;
		this.$refs.artplayer.playershow();
		if (this.timer) {
			clearInterval(this.timer);
		}
		if (!this.pipstate) {
			this.$refs.artplayer.pause();
		}
	},
	onUnload() {
		this.closeSQL();
		if (this.timer) {
			clearInterval(this.timer);
		}
	},
	methods: {
		openSQL() {
			// 这个是查询有没有打开数据库
			let open = DB.isOpen();
			if (!open) {
				DB.openSqlite();
				DB.selectTableData('vodDig')
					.then((res) => {})
					.catch((error) => {
						let sql = '"id" INTEGER PRIMARY KEY AUTOINCREMENT,"vod_id" text,"up" text,"down" text';
						DB.createTable('vodDig', sql);
					});

				DB.selectTableData('vodHistory')
					.then((res) => {})
					.catch((error) => {
						let sql = `
							  "id" INTEGER PRIMARY KEY AUTOINCREMENT,
							  "vod_id" text,
							  "time" INTEGER
							`;
						DB.createTable('vodHistory', sql);
					});
				DB.selectTableData('vodFav')
					.then((res) => {})
					.catch((error) => {
						let sql = `
								  "id" INTEGER PRIMARY KEY AUTOINCREMENT,
								  "vod_id" text,
								  "status" INTEGER,
								  "time" INTEGER
								`;
						DB.createTable('vodFav', sql);
					});
			}
		},
		closeSQL() {
			let open = DB.isOpen();
			if (open) {
				DB.closeSqlite();
			}
		},
		// async getdanmu() {
		// 	await app.danmu(this.id).then(res => {
		// 		this.danmulist = res.data || []
		// 	})
		// },
		async addDanmu(danmu) {
			danmu.timestamp = Math.round(new Date());
			await app.addDanmu(this.id, danmu.color, danmu.time, danmu.mode, danmu.text, danmu.timestamp);
		},
		playpip(pipstate) {
			this.pipstate = pipstate;
		},
		scanairplay() {
			this.$refs.artplayer.fullScreen(false);
			lyzmlDLNA.startSearch((resp) => {
				if (resp.code == 0) {
				} else if (resp.code == 1) {
					lyzmlDLNA.getSearchResult((devList) => {
						this.tvList = devList;
					});
					this.triggertv(true);
				} else if (resp.code == 2) {
				}
			});
		},
		connecttv(item) {
			this.tvitem = item;
			lyzmlDLNA.playVideo(
				{
					udn: item.udn,
					mediaURL: this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url
				},
				(resp) => {
					if (resp && 0 != resp.code) {
						uni.showToast({
							icon: 'none',
							title: '若投屏失败，请尝试重新扫描'
						});
					} else {
						this.triggertv(false);
						this.tvShow = true;
						this.$refs.artplayer.pause();
						this.$refs.artplayer.playerhide();
					}
				}
			);
		},
		getdanmu(url) {
			let apiDomain = uni.getStorageSync('API_DOMAIN');
			let index = uni.getStorageSync('API_DOMAIN_INDEX') || 0;
			return new Promise((resolve, reject) => {
				uni.request({
					method: 'GET',
					url: apiDomain[index] + url
				}).then((response) => {
					const [error, res] = response;
					if (res && res.statusCode === 200) {
						resolve(res.data);
					} else {
						reject(error);
					}
				});
			});
		},
		async getData() {
			this.loading = true;
			await app
				.vodDetails(this.id)
				.then((res) => {
					if (res.code == 1) {
						this.data = res.data;
						console.log(this.data);
						if (this.data.danmu) {
							this.getdanmu(this.data.danmu).then((data) => {
								this.danmulist = data || [];
							});
						}
						DB.selectTableData('vodDig', 'vod_id', this.id).then((res) => {
							if (res.length) {
								this.data.is_up = res[0].up == 1 ? 1 : 0;
								this.data.is_down = res[0].down == 1 ? 1 : 0;
								if (this.data.is_up) {
									this.data.vod_up += 1;
								}
								if (this.data.is_down) {
									this.data.vod_down += 1;
								}
							}
						});
						DB.selectTableData('vodFav', 'vod_id', this.id).then((res) => {
							if (res) {
								this.data.is_fav = res[0].status;
							}
						});
						try {
							if (this.data.adv_list.full_adv.length > 0) {
								this.advList.full_adv = this.data.adv_list.full_adv;
							}
						} catch (err) {}
						if (this.data.adv_list.play_adv.length > 0) {
							this.advList.play_adv = this.data.adv_list.play_adv[Math.floor(Math.random() * this.data.adv_list.play_adv.length)];
						}
						if (this.data.adv_list.banner_adv1.length > 0) {
							this.advList.banner_adv1 = this.data.adv_list.banner_adv1[Math.floor(Math.random() * this.data.adv_list.banner_adv1.length)];
						}
						if (this.data.adv_list.banner_adv2.length > 0) {
							this.advList.banner_adv2 = this.data.adv_list.banner_adv2[Math.floor(Math.random() * this.data.adv_list.banner_adv2.length)];
						}
						this.lookVod();
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration: 3000
						});
						setTimeout(() => {
							this.toBack();
						}, 1500);
					}
				})
				.catch((e) => {
					setTimeout(() => {
						this.toBack();
					}, 1500);
				});
		},
		getVideoUrl(url) {
			let vod_name = this.data.vod_name;
			let vod_id = this.data.vod_id;
			let name = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].name;
			let fileType = '.mp4';
			let mainName = vod_name + '-' + name + '_' + vod_id + fileType;
			let localPath = fileManager.getLocalVideoUrl(mainName, this.videoCachePath);

			return localPath.length > 0 ? localPath : this.lookedUrl;
		},
		async lookVod() {
			if (this.looked.indexOf(this.videoEpisodes) === -1) {
				this.lookLoading = true;
				const playUrl = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url;
				const key = this.data.vod_play_url[this.playIndex].key;

				const res = await app.lookVod(this.id + '_' + this.videoEpisodes, playUrl).then(res);
				this.lookLoading = false;
				this.lookcode = res.code;
				this.loading = false;
				if (res.data.url) {
					this.lookedUrl = res.data.url.h264;
					this.p2p = res.data.p2p;
					this.urlarr.push({
						displayName: '264',
						resName: key + '.' + this.id + '.' + this.playIndex + (res.data.url.ver ? '.' + res.data.url.ver : '') + '.264',
						p2pM3u8Url: this.lookedUrl,
						maxLruCacheSize: 3000
					});
				}
				if (res.code == 0) {
					this.$refs.artplayer.destroy();
					uni.showToast({
						icon: 'none',
						title: res.msg,
						duration: 3000
					});
					setTimeout(() => {
						// this.toBack()
					}, 1500);
					return;
				} else if (res.code == 2) {
					this.trySee = true;
					if (this.data.vod_trysee <= 0) {
						this.$refs.artplayer.destroy();
						this.toVip();
						return;
					}
				} else if (res.code == 3) {
					try {
						this.adLookNum = res.data.adv_look_num;
					} catch (err) {
						this.adLookNum = 0;
					}
					this.toAdv();
					return;
				} else if (res.code == 4) {
					this.trySee = true;
					if (this.data.vod_trysee <= 0) {
						this.$refs.artplayer.pause();
						this.toPay();
						return;
					}
				} else {
					this.trySee = false;
					this.looked.push(this.videoEpisodes);
					app.updateHits(this.id, 1);
					this.addHistory();
					if (this.data.adv_list.play_adv.length > 0) {
						setTimeout(() => {
							this.$refs.artplayer.fullScreen(false);
						}, 100);
						this.$refs.artplayer.pause();
						this.playerLoadData();
						this.$refs.artplayer.playerhide();
						this.adShow = true;
					} else {
						this.$nextTick(() => {
							this.$refs.artplayer.pause();
							this.playerLoadData();
						});
					}
					return;
				}
			}
			this.$nextTick(() => {
				this.$refs.artplayer.pause();
				this.playerLoadData();
			});
		},
		async playerLoadData() {
			let name = this.data['vod_name'] + ' ' + this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].name;
			let url = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url;
			this.playerUrl = this.getVideoUrl(url);
			const match = this.data.vod_thumbnails.match(/-(\d+).[jpg|jpeg|png|webp|gif|bmp]+$/i);
			const thumbnailsNum = match ? parseInt(match[1]) : 100;
			const pic = await loadImage(this.data['vod_pic']);
			let vod_thumbnails = this.data.vod_thumbnails;
			if (!vod_thumbnails.includes('http:')) {
				vod_thumbnails = 'http:' + vod_thumbnails;
			}
			this.$refs.artplayer.loadData({
				id: this.id,
				adData: {},
				url: this.playerUrl,
				title: name,
				pic: pic,
				playList: this.data.vod_play_url[this.playIndex]['list'],
				videoEpisodes: this.videoEpisodes,
				isios: this.isios,
				danmulist: this.danmulist || [],
				thumbnails: {
					url: vod_thumbnails,
					number: thumbnailsNum,
					column: thumbnailsNum,
					width: 250,
					height: 165
				},
				urlarr: this.urlarr,
				p2p: this.p2p
			});
		},
		toTask() {
			const token = getApp().globalData.userToken;
			if (token) {
				user.task(2).then((res) => {
					if (res.code == 1 && res.data) {
						this.toReward(res.data.task_coin);
					}
				});
			}
		},
		addHistory() {
			const record = {
				id: this.id,
				time: Math.round(new Date() / 1000)
			};

			DB.selectTableData('vodHistory', 'vod_id', this.id)
				.then((res) => {
					if (res.length > 0) {
						let condition = `time = '${record.time}'`;
						DB.updateTableData('vodHistory', condition, 'vod_id', this.id);
					} else {
						let sql = `'${this.id}','${record.time}'`;
						let condition = `'vod_id','time'`;
						DB.insertTableData('vodHistory', sql, condition);
					}
				})
				.catch((error) => {
					console.error('Error selecting vodHistory data:', error);
				});
		},
		async favVod() {
			const token = getApp().globalData.userToken;
			if (token) {
				if (this.faved) {
					return;
				}
				this.faved = true;
				this.data.is_fav = this.data.is_fav === 1 ? 0 : 1;
				const record = {
					id: this.id,
					time: Math.round(new Date() / 1000),
					status: this.data.is_fav
				};

				DB.selectTableData('vodFav', 'vod_id', this.id).then((res) => {
					if (res.length > 0) {
						if (record.status == 1) {
							let condition = `time = '${record.time}',status = '${record.status}'`;
							DB.updateTableData('vodFav', condition, 'vod_id', this.id);
						} else {
							DB.deleteTableData('vodFav', 'vod_id', this.id);
						}
					} else {
						let sql = `'${this.id}','${record.time}','${record.status}'`;
						let condition = `'vod_id','time','status'`;
						DB.insertTableData('vodFav', sql, condition);
					}
				});

				this.faved = false;
			} else {
				uni.navigateTo({
					url: '/pages/user/login'
				});
			}
		},
		digVod(e) {
			app.updateDig(this.id, 1, e).then((res) => {
				const status = this.data['is_' + e] ? 0 : 1;
				if (res.code == 1) {
					if (this.data['is_' + e] === 1) {
						this.data['is_' + e] = 0;
					} else {
						this.data['is_' + e] = 1;
					}
					let data = {};
					data[e] = this.data['is_' + e];

					if (status === 1) {
						this.data['vod_' + e] += 1;
					} else if (this.data['vod_' + e] > 0) {
						this.data['vod_' + e] -= 1;
					}
					DB.selectTableData('vodDig', 'vod_id', this.id).then((res) => {
						if (res.length) {
							let condition = `${e} = '${status}'`;
							DB.updateTableData('vodDig', condition, 'vod_id', this.id);
						} else {
							let sql = `'${this.id}','${status}'`;
							let condition = `'vod_id','${e}'`;
							DB.insertTableData('vodDig', sql, condition);
						}
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg
					});
				}
			});
		},

		// xgplayerReady(status) {
		//   this.playerReady = status
		// },
		// xgplayerControlShow(status) {
		//   this.controllerShow = status
		// },
		// switchLine(status) {
		//   if (status) {
		//     this.controllerShow = false
		//     this.panelShow = true
		//   } else {
		//     this.controllerShow = true
		//     this.panelShow = false
		//   }
		// },
		changePlay(index) {
			this.$refs.artplayer.pause();
			this.playIndex = index;
		},
		swiperChange(e) {
			this.videoTabsIndex = e.detail.current;
			if (this.videoTabsIndex === 1 && this.loading === false) {
				this.$refs.comment.init();
			}
		},
		tabsClick(index) {
			if (this.videoTabsIndex != index) {
				this.videoTabsIndex = index;
			}
			if (index == 1) {
				this.scrollTop = 510;
			} else {
				this.scrollTop = 0;
			}
		},
		closeIntro() {
			this.introShow = false;
		},
		triggerEpisodes(status) {
			this.episodesShow = status;
			if (status) {
				this.$nextTick(async () => {
					const grid = await new Promise((resolve) => {
						uni.createSelectorQuery()
							.in(this)
							.select('.episodes-popup-grid')
							.boundingClientRect((data) => {
								resolve(data);
							})
							.exec();
					});
					const item = await new Promise((resolve) => {
						uni.createSelectorQuery()
							.in(this)
							.select('.episodes-popup-grid .selected')
							.boundingClientRect((data) => {
								resolve(data);
							})
							.exec();
					});
					let scrollTop = item.top - grid.top - 90;
					scrollTop = Math.min(scrollTop, grid.height);
					this.episodesScroll = Math.max(0, scrollTop);
				});
			}
		},
		selectNextEpisodes() {
			if (this.data.vod_play_url[this.playIndex]['list'].length > this.videoEpisodes) {
				this.videoEpisodes += 1;
				this.triggerEpisodes(false);
			}
		},
		selectEpisodes(index) {
			this.videoEpisodes = index;
			this.triggerEpisodes(false);
		},
		openShare() {
			this.$refs.share.showSharePopup = true;
		},
		adClose() {
			this.adShow = false;
			this.$refs.artplayer.playershow();
		},
		timeChange(e) {
			this.adTime = e;
		},
		async download() {
			let vod_name = this.data.vod_name;
			let vod_id = this.data.vod_id;
			let name = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].name;
			let url = this.data.vod_down_url[this.playIndex]['list'][this.videoEpisodes].url;
			let fileType = '.mp4';
			let mainName = vod_name + '-' + name + '_' + vod_id + fileType;
			await app.downVod(this.id).then((res) => {
				if (res.code == 0) {
					uni.showToast({
						icon: 'none',
						title: res.msg,
						duration: 3000
					});
					return;
				} else if (res.code == 2) {
					this.toVip();
					return;
				} else if (res.code == 3) {
					if (res.data.adv_look_num > 0) {
						this.toAdvdown(res.data.adv_look_num);
					}
					return;
				} else if (res.code == 4) {
					this.toPay();
					return;
				} else {
					fileManager.checkFile(mainName).then(async (res) => {
						if (!res) {
							if (url != '') {
								if (!this.isStartDownload) {
									await fileManager
										.createDir()
										.then(async (res) => {
											let download = await fileManager
												.downloadVideo(url, mainName, (state, progress) => {
													if (!this.isStartDownload) {
														uni.showToast({
															icon: 'none',
															title: '已加入下载列表',
															duration: 3000
														});
														setTimeout(() => {
															uni.navigateTo({
																url: '/pages/user/download'
															});
														}, 1500);
													}
													this.isStartDownload = true;
												})
												.then(() => {})
												.catch((res) => {
													uni.showToast({
														icon: 'none',
														title: '下载失败, 请稍后重试',
														duration: 3000
													});
												});
										})
										.catch((res) => {
											uni.showToast({
												icon: 'none',
												title: '无法创建下载路径, 请检查权限',
												duration: 3000
											});
										});
								} else {
									uni.showToast({
										icon: 'none',
										title: '下载中...',
										duration: 3000
									});
								}
							} else {
								uni.showToast({
									icon: 'none',
									title: '暂无下载资源',
									duration: 3000
								});
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '视频已下载',
								duration: 3000
							});
							return;
							//检测成功列表中是否已有
							fileManager.checkSuccessFile(mainName).then(async (res) => {
								if (res) {
									uni.showToast({
										icon: 'none',
										title: '视频已下载',
										duration: 3000
									});
								} else {
									await fileManager.deleteFile(mainName).then(async (res) => {
										this.isStartDownload = false;
										await downloadVideo();
									});
								}
							});
						}
					});
				}
			});
			return;
		},
		toAdvdown(num) {
			this.$refs.artplayer.pause();
			if (this.data.adv_list.full_adv.length == 0) {
				num = 0;
			}
			uni.showModal({
				title: '下载提示',
				confirmText: '购买VIP特权',
				confirmColor: '#fd6202',
				cancelText: num > 0 ? '看广告解锁视频' : '今日解锁次数已满',
				content: '您的今日免费下载次数已用尽~!',
				success: (res) => {
					if (res.confirm) {
						uni.redirectTo({
							url: '/pages/user/recharge'
						});
					} else {
						if (num > 0) {
							plus.screen.lockOrientation('portrait-primary');
							if (this.data.adv_list.full_adv.length > 0) {
								// let url = this.data.vod_play_url[this.playIndex]['list'][this
								// 	.videoEpisodes
								// ].url
								// this.playerUrl = this.getVideoUrl(url)
								// this.playerLoadData()
								this.$refs.artplayer.playerhide();
								this.showFullAdv('video');
							}
						} else {
							this.toBack();
						}
					}
				}
			});
		},
		toReward(value) {
			this.$refs.reward.onshow(value);
		},
		toVip() {
			uni.showModal({
				title: '观影提示',
				confirmText: '充值VIP',
				confirmColor: '#fd6202',
				content: '该影片是VIP专属，请先升级VIP再进行观看~!',
				success: (res) => {
					if (res.confirm) {
						uni.redirectTo({
							url: '/pages/user/recharge'
						});
					} else {
						this.back();
					}
				}
			});
		},
		toBack() {
			const pages = getCurrentPages();
			const pagesLength = pages.length;
			if (pagesLength === 1) {
				uni.switchTab({
					url: '/pages/home/index'
				});
			} else {
				for (let delta = 1; delta < pagesLength; delta++) {
					if (pages[pagesLength - delta - 1].route == 'pages/video/video-app') {
						continue;
					}
					uni.navigateBack({
						delta: delta
					});
					break;
				}
			}
		},
		toAdv() {
			this.$refs.artplayer.pause();

			if (this.data.adv_list.full_adv.length == 0) {
				this.adLookNum = 0;
			}
			uni.showModal({
				title: '观影提示',
				confirmText: '购买VIP特权',
				confirmColor: '#fd6202',
				cancelText: this.adLookNum > 0 ? '看广告解锁视频' : '今日解锁次数已满',
				content: '您的今日免费观影次数已用尽~!',
				success: (res) => {
					if (res.confirm) {
						uni.redirectTo({
							url: '/pages/user/recharge'
						});
					} else {
						if (this.adLookNum > 0) {
							plus.screen.lockOrientation('portrait-primary');
							if (this.data.adv_list.full_adv.length > 0) {
								// let url = this.data.vod_play_url[this.playIndex]['list'][this
								// 	.videoEpisodes
								// ].url
								// this.playerUrl = this.getVideoUrl(url)
								// this.playerLoadData()
								this.$refs.artplayer.playerhide();
								this.showFullAdv('video');
							}
						} else {
							this.toBack();
						}
					}
				}
			});
		},
		toPay() {
			uni.showModal({
				title: '观影提示',
				confirmText: '购买视频',
				confirmColor: '#fd6202',
				content: '该影片是付费视频，请先购买视频再进行观看~!',
				success: async (res) => {
					if (res.confirm) {
						// uni.redirectTo({
						// 	url: '/pages/user/recharge'
						// })
						const res = await app.buyVod(this.id).then(res);
						if (res.code == 0) {
							uni.showToast({
								icon: 'none',
								title: res.msg,
								duration: 3000
							});
							setTimeout(() => {
								this.toBack();
							}, 2000);
							return;
						} else if (res.code == 2) {
							uni.showToast({
								icon: 'none',
								title: res.msg,
								duration: 3000
							});
							setTimeout(() => {
								uni.redirectTo({
									url: '/pages/user/bullion'
								});
							}, 2000);

							return;
						} else if (res.code == 3) {
							this.toVip();
							return;
						}
						uni.showToast({
							icon: 'none',
							title: res.msg,
							duration: 3000
						});
					} else {
						this.toBack();
					}
				}
			});
		},
		showPlayAdv() {
			// if (this.advList.play_adv.length > 0) {
			// 	this.playAdv = this.advList.play_adv[Math.floor(Math.random() * this.advList.play_adv.length)]
			// 	this.playAdvShow = true
			// }
		},
		showFullAdv(type) {
			plus.screen.lockOrientation('portrait-primary');
			let url = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url;
			this.playerUrl = this.getVideoUrl(url);

			if (type) {
				this.$refs.fullAdv.type = type;
				this.$refs.fullAdv.toast = null;
			} else {
				this.$refs.fullAdv.type = 'default';
				this.$refs.fullAdv.toast = '视频极速加载中';
			}
			this.$refs.fullAdv.adv = this.advList.full_adv[Math.floor(Math.random() * this.advList.full_adv.length)];
			this.$refs.fullAdv.showPopup = true;
		},
		setplayAdv() {
			this.$refs.artplayer.playershow();
			this.playAdvShow = false;
		},
		async closeFullAdv(type) {
			this.adFull = false;
			if (this.data.adv_list.play_adv.length > 0) {
				// this.adShow = true
			} else {
				// let url = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url
				// this.playerUrl = this.getVideoUrl(url)
				// this.playerLoadData()
			}
			if (type == 'video') {
				this.lookLoading = true;
				const playUrl = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url;
				const res = await app.advUnlockVod(this.id + '_' + this.videoEpisodes, playUrl).then(res);
				const key = this.data.vod_play_url[this.playIndex].key;
				if (res.data.url) {
					this.lookedUrl = res.data.url.h264;
					this.p2p = res.data.p2p;
					this.urlarr.push({
						displayName: '264',
						resName: key + '.' + this.id + '.' + this.playIndex + (res.data.url.ver ? '.' + res.data.url.ver : '') + '.264',
						p2pM3u8Url: this.lookedUrl,
						maxLruCacheSize: 3000
					});
				}
				this.lookLoading = false;
				if (res.code == 1) {
					this.looked.push(this.videoEpisodes);
					app.updateHits(this.id, 1);
					this.addHistory();
					this.playerLoadData();
					this.$refs.artplayer.playershow();
					// let url = this.data.vod_play_url[this.playIndex]['list'][this.videoEpisodes].url
					// this.playerUrl = this.getVideoUrl(url)
				}
				uni.showToast({
					icon: 'none',
					title: res.msg,
					duration: 3000
				});
			}
		},
		commentData() {
			this.$refs.comment.getData();
		},
		handleScroll(event) {
			const scrollTop = event.detail.scrollTop;
			if (scrollTop > 400) {
				this.videoTabsIndex = 1;
			} else {
				this.videoTabsIndex = 0;
			}
		},
		openComment() {
			this.videoTabsIndex = 1;
			this.scrollTop = 510;
		}
	}
};
</script>

<style lang="scss">
page {
	background-color: $uni-bg-color;
}

.page-container {
	height: 100%;
	background-color: $uni-bg-color;

	.status-bar {
		background-color: #000;
	}

	.video {
		width: 100%;
		height: 234px;
		background-color: #000;
		position: relative;

		.video-box {
			width: 100%;
			height: 100%;
			background-color: #ffa527;
		}

		.u-loading-icon {
			background-color: #000;
			z-index: 999;
			pointer-events: none;
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;
		}

		.play-tv {
			z-index: 9999;
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;

			uni-image {
				width: 100%;
				height: 100%;
			}

			uni-text {
				padding: 5px 10px;
				font-size: 12px;
				color: #fff;
				border-radius: 13px;
				background-color: rgba(0, 0, 0, 0.7);
				position: absolute;
				top: 65%;
				right: 315rpx;
			}
		}

		.play-adv {
			z-index: 9999;
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;

			uni-image {
				width: 100%;
				height: 100%;
			}

			uni-text {
				padding: 5px 10px;
				font-size: 12px;
				color: #fff;
				border-radius: 13px;
				background-color: rgba(0, 0, 0, 0.7);
				position: absolute;
				top: 15px;
				right: 15px;
			}
		}

		.controller {
			z-index: 999;
			pointer-events: none;
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;

			.controller-header {
				pointer-events: auto;
				padding: 10px 8px 0;
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				position: absolute;
				top: 0;
				left: 0;
				right: 0;

				.uni-icons {
					text-shadow: 0 0 4px rgba(0, 0, 0, 0.75);
				}

				.switch-line {
					margin: 0 11px;
					font-size: 14px;
					color: #fff;
					text-shadow: 0 0 4px rgba(0, 0, 0, 0.75);
				}
			}
		}

		.panel {
			z-index: 999;
			position: absolute;
			left: 0;
			top: 0;
			right: 0;
			bottom: 0;

			.line-panel {
				position: absolute;
				top: 0;
				right: 0;
				bottom: 0;
				width: 90px;
				background-image: linear-gradient(90deg, transparent, rgba(0, 0, 0, 0.8));

				uni-scroll-view {
					position: absolute;
					top: 0;
					bottom: 0;
				}

				.line-panel-content {
					padding: 5px 0;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					position: relative;
					z-index: 999;

					.line-panel-item {
						margin: 10px 0;
						padding: 0 10px;
						height: 17px;
						line-height: 17px;
						font-size: 14px;
						color: #fff;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						text-shadow: 0 0 4px rgba(0, 0, 0, 0.75);

						&.selected {
							color: #ffa527;
						}
					}
				}
			}
		}
	}

	.video-info {
		height: calc(100% - var(--safe-top) - 234px);
		display: flex;
		flex-direction: column;

		.ad-banner {
			width: 100%;
			padding: 5px;

			uni-image {
				width: 100%;
				border-radius: 8px;
				min-height: 50px;
			}
		}

		.video-info-header {
			height: 40px;
			position: relative;

			.header-bg {
				height: 100%;
				position: absolute;
				background: linear-gradient(111deg, #d2fee1, #ecfafa 53%, #e9fde5);
			}

			.video-tabs {
				height: 100%;
				align-items: center;

				.video-tabs-title {
					margin: 0 5px;
					position: relative;

					uni-text {
						margin: 0 10px;
						font-size: 18px;
						color: #fff;

						&.selected {
							font-weight: 700;
						}
					}
				}

				.video-msg {
					position: relative;
					color: #787bdc;
					font-size: 12px;
				}

				.video-bar {
					margin: 0 5px;
					position: relative;

					.uni-icons {
						margin: 0 8px;
					}
				}
			}
		}

		.video-info-swiper {
			flex: 1 1 0%;
			height: calc(100% - var(--safe-top) - 234px);

			.swiper-container {
				height: 1000rpx;
			}
		}
	}

	.video-episodes-popup {
		uni-scroll-view {
			max-height: 240px;

			.episodes-popup-grid {
				padding: 10px;
				display: grid;
				grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));

				.grid-item {
					padding: 5px;
					position: relative;

					.grid-text {
						width: 100%;
						padding: 0 15px;
						height: 48px;
						line-height: 48px;
						text-align: center;
						font-size: 14px;
						color: #1a1a2a;
						background: #f2f5fa;
						border-radius: 4px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
						display: block;
					}

					.u-badge {
						border-radius: 0 7px 0 7px;
						position: absolute;
						right: 5px;
						top: 5px;
					}

					&.selected {
						.grid-text {
							font-weight: 700;
							background: #da2538;
							border-radius: 5px;
							color: #fff;
						}
					}
				}
			}
		}
	}
}
</style>
