import React, { Component } from 'react';
import './gamePage.less';
import { minusProbability, plusProbability } from './gameData';
import modalStore from '@src/store/modal';
import store from '@src/store';
import { second2Date } from '@src/utils/utils';
import { SvgaPlayer } from '@spark/svgaplayer';
import { RES_PATH } from '../../../sparkrc';

class GamePage extends Component {

  min = 1;

  max = 99;

  firstInFlag = true;

  state = {
    addition: 'plus',
    symbolInfo1: {
      number: 0,
      fen1: 2,
      fen2: 1,
      symbolName: '',
      symbolText: ''
    },
    symbolInfo2: {
      number: 0,
      fen1: 2,
      fen2: 1,
      symbolName: '',
      symbolText: ''
    },
    selectIndex: 0,
    currentNum: 1,
    numElements: [{
      top: '3.71rem'
    }],
    seconds: '00:00',
    showCountSvga: false,
    // fen1: 1,
    // fen2: 1,
    // fen3: 1,
    // fen4: 1,
    // number1: 0,
    // number2: 0
  }

  componentDidMount() {
    
    this.createAddition();
    if(store.startInfo?.guide) {
      modalStore.pushPop("GuideModal", {handleStartSvga: this.handleStartSvga})
    } else {
      // this.doCount();
      this.handleStartSvga(true)
    }
  }

  handleStartSvga = (status) => {

    this.setState({
      showCountSvga: status
    }, () => {
      !status && this.doCount()
    })
    
  }

  countdownSeconds = (store.startInfo?.countdownSeconds || 60) * 1000;

  gameOver = false;
  doCount = () => {
    const timeObj = second2Date(this.countdownSeconds);
    // 倒计时结束提交

    setTimeout(() => {

      if(this.countdownSeconds <= 0) {
        store.submitScore(this.currentNumber);
        this.gameOver = true;
        this.setState({
          seconds: '00:00'
        })
        return;
      }
      this.countdownSeconds -= 1000;

      this.setState({
        seconds: `${timeObj.minute}:${timeObj.second}`
      })

      this.doCount();


    }, 1000);

  }

  // 生成加减
  createAddition = () => {

    // 随机生成加减
    let addition = Math.random() > 0.5 ? 'minus' : 'plus';
    if(this.firstInFlag) {
      this.firstInFlag = false;
      addition = 'plus';
    }
    if(this.currentNumber == 0) {
      addition = 'plus';
    }
    if(this.divNum >= 10) {
      addition = 'minus';
    }
    this.currentOpt = addition;
    const symbolInfo1 = this.createSymbol(addition);
    const symbolInfo2 = this.createSymbol(addition);
    
    // console.error(symbolInfo);

    this.setState({
      addition,
      symbolInfo1,
      symbolInfo2,
      number1: symbolInfo1?.number,
      number2: symbolInfo2?.number,
      fen1: symbolInfo1?.fen1,
      fen2: symbolInfo1?.fen2,
      fen3: symbolInfo2?.fen1,
      fen4: symbolInfo2?.fen2
    })

  }

  // 生成计算字符
  createSymbol = (addition) => {
    
    const probabilityList = addition == 'plus' ? plusProbability : minusProbability;

    let probability = Math.random();
    
    let symbolText =  probabilityList[0].symbolText;
    let symbolName = probabilityList[0].name;
   
    for(let i = 0; i < probabilityList.length; i++) {
      const radioItem = probabilityList[i]?.radio;
      probability -= radioItem;
      if(probability <= 0) {
        symbolText = probabilityList[i].symbolText;
        symbolName = probabilityList[i].name;
        break;
      }
    }

    // console.error(symbolText, symbolName);

    return this.createNum({
      symbolName,
      symbolText,
    })

  }

  // 在最大和最小值之间选择一个数字
  createSpecialNum = (min, max) => {
    return Math.floor(Math.random() * (max - min + 1) + min);
  }

  // 生成任意的数字
  createNum = (symbolInfo) => {
    // 这里分几种类型生成 都需要有范围限制
    const { currentNum, addition } = this.state;

    const symbolName = symbolInfo?.symbolName;
    const symbolText = symbolInfo?.symbolText;

    let number = 1;

    let fen1 = 2;
    let fen2 = 1;
    switch(symbolName) {
      case 'plus':
      case 'doublePlus':
        number = this.createSpecialNum(this.min - 1, this.max);
        break;
      case 'minus':
        // const _max = Math.floor(currentNum / 2);
        number = this.createSpecialNum(this.min, Math.min(this.max, this.currentNumber));
        break;
      case 'multiplyZheng':
        number = this.createSpecialNum(1, 9);
        break;
      case 'multiplyFen':
        if(this.currentOpt == 'plus') {
          fen1 = this.createSpecialNum(2, 8);
          if(fen1 == 8) {
            fen2 = 9
          } else {
            fen2 = fen1 + 1
          }
        } else {
          fen1 = this.createSpecialNum(2, 9);
          fen2 = this.createSpecialNum(1, Math.max(1, fen1 - 1));
        }
        console.error("fen1", fen1, "fen2", fen2)
        number = Math.round(fen2 / fen1);
        break;
      case 'percent':
        number = this.createSpecialNum(1, 100);
        break;
      case 'division':
        number = 2;
        break;
      case 'minusDouble':
        number = this.createSpecialNum(0, Math.min(99, Math.floor(this.currentNumber / 2)));
        break;
    }

    return {
      number,
      fen1,
      fen2,
      symbolName,
      symbolText
    };
    

  }

  currentNumber = 1;
  currentOpt = 'plus'
  // 计算数字
  calcNum(symbolName, index) {
    const {currentNum, symbolInfo1, symbolInfo2} = this.state;

    let newNumber1 = this.currentNumber;

    const symbolInfo = index == -1 ? symbolInfo1 : symbolInfo2;

    const operate = this.currentOpt == 'plus' ? 1 : -1;
    // console.warn("operate", operate)
    switch(symbolName) {
      case 'plus':
      case 'minus':
        newNumber1 += symbolInfo?.number * operate;
        break;
      case 'multiplyZheng':
        newNumber1 += symbolInfo?.number * newNumber1 
        break;
      case 'multiplyFen':
        console.error("symonl fen2", symbolInfo?.fen2, "fen1", symbolInfo?.fen1, symbolInfo?.fen2 * newNumber1 / symbolInfo?.fen1)
        newNumber1 = Math.round(symbolInfo?.fen2 * newNumber1 / symbolInfo?.fen1);
        break;
      case 'percent':
        newNumber1 += Math.round(symbolInfo?.number * newNumber1 / 100) * operate ;
        break;
      case 'division':
        newNumber1 = Math.round(newNumber1 / symbolInfo?.number);
        break;
      case 'doublePlus':
      case 'minusDouble':
        newNumber1 += symbolInfo?.number * 2 * operate;
        break;
    }

    return newNumber1;
  }

  canChoose = true
  // 选择数字
  chooseNumber = (index) => {

    if(this.gameOver) return;

    if(!this.canChoose) return
    this.canChoose = false

    const {currentNum, addition, symbolInfo1, symbolInfo2} = this.state;

    let newNumber = this.currentNumber;

    const symbolInfo = index == -1 ? symbolInfo1 : symbolInfo2;

    const operate = addition == 'plus' ? 1 : -1;

    const symbolName1 = symbolInfo1?.symbolName;
    const symbolName2 = symbolInfo2?.symbolName;

    const newNumber1 = this.calcNum(symbolName1, -1);
    const newNumber2 = this.calcNum(symbolName2, 1);
    console.error("左边", newNumber1, "右边", newNumber2)

    // 如果是加法 先判断选择的是不是比另一个大 如果不是那就不用计算了
    let correctIndex = ''
    if(addition == 'plus') {
      correctIndex = newNumber1 > newNumber2 ? -1 : 1;
      if(newNumber1 == newNumber2) {
        correctIndex = index;
      }
      if(correctIndex != index && newNumber1 != newNumber2) {
        console.error("选择错误", correctIndex, index)
        this.setState({
          selectIndex: index,
          correctIndex
        })

        setTimeout(() => {
          this.createAddition();
          this.setState({
            selectIndex: 0,
          })
          this.canChoose = true

        }, 500)

        return
      }
      
    } else {
      correctIndex = index == 1 ? -1 : 1;
    }


    newNumber = index == -1 ? newNumber1 : newNumber2;
    this.currentNumber = newNumber;


    if(this.currentOpt == 'plus' && this.currentNumber > 0) {
      this.divNum++;
    }
    if(this.currentOpt == 'minus' && this.divNum > 1 && this.currentNumber != this.state.currentNum) {
      this.divNum--;
    }

    console.error("divNum", this.divNum)
    // this.createNewElement();
    this.updateNumElementsByOpt(this.currentOpt);

    
    // console.warn("newNumber", this.currentNumber)
    this.setState({
      selectIndex: index,
      currentNum: this.currentNumber,
      correctIndex
    })

    
  }

  currentArr = [{
    top: '3.71rem'
  }]
  lastTop = 3.71;
  divNum = 0;
  // 创建新的元素进行叠加
  createNewElement = () => {

    // const { numElements, currentNumber } = this.state;
    const { numElements, currentNumber } = this.state;

    let newArr = this.currentArr;
   
    
    if(this.currentOpt == 'minus' && this.currentArr.length > 1) {
      this.divNum--;
      newArr = newArr.slice(0, newArr.length - 1);
      console.warn("numElements", newArr, newArr.length - 1)
      this.setState({
        numElements: newArr
      })

      return
    }




    const lastTop = newArr.length > 0 ? parseFloat(newArr[newArr.length - 1].top) : 3.71;
    const newTop = 3.71 - 0.05 * this.divNum;

    console.warn("numElements", newArr, newArr.length - 1, this.divNum)
    console.warn("lastTop", lastTop, "newTop", newTop)
    // 创建一个新的 ref 来存储新元素
    const newElementRef = React.createRef();

    this.setState({
      numElements: [
        ...numElements,
        {
          top: `${newTop}rem`, // 初始位置为上一个元素的 top 位置
          number: this.currentNumber,
          ref: newElementRef // 存储 ref
        }
      ]
    }, () => {
      this.currentArr = this.state.numElements;
    })

    // this.setState(prevState => {
    //   return {
    //     numElements: [
    //       ...prevState.numElements,
    //       {
    //         top: `${newTop}rem`, // 初始位置为上一个元素的 top 位置
    //         number: this.currentNumber,
    //         ref: newElementRef // 存储 ref
    //       }
    //     ]
    //   }
    // })
    // , () => {
    //   // 在 setState 回调中执行动画
    //   this.currentArr = this.state.numElements;
    //   const element = newElementRef.current;
    //   if (element) {
    //     // 设置过渡效果
    //     element.style.transition = 'top 0.1s ease-in-out';
    //     // 延迟一小段时间以确保过渡效果生效
    //     setTimeout(() => {
    //       element.style.top = `${newTop}rem`; // 移动到新的 top 位置
    //       this.lastTop = newTop;
    //     }, 10);
    //   }
    // });
  }

  updateNumElementsByOpt = (opt) => {
    let { numElements } = this.state;
    if (opt === 'minus' && this.currentArr.length > 1 && this.currentNumber != this.state.currentNum) {
      // 如果是 minus 类型且数组长度大于 1，则减少一个元素
      numElements = numElements.slice(0, this.currentArr.length - 1);
      // this.divNum--;
    } else if(opt === 'plus' && this.currentNumber > 0){
      // 否则增加一个元素
      // const lastTop = numElements.length > 0 ? parseFloat(numElements[numElements.length - 1].top) : 3.71;
      const newTop = 3.71 - 0.1 * this.currentArr.length;
      console.warn("newTop", newTop)
      const newElementRef = React.createRef();
      numElements = [
        ...numElements,
        {
          top: `${newTop}rem`,
          number: this.currentNumber,
          ref: newElementRef
        }
      ];
      // this.divNum++;
    }
    this.setState({ numElements }, () => {
      this.currentArr = this.state.numElements;
    });
  }

  handEnd = () => {
    // setTimeout(() => {
      this.createAddition();
      this.canChoose = true
      this.setState({
        selectIndex: 0,
      })

    // }, 500)
  }


  render() {
    const { addition, symbolInfo1, symbolInfo2, selectIndex, currentNum, numElements, seconds, correctIndex, showCountSvga } = this.state;

    // console.error(symbolInfo1, symbolInfo2);

    // console.error(number1, number2);
    return (
      <div className="gamePage" id="gamePage1">
        <div className="bg"></div>
        <div className="countBg">
          <div className="count">{seconds}</div>
        </div>
        {/* <div className="numPaper">
          <div className="number">${currentNum}</div>
        </div> */}
        {/* 渲染新创建的元素 */}
        {numElements.map((element, index) => (
          <div key={index} className={`numPaper ${numElements.length > 1 && index == numElements.length - 1 ? 'moneyAni' : ''}`} ref={element.ref} style={{ top: element.top }}>
            {index == numElements.length - 1 && <div className="number">${currentNum}</div>}
          </div>
        ))}
        <div className="leftNum" onClick={() => this.chooseNumber(-1)}>
          {(correctIndex == selectIndex && selectIndex == -1) && <SvgaPlayer className="rightSvga" src={RES_PATH + "svga/6输出选中动效.svga"} loop={1} onEnd={this.handEnd}/>}
          {(correctIndex != selectIndex && selectIndex == -1) && <SvgaPlayer className="wrongSvga" src={RES_PATH + "svga/7输出选错.svga"} loop={1} onEnd={this.handEnd}/>}
          {/* {selectIndex == -1 && <div className="selected"></div>} */}
          {(addition == 'plus' && symbolInfo1?.symbolName != 'doublePlus' && symbolInfo1?.symbolName != 'minusDouble') && <div className="number1">
            {symbolInfo1?.symbolName != 'multiplyFen' && <div className="text1">{symbolInfo1?.symbolText}{symbolInfo1?.number}{symbolInfo1?.symbolText == '+' ? '%' : ''}</div>}
            {symbolInfo1?.symbolName == 'multiplyFen' && <div className="text2">{symbolInfo1?.symbolText}{symbolInfo1?.symbolText == '+'? '%' : ''}
              <div className="fenBox">
                <div className="fen1">{symbolInfo1?.fen2}</div>
                <div className="fen2">{symbolInfo1?.fen1}</div>
              </div>
            </div>}
          </div>}
          {(addition == 'minus' && symbolInfo1?.symbolName != 'doublePlus' && symbolInfo1?.symbolName != 'minusDouble') && <div className="minusNumber1">
            {symbolInfo1?.symbolName != 'multiplyFen' && <div className="text1">{symbolInfo1?.symbolText}{symbolInfo1?.number}{symbolInfo1?.symbolText == '-' ? '%' : ''}</div>}
            {symbolInfo1?.symbolName == 'multiplyFen' && <div className="text2">{symbolInfo1?.symbolText}{symbolInfo1?.symbolText == '+'? '%' : ''}
              <div className="fenBox">
                <div className="fen1">{symbolInfo1?.fen2}</div>
                <div className="fen2">{symbolInfo1?.fen1}</div>
              </div>
            </div>}
          </div>}
          {(symbolInfo1?.symbolName == 'doublePlus' || symbolInfo1?.symbolName == 'minusDouble') && <div className="twoNum">
            <div className={`left1 ${addition == 'minus' ? 'minusBg' : ''}`}>{symbolInfo1?.symbolText}{symbolInfo1?.number}{(symbolInfo1?.symbolText == '+' || symbolInfo1?.symbolText == '-') ? '%' : ''}</div>
            <div className={`left2 ${addition == 'minus' ? 'minusBg' : ''}`}>{symbolInfo1?.symbolText}{symbolInfo1?.number}{(symbolInfo1?.symbolText == '+' || symbolInfo1?.symbolText == '-') ? '%' : ''}</div>
          </div>}
        </div>
        <div className="rightNum" onClick={() => this.chooseNumber(1)}>
          {(correctIndex == selectIndex && selectIndex == 1) && <SvgaPlayer className="rightSvga" src={RES_PATH + "svga/6输出选中动效.svga"} loop={1} onEnd={this.handEnd}/>}
          {(correctIndex != selectIndex && selectIndex == 1) && <SvgaPlayer className="wrongSvga" src={RES_PATH + "svga/7输出选错.svga"} loop={1} onEnd={this.handEnd}/>}
          {/* {selectIndex == 1 && <div className="selected"></div>} */}
          {(addition == 'plus' && symbolInfo2?.symbolName != 'doublePlus' && symbolInfo2?.symbolName != 'minusDouble') && <div className="number2">
            {symbolInfo2?.symbolName != 'multiplyFen' && <div className="text1">{symbolInfo2?.symbolText}{symbolInfo2?.number}{symbolInfo2?.symbolText == '+' ? '%' : ''}</div>}
            {symbolInfo2?.symbolName == 'multiplyFen' && <div className="text2">{symbolInfo2?.symbolText}{symbolInfo2?.symbolText == '+'? '%' : ''}
              <div className="fenBox">
                <div className="fen1">{symbolInfo2?.fen2}</div>
                <div className="fen2">{symbolInfo2?.fen1}</div>
              </div>
            </div>}
          </div>}
          {(addition == 'minus' && symbolInfo2?.symbolName != 'doublePlus' && symbolInfo2?.symbolName != 'minusDouble') && <div className="minusNumber2">
            {symbolInfo2?.symbolName != 'multiplyFen' && <div className="text1">{symbolInfo2?.symbolText}{symbolInfo2?.number}{symbolInfo2?.symbolText == '-' ? '%' : ''}</div>}
            {symbolInfo2?.symbolName == 'multiplyFen' && <div className="text2">{symbolInfo2?.symbolText}{symbolInfo2?.symbolText == '+'? '%' : ''}
              <div className="fenBox">
                <div className="fen1">{symbolInfo2?.fen2}</div>
                <div className="fen2">{symbolInfo2?.fen1}</div>
              </div>
            </div>}
          </div>}
          {(symbolInfo2?.symbolName == 'doublePlus' || symbolInfo2?.symbolName == 'minusDouble') && <div className="twoNum">
            <div className={`right1 ${addition == 'minus' ? 'minusBg' : ''}`}>{symbolInfo2?.symbolText}{symbolInfo2?.number}{(symbolInfo2?.symbolText == '+' || symbolInfo2?.symbolText == '-') ? '%' : ''}</div>
            <div className={`right2 ${addition == 'minus' ? 'minusBg' : ''}`}>{symbolInfo2?.symbolText}{symbolInfo2?.number}{(symbolInfo2?.symbolText == '+' || symbolInfo2?.symbolText == '-') ? '%' : ''}</div>
          </div>}
        </div>
        {showCountSvga && <div className="count321">
          <SvgaPlayer className='countSvga' src={RES_PATH + "svga/5倒计时.svga"} loop={1} onEnd={() => this.handleStartSvga(false)}/>
        </div>}
      </div>
    );
  }
}

export default GamePage;
