const tools = require("../script/tools");

cc.Class({
    extends: cc.Component,

    properties: {
        hitPre: cc.Prefab,
        borders: [cc.Node]
    },

    onLoad() {
        this._hitItem = []
        this._items = this.node.getChildByName('items')
        this._sprite = this.getComponentInChildren(cc.Sprite)
        this.borders[0].active = false
        this.borders[1].active = false
    },

    initWithData(data) {
        this.clearItems()
        tools.getSpriteFrimeByUrl(data.bgItem.url, (sp) => {
            let rect = sp.getRect()
            let scale = rect.width / rect.height
            let originRect = cc.size(1280, 720)
            let originScale = originRect.width / originRect.height
            if (scale < originScale) {
                scale = rect.height / originRect.height
                let width = rect.width / scale
                this.node.width = width
                this.node.height = originRect.height

            } else if (scale > originScale) {
                scale = rect.width / originRect.width
                this.node.height = rect.height / scale
                this.node.width = originRect.width
            } else {
                scale = rect.width / originRect.width
                this.node.width = originRect.width
                this.node.height = originRect.height
            }
            this.borders[0].active = true
            this.borders[1].active = true
            this.borders[0].x = -this.node.width / 2
            this.borders[1].x = this.node.width / 2
            this._sprite.spriteFrame = sp
            this._sprite.node.width = this.node.width
            this._sprite.node.height = this.node.height
            this._items.width = this.node.width
            this._items.height = this.node.height
            this._items.x = -this.node.width / 2
            this._items.y = this.node.height / 2
            scale = data.bgItem.rect.width / this.node.width
            //初始化点击区域
            let node, comp
            for (let data of data.hotZoneItemArr) {
                node = cc.instantiate(this.hitPre)
                this._items.addChild(node)
                comp = node.getComponent('hitItem')
                comp.initWithData(data, scale)
                this._hitItem.push(node)
            }
        })
    },

    /** 清除item */
    clearItems() {
        this._items.removeAllChildren(true)
        this._hitItem.length = 0
    }
});
