// __SmallApp_env_run_type 判断是否在Service层里，然后是否是安卓降级方案。
export default {};

export function judgeEnv() {
    let output = {
        env: '',
        isDowngrade: false
    };
    if (global.document) {
        if (global.__SmallApp_env_run_type) {
            if (global.__SmallApp_env_run_type === 2) {
                output.env = 'Service';
                output.isDowngrade = true;
            } else if (global.__SmallApp_env_run_type === 5){
                output.env = 'Render';
            } else if (global.__SmallApp_env_run_type === 6) {
                output.env = 'Render';
                output.isDowngrade = true;
            }
        } else {
            output.env = 'Render';
        }
    } else {
        output.env = 'Service';
    }
    return output;
}

export function compareVersion(v1, v2) {
    v1 = v1.split('.');
    v2 = v2.split('.');
    const len = Math.max(v1.length, v2.length);

    while (v1.length < len) {
        v1.push('0');
    }
    while (v2.length < len) {
        v2.push('0');
    }

    for (let i = 0; i < len; i++) {
        const num1 = parseInt(v1[i]);
        const num2 = parseInt(v2[i]);

        if (num1 > num2) {
            return 1;
        } else if (num1 < num2) {
            return -1;
        }
    }

    return 0;
}

// 是否支持canvas 2期方案
export function judgeCanvasSync(type, _sysInfo, output) {
    // 用户写法支持
    let isOKByCanvas = type.toLowerCase() === '2d' || type.toLowerCase() === 'webgl';
    const _sys = _sysInfo || bl.getSystemInfoSync();

    // 客户端版本支持
    let _isSupport = false;
    // 大于SDKVersion = 3.58.0
    if (compareVersion(_sys.SDKVersion, '3.58.0') >= 0) {
        if (_sys.platform.toLowerCase() === 'android') {
            if (_sys.innerSDKVersion && _sys.innerSDKVersion.length > 2 && compareVersion(_sys.innerSDKVersion, '3.58.0')>= 0) {
                if (!judgeEnv().isDowngrade) _isSupport = true;
            }
        } else {
            _isSupport = true
        }
    }

    if (output === 'all') {
        return {
            canvas_type: isOKByCanvas,
            canvas_version: _isSupport
        }
    } else {
        return _isSupport && isOKByCanvas;
    }
}

export class CanvasOnRender {
    constructor(that) {
        if (judgeEnv().env === 'Render') {
            this.that = that;
            this.styleCache = {};
            this.el = that.$el;
            this.systemInfo = global.bl.getSystemInfoSync();
            this.id = that.id || that.canvasId;
            this.observer = null;
            this.disableScroll = that.disableScroll;
            this.uid = that._uid;
            this.type = that.type;
            // console.log('-- canvas message[Render]：CanvasOnRender属性初始化完毕 ok');
        }
    }

    monitorDom() {
        if (judgeEnv().env === 'Render') {
            // console.log('-- canvas message[Render]：全局body开启监控 ok');
            let timer = null;
            // 监控整个body变化，如有变化则重新计算样式是否有变动。做节流优化。
            const observer = new MutationObserver(() => {
                if (timer) {
                    clearTimeout(timer);
                    timer = null;
                }
                timer = setTimeout(() => {
                    this.isSame('update');
                }, 200);
            });
            observer.observe(document.body, {
                attributes: true,
                childList: true,
                characterData: true,
                subtree: true
            });
            this.observer = observer;
            // console.log('-- canvas message[Render]：全局body开启监控 ok');
        }
    }
    isSame(type) {
        if (judgeEnv().env === 'Render') {
            SmallApp.waitStyleOver().then(() => {
                let positionInfo = this.el.getBoundingClientRect();
                let styleInfo = global.getComputedStyle(this.el);
                let isFixed = styleInfo.getPropertyValue('position') === 'fixed';
                const newStyle = {
                    "x": isFixed ? positionInfo.left : positionInfo.left + SmallApp.getScrollData('left'),
                    "y": isFixed ? positionInfo.top : positionInfo.top + SmallApp.getScrollData('top'),
                    "width": positionInfo.width,
                    "height": positionInfo.height,
                    "disableScroll": this.disableScroll,
                    "fixed": isFixed,
                    "hidden": styleInfo.getPropertyValue('display') === 'none'
                };

                // 降级模拟 resize
                if (!judgeCanvasSync(this.type, this.systemInfo)) {
                    if (judgeEnv().isDowngrade) {
                        if (!(this.styleCache.width === newStyle.width &&
                            this.styleCache.height === newStyle.height)) {
                            if (global.canvas && global.canvas[this.id]) {
                                global.canvas[this.id].style.width = newStyle.width;
                                global.canvas[this.id].style.height = newStyle.height;
                            }
                            this.el.setAttribute('width', newStyle.width);
                            this.el.setAttribute('height', newStyle.height);
                            // console.log('canvas resize....', newStyle.width, newStyle.height)
                            if (JSON.stringify(this.styleCache) !== "{}") {
                                this.that.$emit('resize', {
                                    width: newStyle.width,
                                    height: newStyle.height,
                                })
                            }
                        }
                    }
                }

                // console.log('-- canvas message[Render]：计算当前变化的样式 ok', newStyle);
                // console.log('-- canvas message[Render]：与缓存样式进行对比，是否需要通知Service ok', JSON.stringify(this.styleCache) !== JSON.stringify(newStyle));
                // 判断样式是否一样
                if (JSON.stringify(this.styleCache) !== JSON.stringify(newStyle)) {
                    this.styleCache = newStyle;
                    SmallApp.postMessage({
                        type: 'canvas',
                        style: newStyle,
                        messageType: type,
                        isDowngrade: judgeEnv().isDowngrade,
                        canvasId: this.id,
                        componentId: this.uid,
                        canvasSyncType: this.type,
                        zIndex: Number(this.el.getAttribute('B-zIndex'))
                    });
                    // console.log('-- canvas message[Render]：样式不一致，发送到Service ok', {
                    //     type: 'canvas',
                    //     style: newStyle,
                    //     messageType: type,
                    //     isDowngrade: judgeEnv().isDowngrade,
                    //     canvasId: this.id,
                    //     componentId: this.uid
                    // });
                }
            });
        }
    }

    disconnect(){
        if (judgeEnv().env === 'Render') {
            // console.log('-- canvas message[Render]：停止监控body ok')
            // 停止监控
            this.observer.disconnect();
        }
    }
}
