import lib from './library'
import GameLife from './GameLife'
import md5 from './md5'
let timer


function _renderIcon(gameName, adList, name, x, y, pNode) {
    var curAd = { id: -1 }

    //定时切换
    _randomImage()
    timer = setInterval(() => {
        _randomImage()
    }, 3000)

    /**
     * 随机渲染一张图片
     */
    function _randomImage() {
        let index = (new Date()).getTime() % adList.length

        //不渲染和上一个一样的图标
        if (curAd.id === adList[index].id) {
            index = (index + 1) % adList.length
        }

        curAd = adList[index]

        let icon = curAd['small_icon'];
        // icon = 'http://ben.wiki.webdev2.duowan.com/house.png';
        let options = curAd['small_icon_options'] || {}
        options['pNode'] = pNode
        // options['rows'] = 4
        // options['cols'] = 2
        // options['num'] = 8
        // options['interval'] = 10

        lib.drawImage(name, icon, x, y, function () {
            // 点击后，更换图标广告
            // _randomImage();
            // 打开这个广告
            _openMp(gameName, curAd)
        }, options);
    }
}


//加载Prefab
function _loadPrefab(data,gameName) {
    cc.loader.loadRes("duowansdk/prefab/homeAd", function (err, prefab) {
        var newNode = cc.instantiate(prefab);
        cc.director.getScene().addChild(newNode);

        let head = newNode.getChildByName('head')
        head.getComponent(cc.Label).string = data.title
        newNode.getChildByName('content').getChildByName('desc').getComponent(cc.Label).string = data.content
        newNode.getChildByName('content').getChildByName('time').getComponent(cc.Label).string = `时间：${data.start_time}-${data.end_time}`
        let closeBtn = newNode.getChildByName('icon-close').addComponent(cc.Button)
        closeBtn.node.on(cc.Node.EventType.TOUCH_START,() => {
            newNode.destroy()
        })
        let detailBtn = newNode.getChildByName('btn').addComponent(cc.Button)
        detailBtn.node.on(cc.Node.EventType.TOUCH_START,() => {
            wx.navigateToMiniProgram({
                appId: data.app_id,
                path: '',
                extraData: {}
            })
        })
    });
}



/**
 * 尝试直接访问，失败则打开图片的方式
 * @param {*} gameName 
 * @param {*} curAd 
 */
function _openMp(gameName, curAd) {
    console.log(curAd)
    if (lib.wx) {
        // 优先直接打开小程序
        if (curAd.app_id) {
            wx.navigateToMiniProgram({
                appId: curAd.app_id,
                path: curAd.path,
                extraData: {},
                success() {
                    // 上报跳转成功数据 
                    lib.get(`${lib.host}hz/static?field=navigate&name=${gameName}`)
                },
                fail() {
                    // 打开失败，则打开图片
                    _previewImage(gameName, curAd)
                }
            })
        } else {
             _previewImage(gameName, curAd)
        }
    } else {
        console.debug("点击了图标广告，显示图片：" + curAd['big_image'])
        // 上报打开图片数据 
        lib.get(`${lib.host}hz/static?field=img&name=${curAd.name}`)
        window.open(curAd['big_image'])
    }
}

function _previewImage(gameName, curAd) {
    if(!curAd) {
        return
    }
    // 上报打开图片数据 
    lib.get(`${lib.host}hz/static?field=img&name=${curAd.name}`)

    // 打开失败，则打开图片
    wx.previewImage({
        urls: [curAd['big_image']]
    })
}

export default class DwSdk {
    constructor(name, debug = false) {
        this.name = name
        lib.setDebug(debug)

        // 游戏的生命周期
        this.objGameLife = new GameLife(name)
        this.objGameLife.initEvent()
    }

    /**
     * 显示小图标广告
     * @param {int} x  X轴位置，默认0
     * @param {int} y  Y轴位置，默认0
     * @param {object} node 可选参数（Cocos引擎的节点） 
     */
    showAdIcon(x = 0, y = 0, node = null) {
        //兼容不报错
        if(!cc) {
            return 
        }
        let self = this
        //装配启动参数
        let lunchData = wx.getLaunchOptionsSync()
        let sdkParam = {}
        try {
            lunchData.query = JSON.parse(lunchData.query)
            lunchData.referrerInfo = JSON.parse(lunchData.referrerInfo)
            delete lunchData.__public
        } catch (error) {
            
        }
        sdkParam.query = lunchData.query
        sdkParam.referrerInfo = lunchData.referrerInfo
        let sdkStr = JSON.stringify(sdkParam)
        console.log(sdkStr)
        lib.get(`${lib.host}hz/showAd?name=${self.name}&ips=1&sdk_param=${sdkStr}`, function (ret) {
            _renderIcon(self.name, ret.data, "DwSdk_AdIcon", x, y, node)
        });
    }

    /**
     * 隐藏小图标广告
     * @param {object} node 可选参数（Cocos引擎的节点） 
     */
    hideAdIcon(node = null) {
        lib.hideImage("DwSdk_AdIcon", node);
        clearInterval(timer)
    }

    showHomeAd() {
        let self = this

        if (lib.cc) {
            lib.get(`${lib.host}hz/mainAd?name=${self.name}`, (ret) => {
                let data = ret.data

                //无数据
                if (!data.app_id) {
                    return
                }
                //根据时长判断是否加载首屏广告
                let lastTime = lib.getStorage("showAdTime");
                let interval = data.interval_time * 60 * 1000;
                let ts = new Date().getTime();
                if (lastTime && interval > ts - lastTime) {
                    return
                } else {
                    _loadPrefab(data,'多玩游戏中心')
                    lib.setStorage("showAdTime",ts)
                    
                }

            })
        }
    }

    /**
     * 打开多玩游戏中心
     */
    openGameCenter() {
        let app_id = 'wx582548bc3a843fed';
        let gameName = '多玩游戏中心';

        if (lib.wx) {
            wx.navigateToMiniProgram({
                appId: app_id,
                extraData: {},
                success() {
                    // 上报跳转成功数据 
                    lib.get(`${lib.host}hz/static?field=navigate&name=${gameName}`)
                },
                fail() {
                    // 打开失败，则打开图片
                    lib.get(`${lib.host}hz/common`, function ({ data }) {
                        // 上报打开图片数据 
                        // lib.get(`${lib.host}hz/static?field=img&name=${gameName}`)
                        wx.previewImage({
                            urls: [data.hz_picture]
                        })
                    });
                }
            })
        } else {
            // 打开失败，则打开图片
            lib.get(`${lib.host}hz/common`, function ({ data }) {
                window.open(data.hz_picture)
            });
        }
    }

    setCanvasTranslate(dx, dy) {
        lib.setCanvasTranslate(dx, dy)
    }

    update() {
        lib.updateImage();
    }

    //获取广告图标列表
    getAdList(cb) {
        lib.get(`${lib.host}hz/showAd?name=${self.name}&ips=1`, (ret) => {
            if(ret.data) {
                cb(ret.data)
            }
            
        })
        
    }

    
    /**
     * 点击图标上报
     * @param {string} name 被点击的图标的游戏的名称
     */
    reportClickAdIcon(name) {
        lib.get(`${lib.host}hz/static?field=img&name=${name}`)
    }

}