// Learn cc.Class:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/class/index.html
// Learn Attribute:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/reference/attributes/index.html
// Learn life-cycle callbacks:
//  - [Chinese] http://www.cocos.com/docs/creator/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/editors_and_tools/creator-chapters/scripting/life-cycle-callbacks/index.html

const OFFLINE_TIPS = 'data:image/png;base64, ';
const RECONNECT_BTN = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAJYAAAAzCAMAAABCDgGNAAAAZlBMVEUAAAAAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOUAiOXHNmdXAAAAIXRSTlMACH8P7PjcBPG0YFYl4NXQyr6rd2lbQjkzGpTlIHr5jJUXB7SdAAABgUlEQVRYw8zVx27CUBCF4XOLKwaXuAKG/O//kpGFnEhAkp19v9XsRjqaolemt015SdlAeikb2xv9y3RZxMairDP6i7OeXXjr9KvWszh95sPktAE3Dfn5xMK3eq+oAI620MYKewSo3jY+pECcJ9pBksdAetCLDyCyRjsxNgI+9OQOxKN2NMbA/TWr2mlXrn7O6wBkRjszGXDQtyKCOtHukhrSQqsKYqcAuBiqNZ8WbqOCMN6glRbOg1UgLHinxQzx7uO+MjHMWgoPnYLRgTeP43AMYAtXyfFxJDKYFZAZMslEcFVArhAZ9XBSUE7Qy8JZQTmDVQO5gpJDoxIGBWWAUh4mBWWCi24QxJf+4SAVoMB8VWfHKAACMRBFw8KC1qYSm7n/Ja3E0k6fV1g2ycz/SdTXQv8WOono3kK3PHoT0QTB5a0tWd10im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5R+bq1Qwghb0yt5zEJgoEKITDJxNH7pWZTqcxAVTTM6y0WtA2BMdTNqq8sBMrd2AFRJwHkLxvUOQm+rlloQDEC4Op6OrFDY4AVs+pNQKtqrZG4NZ8V0t5q5UGVrarVy847jYr2yh9bm0LWPiOW9vicwOlrYG2Ebi68PAFT10OkDeQg9wyuWxxQQDFi8SsGQa22q+osfI6aM2AqwmPpy4HyBuCJ40t7ue2FLf6E1FQdtSJulF6hhvTbEfXnMdTNwwwXOhute/mkCJtrSow5D7NT4llZ1vrateyTasLn/ugb4tsWiiU+5rXCqkBq2ZqRmObVVxTEKMnhZXZQj+3/NQ6cKL1bGjTHSdVm+nMZi5CM+Vv9TktgYpW/j9/8SATU4JrTAAAAABJRU5ErkJggg==';
const BAR = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAcAAAAHCAYAAADEUlfTAAAAFklEQVQImWOcPHnyfwYcgAmXxKCUBAAm8ALGxCtPnQAAAABJRU5ErkJggg==';
const CIRCLE = 'data:image/png;base64, ';
const LINE = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAABAQMAAABQVuppAAAAA1BMVEXZ2dmK1ydDAAAACklEQVQI12OAAwAACgABaQY5MgAAAABJRU5ErkJggg==';
const BLACKARROW = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAlCAYAAACtbaI7AAACMklEQVRIS6XWT8gOURTH8c+bIjaSZGMjr6xkJUlKJAnlTyglRYpIQlFIYcFbSEKSiBD5F/K/XrGQpY0VZWFnQ2GhRKdm3sa488zM85zlnfv73nPm3HPO7dOb9eE03uBKjorFXuwEtuM3VuN2wHqBHsK+gke/sAyPuoXuxeFEiN/R3w00wo2wy/YHG3GhLTRE5yp+2zacavtP1+IihiW83IOjbbO/AjcqgAdxoHhQk/AX4Q6GJzw8jp3l9TroPDzAyATwLLYgEvSPdYLOwjOMSgAvYX0K2ClR0/EcoxPAm1iTVVGyGlOeTsUgxiYU97ESUT2VVoZOwW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T_ITEM_HEIGHT = 202,
    PORTRAIT_ITEM_SPACE = 25,
    LANDSCAPE_ITEM_WIDTH = 272,
    LANDSCAPE_ITEM_HEIGHT = 440,
    LANDSCAPE_ITEM_SPACE = 30;

class RecommendUI {
    constructor(appid = 'default') {
        this.appid = appid;
        this.touching = false;
        this.firstShow = true;
        this.loadSuccess = false;
        this.specPanels = [];
        let window = cc.Canvas.instance; //获取游戏的canvas对象作为游戏窗口，以作为大小适配的基准参考
        if (window instanceof cc.Canvas) {
            this.window = window.node;
            this.initRoot();
            this.createBackground();

            this.initTitle();
            this.getSession(); // 获取上报的session
            this.fetchData();
        } else {
            cc.error('Can\'t find the canvas node in the current scene.');
        }
    }
    getSession() {
        let session = window.localStorage.getItem('session');
        if (!session) {
            this.request('POST', 'https://goplatform.minigame.qq.com/mplogin/getsessionid', {
                AppID: this.appid + ''
            }).then(res => {
                if (res.result === 0) {
                    session = res.session;
                    window.localStorage.setItem('session', session);
                    this.session = session;
                }
            });
        } else {
            this.session = session;
        }
    }
    fetchData(reconnect = false) {
        this.request('GET', 'https://goplatform.minigame.qq.com/3366game/getcurrentgame?appid=' + this.appid)
            .then((res) => {
                if (res.result == 0) {
                    this.loadSuccess = true;
                    if (this.offlineNode) {
                        this.offlineNode.active = false;
                    }
                    if (reconnect) {
                        this.firstReport();
                    }
                    this.games = [];
                    this.moreGames = [];
                    for (let i = 0; i < res.data.Games.length; ++i) {
                        this.games.push({
                            app_id: res.data.Games[i]['app_id'],
                            name: res.data.Games[i]['app_name'],
                            icon: res.data.Games[i]['app_icon'],
                            desc: res.data.Games[i]['app_introduction'],
                            qrcode: res.data.Games[i]['mini_program_code']
                        });
                    }
                    for (let i = 0; i < res.data.More_games.length; ++i) {
                        this.moreGames.push({
                            name: res.data.More_games[i]['app_name'],
                            icon: res.data.More_games[i]['app_icon'],
                            desc: res.data.More_games[i]['app_introduction'],
                            qrcode: res.data.More_games[i]['mini_program_code']
                        });
                    }
                    this.banner = this.choose(res.data.Banner, res.data.Banner_landscape);
                    this.poster = res.data.App_poster;
                    if (res.data.More_game_image) {
                        this.moreGameQrcode = res.data.More_game_image;
                    } else {
                        this.moreGameQrcode = '';
                    }
                    this.loadResource();
                } else {
                    this.loadOfflineResource();
                }
            }).catch(e => {
                cc.error(e);
                this.loadOfflineResource();
            });
    }
    // 拉取图片资源
    loadResource() {
        let promises = [];
        for (let i = 0; i < this.games.length; ++i) {
            promises.push(this.loadRemoteImage(this.games[i].icon)); // 游戏图标
        }
        for (let i = 0; i < this.moreGames.length; ++i) {
            promises.push(this.loadRemoteImage(this.moreGames[i].icon)); //更多游戏图标
        }
        promises.push(this.loadRemoteImage(this.banner));
        promises.push(this.loadRemoteImage(BAR));
        promises.push(this.loadRemoteImage(PANEL));
        promises.push(this.loadRemoteImage(CIRCLE));
        promises.push(this.loadRemoteImage(LINE));
        promises.push(this.loadRemoteImage(GREYARROW));
        Promise.all(promises).then((results) => {
            this.gameIcons = [];
            this.moreGameIcons = [];
            for (let i = 0; i < this.games.length; ++i) {
                this.gameIcons.push(results[i]);
            }
            for (let i = 0; i < this.moreGames.length; ++i) {
                this.moreGameIcons.push(results[i + this.games.length]);
            }
            this.bannerImg = results[this.games.length + this.moreGames.length];
            this.bar = results[this.games.length + this.moreGames.length + 1];
            this.panel = results[this.games.length + this.moreGames.length + 2];
            this.circle = results[this.games.length + this.moreGames.length + 3];
            this.line = results[this.games.length + this.moreGames.length + 4];
            this.greyArrow = results[this.games.length + this.moreGames.length + 5];
            this.createUI();
        }).catch((e) => {
            cc.error(e);
        });
    }
    // 拉取离线图片资源
    loadOfflineResource() {
        if (this.offlineNode) {
            this.offlineNode.active = true;
            return;
        }
        let promises = [];
        promises.push(this.loadRemoteImage(OFFLINE_TIPS));
        promises.push(this.loadRemoteImage(RECONNECT_BTN));
        Promise.all(promises).then((results) => {
            this.offlineTips = results[0];
            this.reconnectBtn = results[1];
            this.createUI();
        }).catch((e) => {
            cc.error(e);
        });
    }
    createNode(options) {
        let node = new cc.Node(options.name);
        let customProps = ['x', 'y', 'width', 'height', 'anchorX', 'anchorY', 'active', 'scaleX', 'scaleY', 'color', 'rotation'];
        if (options.components) {
            for (let component of options.components) {
                this.addComponent(node, component, options);
            }
        }
        for (let prop of customProps) {
            node[prop] = options[prop] !== undefined ? options[prop] : node[prop];
            if (prop == 'width' && options[prop] == 476) {
                window.line = node;
            }
        }
        if (options.children) {
            for (let child of options.children) {
                let childNode = this.createNode(child);
                node.addChild(childNode);
            }
        }
        return node;
    }
    addComponent(node, component, options) {
        let spriteFrames = this.uis;
        let props = {
            'sprite': ['spriteFrame', 'type', 'sizeMode', 'trim'],
            'mask': ['type', 'segements', 'alphaThreshold', 'spriteFrame'],
            'richText': ['horizontalAlign', 'fontSize', 'maxWidth', 'lineHeight', 'string'],
            'label': ['horizontalAlign', 'verticalAlign', 'fontSize', 'maxWidth', 'lineHeight', 'string', 'overflow'],
            'widget': ['isAlignHorizontalCenter', 'isAlignVerticalCenter', 'isAlignTop', 'isAlignBottom', 'isAlignLeft', 'isAlignRight', 'top', 'bottom', 'left', 'right'],
            'scrollview': ['vertical', 'horizonal', 'elastic'],
            'layout': ['type', 'paddingTop', 'paddingBottom', 'paddingLeft', 'paddingRight', 'spacingX', 'spacingY'],
            'graphics': [],
            'scrollbar': ['direction', 'enableAutoHide'],
            'blockInputEvents': []
        };
        let classes = {
            'sprite': cc.Sprite,
            'mask': cc.Mask,
            'richText': cc.RichText,
            'label': cc.Label,
            'widget': cc.Widget,
            'scrollview': cc.ScrollView,
            'graphics': cc.Graphics,
            'layout': cc.Layout,
            'scrollbar': cc.Scrollbar,
            'blockInputEvents': cc.BlockInputEvents
        };
        let cp = node.addComponent(classes[component.name]);
        if (component.name == 'graphics' && component.drawFunc) {
            component.drawFunc(cp);
        }
        for (let prop of props[component.name]) {
            // if (prop == 'sizeMode') {
            //     debugger;
            // }
            if (prop == 'spriteFrame') {
                let value = component[prop];
                if (value != undefined) {
                    if (typeof (value) == 'string') {
                        cp[prop] = spriteFrames[value];
                    }
                    if (value instanceof cc.SpriteFrame) {
                        cp[prop] = value;
                    }
                }
            } else {
                cp[prop] = component[prop] !== undefined ? component[prop] : cp[prop];
            }
        }
    }
    request(method, url, data) {
        return new Promise((resolve, reject) => {
            let timeoutcb = setTimeout(() => {
                reject('timeout');
            }, 3000);
            if (typeof (wx) != "undefined") {
                let xhr = new XMLHttpRequest();
                xhr.onreadystatechange = () => {
                    if (xhr.readyState == 4) {
                        clearTimeout(timeoutcb);
                        if ((xhr.status >= 200 && xhr.status < 400)) {
                            let res = xhr.responseText;
                            try {
                                res = JSON.parse(res);
                            } catch (e) {
                                reject('json parse err');
                            }
                            resolve(res);
                        } else {
                            reject('server error: ' + xhr.status);
                        }
                    }
                };
                xhr.open(method, url, true);
                xhr.setRequestHeader('Content-Type', 'application/json');
                if (typeof(wx) !== 'undefined') {
                    xhr.send(data || {});
                } else {
                    xhr.send(JSON.stringify(data || {}));
                }
            } else {
                clearTimeout(timeoutcb);
                reject();
            }
        });
    }
    loadRemoteImage(url) {
        return new Promise((resolve, reject) => {
            if (url) {
                let image = new Image();
                image.src = url;
                image.crossOrigin = "Anonymous";
                image.onload = () => {
                    let texture = new cc.Texture2D();
                    texture.initWithElement(image);
                    texture.handleLoadedTexture();
                    resolve(texture);
                };
                image.onerror = () => {
                    resolve(new cc.Texture2D());
                }
            } else {
                resolve(null);
            }
        });
    }
    createUI() {
        if (this.loadSuccess) {
            this.scrollView = this.createScrollView();
            this.root.addChild(this.scrollView);
            this.bindScrollEvents(this.scrollView);
            this.gameListContainer = this.createContainer();
            this.scrollView.addChild(this.gameListContainer);
            this.scrollView.getComponent(cc.ScrollView).content = this.gameListContainer;

            this.gameListPanels = this.createGameListPanels(this.gameListContainer);
            this.moreGamePanel = this.createMoreGamePanel(this.gameListContainer);
            if (this.bannerImg) {
                this.gameBanner = this.createGameBanner(this.gameListContainer);
            }
        } else {
            this.createOffLineUI();
        }
    }
    createOffLineUI() {
        let options = {
            name: 'offline-tips-container',
            width: this.choose(720, 1280),
            height: this.choose(1280, 720),
            scaleX: this.measureScale,
            scaleY: this.measureScale,
            children: [
                {
                    name: 'offline-tips',
                    width: 219,
                    height: 265,
                    y: this.choose(171, 27),
                    components: [{
                        name: 'sprite',
                        spriteFrame: new cc.SpriteFrame(this.offlineTips)
                    }]
                },
                {
                    name: 'offline-text',
                    y: this.choose(17, -127),
                    color: cc.hexToColor('#525252'),
                    height: 23,
                    components: [{
                        name: 'label',
                        string: '您的网络貌似有问题，请刷新试试哦',
                        fontSize: 22
                    }]
                },
                {
                    name: 'reconnect-btn',
                    y: this.choose(-64, -208),
                    components: [{
                        name: 'sprite',
                        spriteFrame: new cc.SpriteFrame(this.reconnectBtn)
                    }],
                    children: [{
                        name: 'btn-text',
                        color: cc.hexToColor('#3086de'),
                        components: [{
                            name: 'label',
                            string: '刷新',
                            fontSize: 28,
                            verticalAlign: cc.Label.VerticalAlign.CENTER
                        }]
                    }]
                }
            ]
        };
        this.offlineNode = this.createNode(options);
        this.root.addChild(this.offlineNode);
        cc.find('reconnect-btn', this.offlineNode).on(cc.Node.EventType.TOUCH_START, (e) => {
            this.fetchData(true);
        });
    }
    createScrollView() {
        let options = {
            name: '3666-game-scrollview',
            width: this.mode == 'portrait' ? 720 : 1280,
            height: this.mode == 'portrait' ? 1280 : 720,
            x: 0,
            y: 0,
            components: [
                {
                    name: 'scrollview',
                    vertical: this.mode == 'portrait',
                    horizonal: this.mode == 'landscape',
                    elastic: false
                },
                {
                    name: 'mask',
                    type: cc.Mask.Type.RECT
                }
            ]
            // children: [
            //     {
            //         name: 'scroll-bar',
            //         width: this.mode == 'portrait' ? 5 : 1120,
            //         height: this.mode == 'portrait' ? 1120 : 5,
            //         components: [
            //             {
            //                 name: 'scrollbar',
            //                 direction: this.mode == 'portrait' ? cc.Scrollbar.Direction.VERTICAL : cc.Scrollbar.Direction.HORIZONTAL,
            //                 enableAutoHide: true
            //             },
            //             {
            //                 name: 'widget',
            //                 isAlignBottom: this.mode == 'portrait',
            //                 isAlignTop: this.mode == 'landscape',
            //                 top: 10,
            //                 bottom: 0,
            //                 isAlignRight: true,
            //                 right: this.mode == 'portrait' ? 10 : 0
            //             },
            //             {
            //                 name: 'graphics',
            //                 drawFunc: (graphics) => {
            //                     this.drawRect(graphics, this.mode == 'portrait' ? 5 : 1120, this.mode == 'portrait' ? 1120 : 5, cc.hexToColor('#cccccc'));
            //                 }
            //             }
            //         ],
            //         children: [{
            //             name: 'bar',
            //             width: this.mode == 'portrait' ? 7 : 30,
            //             height: this.mode == 'portrait' ? 30 : 7,
            //             components: [
            //                 {
            //                     name: 'sprite',
            //                     spriteFrame: new cc.SpriteFrame(this.bar)
            //                 }
            //             ]
            //         }]
            //     }
            // ]
        };
        let node = this.createNode(options);
        // let scrollBar = cc.find('scroll-bar', node);
        // let bar = cc.find('scroll-bar/bar', node);
        // scrollBar.getComponent(cc.Scrollbar).handle = bar.getComponent(cc.Sprite);
        // node.getComponent(cc.ScrollView).verticalScrollBar = scrollBar.getComponent(cc.Scrollbar);
        node.scaleX = node.scaleY = this.measureScale; // 大小适配(等比例缩放)
        return node;
    }
    bindScrollEvents(node) {
        node.on('scroll-ended', () => {
            this.checkExposedGames();
        });
    }
    // 检查曝光的游戏并上报（曝光条件：在显示屏幕区域占一半以上）
    checkExposedGames(first = false) {
        let component = this.scrollView.getComponent(cc.ScrollView);
        let offset = component.getScrollOffset();
        let gameOffset;
        let datas = [];
        if (this.mode == 'landscape') {
            gameOffset = -offset.x
        } else {
            gameOffset = offset.y;
        }
        if (first) gameOffset = 0;
        let extraNum = 2;
        if (!this.moreGameIcons || this.moreGameIcons.length == 0) {
            extraNum = 1;
        }
        // 检测游戏曝光
        for (let i = 0; i < this.games.length + extraNum; ++i) {
            let x = this.choose(145 + i * 227, 51 + i * 302);
            if (x > gameOffset - this.choose(PORTRAIT_ITEM_HEIGHT, LANDSCAPE_ITEM_WIDTH) / 2
                && x + this.choose(PORTRAIT_ITEM_HEIGHT, LANDSCAPE_ITEM_WIDTH) < gameOffset + 1280 + this.choose(PORTRAIT_ITEM_HEIGHT, LANDSCAPE_ITEM_WIDTH) / 2) {
                if (i < this.games.length && !this.games[i].exposed) {
                    this.games[i].exposed = true;
                    this.reportItem(datas, i, 100, 2);
                }
                if (i >= this.games.length) {
                    let name = this.specPanels[i - this.games.length];
                    if (name == 'more-game' && !this.moreGameIsExposed) {
                        this.reportItem(datas, null, 100, 3);
                        this.moreGameIsExposed = true;
                    }
                    if (name == 'game-banner' && !this.bannerIsExposed) {
                        this.reportItem(datas, null, 100, 4);
                        this.bannerIsExposed = true;
                    }
                }
            } else {
                if (i < this.games.length) {
                    this.games[i].exposed = false;
                } else {
                    var name = this.specPanels[i - this.games.length];
                    if (name == 'more-game') {
                        this.moreGameIsExposed = false;
                    }
                    if (name == 'game-banner') {
                        this.bannerIsExposed = false;
                    }
                }
            }
        }
        if (datas.length > 0) {
            this.report(datas); // 统一批量上报
        }
    }
    // 生成单个上报数据
    reportItem(datas, i, actionId, slotId) {
        let data = {
            iSceneLevel1: 1000000,
            iSceneLevel2: slotId,
            iActionId: actionId,
            iResourceId2: this.appid,
            vV1: 1
        };
        if (i !== null) {
            data.iSceneLevel3 = i + 1;
            data.iResourceId1 = this.games[i].app_id;
        } else {
            data.iSceneLevel3 = 1;
        }
        datas.push(data);
    }
    createContainer() {
        let extraNum = 0;
        if (this.moreGameIcons && this.moreGameIcons.length > 0) {
            ++extraNum;
        }
        if (this.banner) {
            ++extraNum;
        }
        let landscapeWidth = (this.games.length + extraNum) * (LANDSCAPE_ITEM_WIDTH + LANDSCAPE_ITEM_SPACE) + 72;
        let portraitHeight = (this.games.length + extraNum) * (PORTRAIT_ITEM_HEIGHT + PORTRAIT_ITEM_SPACE) + 145;
        let options = {
            name: 'container',
            width: this.choose(720, landscapeWidth),
            height: this.choose(portraitHeight, 720),
            // x: this.choose(0, (this.games.length > 3 ? landscapeWidth / 2 - 640 : 0)),
            x: this.choose(0, (landscapeWidth / 2 - 640)),
            y: this.choose((this.games.length > 3 ? 640 - portraitHeight / 2 : 0), 0),
            components: [
                {
                    name: 'widget',
                    isAlignHorizontalCenter: this.mode == 'portrait',
                    isAlignVerticalCenter: this.mode == 'landscape'
                },
                {
                    name: 'layout',
                    type: this.mode == 'portrait' ? cc.Layout.Type.VERTICAL : cc.Layout.Type.HORIZONTAL,
                    paddingTop: this.choose(145 - 5, 100),
                    // paddingBottom: this.choose(undefined, 70 - 18),
                    paddingLeft: this.choose(0, 51 - 7),
                    spacingY: this.choose(PORTRAIT_ITEM_SPACE - 20, 0),
                    spacingX: this.choose(0, LANDSCAPE_ITEM_SPACE - 16)
                }
            ]
        };
        let node = this.createNode(options);
        return node;
    }
    createGameListPanels(parent) {
        let panels = [];
        let panelFrame = new cc.SpriteFrame(this.panel);
        panelFrame.insetTop = 13;
        panelFrame.insetBottom = 23;
        panelFrame.insetLeft = 17;
        panelFrame.insetRight = 19;
        for (let i = 0; i < this.games.length; ++i) {
            let desc = this.games[i].desc;
            if (this.mode == 'portrait') {
                if (desc.length > 16) {
                    desc = desc.substr(0, 15) + '...';
                }
            } else {
                if (desc.length > 20) {
                    desc = desc.substr(0, 19) + '...';
                }
            }
            let realWidth = this.choose(PORTRAIT_ITEM_WIDTH + 16, LANDSCAPE_ITEM_WIDTH + 16);
            let realHeight = this.choose(PORTRAIT_ITEM_HEIGHT + 20, LANDSCAPE_ITEM_HEIGHT + 20);
            let options = {
                name: 'game-item',
                width: realWidth,
                x: 0,
                y: this.choose(0, -80),
                anchorX: 0.5 - 1 / (realWidth * 2),
                anchorY: 0.5 + 5 / realHeight,
                height: realHeight,
                components: [
                    {
                        name: 'sprite',
                        spriteFrame: panelFrame,
                        type: cc.Sprite.Type.SLICED,
                        sizeMode: cc.Sprite.SizeMode.CUSTOM,
                        trim: false
                    }
                ],
                children: [
                    {
                        name: 'icon-bg',
                        width: 130,
                        height: 130,
                        x: this.choose(-250, 0),
                        y: this.choose(0, 200),
                        components: [{
                            name: 'sprite',
                            spriteFrame: new cc.SpriteFrame(this.circle)
                        }],
                        active: this.mode == 'landscape'
                    },
                    {
                        name: 'icon',
                        x: this.choose(-250, 0),
                        y: this.choose(0, 205),
                        width: 122,
                        height: 122,
                        components: [
                            {
                                name: 'sprite',
                                sizeMode: cc.Sprite.SizeMode.CUSTOM,
                                type: cc.Sprite.Type.SIMPLE,
                                spriteFrame: new cc.SpriteFrame(this.gameIcons[i])
                            }
                        ]
                    },
                    {
                        name: 'name',
                        x: this.choose(-165, 0),
                        y: this.choose(55, 78),
                        width: this.choose(440, 205),
                        height: this.choose(48, 72),
                        color: cc.hexToColor('#000000'),
                        anchorX: this.choose(0, 0.5),
                        anchorY: this.choose(1, 1),
                        components: [{
                            name: 'label',
                            horizontalAlign: this.choose(cc.Label.HorizontalAlign.LEFT, cc.Label.HorizontalAlign.CENTER),
                            overflow: cc.Label.Overflow.RESIZE_HEIGHT,
                            fontSize: this.choose(40, 30),
                            lineHeight: this.choose(48, 42),
                            string: this.games[i].name.length > 12 ? this.games[i].name.substr(0, 11) + '...' : this.games[i].name
                        }],
                    },
                    {
                        name: 'line',
                        // width: this.choose(476, 200),
                        scaleX: this.choose(476 / 66, 200 / 66),
                        height: 1,
                        x: this.choose(73, 0),
                        y: this.choose(1, -40),
                        active: this.mode == 'portrait',
                        components: [
                            {
                                name: 'sprite',
                                spriteFrame: new cc.SpriteFrame(this.line),
                                type: cc.Sprite.Type.SIMPLE,
                                sizeMode: cc.Sprite.SizeMode.COSTOM
                                // drawFunc: (graphics) => {
                                //     graphics.lineWidth = 1;
                                //     graphics.strokeColor = cc.hexToColor('#999999');
                                //     graphics.moveTo(0, 0);
                                //     graphics.lineTo(476, 0);
                                //     graphics.stroke();
                                // }
                            }
                        ]
                    },
                    {
                        name: 'desc',
                        x: this.choose(-165, 0),
                        y: this.choose(-11, -26),
                        width: this.choose(416, 220),
                        height: this.choose(31, 36),
                        anchorX: this.choose(0, 0.5),
                        anchorY: this.choose(1, 1),
                        color: cc.hexToColor('#999999'),
                        components: [{
                            name: 'label',
                            horizontalAlign: this.choose(cc.Label.HorizontalAlign.LEFT, cc.Label.HorizontalAlign.CENTER),
                            verticalAlign: cc.Label.VerticalAlign.TOP,
                            overflow: cc.Label.Overflow.RESIZE_HEIGHT,
                            fontSize: this.choose(26, 22),
                            lineHeight: this.choose(31, 36),
                            string: desc
                        }]
                    }
                ],
            };
            let node = this.createNode(options);
            this.bindTouchEvent(node, ((currentIndex) => {
                return () => {
                    let datas = [];
                    this.reportItem(datas, currentIndex, 101, 2);
                    this.report(datas);
                    this.showQrcode(this.games[currentIndex]);
                };
            })(i));
            panels.push(node);
        }
        for (let panel of panels) {
            parent.addChild(panel);
        }
        return panels;
    }
    bindTouchEvent(node, cb) {
        let distance, x1, y1, x2, y2;
        node.on(cc.Node.EventType.TOUCH_START, (e) => {
            let loc = e.getLocation();
            x1 = loc.x;
            y1 = loc.y;
        });
        node.on(cc.Node.EventType.TOUCH_END, (e) => {
            let loc = e.getLocation();
            x2 = loc.x;
            y2 = loc.y;
            distance = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2);
            if (distance < 25) {
                if (!this.touching) {
                    this.touching = true;
                    setTimeout(() => {
                        this.touching = false;
                    }, 10);
                    cb();
                }
            }
        });
    }
    showQrcode(data) {
        if (typeof (wx) != 'undefined') {
            wx.previewImage({
                urls: [data.qrcode]
            });
        }
    }
    createTitle() {
        let options = {
            name: 'title',
            // x: -this.width / 2,
            // y: -this.height / 2,
            x: 0,
            y: this.root.height / 2 - 60 * this.measureScale,
            width: this.root.width,
            height: 120 * this.measureScale,
            components: [
                // {
                //     name: 'widget',
                //     isAlignTop: true,
                //     top: 0
                // },
                {
                    name: 'blockInputEvents'
                },
                {
                    name: 'graphics',
                    drawFunc: (graphics) => {
                        this.drawRect(graphics, this.root.width,
                            120 * this.measureScale);
                    }
                }
            ],
            children: [
                {
                    name: 'title-container',
                    width: this.root.width,
                    height: 120 * this.measureScale,
                    children: [
                        {
                            name: 'arrow_container',
                            width: this.choose(21 * 0.8 + 60, 21 * 0.8 + 50),
                            height: 120,
                            scaleX: this.measureScale,
                            scaleY: this.measureScale,
                            children: [{
                                name: 'button_arrow',
                                width: 21,
                                height: 37,
                                components: [
                                    {
                                        name: 'sprite',
                                        type: cc.Sprite.Type.SIMPLE,
                                        sizeMode: cc.Sprite.SizeMode.CUSTOM,
                                        spriteFrame: new cc.SpriteFrame(this.blackArrow)
                                    }
                                ]
                            }],
                            components: [{
                                name: 'widget',
                                isAlignLeft: true,
                                left: 0,
                                isAlignVerticalCenter: true
                            }]
                        },
                        {
                            name: 'title-text',
                            color: cc.hexToColor('#000000'),
                            height: 46,
                            x: this.choose(0, -438),
                            scaleX: this.measureScale,
                            scaleY: this.measureScale,
                            components: [
                                {
                                    name: 'richText',
                                    string: '<bold>精彩游戏推荐<bold>',
                                    horizontalAlign: cc.RichText.HorizontalAlign.CENTER,
                                    fontSize: 34,
                                    lineHeight: 36
                                },
                                {
                                    name: 'widget',
                                    isAlignHorizontalCenter: this.choose(true, false),
                                    isAlignVerticalCenter: true,
                                    isAlignLeft: this.mode == 'landscape',
                                    left: 90 * this.measureScale
                                }
                            ]
                        }
                    ]
                }
            ]
        };
        let node = this.createNode(options);
        let backBtn = cc.find('title-container/arrow_container', node);
        backBtn.on(cc.Node.EventType.TOUCH_START, () => {
            this.hide();
        });
        return node;
    }
    createMoreGamePanel(parent) {
        if (!this.moreGameIcons || this.moreGameIcons.length == 0) {
            return null;
        }
        let panels = [];
        let panelFrame = new cc.SpriteFrame(this.panel);
        panelFrame.insetTop = 13;
        panelFrame.insetBottom = 23;
        panelFrame.insetLeft = 17;
        panelFrame.insetRight = 19;
        let realWidth = this.choose(PORTRAIT_ITEM_WIDTH + 16, LANDSCAPE_ITEM_WIDTH + 16);
        let realHeight = this.choose(PORTRAIT_ITEM_HEIGHT + 20, LANDSCAPE_ITEM_HEIGHT + 20);
        let options = {
            name: 'more-game-panel',
            width: realWidth,
            height: realHeight,
            anchorX: 0.5 - 1 / realWidth,
            anchorY: 0.5 + 5 / realHeight,
            y: this.choose(0, -80),
            components: [
                // {
                //     name: 'graphics',
                //     drawFunc: (graphics) => {
                //         this.drawRoundRect(graphics, this.choose(PORTRAIT_ITEM_WIDTH, 250), this.choose(PORTRAIT_ITEM_HEIGHT, 400));
                //     }
                // }
                {
                    name: 'sprite',
                    spriteFrame: panelFrame,
                    type: cc.Sprite.Type.SLICED,
                    sizeMode: cc.Sprite.SizeMode.CUSTOM,
                    trim: false
                }
            ],
            children: []
        };
        for (let i = 0; i < 3; ++i) {
            if (this.moreGameIcons && this.moreGameIcons[i]) {
                options.children.push(
                    {
                        name: 'icon',
                        width: this.choose(86 + 2 * 86 / 120, 70 + 2 * 70 / 120),
                        height: this.choose(86 + 2 * 86 / 120, 70 + 2 * 70 / 120),
                        x: this.choose(-267 + 106 * i, -76 + 76 * i),
                        y: this.choose(0, 50),
                        components: [
                            {
                                name: 'sprite',
                                sizeMode: cc.Sprite.SizeMode.CUSTOM,
                                type: cc.Sprite.Type.SIMPLE,
                                spriteFrame: new cc.SpriteFrame(this.moreGameIcons[i])
                            }
                        ]
                    }
                );
            }
        }
        options.children.push({
            name: 'more-game',
            color: cc.hexToColor('#000000'),
            width: 144,
            height: this.choose(42, 32),
            x: this.choose(150, -10),
            y: this.choose(0, -75),
            components: [
                {
                    name: 'label',
                    string: '更多好玩',
                    horizontalAlign: cc.Label.HorizontalAlign.CENTER,
                    fontSize: this.choose(40, 30),
                    lineHeight: this.choose(42, 32)
                }
            ]
        });
        let btnWidth = 22 * 32 / 37;
        options.children.push({
            name: 'button_arrow',
            width: btnWidth,
            height: 32,
            x: this.choose((PORTRAIT_ITEM_WIDTH / 2 - 50 - btnWidth / 2), (LANDSCAPE_ITEM_WIDTH / 2 - 45 - btnWidth / 2)),
            y: this.choose(-1, -76),
            components: [
                {
                    name: 'sprite',
                    type: cc.Sprite.Type.SIMPLE,
                    sizeMode: cc.Sprite.SizeMode.CUSTOM,
                    spriteFrame: new cc.SpriteFrame(this.greyArrow)
                }
            ]
        });
        let node = this.createNode(options);
        this.bindTouchEvent(node, () => {
            let datas = [];
            this.reportItem(datas, null, 101, 3);
            this.report(datas);
            if (typeof (wx) !== 'undefined') {
                wx.previewImage({
                    urls: [this.moreGameQrcode]
                });
            }
        });
        parent.addChild(node);
        this.specPanels.push('more-game');
        return node;
    }
    drawArrow(ctx, w, h, lineWidth, color = '#999999') {
        ctx.lineWidth = lineWidth || 5;
        ctx.strokeColor = cc.hexToColor(color);
        ctx.moveTo(0, 0);
        ctx.lineTo(w, h / 2);
        ctx.lineTo(0, h);
        ctx.stroke();
    }
    createGameBanner(parent) {
        let options = {
            name: 'game-banner',
            width: this.choose(PORTRAIT_ITEM_WIDTH, LANDSCAPE_ITEM_WIDTH),
            height: this.choose(PORTRAIT_ITEM_HEIGHT, LANDSCAPE_ITEM_HEIGHT),
            y: this.choose(0, -70),
            children: [{
                name: 'game-banner-img',
                width: this.choose(PORTRAIT_ITEM_WIDTH, LANDSCAPE_ITEM_WIDTH),
                height: this.choose(PORTRAIT_ITEM_HEIGHT, LANDSCAPE_ITEM_HEIGHT),
                x: this.choose(2, 11),
                components: [{
                    name: 'sprite',
                    sizeMode: cc.Sprite.SizeMode.CUSTOM,
                    type: cc.Sprite.Type.SIMPLE,
                    spriteFrame: new cc.SpriteFrame(this.bannerImg)
                }, {
                    name: 'widget',
                    isAlignTop: true,
                    top: this.choose(5, 9)
                }]
            }]
        };
        let node = this.createNode(options);
        this.bindTouchEvent(node, () => {
            let datas = [];
            this.reportItem(datas, null, 101, 4);
            this.report(datas);
            if (typeof (wx) !== 'undefined') {
                wx.previewImage({
                    urls: [this.poster]
                });
            }
        });
        parent.addChild(node);
        this.specPanels.push('game-banner');
        return node;
    }
    initRoot() {
        this.root = new cc.Node('wx-game-cross');
        this.calSize();
    }
    initTitle() {
        this.loadRemoteImage(BLACKARROW).then((texture) => {
            this.blackArrow = texture;
            this.title = this.createTitle();
            this.title.zIndex = 1;
            this.root.addChild(this.title);
        });
    }
    calSize() {
        this.root.setPosition(0, 0);
        this.width = Math.ceil(this.window.width);
        this.height = Math.ceil(this.window.height);
        if (this.width > this.height) {
            this.mode = 'landscape';
            if (this.width / this.height > 1280 / 720) {
                this.measureScale = this.height / 720; // 比例尺，根据实际游戏高度换算
                this.root.width = this.width;
                this.root.height = 720 * this.measureScale;
            } else {
                this.measureScale = this.width / 1280; // 比例尺，根据实际游戏宽度换算
                this.root.width = 1280 * this.measureScale;
                this.root.height = this.height;
            }
        } else {
            this.mode = 'portrait';
            if (this.width / this.height > 720 / 1280) {
                this.measureScale = this.height / 1280;
                this.root.width = this.width;
                this.root.height = 1280 * this.measureScale;
            } else {
                this.measureScale = this.width / 720; // 比例尺，根据实际游戏宽度换算
                this.root.width = 720 * this.measureScale;
                this.root.height = this.height;
            }
        }
        this.root.active = false;
    }
    createBackground() {
        this.background = this.createNode({
            name: 'wx-cross-background',
            width: this.root.width,
            height: this.root.height,
            components: [
                {
                    name: 'graphics',
                    drawFunc: (graphics) => {
                        this.drawRect(graphics, this.root.width, this.root.height, cc.hexToColor('#f5f5f5'), 256);
                    }
                }
            ]
        });
        this.root.addChild(this.background);
    }
    drawRect(ctx, width, height, color = cc.Color.WHITE, opacity = 256) {
        let fillColor = color;
        // fillColor.a = opacity;
        ctx.fillColor = fillColor;
        ctx.rect(0, 0, width, height);
        ctx.fill();
    }
    drawRoundRect(ctx, width, height, color = cc.Color.WHITE, opacity = 256) {
        ctx.fillColor = color;
        ctx.fillColor.opacity = opacity;
        ctx.roundRect(0, 0, width, height, 15);
        ctx.fill();
    }
    hide() {
        this.root.active = false;
        for (let game of this.games) {
            game.exposed = false;
        }
        this.moreGameIsExposed = false;
        this.bannerIsExposed = false;
    }
    show() {
        if (this.scrollView) {
            this.firstReport();
        }
        this.root.active = true;
    }
    firstReport() {
        let datas = [];
        this.reportItem(datas, null, 100, 1);
        this.report(datas);
        this.checkExposedGames(this.firstShow);
        this.firstShow = false;
    }
    report(datas) {
        let map = {
            dtLoginTime: -1, vQimei: -1, vAppVer: -1, PlatID: -1, vOsType: -1, osversion: -1, nettype: -1, model: -1,
            iActionId: -1, iSceneLevel1: -1, iSceneLevel2: -1, iSceneLevel3: -1, iResourceId1: -1,
            iResourceId2: -1, iResourceId3: -1, iResourceId4: -1, iResourceId5: -1, iRet: -1,
            vV1: -1, vV2: -1, vV3: -1, vV4: -1, vV5: -1, vV6: -1, vV7: -1, vV8: -1, vV9: -1, vV10: -1,
        };
        return new Promise((resolve, reject) => {
            datas = datas.map(item => {
                let data = Object.assign({}, map, item);
                let content = (() => {
                    let arr = [];
                    Object.keys(data).forEach(key => arr.push(data[key]));
                    return arr.join('|');
                })();
                return content;
            });
            this.request('POST', 'https://goplatform.minigame.qq.com/mpreport/reportplugintlog', {
                data: datas,
                session: this.session
            });
        });
    }
    choose(portraitVal, landscapeVal) {
        return this.mode == 'portrait' ? portraitVal : landscapeVal;
    }
}

// 营销插件渠道进入上报
function enterReport(appid = '', userid = '') {
    let launchOptions = {
        query: ''
    };
    if (typeof (wx) != "undefined") {
        launchOptions = wx.getLaunchOptionsSync();
    }
    let plan = '';
    let query = launchOptions.query;
    const getParam = (search, key) => {
        const reg = new RegExp(`(^|&)${key}=([^&]*)(&|$)`);
        const r = search.substr(1).match(reg);
        if (r !== null) return String(decodeURIComponent(r[2]));
        return '';
    };
    if (query.scene) {
        let scene = decodeURIComponent(query.scene);
        plan = getParam(scene, 'plan');
    } else {
        if (query.path) {
            plan = getParam(query.path, 'plan');
        }
    }

    if (plan !== '') {
        let url = 'https://goplatform.minigame.qq.com/mpreport/reportsource';
        let xhr = new XMLHttpRequest();
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/json');
        if (typeof(wx) !== 'undefined') {
            xhr.send({
                appid,
                userid,
                from: '',
                plan
            });
        } else {
            xhr.send(JSON.stringify({
                appid,
                userid,
                from: '',
                plan 
            }));
        }
    }
}

export {
    RecommendUI,
    enterReport
}