import { RES } from "../../module/RES";
import { layers } from "../../module/views/layers";
import { Scene } from "../../module/views/Scene";
import { GDispatcher } from "../Main";
import { Tools } from "../Tools";
import UI from "../UI";
import { guideList, list } from "./GameConfig";

let lastIndex = -1; // 最后一次点击的下标
export class Game extends Scene {
  get groupNames() {
    return ["game"];
  }
  needGuide = false;

  backBtn: FYGE.Sprite;
  ruleBtn: FYGE.Sprite;
  startBtn: FYGE.Sprite;
  handSvga: Hand;
  // 引导部分
  guidelayer;
  guideWrap: FYGE.Container;

  // 游戏部分
  gamelayer;
  gameWrap: FYGE.Container;
  gameBack: FYGE.Sprite;

  list = []; // 数组
  guideCardList = []; // 新手引导中的卡片列表
  cardList = []; // 游戏中的卡片列表
  guideStep = 1; // 引导步数
  initUi() {
    this.needGuide = Tools.gameData.needGuide; // 模板中传过来的

    UI.Sp(this, "cardBg.jpg", 0, 0);
    this.backBtn = UI.Sp(this, "返回.png", 0, 274);
    this.ruleBtn = UI.Sp(this, "规则.png", 663, 274);
    this.startBtn = UI.Sp(this, "按钮.png", 198, 1231);
    // 遍历生成底图
    for (let i = 0; i < 8; i++) {
      UI.Sp(
        this,
        "back.png",
        Math.floor(i % 4) * 168 + 50,
        Math.floor(i / 4) * 360 - 15 + 538
      );
    }
    // 如果是新手引导阶段, 有手势引导
    if (this.needGuide) {
      this.handSvga = this.startBtn.addChild(new Hand());
      this.handSvga.position.set(200, -120);
    }

    // 添加点击事件
    this.backBtn.addEventListener(
      FYGE.MouseEvent.CLICK,
      function () {
        // 返回-wyx
        GDispatcher.dispatchEvent("backIndex");
      },
      this
    );
    this.ruleBtn.addEventListener(
      FYGE.MouseEvent.CLICK,
      function () {
        // 活动规则-wyx
        GDispatcher.dispatchEvent("openRule");
      },
      this
    );
    this.startBtn.addEventListener(
      FYGE.MouseEvent.CLICK,
      function () {
        // 开始游戏-wyx
        Tools.btnDelay(this.startBtn);
        if (this.needGuide) {
          this.needGuide = false;
          this.onEnterGuide();
        } else {
          GDispatcher.dispatchEvent("startId");
          this.gameUIRender();
        }
      },
      this
    );
  }
  guideUIRender() {
    this.guidelayer = UI.Ctn(this, 0, 0);
    this.guidelayer.addChild(
      Tools.getRect(layers.stageWidth, 1624, 0x0000000, 0.6)
    );
    this.guideWrap = UI.Ctn(this.guidelayer, 50, 530);
    UI.Sp(this.guideWrap, "tips.png", 56,720);
    this.list = JSON.parse(JSON.stringify(guideList));
    this.cardList = [];
    this.list.map((item, i) => {
      const card = new GuideCard({
        ...item,
        index: i,
        list: this.list,
        cardList: this.guideCardList,
      });
      this.guideCardList.push(card);

      this.guideWrap
        .addChild(card)
        .position.set(Math.floor(i % 4) * 168, Math.floor(i / 4) * 360 - 15);
      this.guideCardList[i].alpha = 0;
      FYGE.Tween.get(this.guideCardList[i])
        .wait(i * 200)
        .to(
          {
            y: Math.floor(i / 4) * 360,
            alpha: 1,
          },
          500
        );
    });
    this.guidelayer.addEventListener(
      FYGE.MouseEvent.CLICK,
      function () {
        this.clickGuideCard();
      },
      this
    );
  }
  gameUIRender() {
    this.gamelayer = UI.Sp(this, "cardBg.jpg", 0, 0);
    this.gameBack = UI.Sp(this.gamelayer, "返回.png", 0, 274);
    this.gameBack.addEventListener(
      FYGE.MouseEvent.CLICK,
      function () {
        this.removeChild(this.gamelayer)
      },
      this
    );
    this.gameWrap = UI.Ctn(this.gamelayer, 50, 530);
    this.list = JSON.parse(JSON.stringify(list)).sort(
      () => Math.random() - 0.5
    );
    this.cardList = [];
    this.list.map((item, i) => {
      const card = new Card({
        ...item,
        index: i,
        list: this.list,
        cardList: this.cardList,
      });
      this.cardList.push(card);

      this.gameWrap
        .addChild(card)
        .position.set(Math.floor(i % 4) * 168, Math.floor(i / 4) * 360 - 15);
      this.cardList[i].alpha = 0;
      FYGE.Tween.get(this.cardList[i])
        .wait(i * 200)
        .to(
          {
            y: Math.floor(i / 4) * 360,
            alpha: 1,
          },
          500
        );
    });
  }
  onEnterGuide() {
    this.startBtn.removeChild(this.handSvga);
    this.guideUIRender();
  }
  clickGuideCard() {
    console.log("点击卡片");
    if (this.guideStep == 1) {
      this.guideCardList[2].removeHand();
      this.guideCardList[5].handSvga = this.guideCardList[5].addChild(
        new Hand()
      );
      this.guideCardList[2].onOverTurn(this.guideCardList[2]);
    } else if (this.guideStep == 2) {
      this.guideCardList[5].removeHand();
      this.guideCardList[5].onOverTurn(this.guideCardList[5], () => {
        setTimeout(() => {
          this.guideCardList[2].onZoomCard(this.guideCardList[2]);
          this.guideCardList[5].onZoomCard(this.guideCardList[5]);
        });
      });
    } else if (this.guideStep == 3) {
      // 回到游戏
      this.removeChild(this.guidelayer);
    }
    this.guideStep += 1;
  }
  start(data) {
    super.start();
  }
  closeGame() {
     // e.data.isGuide;
    this.removeChild(this.gamelayer)
  }

  initEvents() {
    super.initEvents();
    GDispatcher.addEventListener("closeGame", this.closeGame, this);
  }
  removeEvents() {
    super.removeEvents();
    GDispatcher.removeEventListener("closeGame", this.closeGame, this);
  }
}

class Card extends FYGE.Container {
  img;
  public isFront = false; // 是否正面
  public match = false; // 是否匹配
  public type; // 类型
  constructor(data?) {
    super();
    this.initUi(data);
  }

  initUi(data) {
    this.type = data.type;
    this.img = UI.Sp(this, "back.png", 0, 0);
    this.img.anchorX = 70;
    this.img.anchorY = 133;
    this.addEventListener(
      FYGE.MouseEvent.CLICK,
      function () {
        Tools.btnDelay(this);
        this.clickCard(data);
      },
      this
    );
  }
  clickCard(data) {
    if (this.isFront) return;
    this.isFront = true;
    this.onOverTurn(this, () => {
      if (lastIndex > -1) {
        console.log(data.list[lastIndex].type, data.type)
        if (data.list[lastIndex].type === data.type) {
          const tempIndex = lastIndex;
          lastIndex = -1;
          // 匹配成功, 进行动画缩放
          // 当前卡片缩放
          this.onZoomCard(data.cardList[data.index]);
          // 上一个卡片缩放
          this.onZoomCard(data.cardList[tempIndex], () => {
            // 检测是否完成, 提交游戏
            if (this.checkIsAllMatch(data.cardList)) {
              console.log("提交游戏");
              GDispatcher.dispatchEvent("submit");
            }
          });
        } else {
          const tempIndex = lastIndex;
          lastIndex = -1;
          // 等待一段时间翻转
          setTimeout(() => {
            // 当前卡片翻转
            this.onOverTurn(data.cardList[data.index], () => {
              data.cardList[data.index].isFront = false;
            });

            // 上一个卡片翻转
            this.onOverTurn(data.cardList[tempIndex], () => {
              data.cardList[tempIndex].isFront = false;
            });
          }, 500);
        }
      } else {
        lastIndex = data.index;
      }
    });
  }
  onOverTurn(that, callback = () => {}) {
    FYGE.Tween.get(that.img)
      .to(
        {
          scaleX: 0,
        },
        200
      )
      .call(() => {
        if (that.match) {
          that.img.texture = FYGE.Texture.fromUrl("back.png");
          that.match = false;
        } else {
          that.img.texture = FYGE.Texture.fromUrl(that.type + ".png");
          that.match = true;
        }
        FYGE.Tween.get(that.img)
          .to(
            {
              scaleX: 1,
            },
            200
          )
          .call(() => {
            console.log("翻转结束");
            if (callback) {
              callback();
            }
          });
      });
  }
  onZoomCard(that, callback = () => {}) {
    FYGE.Tween.get(that.img)
      .to(
        {
          scaleX: 1.2,
          scaleY: 1.2,
        },
        300
      )
      .call(() => {
        FYGE.Tween.get(that.img)
          .to(
            {
              scaleX: 1,
              scaleY: 1,
            },
            300
          )
          .call(() => {
            console.log("缩放结束");
            that.match = true;
            if (callback) {
              callback();
            }
          });
      });
  }
  // 检测是否全部翻完
  checkIsAllMatch(list) {
    for (const item of list) {
      if (!item.match) {
        return false;
      }
    }
    return true;
  }
  destroy() {
    super.destroy();
    FYGE.Tween.removeTweens(this.img);
  }
}

class GuideCard extends FYGE.Container {
  img;
  public isFront = false; // 是否正面
  public match = false; // 是否匹配
  public type; // 类型
  handSvga: Hand; // 手指引导
  constructor(data?) {
    super();
    this.initUi(data);
  }

  removeHand() {
    this.removeChild(this.handSvga);
  }
  initUi(data) {
    this.type = data.type;
    this.img = UI.Sp(this, "back.png", 0, 0);
    this.img.anchorX = 70;
    this.img.anchorY = 133;
    if (data.index == 2) {
      this.handSvga = this.addChild(new Hand());
    }
  }
  onOverTurn(that, callback = () => {}) {
    FYGE.Tween.get(that.img)
      .to(
        {
          scaleX: 0,
        },
        200
      )
      .call(() => {
        if (that.match) {
          that.img.texture = FYGE.Texture.fromUrl("back.png");
          that.match = false;
        } else {
          that.img.texture = FYGE.Texture.fromUrl(that.type + ".png");
          that.match = true;
        }
        FYGE.Tween.get(that.img)
          .to(
            {
              scaleX: 1,
            },
            200
          )
          .call(() => {
            console.log("翻转结束");
            if (callback) {
              callback();
            }
          });
      });
  }
  onZoomCard(that, callback = () => {}) {
    FYGE.Tween.get(that.img)
      .to(
        {
          scaleX: 1.2,
          scaleY: 1.2,
        },
        300
      )
      .call(() => {
        FYGE.Tween.get(that.img)
          .to(
            {
              scaleX: 1,
              scaleY: 1,
            },
            300
          )
          .call(() => {
            console.log("缩放结束");
            that.match = true;
            if (callback) {
              callback();
            }
          });
      });
  }
  destroy() {
    super.destroy();
    FYGE.Tween.removeTweens(this.img);
  }
}

class Hand extends FYGE.Container {
  img;
  constructor(data?) {
    super();
    this.initUi();
  }
  initUi() {
    this.img = UI.Sp(this, "hand.png", 56, 166);
    FYGE.Tween.get(this.img, {
      loop: true,
    })
      .to(
        {
          x: 70,
          y: 185,
        },
        500
      )
      .to(
        {
          x: 56,
          y: 166,
        },
        400
      );
  }

  destroy() {
    super.destroy();
    FYGE.Tween.removeTweens(this.img);
  }
}
