<template>
    <view class="video-page-wrap flex-column">
        <view class="player flex-column">
            <view class="back" @click="goBack">
                <u-icon name="arrow-left" color="#fff" size="20"></u-icon>
            </view>

            <!-- <xt-video
                v-if="form.playVideoUrl"
                ref="xtVideoRef"
                video-id="video"
                :src="form.playVideoUrl"
                :poster="form.poster"
                :episodes="episodes"
                :ratios="ratios"
                @Ratio="handleChangeRatio"
                @Epi="handleChangeEpi"
                @timeupdate="timeupdate"
                :initialTime="form.second"
                showSpeed
                autoplay
            ></xt-video> -->

            <sunny-video
                style="width: 100%; height: 100%"
                ref="sunnyVideo"
                :src="form.playVideoUrl"
                :poster="form.poster"
                @timeupdate="timeupdate"
                :trialTime="0"
                tipText="试看结束，若想观看全剧请移步首页购买VIP服务"
                btnText="充值VIP"
                :seekTime="form.second"
                showMuteBtn
            ></sunny-video>
        </view>

        <view class="main-content">
            <view class="flex justify-between">
                <view class="title">{{ form.title }}</view>
                <view
                    class="text-but flex-left justify-center"
                    @click="isOpen = !isOpen"
                >
                    <text>简介</text>
                    <u-icon
                        :name="isOpen ? 'arrow-down' : 'arrow-right'"
                        color="#696969"
                        size="10"
                        bold
                    ></u-icon>
                </view>
            </view>
            <view class="describe" v-show="isOpen">
                {{ form.content }}
            </view>

            <view class="handle-box flex-left">
                <view
                    @click="goProjection"
                    class="handle-row flex-left flex-column"
                >
                    <img src="@/static/img/icon-projection.svg" />
                    <view class="handle-text">投屏</view>
                </view>
                <view
                    @click="setCollect"
                    class="handle-row flex-left flex-column"
                >
                    <img
                        src="@/static/img/icon-collect-active.svg"
                        v-if="collectState"
                    />
                    <img src="@/static/img/icon-collect.svg" v-else />
                    <view class="handle-text">{{
                        collectState ? "取消收藏" : "收藏"
                    }}</view>
                </view>
            </view>

            <view class="flex justify-between" style="margin-top: 60rpx">
                <view class="title">选集</view>
                <view
                    class="flex-left justify-center"
                    @click="showAllEpisode = true"
                >
                    <text>{{ form.plan }}</text>
                    <u-icon
                        name="arrow-right"
                        color="#696969"
                        size="10"
                        bold
                    ></u-icon>
                </view>
            </view>
            <view class="flex" style="overflow-y: hidden; margin-top: 40rpx">
                <view
                    v-for="(item, index) in videoCollectionList"
                    @click="setEpisode(item, index)"
                    class="flex-left justify-center gather_but"
                    ><text
                        :style="{
                            color: form.page == index ? '#1DBC46' : '#000',
                        }"
                        style="font-size: 26rpx; text-align: center"
                        >{{ item.name }}</text
                    >
                </view>
            </view>

            <view style="margin-top: 60rpx">
                <view class="title">猜你喜欢</view>
                <view class="flex-row flex-wrap" style="margin-top: 20rpx">
                    <view
                        class="videoCardMain flex-column"
                        @click="goPlayVideo(item)"
                        v-for="(item, index) in recommendVideoList"
                    >
                        <view class="videoCardImgBox">
                            <image
                                class="videoCardImg"
                                :src="item.img"
                                mode="aspectFill"
                            ></image>
                            <text class="video-state">{{ item.state }}</text>
                        </view>
                        <view class="videoCardName line_1">
                            {{ item.title }}
                        </view>
                    </view>
                </view>
            </view>
        </view>

        <u-action-sheet
            title="选集"
            @close="showAllEpisode = false"
            :show="showAllEpisode"
            safeAreaInsetBottom
        >
            <view
                style="height: 800rpx; overflow-x: hidden; padding: 16rpx 20rpx"
            >
                <view class="flex-row flex-wrap">
                    <view
                        v-for="(item, index) in videoCollectionList"
                        @click="setEpisode(item, index)"
                        class="flex-left justify-center gather_but"
                    >
                        <text
                            :style="{
                                color: form.page == index ? '#1DBC46' : '#000',
                            }"
                            style="font-size: 26rpx; text-align: center"
                            >{{ item.name }}</text
                        >
                    </view>
                </view>
            </view>
        </u-action-sheet>

        <u-popup :show="tpshow" :round="10" closeable @close="tpshow = false">
            <view class="tbbox">
                <view class="tptitle">
                    <text class="tptitletext">投屏</text>
                </view>
                <view
                    class="tbitem"
                    v-for="dev in tpdevList"
                    :key="dev.id"
                    @click="tpStart(dev.id)"
                >
                    <u-icon
                        name="wifi"
                        size="30"
                        style="margin-right: 15rpx"
                    ></u-icon>
                    <text class="tbitemtext">{{ dev.name }}</text>
                </view>
                <u-empty
                    v-if="tpdevList.length == 0"
                    mode="wifi"
                    icon="http://cdn.uviewui.com/uview/empty/wifi.png"
                    text="无媒体"
                />
                <u-button
                    class="tbbtn"
                    text="点我刷新列表"
                    @click="tpSearch()"
                    shape="circle"
                    color="linear-gradient(to right,  #ff9800, #ff2a14)"
                ></u-button>
            </view>
        </u-popup>
        <u-overlay :show="showPoster">
            <div class="poster">
                <view class="icon-close" @click="showPoster = false">
                    <u-icon name="close" color="#fff" size="28"></u-icon>
                </view>
                <img src="@/static/img/poster.png" />
            </div>
        </u-overlay>
    </view>
</template>

<script>
// const dlna = uni.requireNativePlugin('JX-Dlna');
import $req from "@/service/serviceConfig";
import { listPackage } from "@/utils/apiMethods.js";
export default {
    data() {
        return {
            form: {
                url: "",
                page: 0, //当前集
                second: 0, //当前播放秒
                title: "",
                content: "",
                plan: "",
                playVideoUrl: "",
            },
            isOpen: false, //是否打开简介
            recommendVideoList: [], //推荐的视频列表
            videoCollectionList: [], //视频合集列表
            showAllEpisode: false,
            collectState: false, //是否收藏
            currentTime: 0, //当前播放时间

            tpshow: false,
            tptitle: "",
            tpdevList: [],

            ratios: [
                // {
                //     id: "480p",
                //     url: "xxx.mp4",
                //     name: "标清",
                // },
                // {
                //     id: "720p",
                //     url: "xxx1.mp4",
                //     name: "高清",
                // },
                // {
                //     id: "1080p",
                //     url: "xxx2.mp4",
                //     name: "超清",
                // },
            ],
            episodes: [
                // {
                //     id: "1",
                //     url: "xxx.mp4",
                //     name: "1",
                //     isVip: false,
                // },
                // {
                //     id: "2",
                //     url: "xxx.mp4",
                //     name: "2",
                //     isVip: false,
                // },
                // {
                //     id: "3",
                //     url: "xxx.mp4",
                //     name: "3",
                //     isVip: true,
                // },
            ],
            showPoster: false,
        };
    },
    async onLoad(option) {
        let vm = this;
        vm.form.url = option.url;
        uni.showLoading({
            title: "加载中",
        });
        await vm.getVideoBasicInfo();
        await vm.getVideoDetail();
        vm.getform(vm.videoCollectionList[vm.form.page].url);
        uni.hideLoading();
    },
    // 监听页面隐藏事件
    onHide() {
        let vm = this;
        vm.recordVideos();
    },
    methods: {
        // 自定义切换分辨率方法
        handleChangeRatio(item) {
            this.$refs.xtVideoRef.xtVideoReload({
                url: item.url,
            });
        },
        // 自定义切换集数方法
        handleChangeEpi(item) {
            this.$refs.xtVideoRef.xtVideoReload({
                url: item.url,
                startTime: 0,
            });
        },
        goProjection() {
            // uni.showToast({
            //     icon: "none",
            //     title: "请使用百度浏览器APP播放，然后点击视频右上角投屏按钮",
            //     duration: 2000,
            // });
            this.showPoster = true;
        },
        tpSearch() {
            this.tpshow = true;
            this.tptitle = "";
            this.tpdevList = [];
            dlna.search((result) => {
                //alert(result.type)
                this.tptitle +=
                    "通知类型:" +
                    result.type +
                    " 设备名:" +
                    result.name +
                    " 设备Id:" +
                    result.id +
                    "<br />";
                if (result.type === "add") {
                    this.tpdevList.push({
                        id: result.id,
                        name: result.name,
                    });
                } else {
                    this.tpdevList = this.tpdevList.filter(
                        (x) => x.id != result.id
                    );
                }
            });
        },
        tpStart(id) {
            this.tpshow = false;
            dlna.play(
                {
                    id: id,
                    url: this.vUrl,
                    title: this.detail.vod_name,
                },
                (result) => {
                    this.tptitle = result.msg;
                }
            );
        },
        // 屏幕共享触发的方法
        startScreenSharing() {
            // 检查浏览器是否支持屏幕共享
            if (navigator.mediaDevices.getDisplayMedia) {
                navigator.mediaDevices
                    .getDisplayMedia({ video: true })
                    .then((stream) => {
                        // 这里可以处理获取到的媒体流，例如播放视频等
                        // 为了简化代码，这里只是打印流信息
                        console.log("Screen sharing started:", stream);
                    })
                    .catch((error) => {
                        console.error("Screen sharing error:", error);
                    });
            } else {
                alert("Screen sharing not supported by this browser");
            }
        },
        // 获取视频基本信息
        getVideoBasicInfo() {
            return new Promise((resolve, reject) => {
                let vm = this;
                let query = {
                    videoUrl: vm.form.url,
                };
                $req.request({ alias: "view-records-get", query })
                    .then(async (res) => {
                        if (res.code == 0) {
                            vm.form.page = Number(res.data.currentSet);
                            vm.form.second = res.data.duration;
                            vm.collectState = res.data.isFavorite;
                            resolve();
                        } else {
                            await vm.recordVideos();
                            resolve();
                        }
                    })
                    .catch(() => {
                        resolve();
                    });
            });
        },
        //收藏||取消收藏
        setCollect() {
            let vm = this;
            let query = {
                videoUrl: vm.form.url,
            };
            let url = vm.collectState ? "favorite-cancel" : "favorite-add";
            $req.request({ alias: url, query })
                .then((res) => {
                    if (res.code == 0) {
                        vm.collectState = !vm.collectState;
                        uni.showToast({
                            title: vm.collectState ? "已收藏" : "已取消",
                            icon: "success",
                            duration: 2000,
                        });
                    }
                })
                .catch(() => {});
        },
        //记录视频
        recordVideos() {
            let vm = this;
            console.log(vm.form, "vm.form");
            return new Promise((resolve, reject) => {
                let body = {
                    videoUrl: vm.form.url,
                    name: vm.form.title,
                    poster: vm.form.poster,
                    duration: vm.currentTime,
                    currentSet: vm.form.page,
                };
                $req.request({ alias: "view-records-add", body })
                    .then((res) => {
                        if (res.code == 0) {
                            resolve();
                        } else {
                            // vm.recordVideos();
                        }
                    })
                    .catch(() => {
                        // vm.recordVideos();
                    });
            });
        },
        // 返回上一页
        async goBack() {
            let vm = this;
            // uni.showLoading();
            vm.recordVideos();
            uni.navigateBack({
                url: "/pages/index/index",
            });
            // uni.hideLoading();
        },
        // 播放上一个视频
        prevBtnClick() {
            let vm = this;
            vm.form.page--;
            vm.getform(vm.videoCollectionList[vm.form.page].url);
        },
        //播放下一个视频
        onNextBtnclick() {
            let vm = this;
            vm.form.page++;
            vm.getform(vm.videoCollectionList[vm.form.page].url);
        },
        timeupdate(data) {
            let num = data.detail.currentTime;
            this.currentTime = Math.round(num);
        },
        // 播放视频
        goPlay() {
            let vm = this;
            vm.$refs.yingbingVideo.play();
        },
        // 获取视频详情
        getVideoDetail() {
            return new Promise((resolve, reject) => {
                let vm = this;
                uni.request({
                    url: vm.form.url, // 接口地址
                    method: "GET", // 请求方法，可选值：GET、POST等
                    success: (res) => {
                        let parser = new DOMParser();
                        let doc = parser.parseFromString(res.data, "text/html");
                        //获取标题
                        vm.form.title = doc.querySelector(
                            ".detail-title>strong"
                        ).innerHTML;
                        //简介
                        vm.form.content =
                            doc.querySelector(".detail-desc>p").innerHTML;

                        let detailRowEl =
                            doc.querySelectorAll(".detail-info-row");
                        detailRowEl.forEach((item) => {
                            if (
                                item.querySelector(".detail-info-row-side")
                                    .innerHTML == "备注:"
                            ) {
                                vm.form.plan = item.querySelector(
                                    ".detail-info-row-main"
                                ).innerHTML;
                            }
                        });

                        vm.form.poster =
                            "https://61.147.93.252:15002" +
                            doc
                                .querySelector(".detail-pic>img")
                                .getAttribute("data-original");

                        //获取播放视频源-默认选第一个
                        let episodeEl = doc.querySelectorAll(".episode-list");
                        let episodeListEl =
                            episodeEl[0].querySelectorAll(".episode-item");
                        episodeListEl.forEach((a) => {
                            // let name = /\d/.test(a.innerHTML)
                            //     ? a.innerHTML.match(/\d+/g).map(Number)[0]
                            //     : a.innerHTML;
                            vm.videoCollectionList.push({
                                name: a.innerHTML,
                                url:
                                    "https://www.keke1.app" +
                                    a.getAttribute("href"),
                            });
                        });
                        vm.recommendVideoList = listPackage(
                            res.data
                        )[0].children;
                        resolve();
                    },
                    fail: (err) => {
                        resolve();
                    },
                });
            });
        },
        // 获取播放信息
        getform(url) {
            let vm = this;
            return new Promise((resolve, reject) => {
                uni.request({
                    url: url, // 接口地址
                    method: "GET", // 请求方法，可选值：GET、POST等
                    success: (res) => {
                        vm.form.playVideoUrl = res.data
                            .split("function initVideoPlayer() {")[1]
                            .split("src")[1]
                            .split(",")[0]
                            .split('"')[1];
                        // vm.$nextTick(() => {
                        //     vm.$refs.sunnyVideo.changePlay();
                        // });
                        resolve();
                    },
                    fail: (err) => {
                        resolve();
                    },
                });
            });
        },
        async setEpisode(item, index) {
            let vm = this;
            vm.$refs.sunnyVideo.closeTrialEnd();
            vm.form.page = index;
            vm.getform(item.url);
        },
        goPlayVideo(row) {
            uni.reLaunch({
                url: "/pages/play/play?url=" + row.url,
            });
        },
    },
};
</script>

<style lang="less" scoped>
.video-page-wrap {
    overflow: hidden;
    flex: 1;
    .player {
        width: 100%;
        height: 480rpx;
        // background-color: #000;
        .back {
            position: absolute;
            top: 10px;
            left: 8px;
            z-index: 999;
        }
        .icon-play {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            // opacity: 1;
            img {
                width: 120rpx;
                height: 120rpx;
            }
        }
        .time-text {
            position: absolute;
            width: 100%;
            height: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #fff;
            font-size: 48rpx;
        }
    }
    .main-content {
        flex: 1;
        overflow-x: hidden;
        margin-top: 36rpx;
        padding: 0 36rpx 30rpx;
        .title {
            color: #000;
            font-size: 32rpx;
            font-weight: bold;
        }
        .text-but {
            width: 100rpx;
            height: 50rpx;
            background-color: #f7f7f7;
            border-radius: 10rpx 10rpx 10rpx 10rpx;
            text-align: center;
        }
        .describe {
            color: #a6a6a6;
            font-size: 24rpx;
            margin-top: 30rpx;
            line-height: 1.5;
        }
        .handle-box {
            padding: 28rpx 38rpx 34rpx;
            // height: 160rpx;
            background-color: #f7f7f7;
            border-radius: 14rpx;
            margin-top: 60rpx;

            display: flex;
            justify-content: space-around;
            align-items: center;
            .handle-row {
                // width: 140rpx;
                img {
                    width: 60rpx;
                    height: 60rpx;
                }
            }
            .handle-text {
                font-size: 28rpx;
                font-weight: 500;
                color: #464646;
                margin-top: 5rpx;
            }
        }
        text {
            font-size: 24rpx;
            color: #717171;
            margin-right: 4rpx;
            font-weight: bold;
        }
    }
    .gather_but {
        margin: 10rpx;
        min-width: 11.4%;
        height: 68rpx;
        padding: 16rpx 20rpx;
        border-radius: 8rpx;
        background-color: #f7f7f7;
    }
}
/deep/.u-popup {
    flex: unset;
}

.tbbox {
    height: 500rpx;
    padding-top: 30rpx;

    .tptitle {
        position: absolute;
        top: 18rpx;
        left: 30rpx;

        .tptitletext {
            font-size: 28rpx;
            font-weight: bold;
        }
    }

    .tbitem {
        padding: 30rpx;
        flex-direction: row;
        align-items: center;

        .tbitemtext {
            font-size: 28rpx;
            font-weight: bold;
        }
    }

    .tbbtn {
        position: absolute;
        bottom: 20rpx;
        left: 225rpx;
        width: 300rpx;
    }
}
.poster {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
    width: 100%;
    img {
        width: 600rpx;
    }
    .icon-close {
        position: absolute;
        top: 60rpx;
        right: 40rpx;
        z-index: 1;
    }
}
</style>