import getSkinPath from "../libs/new_wx/utils/getSkinPath";
import getDefaultPic from "./getDefaultPic";


export default class ListItemRenderer extends eui.ItemRenderer {
    constructor() {
        super();
        this.skinName = getSkinPath('ListItem');
    }
    btn: eui.Button;
    dataChanged() {
        if (!this['img'].mask)
            this['img'].mask = this['imgMask'];
        if (!this.btn.hasEventListener(egret.TouchEvent.TOUCH_TAP)) {
            this.btn.addEventListener(egret.TouchEvent.TOUCH_TAP, () => { this.data.func(this.data.id) }, this);
        }
        this['img'].source = null;
        this['img'].x = 31.7;
        this['img'].y = 5.1;
        this['img'].width = 181;
        this['img'].height = 125;

        this.loadImg();

        this['idtxt'].text = '编号：' + this.data.id;
        this['title'].text = this.data.dreamTitle;
        if (this.data.dreamContent && this.data.dreamContent.length > 30) {
            this.data.dreamContent = this.data.dreamContent.slice(0, 30) + '...';
        }
           
        this['content'].text = this.data.dreamContent;
        this['energy'].text = `能量值:${this.data.energy}   排名:${this.data.rank}`;
    }

    loadImg() {
        this.data.dreamPic = this.data.dreamPic || getDefaultPic()
        const maskRatio = this['imgMask'].width / this['imgMask'].height;
        const url = this.data.dreamPic;
        RES.getResByUrl(url, (img: egret.Texture) => {
            if (url != this.data.dreamPic) return;
            this['img'].source = img;

            const imgRatio = img.textureWidth / img.textureHeight;

            if (imgRatio < maskRatio) {
                const scale = this['imgMask'].width / img.textureWidth;
                this['img'].width = this['imgMask'].width;
                this['img'].height = img.textureHeight * scale;
                this['img'].y = 5.1 - this['img'].height / 2 + this['imgMask'].height / 2;
            } else {
                const scale2 = this['imgMask'].height / img.textureHeight;
                this['img'].height = this['imgMask'].height;
                this['img'].width = img.textureWidth * scale2;
                this['img'].x = 31.7 - this['img'].width / 2 + this['imgMask'].width / 2;
            }



        }, this, RES.ResourceItem.TYPE_IMAGE);
    }
}