import {getSkinPath} from "../utils";
import {MainStage} from "../Main";
import {MainDispatcher} from "../Scenes/MainScene/MainScene";

export class ProgressNum extends eui.Component {
    public numLabel: eui.Label;
    public touchGroup: eui.Group;
    public bar: eui.Rect;
    public fill: eui.Rect;
    public hand: eui.Image;

    private canMove = false;

    private data = null;
    private total = 0;  // 总个数
    private number = 1; // 当前个数
    public get value() {
        return this.number;
    }

    constructor(data?) {
        super();
        this.skinName = getSkinPath('Component/ProgressNum');
        this.data = data || null;

        this.total = this.data.total;

        // this.numLabel.text = `${this.number}`;
        this.setHandX(0);

        this.initEvents();
        this.hand.anchorOffsetX = 19;
    }

    private initEvents() {
        MainStage.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.groupTouchBegin, this);
        MainStage.addEventListener(egret.TouchEvent.TOUCH_MOVE, this.groupTouchMEC, this);
        MainStage.addEventListener(egret.TouchEvent.TOUCH_END, this.groupTouchMEC, this);
        MainStage.addEventListener(egret.TouchEvent.TOUCH_CANCEL, this.groupTouchMEC, this);
    }

    private setHandX(x) {
        let aWidth = this.bar.width / (this.total - 1);
        if (aWidth == Infinity) {
            aWidth = this.bar.width + 10;   /// TODO +10 保证total为1是显示正常 临时方案
        }
        let dx = x % aWidth;    // 取余数
        x = (~~(x / aWidth) + (dx >= (aWidth / 2) ? 1 : 0)) * aWidth;   // 过半吸附
        this.hand.x = x;
        if (this.hand.x < 0) {
            this.hand.x = 0;
        } else if (this.hand.x > this.bar.width) {
            this.hand.x = this.bar.width;
        }
        this.fill.width = this.hand.x;

        this.number = Math.ceil(this.hand.x / aWidth) + 1; // * (this.total) + 1);

        this.setNumber();
        MainDispatcher.dispatchEvent('updateSellValue');
    }

    private setNumber() {
        if (this.total == 0) {
            this.number = 0;
        }
        this.numLabel.text = `${this.number}`;
    }

    private groupTouchBegin(e: egret.TouchEvent) {
        this.canMove = this.touchGroup.hitTestPoint(e.stageX, e.stageY);
        if (this.canMove) {
            this.setHandX(e.stageX - this.x);
        }
    }

    private groupTouchMEC(e: egret.TouchEvent) {
        if (!this.canMove) {
            return;
        }
        this.setHandX(e.stageX - this.x);
    }

    public destroy() {
        MainStage.removeEventListener(egret.TouchEvent.TOUCH_BEGIN, this.groupTouchBegin, this);
        MainStage.removeEventListener(egret.TouchEvent.TOUCH_MOVE, this.groupTouchMEC, this);
        MainStage.removeEventListener(egret.TouchEvent.TOUCH_END, this.groupTouchMEC, this);
        MainStage.removeEventListener(egret.TouchEvent.TOUCH_CANCEL, this.groupTouchMEC, this);
    }
}