import { Color, find, instantiate, Label, Node, Quat, v3, _decorator } from 'cc';
import { BaseLayer } from '../../common/BaseLayer';
import { utilTools } from '../../utils/utilTools';
import { constants } from '../data/constants';
import { designManager } from '../manager/designManager';
import { iconManager } from '../manager/iconManager';
import { sdkManager } from '../manager/sdkManager';
import { playerModel } from '../model/playerModel';
const { ccclass, property } = _decorator;

@ccclass('TurnTableLayer')
export class TurnTableLayer extends BaseLayer {

    turnTable: Node;
    idAwardObj: any = {};

    // 奖励物品存放在圆盘上的半径点
    radius: number;

    // 快速转动的角度
    angleSpeed: number = 0;
    // 此次抽奖转动的角度
    angle: number = 0;

    // 前半段每秒转动的角度
    speed: number = 360;
    // 转盘结果奖励
    awardRow: any;

    speedCount: number = 0;
    angleCount: number = 0;

    btnFree: Node;
    btnAd: Node;

    textColor2: Color = new Color();

    onLoad() {
        super.onLoad();

        this.btnFree = this.getNodeByPath("info/btnFree");
        this.btnAd = this.getNodeByPath("info/btnAd");



        // this.textColor1 = "644a34";
        Color.fromHEX(this.textColor2, "#644a34");

        this.turnTable = this.getNodeByPath("info/turnTable");
        let awardNode = find("award", this.turnTable);
        this.radius = awardNode.getPosition().y;
        for (let i = 1; i < 6; i++) {
            awardNode = instantiate(awardNode);
            awardNode.parent = this.turnTable;
        }

        this.loadTurnTableAward();

        this.initUI();
    }

    loadTurnTableAward() {
        let tb = designManager.instance.getTable(constants.tableName.turn_table);
        let coinArr = [];
        let skillArr = [];
        for (let i in tb) {
            let row = tb[i];
            if (row.type == constants.turnTableAwardTypes.coin) {
                coinArr.push(row);
            } else if (row.type == constants.turnTableAwardTypes.skill) {
                skillArr.push(row);
            }
        }
        coinArr = utilTools.getRowsByWeightAndNum(coinArr, 4);
        skillArr = utilTools.getRowsByWeightAndNum(skillArr, 2);

        let arr = utilTools.randomArr(coinArr.concat(skillArr));
        for (let i = 0; i < arr.length; i++) {
            let row = arr[i];
            row.angle1 = i * 60;
            row.angle2 = (i + 1) * 60;
        }

        let chs = this.turnTable.children;
        for (let i = 0, len = chs.length; i < len; i++) {
            let awardNode = chs[i];
            let row = arr[i];
            awardNode["row"] = row;
            this.idAwardObj[row.id] = awardNode;
            // 每个奖励物品获得的权重是一样的
            row.weight = 1;
            let label = find("text", awardNode).getComponent(Label);
            if (i % 2 == 0) {
                label.color = this.textColor2;
            } else {
                label.color = Color.WHITE;
            }
        }

    }

    initUI() {
        this.initTurnTable();
        this.initBtns();
    }

    initBtns() {
        if (utilTools.overDay(playerModel.instance.getTurnTableFreeTime())) {
            this.btnFree.active = true;
            this.btnAd.active = false;
        } else {
            this.btnFree.active = false;
            this.btnAd.active = true;
        }
    }

    initTurnTable() {
        for (let i in this.idAwardObj) {
            let awardNode = this.idAwardObj[i];
            this.refreshAwardNode(awardNode);
        }
    }

    refreshAwardNode(awardNode: Node) {
        let row = awardNode["row"];

        let textNode = find("text", awardNode);
        let iconNode = find("icon", awardNode);
        let getNode = find("get", iconNode);

        switch (row.type) {
            case constants.turnTableAwardTypes.coin:
                // 金币奖励
                textNode.active = true;
                this.setString(textNode, row.p1);
                break;
            case constants.turnTableAwardTypes.skill:
                // 技能奖励
                textNode.active = false;
                // let skillRow = designManager.instance.getRowById(constants.tableName.skill, row.p1);
                // this.setString(textNode, skillRow.name);
                break;
            default:
                break;
        }
        iconManager.instance.setSprite(iconNode, row.icon);

        if (this.hasGetAward(row)) {
            getNode.active = true;
        } else {
            getNode.active = false;
        }

        // 计算位置和旋转
        let angle1 = row.angle1;
        let angle2 = row.angle2;

        let angle = (angle1 + angle2) * 0.5;
        // 角度转换为弧度制
        let rad = angle / 180 * Math.PI;
        let x = this.radius * Math.sin(rad);
        let y = this.radius * Math.cos(rad);
        awardNode.setPosition(x, y);

        let quat = new Quat();
        Quat.fromEuler(quat, 0, 0, -angle);
        awardNode.setRotation(quat);

    }

    hasGetAward(row: any) {
        switch (row.type) {
            case constants.turnTableAwardTypes.coin:
            case constants.turnTableAwardTypes.skill:
                if (playerModel.instance.getTurnTableAwardIdArr().indexOf(row.id) != -1) {
                    return true;
                }
                break;
            case constants.turnTableAwardTypes.skin:
                break;
            default:
                break;
        }

        return false;
    }

    getAwardRowArr() {
        let arr = [];
        for (let i in this.idAwardObj) {
            let awardNode = this.idAwardObj[i];
            let row = awardNode["row"];
            if (this.hasGetAward(row)) {
                continue;
            }
            arr.push(row);
        }

        return arr;
    }

    // 开始转动圆盘
    startTurnTable() {
        if (this.angleCount > 0) {
            return;
        }

        // 根据权重，计算获得的奖励
        let row = utilTools.getRowByWeight(this.getAwardRowArr());
        this.awardRow = row;

        // 额外再需要转的角度
        let targetAngle = (row.angle2 + row.angle1) * 0.5;

        this.angle = 360 * 2 + targetAngle;
        this.angleSpeed = this.angle - 360;
        // console.log(this.angleSpeed, this.angle);

        this.speedCount = this.speed;
        this.angleCount = 1;

    }

    // 发放转盘奖励
    getAward() {
        let awardRow = this.awardRow;
        playerModel.instance.addTurnTableAwardId(awardRow.id);
        let obj: any = {};
        switch (awardRow.type) {
            case constants.turnTableAwardTypes.coin:
                obj.coin = awardRow.p1;
                break;
            case constants.turnTableAwardTypes.skill:
                obj.skillId = awardRow.p1;
                break;
            default:
                break;
        }
        this.openLayer(constants.layers.AwardGetLayer, obj, () => {
            this.refreshAwardNode(this.idAwardObj[awardRow.id]);
            this.checkAwardAllGet();
        });

    }

    checkAwardAllGet() {
        for (let i in this.idAwardObj) {
            let awardNode = this.idAwardObj[i];
            let row = awardNode["row"];
            if (!this.hasGetAward(row)) {
                return;
            }
        }

        // 已全部领取，自动重置奖励
        this.onClickBtnRefresh();

    }

    onButtonClick(node: Node, name: string) {
        switch (name) {
            case "btnAd":
                this.onClickBtnAd(node);
                break;
            case "btnRefresh":
                this.onClickBtnRefresh(node);
                break;
            case "btnFree":
                this.onClickBtnFree(node);
                break;
            case "btnClose":
                this.onClickBtnClose(node);
                break;
            default:
                break;
        }
    }

    onClickBtnAd(node: Node) {
        sdkManager.instance.sendEvent("观看激励视频-幸运转盘再抽一次");
        sdkManager.instance.openAd((st: number) => {
            if (st != 1) {
                return;
            }
            this.startTurnTable();
            sdkManager.instance.sendEvent("观看完激励视频-幸运转盘再抽一次");
        });
    }

    onClickBtnRefresh(node?: Node) {
        playerModel.instance.resetTurnTableAward();
        this.loadTurnTableAward();
        this.initTurnTable();
    };

    onClickBtnFree(node: Node) {
        this.startTurnTable();
        playerModel.instance.setTurnTableFreeTime(new Date());
        this.initBtns();
    }

    onClickBtnClose(node: Node) {
        this.closeLayer();
    }

    update(dt: number) {
        if (this.angleCount <= 0) {
            return;
        }

        let speed = 0;
        if (this.angleCount < this.angleSpeed) {
            speed = this.speed;
        } else {
            this.speedCount -= 3;
            speed = this.speedCount;
        }
        if (speed < 30) {
            speed = 30;
        }

        this.angleCount += dt * speed;
        if (this.angleCount > this.angle) {
            this.angleCount = this.angle;
        }
        this.turnTable.setRotationFromEuler(v3(0, 0, this.angleCount));

        if (this.angleCount >= this.angle) {
            this.angleCount = 0;
            this.getAward();
        }
    }

}

