import {
    _decorator,
    BoxCollider,
    color,
    Color,
    Component,
    Enum,
    find,
    Material,
    MeshRenderer,
    Node,
    tween,
    Vec3
} from 'cc';
import { CarColors, CarTypes } from '../CarColorsGlobalTypes';
import { RoleCarColorsComponent } from './RoleCarColorsComponent';
import { CarColorsGlobalInstance } from '../CarColorsGlobalInstance';
import { MainGame } from "db://assets/Scripts/Scenes/MainGame/MainGame";

import { EDITOR } from "cc/env";

const { ccclass, property, executeInEditMode } = _decorator;

@ccclass('CarCarColorsComponent')
@executeInEditMode
export class CarCarColorsComponent extends Component {
    @property({ type: Enum(CarTypes) })
    carType: CarTypes = CarTypes.CAR10;

    @property({ type: Enum(CarColors) })
    get carColor() {
        return this._carColor;
    }

    set carColor(value) {
        this._carColor = value;
        this.changeColor();
    }

    @property({ type: Enum(CarColors) })
    private _carColor: CarColors = CarColors.Purple;

    @property({ type: [Material] })
    colorMaterials: Array<Material> = [];

    @property(MeshRenderer) bodyMesh: MeshRenderer = null;
    @property(MeshRenderer) top: MeshRenderer = null;

    get sitNum() {
        return this.node.getChildByName("Seets").children.length;
    }

    halfLen: number = 2;

    roleNum: number = 0;
    isFull: boolean = false;

    tweenCount = 0;

    onLoad() {
        this.changeColor();
        this.halfLen = this.getComponent(BoxCollider).size.z / 2;
        this.roleNum = 0;
        this.isFull = false;
    }

    changeColor() {
        // if (!EDITOR_NOT_IN_PREVIEW){
        //     this.colorMaterials = find("Scene/mtl").getComponent(MeshRenderer).sharedMaterials
        // }
        if (EDITOR && this.bodyMesh.getSharedMaterial(1) == this.colorMaterials[this.carColor]) return;

        this.bodyMesh.setSharedMaterial(this.colorMaterials[this.carColor], 1);
        this.top.setSharedMaterial(this.colorMaterials[this.carColor], this.top.materials.length - 1);

        this.node.getChildByName("arrow").active = true;

        tween(this.node)
            .to(0.2, { scale: new Vec3(1.4, 1.4, 1.4) })
            .to(0.2, { scale: new Vec3(0.96, 0.96, 0.96) })
            .start();
    }

    addRole(role: Node): boolean {
        const carPoint = this.node.parent
        role.setParent(this.node.getChildByName("Seets").children[this.roleNum], true)
        role.getComponent(RoleCarColorsComponent).playWalk()
        tween(role).to(0.2, {
            position: new Vec3(0, 0, -0.1)
        }).call(() => {
            this.tweenCount -= 1;
            role.setScale(0.9, 0.9, 0.9);
            role.setRotationFromEuler(0, 0, 0);
            role.getComponent(RoleCarColorsComponent).playSit();
            if (this.tweenCount <= 0 && this.isFull) {
                const index = carPoint.getSiblingIndex();
                if (index === 7 || index == 6 || index == 5 || index == 4) {
                    carPoint.name = "lock";
                    carPoint.children[0].children[0].active = false;
                    carPoint.children[0].children[1].active = true;
                    if (index == 4) {
                        carPoint.children[0].children[1].active = false;
                        carPoint.children[0].children[2].active = true;
                    }
                } else {
                    carPoint.name = "empty";
                }
                this.carOutTween(carPoint);
            }
        }).start();

        this.tweenCount += 1;
        this.roleNum += 1;
        this.isFull = this.roleNum >= this.sitNum;
        return this.isFull;
    }

    carOut() {
        this.node.getChildByName("Seets").children.forEach(seat => {
            if (seat.children.length === 0) return;
            const roleCom = seat.children[0].getComponent(RoleCarColorsComponent);
            CarColorsGlobalInstance.instance.roleSysterm.clearOne(roleCom);
        });
        CarColorsGlobalInstance.instance.carSysterm.removeCar(this.node);
        this.node.removeFromParent();
        this.node.destroy();

        // console.log("carOut:", find("Scene/Levels").children.length, find("Scene/Levels").children[0].children.length, find("Scene/Roles").children.length)
        // 判定胜利
        if (CarColorsGlobalInstance.instance.carSysterm.activeCar.size === 0) {
            if (find("Scene/Roles").children.length === 0) {
                // showPanel(SuccessPage);
                MainGame.ins.nextLevel();
            }
        }
    }

    // 车离开
    carOutTween(target: Node) {
        tween(this.node)
            .to(0.2, {
                worldPosition: target.getWorldPosition()
            })
            .call(() => {
                const carforward = this.node.forward.clone();
                tween(carforward).to(0.1, { x: -1, y: 0, z: 0 }, {
                    onUpdate: () => {
                        this.node.forward = carforward;
                    }
                }).start();
            })
            .delay(0.1)
            .to(0.2, {
                worldPosition: find("Scene/physicRoodTop/rightPoint").getWorldPosition(),
            })
            .call(() => {
                this.carOut();
            })
            .start();
    }
}


