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

var picNode = cc.Class({
	extends: cc.Component,

	properties: {
		hitPre: cc.Prefab,
		quan: cc.Node,
	},

	onLoad() {
	},

	ctor: function () {
		picNode.inst = this;
		g.picNode = picNode;
	},

	onEnable() {
		this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)
	},
	onDisable() {
		this.node.off(cc.Node.EventType.TOUCH_START, this.onTouchStart, this)
	},

	onTouchStart() {
		if (g.data_mgr.nodPlayer) {
			g.data_mgr.nodPlayer.onStopAudio();
		}
		g.speaker.inst.playEffect(g.enum.E_Audio.Error);
	},

	onShow(data) {
		this._hitItem = []
		this._sprite = this.getComponentInChildren(cc.Sprite)
		this._items = this.quan;
		this.initWithData(data);
	},

	initWithData(data) {
		this.clearItems()
		tools.getSpriteFrimeByUrl(data.bgItem.url, (sp) => {
			//设置图片
			this._sprite.spriteFrame = sp
			this.photoScare(this._sprite.node);

			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

			if (this._items.height / data.bgItem.rect.height < this._items.width / data.bgItem.rect.width) {
				var scale = this.node.height / data.bgItem.rect.height
				//X不够补X偏移量
				var Xvalue = (this.node.width - data.bgItem.rect.width * scale) / 2
				var Yvalue = 0;
			} else {
				var scale = this.node.width / data.bgItem.rect.width
				//Y不够补Y偏移量
				var Xvalue = 0;
				var Yvalue = (this.node.height - data.bgItem.rect.height * scale) / 2
			}

			//初始化点击区域
			let node, comp
			for (let data of data.hotZoneItemArr) {
				node = cc.instantiate(this.hitPre)
				comp = node.getComponent('demo_jj_game_02_hitItem')
				comp.initWithData(data, scale, Xvalue, Yvalue);

				this._items.addChild(node)
				this._hitItem.push(node)
			}
		})
	},

	//图片适配
	photoScare: function (node) {
		var height = 550;
		var width = 960;
		// var maxNum = type == 0 ? 50 : 280;
		let maxSize = Math.min(height / node.height, width / node.width);
		if (node.perScale == undefined) {
			node.perScale = node.scaleX;
		} else {
			node.scaleX = node.perScale;
			node.scaleY = node.perScale;
		}
		node.scaleX *= maxSize;
		node.scaleY *= maxSize;
		this.maxSize = maxSize;
	},

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