import { asyncDelay, asyncGetSpriteFrimeByUrl, onHomeworkFinish} from "../Script/dg_video_util";
import { defaultData } from "../Script/dg_video_defaultData";

cc.Class({
    extends: cc.Component,

    properties: {
        videoPlayer: {
            default: null,
            type: cc.VideoPlayer
        },
        ProgressBar: {
            default: null,
            type: cc.Node
        },
        playButton: {
            default: null,
            type: cc.Button
        },
        pauseButton: {
            default: null,
            type: cc.Button
        },
        restartButton: {
            default: null,
            type: cc.Button
        },
        backButton: {
            default: null,
            type: cc.Button
        },
        forwardButton: {
            default: null,
            type: cc.Button
        },
        durationLabel: {
            default: null,
            type: cc.Label
        },
        currentTimeLabel: {
            default: null,
            type: cc.Label
        },
        barTag: {
            default: null,
            type: cc.Node
        },
        bar: {
            default: null,
            type: cc.Node
        }
        // defaults, set visually when attaching this script to the Canvas
        // text: 'Hello, World!'
    },

    _designSize: null,  // 设计分辨率
    _frameSize: null,  // 屏幕分辨率
    _mapScaleMin: null,  // 场景中常用缩放（取大值）
    _mapScaleMax: null,  // 场景中常用缩放（取小值）
    _cocosScale: null,  // cocos 自缩放 （较少用到）
    initSize() {
        // 注意cc.winSize只有在适配后(修改fitHeight/fitWidth后)才能获取到正确的值,因此使用cc.getFrameSize()来获取初始的屏幕大小
        let screen_size = cc.view.getFrameSize().width / cc.view.getFrameSize().height
        let design_size = cc.Canvas.instance.designResolution.width / cc.Canvas.instance.designResolution.height
        let f = screen_size >= design_size
        cc.Canvas.instance.fitHeight = f
        cc.Canvas.instance.fitWidth = !f

        const frameSize = cc.view.getFrameSize();
        this._frameSize = frameSize;

        this._designSize = cc.view.getDesignResolutionSize();

        let sx = cc.winSize.width / frameSize.width;
        let sy = cc.winSize.height / frameSize.height;
        this._cocosScale = Math.min(sx, sy);

        sx = frameSize.width / this._designSize.width;
        sy = frameSize.height / this._designSize.height;
        this._mapScaleMin = Math.min(sx, sy) * this._cocosScale;
        this._mapScaleMax = Math.max(sx, sy) * this._cocosScale;

        cc.director['_scene'].width = frameSize.width;
        cc.director['_scene'].height = frameSize.height;
    },

    getVideoUrl(callback) {
		const url1 = this.data.video_url;

		const url2 = url1.replace(/.mp4$/g, "_h.mp4");
		this.httpHeadCall(url2, (success) => {
			if (success) {
				console.log('return url2: ', url2);
				callback(url2);
			} else {
				console.log('return url1: ', url1);
				callback(url1);
			}
		})
	},

	httpHeadCall(requsetUrl, callback) {

		let xhr = new XMLHttpRequest();
		console.log("Status: Send Post Request to " + requsetUrl);
		try {
			xhr.onreadystatechange = () => {
				try {

					console.log('xhr.readyState: ', xhr.readyState);

					if (xhr.readyState == 4) {
						if ((xhr.status >= 200 && xhr.status < 400)) {
							callback(true);
						} else {
							callback(false);
						}
					}

				} catch (e) {
					console.log(e)
				}
			};

			xhr.open("HEAD", requsetUrl, true);
			xhr.send();

			xhr.timeout = 15000;
			xhr.onerror = (e) => {
				console.log("汪汪汪 posterror", e);
				callback(false);
			};

			xhr.ontimeout = (e) => {
				console.log("汪汪汪 ontimeout", e);
				callback(false);
			};

		} catch (e) {
			console.log("Send Get Request error: ", e)
		}
	},

    // use this for initialization
    _isPlayComplated: null,
    _isReadyToPlay: null,
    onLoad () {
        cc.debug.setDisplayStats(false);

        this.initSize();
        cc.find('Canvas/bg').scale = this._mapScaleMax;
        cc.find('Canvas/video_node/bg').scale = this._mapScaleMax;

        this._isReadyToPlay = false;
        cc.macro.ENABLE_TRANSPARENT_CANVAS = true; 
        
        this.videoPlayer.node.on('ready-to-play', () => {
            console.log('ready-to-play');
            this.playButton.active = true;
            cc.find(`Canvas/bg_video_shadow`).active = false;
            cc.find(`Canvas/loading`).active = false;
            this.durationLabel.string = this.formatTime(this.videoPlayer.getDuration());
            this._isReadyToPlay = true;
            this._isPlayComplated = false;
            this.videoPlayer.currentTime = 0;
            // this.videoPlayer.resume();
            this.play();
        });
        this.videoPlayer.node.on('meta-loaded', () => {
            console.log('meta-loaded');
        });
        this.videoPlayer.node.on('clicked', () => {
            console.log('clicked');
            if (this.isVideoFull) {
                this.videoPlayer.stayOnBottom = true;
                cc.find(`Canvas/Controls`).active = true;
                if (this.time1) {
                    clearTimeout(this.time1);
                }
                this.time1 = setTimeout(() => {
                    this.videoPlayer.stayOnBottom = false;
                    cc.find(`Canvas/Controls`).active = false;
                }, 6000);
            }
        });
        this.videoPlayer.node.on('touchstart', () => {
            console.log('touchstarted');
            if (this.isVideoFull) {
                this.videoPlayer.stayOnBottom = true;
                cc.find(`Canvas/Controls`).active = true;
                if (this.time1) {
                    clearTimeout(this.time1);
                }
                this.time1 = setTimeout(() => {
                    this.videoPlayer.stayOnBottom = false;
                    cc.find(`Canvas/Controls`).active = false;
                }, 6000);
            }
        });
        this.videoPlayer.node.on('playing', () => {
            console.log('playing');
            this.durationLabel.string = this.formatTime(this.videoPlayer.getDuration());
            this.playButton.node.active = false;
            this.restartButton.node.active = false;
            this.pauseButton.node.active = true;
        });
        this.videoPlayer.node.on('paused', () => {
            console.log('paused');
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;
        });
        this.videoPlayer.node.on('stopped', () => {
            console.log('stopped');
            // this.playButton.node.active = true;
            // this.pauseButton.node.active = false;
        });
        this.videoPlayer.node.on('completed', async () => {
            console.log('completed');
            // this.videoPlayer.currentTime = 0;
            this._isPlayComplated = true;
            this.playButton.node.active = false;
            this.pauseButton.node.active = false;
            this.restartButton.node.active = false;

            // this.videoPlayer.stop();
            // this.videoPlayer.remoteURL = '';


            if (this.videoItemList.length == 1) {
                this.replay();
                return;
            }

            // 循环播放下一个
            const nextItem = this.videoItemList[this.videoPlayIndex + 1];

            if(nextItem) {
                // nextItem.emit('my_item_click');
                this.clickVideoItem(null, nextItem);

            } else {
                // this.videoItemList[0].emit('my_item_click');
                this.clickVideoItem(null, this.videoItemList[0]);
            }
        });
        cc.view.setResizeCallback((params) => {
            console.log('Resize', params);
            this.initdDrag()
        });
        
        this.initdDrag();
    },


    initListener() {
    },
    initdDrag() {
        const maxX = this.ProgressBar.width;
        const minX = 0;
        
        this.barTag.off(cc.Node.EventType.TOUCH_START);
        this.barTag.on(cc.Node.EventType.TOUCH_START, (e) => {
			if (!this._isReadyToPlay) {
                return;
			}
            console.log("TOUCH_START");
        });
        this.barTag.off(cc.Node.EventType.TOUCH_MOVE);
        this.barTag.on(cc.Node.EventType.TOUCH_MOVE,(e) => {
			if (!this._isReadyToPlay) {
                return;
			}
            const worldPos = e.getLocation();
			const localPos = this.barTag.parent.convertToNodeSpaceAR(worldPos);
            let newX = localPos.x;
            newX = Math.min(maxX, Math.max(newX, minX));
            this.barTag.x = newX;
            const percent = newX / maxX;
            const dur = this.videoPlayer.getDuration();
            this.currentTimeLabel.string = this.formatTime(percent * dur );
            this.videoPlayer.currentTime = percent * dur;
        });
        this.barTag.off(cc.Node.EventType.TOUCH_ENDED);
        this.barTag.on(cc.Node.EventType.TOUCH_ENDED, (e) => {
            if (!this._isReadyToPlay) {
                return;
            }
            console.log("TOUCH_ENDED");
            this.updateBarByPos(this.barTag.x);
        });
        this.barTag.off(cc.Node.EventType.MOUSE_UP);
        this.barTag.on(cc.Node.EventType.MOUSE_UP, (e) => {
            if (!this._isReadyToPlay) {
                return;
            }
            console.log("MOUSE_UP");
            this.updateBarByPos(this.barTag.x);
        });
    },

    videoItemList: null,
    videoPlayIndex: null,
    async initView() {
        this.videoItemList = [];
        const videoListContent = cc.find(`Canvas/videolist/view/content`);
        const templateItem = cc.find(`item`, videoListContent);
        for (let i = 0; i < this.data.dataArr.length; i++) {
            const row = this.data.dataArr[i];
            const itemClone = cc.instantiate(templateItem);
            itemClone.parent = videoListContent;
            itemClone.active = true;
            const spriteFrame = await asyncGetSpriteFrimeByUrl(row.cover);
            const picNode = cc.find(`cover`, itemClone);
            picNode.getComponent(cc.Sprite).spriteFrame = spriteFrame;
            const sx = 226 / picNode.width;
            const sy = 126 / picNode.height;
            picNode.scale = Math.min(sx, sy);

            cc.find(`item_active/title`, itemClone).getComponent(cc.Label).string = row.title;
            cc.find(`item/title`, itemClone).getComponent(cc.Label).string = row.title;

            cc.find(`item_active/num`, itemClone).getComponent(cc.Label).string = (i+1>9?(i+1):`0${i+1}`);
            cc.find(`item/num`, itemClone).getComponent(cc.Label).string = (i+1>9?(i+1):`0${i+1}`);

            itemClone.attr({video_url: row.video_url, playIndex: i});
            itemClone.on('my_item_click', () => {
                // 无法用代码触发click事件，所以只能写一个自定义事件了
                this.clickVideoItem(null, itemClone);
            });
            this.videoItemList.push(itemClone);
        }
    },

    showTips(tips) {
		const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
		if (middleLayer) {
			middleLayer.showTips(tips);
		} else {
			console.log(tips);
		}
	},
    // 选择视频播放
	async clickVideoItem(evt, _node) {
        const item = evt?evt.currentTarget:_node;
		if (!item.video_url) {
            this.showTips("视频不存在");
			return;
        }
        if (item.video_url == this.videoPlayer.remoteURL) {
            this.showTips("该视频正在播放");
			return;
        }
        this.videoPlayIndex = item.playIndex;
        this._isReadyToPlay = false;
        cc.find(`Canvas/loading`).active = true;
        cc.find(`Canvas/bg`).active = true;
        cc.find(`Canvas/bgwhite`).active = true;
        cc.find(`Canvas/bg_video_shadow`).active = true;
        this.videoPlayer.node.x = -5000;
        this.videoPlayer.node.y = -5000;

        cc.find(`Canvas/videolist/view/content`).children.forEach(row => {
            cc.find(`item_active`, row).active = false;
        });

        cc.find(`item_active`, item).active = true;
        this.videoPlayer.remoteURL = item.video_url;

        // 数据采集
        for (let i = 0; i < this.data.dataArr.length; i++) {
            const element = this.data.dataArr[i];
            if (element.video_url == item.video_url) {
                const count = this.data.dataArr[i].count;
                if (count) {
                    this.data.dataArr[i].count ++;
                } else {
                    this.data.dataArr[i].count = 1;
                }
            }
        }
        const totalCount = this.data.totalCount;
        if (totalCount) {
            this.data.totalCount ++;
        } else {
            this.data.totalCount = 1;
        }

	},

    start() {
        let getData = this.getData.bind(this);
		if (window && window.courseware) {
			// console.log('has window');
            getData = window.courseware.getData;
        }
		getData(async (data) => {
			console.log('data:', JSON.stringify(data));
            this.data = data || this.getDefaultData();
            await this.initView();

            if (window && window["air"]) {
                window["air"].hideAirClassLoading();
            }
        });

        if(window.CustomEvent){
            window.dispatchEvent(new CustomEvent('resize'), true)
        }
        this.initListener();
    },
    updateBarByPos(newX) {
        const maxX = this.ProgressBar.width;
        const minX = 0;
        
        let percent = newX / maxX;
        if (percent > 1) {
			percent = 1
        }
        const dur = this.videoPlayer.getDuration();
        this.videoPlayer.currentTime = percent * dur 
    },
    updateBarByTime(ct){
        if (this._isPlayComplated) {
            return;
        }
        this.currentTimeLabel.string = this.formatTime(ct);
        const dur = this.videoPlayer.getDuration();
        let percent = ct / dur;
        if (percent > 1) {
			percent = 1
        }
        this.ProgressBar.getComponent(cc.ProgressBar).progress = percent;
        const maxX = this.ProgressBar.width;
        const minX = 0;
        let newX = percent * maxX;
        newX = Math.min(maxX, Math.max(newX, minX));
        this.barTag.x = newX;
    },
    formatTime(time) {
        if (time === undefined) {
            return '';
          }
          let hh = Math.floor(time / 60 / 60);
          if (hh > 0) {
            hh = `${hh.toString().padStart(2, '0')}:`;
          } else {
              hh = '';
          }
            
          const mm = Math.floor(time / 60).toString().padStart(2, '0');
          const ss = Math.round(time % 60).toString().padStart(2, '0');
      
          return `${hh}${mm}:${ss}`;
    },
    
    getData(func) {
        const middleLayer = cc.find('middleLayer');
        if (middleLayer) {
            const middleLayerComponent = middleLayer.getComponent('middleLayer');
            middleLayerComponent.getData(func);
            return;
        }

		func(this.getDefaultData());
	},
    getDefaultData() {
        return defaultData;
    },
    
    play(){
        if (!this._isReadyToPlay) {
            return;
        }
        const {width, height} = cc.find(`Canvas/bg`);
        cc.find(`Canvas/text_tips`).active = false;
        cc.find(`Canvas/bg`).active = false;
        cc.find(`Canvas/bgwhite`).active = false;
        cc.find(`Canvas/bg_video_shadow`).active = false;

        const videoContainer = cc.find('Canvas/video_node');
        cc.find('bg', videoContainer).width = width;
        cc.find('bg', videoContainer).height = height;
        this.videoPlayer.node.x = videoContainer.x;
        this.videoPlayer.node.y = videoContainer.y;
        this.videoPlayer.play();
    },
    pause(){
        this.videoPlayer.pause();
    },
    forward(){
    },
    backward(){
    },
    replay(){
        this._isPlayComplated = false;
        this.videoPlayer.currentTime = 0;
        this.videoPlayer.play();
    },

    playLocalAudio(audioName) {
        cc.audioEngine.stopAll();
        const audio = cc.find(`Canvas/res/audio/${audioName}`).getComponent(cc.AudioSource);
        cc.audioEngine.playEffect(audio.clip, false);
    },

    time1: null,
    isVideoFull: false,
    tempPos: null,
    fullScreen() {
        if (this.isVideoFull) {
            return;
        }
        if (!this._isReadyToPlay) {
            return;
        }
        this.tempPos = {};
        console.log("====进入全屏===");
        this.isVideoFull = true;
        this.videoPlayer.stayOnBottom = true;
        cc.find(`Canvas/Controls/fullscreen`).active = !this.isVideoFull;
        cc.find(`Canvas/Controls/exitfull`).active = this.isVideoFull;

        const videoContainer = cc.find('Canvas/video_node');
        this.tempPos.videoPos = {x: videoContainer.x, y: videoContainer.y, width: videoContainer.width, height: videoContainer.height};
        videoContainer.width = this.node.width;
        videoContainer.height = this.node.height;
        videoContainer.x = 0;
        videoContainer.y = 0;

        cc.find(`Canvas/videolist`).active = false;

        const controls = cc.find(`Canvas/Controls`);
        this.tempPos.controlPos = {x: controls.x, y: controls.y};
        cc.find(`bg_video_bottom`, controls).active = false;
        controls.x = 0;
        controls.y = 0 - this.node.height / 2 + 130;

        this.videoPlayer.node.height = this.node.height;
        this.videoPlayer.node.width = this.node.width;
        this.videoPlayer.node.x = 0;
        this.videoPlayer.node.y = 0;

        setTimeout(() => {
            // IOS下视频的全屏适配比例有问题，所以做一个计算
            this.videoPlayer.node.width = Math.min(this.node.width, this.node.height*16/9);
        }, 100);

        this.time1 = setTimeout(() => {
            this.videoPlayer.stayOnBottom = false;
            cc.find(`Canvas/Controls`).active = false;
        }, 3000);
    },

    exitFullScreen() {
        if (!this.isVideoFull) {
            return;
        }
        console.log("====退出全屏===", this.tempPos);
        this.isVideoFull = false;
        cc.find(`Canvas/Controls/fullscreen`).active = !this.isVideoFull;
        cc.find(`Canvas/Controls/exitfull`).active = this.isVideoFull;

        const videoContainer = cc.find('Canvas/video_node');
        videoContainer.width = this.tempPos.videoPos.width;
        videoContainer.height = this.tempPos.videoPos.height;
        videoContainer.x = this.tempPos.videoPos.x;
        videoContainer.y = this.tempPos.videoPos.y;

        this.videoPlayer.node.width = this.tempPos.videoPos.width;
        this.videoPlayer.node.height = this.tempPos.videoPos.height;
        this.videoPlayer.node.x = videoContainer.x;
        this.videoPlayer.node.y = videoContainer.y;

        cc.find(`Canvas/videolist`).active = true;

        const controls = cc.find(`Canvas/Controls`);
        cc.find(`bg_video_bottom`, controls).active = true;
        controls.x = this.tempPos.controlPos.x;
        controls.y = this.tempPos.controlPos.y;
    
        if(this.time1) { 
            clearTimeout(this.time1); 
        }
    },

    onDestroy() {
        if(this.time1) { clearTimeout(this.time1); }
    },
    
    exitGame () {
        const middleLayer = cc.find('middleLayer')?.getComponent('middleLayer');
		if (middleLayer) {
            // 有些模板需要在返回时上报数据，直接把数据作为参数传入就可以了
			middleLayer.exitGame(this.data);
		} else {
			console.log("==触发返回事件==");
		}
    },


    // called every frame
    update: function (dt) {
        if (!this._isReadyToPlay) {
            return;
        }
        // if (this.wardState && this.videoPlayer.isPlaying()) {
        //     this.wardState = false;
        //     this.pause();
        // }
        if (this.videoPlayer) {
            const ct = this.videoPlayer.currentTime;
			if (ct) {
				this.updateBarByTime(ct);
			}
            if (this.videoPlayer.isPlaying()) {
                if (this.playButton.node.active) {
                    this.playButton.node.active = false;
                    this.restartButton.node.active = false;
                }
                if (!this.pauseButton.node.active) {
                    this.pauseButton.node.active = true;
                } 
                
            } else {
                if (!this.playButton.node.active) {
                    this.playButton.node.active = true;
                }
                if (this.pauseButton.node.active) {
                    this.pauseButton.node.active = false;
                } 
                if (this.restartButton.node.active) {
                    this.playButton.node.active = false;
                }
            }
        }
        
    },
});
