import { _decorator, assetManager, Component, ImageAsset, Label, Node, Size, Sprite, SpriteFrame, Texture2D, UITransform, Vec3 } from 'cc';
import { ui_att_item } from '../../../data/data';
import { ClientEvent } from '../../clientEvent';
import { config } from '../../config';
import { Attributes } from '../Attributes';
const { ccclass, property } = _decorator;

@ccclass('btn_question_item')
export class btn_question_item extends Component {
    @property(Node) btn_click:Node = null;
    @property(Node) lab_title:Node = null;
    private m_data:ui_att_item = null;
    public initView(data:ui_att_item,index:number){
        if(data===null){
            this.m_data = new ui_att_item;
            this.init()
        }else{
            this.m_data = data;
        }
        this.lab_title.getComponent(Label).string = `按钮${index}`;
        this.updateView()
        this.btn_click.on(Node.EventType.TOUCH_MOVE,(et)=>{
            let p = new Vec3(et.getUILocation().x,et.getUILocation().y)
            let n_p = this.node.parent.getComponent(UITransform).convertToNodeSpaceAR(p)
            this.node.position = n_p;
            this.m_data.x = this.node.position.x;
            this.m_data.y = this.node.position.y;
            ClientEvent.dispatchEvent(config.Event.UpdateAttributes,Attributes.Singleton.get_cur_att_data())
        })
    }

    init(){
        this.m_data.x = this.node.position.x;
        this.m_data.y = this.node.position.y;
        this.m_data.width = this.node.getComponent(UITransform).contentSize.width;
        this.m_data.height = this.node.getComponent(UITransform).contentSize.height;
    }

    public getData(){
        return this.m_data;
    }

    public updateView(){
        this.node.getComponent(UITransform).contentSize = new Size(this.m_data.width,this.m_data.height)
        this.node.position = new Vec3(this.m_data.x,this.m_data.y)
        this.lab_title.position = new Vec3(0,0,0)
        if(this.m_data.res.length>0){
            assetManager.loadRemote<ImageAsset>(this.m_data.res, (err, imageAsset2)=>{
                if (!err && imageAsset2) {        
                    const texture = new Texture2D();
                    texture.image = imageAsset2;
                    let spFrame2 = new SpriteFrame();     
                    spFrame2.texture = texture;
                    this.btn_click.getComponent(Sprite).spriteFrame = spFrame2
                }
            }); 
        }
    }
}


