import {
  Game,
  TouchSprite,
  MyLabel,
  asyncTweenChange,
} from './Game';

import {
  jelly, tweenChange,
} from './../Unit';

import { defaultData } from './DefaultData';

export class MyGame extends Game {

  images = null;

  data = null;
  status = null;

  initData(data) {
    this.images = data.images;

    this.status = {};

    if (!data.data || Object.is(data.data, {})) {
      this.data = defaultData;
    } else {
      this.data = data.data;
    }

    let imgUrlList = [];
    let audioUrlList = [];

    this.data.group.forEach(group => {
      group.forEach(line => {
        imgUrlList.push(line.img);
        audioUrlList.push(line.audio);
        audioUrlList.push(...line.groupAudios.map(data => data.audio));
      });
    });

    audioUrlList.push(...this.data.groupAudio);

    imgUrlList.push(this.data.middleImg);
    audioUrlList.push(this.data.titleLetterAudio);
    audioUrlList.push(this.data.titleAudio);
    audioUrlList.push(this.data.middleImgAudio);
    audioUrlList.push(this.data.totalAudio);

    imgUrlList = imgUrlList.filter((data) => data != null && data != '');
    audioUrlList = audioUrlList.filter((data) => data != null && data != '');

    this.preLoadData(imgUrlList, audioUrlList);
  }

  preLoadData(imgUrlList, audioUrlList) {
    imgUrlList.forEach((data) => {
      this._parent.addUrlToImages(data);
    });
    audioUrlList.forEach((data) => {
      this._parent.addUrlToAudioObj(data);
    });
  }

  mapScale;
  initView() {
    this.mapScale = this._parent.mapScale;

    // 初始化背景
    this.initBg();

    // 初始化标题
    this.initTittle();

    // 初始化中间部分
    this.initMiddle();

    // 初始化右下角音频按钮
    this.initTotalAudio();

    // 初始化弹出窗口
    this.initPopUp();
  }

  bg;
  initBg() {
    const bgBig = new TouchSprite();
    bgBig.init(this.images.get('img_white_bg'));
    bgBig.x = this._parent.canvasWidth / 2;
    bgBig.y = this._parent.canvasHeight / 2;
    bgBig.setScaleXY(this._parent.mapScaleBig);
    this.addChild(bgBig);

    const bg = new TouchSprite();
    bg.init(this.images.get('img_white_bg'));
    bg.x = this._parent.canvasWidth / 2;
    bg.y = this._parent.canvasHeight / 2;
    bg.setScaleXY(this.mapScale);
    this.addChild(bg);
    this.bg = bg;
  }

  initTittle() {
    const titleBg = new TouchSprite();
    titleBg.init(this.images.get('img_title_bg'));
    titleBg.x = titleBg.width / 2 * this.mapScale;
    titleBg.y = titleBg.height / 2 * this.mapScale;
    titleBg.setScaleXY(this.mapScale);
    this.addChild(titleBg);

    const titleLetter = new MyLabel();
    titleLetter.x = titleBg.width * 1 / 8;
    titleLetter.y = 0;
    titleLetter.fontSize = 48;
    titleLetter.fontColor = "#facf46";
    titleLetter.fontName = 'BerlinSansFBDemi';
    titleLetter.anchorX = 0;
    titleLetter.anchorY = 0.5;
    titleLetter.text = this.data.titleLetter;
    titleLetter.refreshSize();
    titleLetter.addTouchBeganListener(() => {
      this.playAudio(this.data.titleLetterAudio);
    });
    titleBg.addChild(titleLetter);

    const titleLabel = new MyLabel();
    titleLabel.x = titleBg.width * 5 / 8;
    titleLabel.y = 0;
    titleLabel.fontSize = 36;
    titleLabel.fontColor = "#000000";
    titleLabel.fontName = 'FuturaStd';
    titleLabel.anchorX = 0;
    titleLabel.anchorY = 0.5;
    titleLabel.text = this.data.title;
    titleLabel.refreshSize();
    titleLabel.addTouchBeganListener(() => {
      this.playAudio(this.data.titleAudio);
    });
    titleBg.addChild(titleLabel);
  }

  initMiddle() {
    this.initGroups();
    this.initMiddleCircle();
  }

  initMiddleCircle() {
    const circle = new TouchSprite();
    circle.init(this.images.get('img_oval_bg'));
    this.bg.addChild(circle);

    const middleImg = new TouchSprite();
    middleImg.init(this.images.get(this.data.middleImg));
    middleImg.setScaleXY(Math.min(circle.width / middleImg.width, circle.height / middleImg.height));
    this.bg.addChild(middleImg);

    circle.addTouchBeganListener(() => {
      jelly(circle);
      jelly(middleImg);
      this.playAudio(this.data.middleImgAudio);
    });
  }

  initGroups() {
    const groupImgList = [
      'img_group_bg_1',
      'img_group_bg_2',
      'img_group_bg_2',
      'img_group_bg_1'
    ];
    const groupPosList = [
      { x: -1, y: -1 },
      { x: 1, y: -1 },
      { x: -1, y: 1 },
      { x: 1, y: 1 },
    ];

    for (let i = 0; i < 4; i++) {
      this.initGroup(i, groupImgList, groupPosList);
    }
  }

  initGroup(idx, groupImgList, groupPosList) {
    const groupBg = new TouchSprite();
    groupBg.init(this.images.get(groupImgList[idx]));
    groupBg.x = groupPosList[idx].x * (groupBg.width / 2 + 2);
    groupBg.y = groupPosList[idx].y * (groupBg.height / 2 + 2);
    this.bg.addChild(groupBg);

    const groupTitle = new MyLabel();
    groupTitle.fontSize = 36;
    groupTitle.fontColor = "#ffffff";
    groupTitle.fontName = 'GOTHICB';
    groupTitle.anchorX = 0;
    groupTitle.anchorY = 0.5;
    groupTitle.text = this.data.groupTitle[idx];
    groupTitle.refreshSize();
    groupTitle.x = 90 - groupBg.width / 2;
    groupTitle.y = groupTitle.height - groupBg.height / 2;
    groupTitle.addTouchBeganListener(() => {
      this.playAudio(this.data.groupAudio[idx]);
    });
    groupBg.addChild(groupTitle);

    this.data.group[idx].forEach((line, lineIdx) => {
      const lineImg = new TouchSprite();
      lineImg.init(this.images.get(line.img));
      lineImg.setScaleXY(Math.min(65 / lineImg.width, 65 / lineImg.height));
      lineImg.x = 120 - groupBg.width / 2;
      lineImg.y = lineIdx * 75 - 50;
      lineImg.addTouchBeganListener(() => {
        jelly(lineImg);
        this.playAudio(line.audio);
      });
      groupBg.addChild(lineImg);

      let numberDataList = [];

      let width = 0;
      line.letterDataList.forEach((letterData, letterIdx) => {
        const letterLabel = new MyLabel();
        letterLabel.fontSize = 36;
        letterLabel.fontColor = letterData.color;
        letterLabel.fontName = 'ahronbd';
        letterLabel.anchorX = 0;
        letterLabel.anchorY = 0.5;
        letterLabel.text = letterData.letter;
        letterLabel.refreshSize();
        letterLabel.x = 160 - groupBg.width / 2 + width;
        letterLabel.y = lineIdx * 75 - 50;
        groupBg.addChild(letterLabel);

        letterLabel.addTouchBeganListener(() => {
          this.popUp(this.data.group[idx][lineIdx]);
        });

        width += letterLabel.width;

        if (letterData.line) {
          const outLine = new TouchSprite();
          if (letterData.color == '#c8161e') {
            outLine.init(this.images.get('img_line_red'));
          } else if (letterData.color == '#696363') {
            outLine.init(this.images.get('img_line_black'));
          } else {
            outLine.init(this.images.get('img_line_grey'));
          }
          outLine.x = letterLabel.width / 2;
          outLine.y = 20;
          outLine.scaleX = letterLabel.width / outLine.width;
          outLine.scaleY = 1.5;
          letterLabel.addChild(outLine);

          if (letterData.number) {
            const numberData = numberDataList[numberDataList.length - 1];
            if (numberDataList.length > 0 && letterIdx - numberData.idx == 1 && numberData.number == letterData.number) {
              numberData.idx = letterIdx;
              numberData.endX = letterLabel.x + letterLabel.width;
              return;
            }
            numberDataList.push({
              idx: letterIdx,
              number: letterData.number,
              color: letterData.color,
              startX: letterLabel.x,
              endX: letterLabel.x + letterLabel.width
            });
          }
        }
      });

      numberDataList.forEach(numberData => {
        const letterLabel = new MyLabel();
        letterLabel.fontSize = 20;
        letterLabel.fontColor = numberData.color;
        letterLabel.fontName = 'ahronbd';
        letterLabel.anchorX = 0;
        letterLabel.anchorY = 0.5;
        letterLabel.text = numberData.number;
        letterLabel.refreshSize();
        letterLabel.x = (numberData.startX + numberData.endX) / 2 - letterLabel.width / 2;
        letterLabel.y = lineIdx * 75 - 20;
        groupBg.addChild(letterLabel);
      });
    });
  }

  initTotalAudio() {
    const totalAudioBtn = new TouchSprite();
    totalAudioBtn.init(this.images.get('btn_play'));
    totalAudioBtn.x = this._parent.canvasWidth - totalAudioBtn.width;
    totalAudioBtn.y = this._parent.canvasHeight - totalAudioBtn.height;
    totalAudioBtn.addTouchBeganListener(() => {
      jelly(totalAudioBtn);
      if (this.data.totalAudio != '') {
        this.playAudio(this.data.totalAudio, true, () => {
          totalAudioBtn.init(this.images.get('btn_play'));
        });
        totalAudioBtn.init(this.images.get('btn_pause'));
      }
    });
    this.addChild(totalAudioBtn);
  }

  initPopUp() {
    const popUpBg = new TouchSprite();
    popUpBg.init(this.images.get('img_grey_bg'));
    popUpBg.setName('popUpBg');
    popUpBg.x = this._parent.canvasWidth / 2;
    popUpBg.y = this._parent.canvasHeight / 2;
    popUpBg.setScaleXY(this._parent.mapScaleBig);
    popUpBg.alpha = 0;
    popUpBg.childDepandAlpha = true;
    popUpBg.addTouchBeganListener(() => {

    });
    this.addChild(popUpBg);

    const popUpWinBg = new TouchSprite();
    popUpWinBg.init(this.images.get('img_win_bg'));
    popUpWinBg.setName('popUpWinBg');
    popUpWinBg.x = this._parent.canvasWidth / 2;
    popUpWinBg.y = this._parent.canvasHeight / 2;
    popUpWinBg.setScaleXY(this.mapScale);
    popUpWinBg.alpha = 0;
    popUpWinBg.childDepandAlpha = true;
    this.addChild(popUpWinBg);

    const btnClose = new TouchSprite();
    btnClose.init(this.images.get('btn_close'));
    btnClose.setName('btnClose');
    btnClose.x = (popUpWinBg.width / 2 - btnClose.width / 3);
    btnClose.y = -(popUpWinBg.height / 2 - btnClose.height / 3);
    btnClose.addTouchBeganListener(() => {
      jelly(btnClose);
      this.hidePopUp();
      this.playAudio('pop_up');
    });
    popUpWinBg.addChild(btnClose);

    const wordMiddle = new MyLabel();
    wordMiddle.fontSize = 72;
    wordMiddle.fontColor = "#680099";
    wordMiddle.fontName = 'GOTHICB';
    wordMiddle.text = '';
    wordMiddle.refreshSize();
    wordMiddle.setName('wordMiddle');
    popUpWinBg.addChild(wordMiddle);

    wordMiddle.addTouchBeganListener(() => {
      console.log('汪汪汪')
      this.playAudio(this.popUpData.audio);
    });

    const changeBtn = new TouchSprite();
    changeBtn.init(this.images.get('btn_switch'));
    changeBtn.x = (popUpWinBg.width / 2 - 100);
    changeBtn.y = (popUpWinBg.height / 2 - 100);
    changeBtn.visible = false;
    changeBtn.setName('changeBtn');
    changeBtn.addTouchBeganListener(async () => {
      jelly(changeBtn);
      tweenChange(changeBtn, { alpha: 0 }, 0.2, () => {
        changeBtn.visible = false;
        changeBtn.alpha = 1;
      });
      this.playAudio('click_green_btn');
      await this.changePopUp();
    });
    popUpWinBg.addChild(changeBtn);
  }

  popUpData;
  popUp(popUpData) {
    this.popUpData = popUpData;
    const popUpBg = this.getChildByName('popUpBg');
    const popUpWinBg = this.getChildByName('popUpWinBg');

    const wordMiddle = this.seekChildByName('wordMiddle');
    wordMiddle.text = popUpData.word;
    wordMiddle.refreshSize();
    wordMiddle.x = 0;
    wordMiddle.y = -150;

    this.playAudio('pop_up');

    const nodePosBaseOld = popUpWinBg.seekChildByName('nodePosBase');
    if (nodePosBaseOld) {
      popUpWinBg.removeChild(nodePosBaseOld);
    }

    const nodePosBase = new TouchSprite();
    nodePosBase.setName('nodePosBase');
    nodePosBase.childDepandAlpha = true;
    popUpWinBg.addChild(nodePosBase);

    const wordBase = new TouchSprite();
    wordBase.childDepandAlpha = true;
    wordBase.setName('wordBase');
    nodePosBase.addChild(wordBase);

    const lineBase = new TouchSprite();
    lineBase.childDepandAlpha = true;
    lineBase.setName('lineBase');
    nodePosBase.addChild(lineBase);

    const groupNumber = Math.max(...popUpData.letterDataList.map(letterData => letterData.group)) + 1;

    const groupShowedList = new Array(groupNumber).fill(false);

    const labelGroupList = [];
    let blankWidth = 0;
    let width = 0;
    popUpData.letterDataList.forEach((letterData, idx) => {
      const wordMiddle = new MyLabel();
      wordMiddle.fontSize = 72;
      wordMiddle.fontColor = "#363333";
      wordMiddle.fontName = 'GOTHICB';
      wordMiddle.text = letterData.letter;
      wordMiddle.setName(`wordMiddle_${idx}`);
      wordMiddle.refreshSize();
      wordMiddle.anchorX = 0;
      wordMiddle.anchorY = 0.5;
      wordMiddle.x = width + letterData.group * 20;
      wordMiddle.y = 120;
      wordMiddle.visible = false;
      wordMiddle.addTouchBeganListener(() => {
        for (const label of labelGroupList[letterData.group]) {
          label.visible = true;
          tweenChange(label, { alpha: 1 }, 0.2);
        }

        if (wordMiddle.alpha == 1) {
          this.playAudio(popUpData.groupAudios[letterData.group].audio);
        } else {
          this.playAudio('click_line');
        }

        groupShowedList[letterData.group] = true;
        if (groupShowedList.every(show => show == true)) {
          const changeBtn = this.seekChildByName('changeBtn');
          changeBtn.visible = true;
          tweenChange(changeBtn, { alpha: 1 }, 0.2);
        }
      });
      wordBase.addChild(wordMiddle);

      if (!labelGroupList[letterData.group]) {
        labelGroupList.push([]);
      }
      labelGroupList[letterData.group].push(wordMiddle);

      blankWidth = letterData.group * 20;

      width += wordMiddle.width;

      const line = new TouchSprite();
      line.init(this.images.get('img_line_purple'));
      line.anchorX = 0;
      line.anchorY = 0.5;
      line.x = wordMiddle.x;
      line.y = 170;
      line.scaleX = wordMiddle.width / line.width;
      line.setName(`line_${idx}`);
      lineBase.addChild(line);
    });
    const changeBtn = this.seekChildByName('changeBtn');
    changeBtn.visible = false;
    changeBtn.alpha = 0;

    lineBase.x = -(width + blankWidth) / 2;
    wordBase.x = -(width + blankWidth) / 2;

    tweenChange(popUpBg, { alpha: 1 }, 0.2);
    tweenChange(popUpWinBg, { alpha: 1 }, 0.2, () => {
      popUpData.letterDataList.forEach((_, idx) => {
        const wordMiddle = wordBase.getChildByName(`wordMiddle_${idx}`);
        wordMiddle.visible = true;
        wordMiddle.alpha = 0.00000001;
      });
    });
  }

  hidePopUp() {
    const popUpBg = this.getChildByName('popUpBg');
    tweenChange(popUpBg, { alpha: 0 }, 0.2);
    const popUpWinBg = this.getChildByName('popUpWinBg');
    tweenChange(popUpWinBg, { alpha: 0 }, 0.2);
  }

  async changePopUp() {
    const wordBaseOld = this.seekChildByName('wordBase');
    await asyncTweenChange(wordBaseOld, { alpha: 0 }, 0.3);

    const popUpWinBg = this.getChildByName('popUpWinBg');
    const wordBaseOld2 = popUpWinBg.seekChildByName('wordBase');
    if (wordBaseOld2) {
      popUpWinBg.removeChild(wordBaseOld2);
    }

    const nodePosBase = this.seekChildByName('nodePosBase');

    const wordBase = new TouchSprite();
    wordBase.setName('wordBase');
    wordBase.childDepandAlpha = true;
    nodePosBase.addChild(wordBase);

    let labelGroupList = [];
    let blankWidth = 0;
    let width = 0;
    this.popUpData.letterDataList.forEach((letterData, idx) => {
      const wordMiddle = new MyLabel();
      wordMiddle.fontSize = 72;
      wordMiddle.fontColor = letterData.color;
      wordMiddle.fontName = 'GOTHICB';
      wordMiddle.text = letterData.letter;
      wordMiddle.setName(`wordMiddle_${idx}`);
      wordMiddle.refreshSize();
      wordMiddle.anchorX = 0;
      wordMiddle.anchorY = 0.5;
      wordMiddle.alpha = 0;
      wordMiddle.x = width + letterData.group * 20;
      wordMiddle.y = 120;
      wordBase.addChild(wordMiddle);
      // tweenChange(wordMiddle, { alpha: 1 }, 0.2);

      const groupNumber = Math.max(...this.popUpData.letterDataList.map(letterData => letterData.group)) + 1;
      const groupShowedList = new Array(groupNumber).fill(false);

      wordMiddle.addTouchBeganListener(() => {
        // changeBtn
        console.log('汪汪汪');
        for (const label of labelGroupList[letterData.group]) {
          label.visible = true;
          tweenChange(label, { alpha: 1 }, 0.2);
        }
        groupShowedList[letterData.group] = true;
        if (groupShowedList.every(show => show == true)) {
          const changeBtn = this.seekChildByName('changeBtn');
          changeBtn.visible = true;
          tweenChange(changeBtn, { alpha: 1 }, 0.2);
        }

        this.playAudio(this.popUpData.groupAudios[letterData.group].audio);
      });

      if (!labelGroupList[letterData.group]) {
        labelGroupList.push([]);
      }
      labelGroupList[letterData.group].push(wordMiddle);

      blankWidth = letterData.group * 20;

      width += wordMiddle.width;

      // const line = new TouchSprite();
      // line.init(this.images.get('img_line_purple'));
      // line.anchorX = 0;
      // line.anchorY = 0.5;
      // line.x = wordMiddle.x;
      // line.y = 170;
      // line.scaleX = wordMiddle.width / line.width;
      // line.setName(`line_${idx}`);
      // nodePosBase.addChild(line);

      if (letterData.point) {
        const point = new TouchSprite();
        point.init(this.images.get('Img_point'));
        point.x = wordMiddle.x + 10;
        point.y = wordMiddle.y - 50;
        wordBase.addChild(point);
      }
    });

    wordBase.x = -(width + blankWidth) / 2;

    wordBase.alpha = 0;
    await asyncTweenChange(wordBase, { alpha: 1 }, 0.3);
  }
}