var Player = require("player");
var Store = require("store");
var RequestVideo = require("request/video");

class videoPage {
    constructor (){
        this.ReqVideo = new RequestVideo();
        this.RelateList;    //相关视频列表
        this.vid = this.getParam('vid');    //当前视频vid
        this.perNum = location.hostname == '127.0.0.1' ? 3 : 10;        //初始化加载的视频个数
        this.playIns = [];      //播放器实例

        this.init();
        this.loadMore();
    }

    init(){
        this.showDetail();//展开视频详情

        this.shareLink();//分享

        var vid = this.vid;
        this.ReqVideo.getVideoInfo(vid).done((data) => {
            //console.log(data);
            this.buildObj(data[vid]);

            this.buildRelate(vid, this.perNum);
            //第一个视频预加载
            $("video:first").attr("preload","metadata");
        })

    }

    shareLink(){
        $(".video-play-list").on("click",".video-share", function () {
            $(".fixed-share-wrap").addClass("show");
            var sinaUrl = encodeURI($(this).siblings(".share-sina-input").val());
            var qqUrl = encodeURI($(this).siblings(".share-qq-input").val());

            $(".fixed-share-wrap").find(".share__item_qq").attr("href",qqUrl);
            $(".fixed-share-wrap").find(".share__item_sina").attr("href",sinaUrl);
            return false;
        })
        $("body").on("click",".cancle-share", function () {
            $(".fixed-share-wrap").removeClass("show");
            return false;
        })

    }


    /** 检查已订阅列表 */
    checkSubscribe () {
        this.ReqVideo.getUserSubscribe().done((ret) => {
            for(var i in ret.list) {
                $(`.follow-btn[data-uid='${ret.list[i].user_id}']`).removeClass('not-follow').addClass("followed").text("已订阅");
            }
        });
    }

    /** 检查用户已收藏列表 */
    checkUserCollected (vids) {
        this.ReqVideo.isVideoCollected(vids).done((ret) => {
            for(var i in ret.map) {
                if(ret.map[i]) {
                    $(`.video-collect[data-vid='${i}']`).addClass("clicked");
                }
            }
        })
    }

    /** 检查用户点赞列表 */
    checkUserSupport () {
        var sups = Store.get("userSupport");
        console.log(sups);
        for(var i in sups) {
            if(sups[i] == 1) {
                $(`.video-agree[data-vid='${i}']`).addClass("clicked");
            }
        }
    }

    buildRelate (vid, num) {
        this.ReqVideo.getVideoRelate(vid).done((ret) => {
            var vids = [];
            for(let i = 1 ; i < num; i++) {
                vids.push(ret[i].vid);
            }
            vids = vids.join(",");
            this.buildVideo(vids);
            if(num == 5) {
                vids = ret[0].vid + "," + vids;
            }
            this.checkUserCollected(vids);
        })
    }

    buildVideo (vids) {
        this.ReqVideo.getVideoInfo(vids).done((obj) => {
            for(let k in obj) {
                this.buildObj(obj[k]);
            }
            this.checkSubscribe();
            this.checkUserSupport();
        })
    }

    buildObj (data) {
        var Req = this.ReqVideo;
        var opts = data;
        opts['element'] = `#player${data.vid}`;
        opts['$wrap'] = `#video-play-list`;
        opts['__PLAYVID__'] = parseInt(this.vid);

        /** 数据解密 */
        var clarity = Req.deCodeArg(opts.c);
        var curUrl = clarity.select.src;
        opts['video_url'] = curUrl;


        /** 实例化一个播放模块 */
        this.playIns[data.vid] = new Player(opts);
        this.checkUserSupport();
    }

    getParam(name) {
        var getParam2 = function (name, str) {
            //获取参数name的值
            var reg = new RegExp("(^|!|&|\\?)" + name + "=([^&]*)(&|$)");

            //再获取?后面的参数
            r = str.match(reg);
            if (r != null) {
                try {
                    return decodeURIComponent(r[2]);
                } catch (e) {
                    console.log(e + "r[2]:" + r[2]);
                    return null;
                }
            }
            return null;
        }

        //先获取#后面的参数
        var str = document.location.hash.substr(2);
        var value = getParam2(name, str);
        if (value == null) {
            str = document.location.search.substr(1);
            value = getParam2(name, str);
        }

        return value;
    };

    loadMore(){
        let self = this;
        let $vpage = $(".video-play");
        /** 加载更多 */
        $vpage.on("click", ".common-look-more", function() {
            $(this).text("努力加载中···");
            self.ReqVideo.getVideoRelate(self.vid).done((ret) => {
                var vids = [];
                for(let i = self.perNum ; i < self.perNum + 5; i++) {
                    vids.push(ret[i].vid);
                }
                vids = vids.join(",");
                self.perNum = self.perNum + 5;
                self.buildVideo(vids);
                setTimeout(() => {
                    $(this).text("点击加载更多···");
                }, 1000);

                if(self.perNum >= 20) {
                    $(this).hide();
                    return;
                }
            })
        })
    }

    showDetail(){
        $(".video-play-list").on('click',".detail-btn", function () {
            $(this).toggleClass("on").parent().next().toggle();
        });
    }

}
$(function() {
    window.videoPage = new videoPage();

})