// Learn cc.Class:
//  - https://docs.cocos.com/creator/manual/en/scripting/class.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

/**
 * 视频进度条控制组件 
 * 发送消息的方式
 * video_play_end - 视频播放完成后发送，可以将播放按钮调整为结束状态
 * update_video_progress - 视频进度更新时调用，传入一个0-1之间的数值
 * update_video_status - 更新按钮状态，需要一个参数 0：暂停状态 1：播放状态 2：重播状态 // 0:暂停 1:播放中 2:重播
 * hide_bar - 隐藏进度条
 * show_bar - 显示进度条
 * set_mark_points - 设置关键点标记 传入一个数组 [0.2， 0.25， 0.6, 1]
 * set_start_end_label - 设置起始和结束，接受两个字符串类型的参数，如果不传参数或者传了空字符串就不显示标签, 第一个参数是起始时间，第二个是结束时间
 * 
 * 直接script调用
 * refreshVideoBtnState - 更新按钮状态，需要一个参数 0：暂停状态 1：播放状态 2：重播状态
 * showBar - 显示进度条
 * hideBar - 隐藏进度条
 * setProgress - 设置进度，参数为0-1之间的一个数字
 * setMarkPoints - 设置关键点标记 传入一个数组 [0.2， 0.25， 0.6, 1]
 * setStartEndTimeLabel - 设置起始和结束，接受两个字符串类型的参数，如果不传参数或者传了空字符串就不显示标签, 第一个参数是起始时间，第二个是结束时间
 */

// 拖拽按钮起点X
const DragItemSartX =  -279.6;

cc.Class({
    extends: cc.Component,

    start () {
        this.init();
        this.initVideoBtn();
        this.addListener();
        this.initdDrag();
    },

    barBaseW: 0, // 进度条宽度
    bgProgress: null, // 进度条背景
    bar: null, // 进度条填充
    dragBtn: null, // 进度条拖拽按钮
    controlBtn: null, // 按钮点击事件挂在这个上面
    playBtn: null, // 播放按钮
    pauseBtn: null, // 暂停按钮
    replayBtn: null, // 重播按钮

    posYShow: 0,
    posYHide: 0,
    
    properties: {
        setTimeoutIDs: [],
        setIntervalIDs: [],
        videoDuration: 0, // 视频时长
    },

    init() {
        // console.log("Init video control component.")
        const canvas = cc.find("Canvas");
        this.bgProgress = cc.find('progress', this.node);
        this.bar = cc.find('progress/bar', this.node);
        this.dragBtn = cc.find('dragButton', this.node);
        this.controlBtn = cc.find('controlButton', this.node);
        this.playBtn = cc.find('controlButton/play', this.node);
        this.pauseBtn = cc.find('controlButton/pause', this.node);
        this.replayBtn = cc.find('controlButton/replay', this.node);

        this.playBtn.active = true;
        this.pauseBtn.active = false;
        this.replayBtn.active = false;
        this.videoStatus = 0; // 0:暂停 1:播放中 2:重播

        this.barBaseW = this.bgProgress.width;;

        const deviceSize = cc.view.getVisibleSize()
        this.posYShow = -deviceSize.height / 2 + this.node.height / 2 + 50;
        this.posYHide = -deviceSize.height / 2 - this.node.height / 2 - 50;

        this.node.x = 0
        this.node.y = this.posYHide;
    
        this.setProgress(0);
    },

    initVideoBtn() {
        this.controlBtn.addComponent(cc.Button);
        this.controlBtn.on('click', () => {
            if (this.videoStatus==null || this.videoStatus ==0) {
                this.refreshVideoBtnState(1);
                this.node.emit('video_btn_click', true)
            } else if (this.videoStatus ==1) {
                this.refreshVideoBtnState(0);
                this.node.emit('video_btn_click', false)
            }
        });
    },

    userDragStart: null,
    initdDrag() {
        const dragStartX = DragItemSartX;
		const maxX = this.bgProgress.width + dragStartX ;
		const minX = dragStartX;

		this.dragBtn.off(cc.Node.EventType.TOUCH_START);
		this.dragBtn.on(cc.Node.EventType.TOUCH_START, (e) => {
			this.userDragStart = true;
            this.node.emit('on_drag_button', true);
		});

		this.dragBtn.off(cc.Node.EventType.TOUCH_MOVE);
		this.dragBtn.on(cc.Node.EventType.TOUCH_MOVE, (e) => {
			const worldPos = e.getLocation();
			const localPos = this.dragBtn.parent.convertToNodeSpaceAR(worldPos);

			let newX = localPos.x;
			newX = Math.min(maxX, Math.max(newX, minX));
			this.dragBtn.x = newX;
			const percent =  Math.abs(newX-dragStartX) / Math.abs(this.bgProgress.width);
            this.setProgress(percent * this.videoDuration);
			this.node.emit('on_drag_percent', percent)
		});

		this.dragBtn.off(cc.Node.EventType.TOUCH_END);
		this.dragBtn.on(cc.Node.EventType.TOUCH_END, (e) => {
            if(this.userDragStart) {
                this.userDragStart = false;
                this.node.emit('on_drag_button', false);
            }
		});

        this.dragBtn.off(cc.Node.EventType.MOUSE_UP);
		this.dragBtn.on(cc.Node.EventType.MOUSE_UP, (e) => {
			if(this.userDragStart) {
                this.userDragStart = false;
                this.node.emit('on_drag_button', false);
            }
		});

        this.dragBtn.off(cc.Node.EventType.TOUCH_CANCEL);
		this.dragBtn.on(cc.Node.EventType.TOUCH_CANCEL, (e) => {
            if(this.userDragStart) {
                this.userDragStart = false;
                this.node.emit('on_drag_button', false);
            }
		});
	},

    // 0:暂停 1:播放中 2:重播
    videoStatus: null,
    refreshVideoBtnState(status) {
        this.videoStatus = status;
        switch(status) {
            case 0: 
                this.playBtn.active = true;
                this.pauseBtn.active = false;
                this.replayBtn.active = false;
            break;
            case 1: 
                this.playBtn.active = false;
                this.pauseBtn.active = true;
                this.replayBtn.active = false;
            break;
            case 2: 
                this.playBtn.active = false;
                this.pauseBtn.active = false;
                this.replayBtn.active = true;
            break;
            default: 
                this.playBtn.active = true;
                this.pauseBtn.active = false;
                this.replayBtn.active = false;
            break;
        };
    },

    addListener() {
        this.node.on('video_play_end', () => {
            // console.log("video_play_end");
            this.refreshVideoBtnState();
        })

        this.node.on('update_video_progress', (value)=>{
            // console.log("update_video_progress");
            if(!this.userDragStart) {
                this.setProgress(value);
            } else {
                // console.log("进度条拖动中")
            }
        })

        this.node.on('update_video_status', (status)=>{
            // console.log("update_video_status", status);
            this.refreshVideoBtnState(status);
        })

        this.node.on('hide_bar', (withAnimation)=>{
            this.hideBar(withAnimation);
        })

        this.node.on('show_bar', (withAnimation)=>{
            this.showBar(withAnimation);
        })

        this.node.on("set_mark_points", (data)=>{
            this.setMarkPoints(data);
        })

        this.node.on("set_start_end_label", (start, end)=>{
            this.setStartEndTimeLabel(start, end);
        })

        this.node.on("set_duration", (duration)=>{
            this.setDuration(duration);
        })

        this.node.off(cc.Node.EventType.TOUCH_START);
        this.node.on(cc.Node.EventType.TOUCH_START, ()=>{
            this.node.emit("on_touch_progressbar")
        })

        this.node.off(cc.Node.EventType.MOUSE_DOWN);
        this.node.on(cc.Node.EventType.MOUSE_DOWN, ()=>{
            this.node.emit("on_touch_progressbar")
        })
    },

    tweening: null,
    // 显示进度条
    showBar(withAnimation) {
        const widget = this.node.getComponent(cc.Widget);
        if(withAnimation) {
            // widget.bottom = -100;
            // let count = 10;
            // let step = 200 / count;
            // const _intervalId = setInterval(()=>{
            //     widget.bottom+=step;
            //     count--;
            //     if(count <=0) {
            //         widget.bottom = 100;
            //         clearInterval(_intervalId)
            //     }
            // },30)
            // this.setIntervalIDs.push(_intervalId);
            this.tweening = cc.tween(this.node)
                .to(0.1, { y: this.posYShow})
                .call(() => {
                    this.tweening = null;
                })
                .start();
        } else {
            this.node.y = this.posYShow;
        }
    },

    // 隐藏进度条
    hideBar(withAnimation) {
        const widget = this.node.getComponent(cc.Widget);
        // console.log(widget)
        if(withAnimation) {
            // widget.bottom = 100;
            // let count = 10;
            // let step = 300 / count;
            // const _intervalId = setInterval(()=>{
            //     widget.bottom-=step;
            //     count--;
            //     if(count <=0) {
            //         widget.bottom = -100;
            //         clearInterval(_intervalId)
            //     }
            // },30)
            // this.setIntervalIDs.push(_intervalId);
            this.tweening = cc.tween(this.node)
            .to(0.1, { y: this.posYHide})
            .call(() => {
                this.tweening = null;
            })
            .start();
        } else {
            widget.bottom = -100;
        }
        
    },

    setTimeoutID: null,
    setProgress(currentDuration) {
        const progress = currentDuration / this.videoDuration
        const dragStartX = DragItemSartX;
        this.setTimeoutID = setTimeout(() => {
            const w = this.barBaseW * progress;
            this.bar.width = w;
            if(!this.userDragStart) {
                this.dragBtn.x = dragStartX + w;
            }
        }, 1);
        this.setStartEndTimeLabel(this.getEndTimeLabel(currentDuration), this.getEndTimeLabel(this.videoDuration - currentDuration))
    },

    // 设置标记点
    setMarkPoints(pArr) {
        // console.log("set_mark_points")
        const markPoint = cc.find("markPoint", this.node);
        const markPointsContainer = cc.find("markNode", this.node);
        for(let i=0; i<pArr.length; i++) {
            const newPoint = cc.instantiate(markPoint);
            newPoint.x = DragItemSartX + this.bgProgress.width * pArr[i];
            newPoint.active = true;
            markPointsContainer.addChild(newPoint);
        }
    },

    // 设置开始和结束标签
    setStartEndTimeLabel(start, end) {
        const startLabel = cc.find("time_label/start", this.node).getComponent(cc.Label);
        const endLabel = cc.find("time_label/end", this.node).getComponent(cc.Label);
        if(start != null && start != undefined && startLabel !=  "") {
            startLabel.active = true;
            startLabel.string = start;
        } else {
            startLabel.active = false;
        }

        if(end != null && end != undefined && endLabel !=  "") {
            endLabel.active = true;
            endLabel.string = end;
        } else {
            endLabel.active = false;
        }
    },

    // 设置音频时长
    setDuration(duration) {
        this.videoDuration = duration;
        this.setStartEndTimeLabel("00:00", this.getEndTimeLabel(duration))
    },

    //秒数转化为时分秒
    getEndTimeLabel(value) {
        const numberFixed2 = (num) => {
            return num<10?"0"+num:num;
        }

        var secondTime = parseInt(value);// 秒
        var minuteTime = 0;// 分
        var hourTime = 0;// 小时
        if(secondTime > 60) {//如果秒数大于60，将秒数转换成整数
            //获取分钟，除以60取整数，得到整数分钟
            minuteTime = parseInt(secondTime / 60);
            //获取秒数，秒数取余，得到整数秒数
            secondTime = parseInt(secondTime % 60);
            //如果分钟大于60，将分钟转换成小时
            if(minuteTime > 60) {
                //获取小时，获取分钟除以60，得到整数小时
                hourTime = parseInt(minuteTime / 60);
                //获取小时后取余的分，获取分钟除以60取余的分
                minuteTime = parseInt(minuteTime % 60);
            }
        }
        var result = "" + numberFixed2(parseInt(secondTime));

        if(minuteTime > 0) {
            result = "" + numberFixed2(parseInt(minuteTime)) + ":" + result;
        } else {
            result = "00:" + result;
        }
        
        if(hourTime > 0) {
            result = "" + numberFixed2(parseInt(hourTime)) + ":" + result;
        }
        
        return result;
    },

    onDestroy() {
        for(let i=0; i<this.setIntervalIDs.length; i++) {
            clearInterval(this.setIntervalIDs[i]);
        }
        clearTimeout(this.setTimeoutID);
    }
});
