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';

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:59'
    // fen1: 1,
    // fen2: 1,
    // fen3: 1,
    // fen4: 1,
    // number1: 0,
    // number2: 0
  }

  componentDidMount() {
    
    this.createAddition();
    if(store.startInfo?.guide) {
      modalStore.pushPop("GuideModal", {doCount: this.doCount})
    } else {
      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}`
      })


    }, 1000);

  }

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

    // 随机生成加减
    let addition = Math.random() > 0.5 ? 'minus' : 'plus';
    if(this.firstInFlag) {
      this.firstInFlag = false;
      addition = 'plus';
    }
    if(this.currentNumber == 0) {
      addition = 'plus';
    }
    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, currentNum));
        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));
        }

        number = fen2 / fen1;

        // if(this.currentOpt == 'plus') {
        //   fen1 = this.createSpecialNum(2, 8);
          
        //   if(fen1 == 8) {
        //     fen2 = 9
        //   } else {
        //     const fenMin = Math.min(8, fen1 + 1);
        //     const fenMax = 9;
        //     fen2 = this.createSpecialNum(fenMin , fenMax);
        //   }
        //   number = fen2 / fen1;
        // } else {
        //   fen1 = this.createSpecialNum(2, 9);
        //   fen2 = this.createSpecialNum(1, Math.max(1, fen1 - 1));
        //   number = fen2 / fen1;
        // }
        break;
      case 'percent':
        number = this.createSpecialNum(1, 100);
        break;
      case 'division':
        number = 2;
        break;
      // case 'multiplyFen':
      //   fen1 = this.createSpecialNum(2, 9);
      //   fen2 = this.createSpecialNum(1, Math.max(1, fen1_m - 1));
      //   number = fen2 / fen1;
      //   break;
      case 'minusDouble':
        // const _maxD = Math.floor(currentNum / 4);
        // number = this.createSpecialNum(0, _maxD);
        number = this.createSpecialNum(0, Math.min(99, Math.floor(currentNum / 2)));
        break;

    }

    // console.error(number);


    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':
        newNumber1 += Math.round(symbolInfo?.fen2 / symbolInfo?.fen1 * newNumber1) * operate;
        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);

    // 如果是加法 先判断选择的是不是比另一个大 如果不是那就不用计算了
    if(addition == 'plus') {
      const correctIndex = newNumber1 > newNumber2 ? -1 : 1;

      if(correctIndex != index && newNumber1 != newNumber2) {
        this.setState({
          selectIndex: index,
        })

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

        return
      }
      
    }

    console.warn("左边", newNumber1, "右边", newNumber2)

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


    if(this.currentOpt == 'plus' && this.currentNumber > 0) {
      this.divNum++;
      this.createNewElement();
    }
    
    console.warn("newNumber", this.currentNumber)
    this.setState({
      selectIndex: index,
      currentNum: this.currentNumber,
    })

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

  lastTop = 3.71;
  divNum = 0;
  // 创建新的元素进行叠加
  createNewElement = () => {
    // const { numElements, currentNumber } = this.state;
    const { numElements, currentNumber } = this.state;
    const lastTop = numElements.length > 0 ? parseFloat(numElements[numElements.length - 1].top) : 3.71;
    const newTop = 3.71 - 0.05 * this.divNum;

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

    this.setState(prevState => ({
      numElements: [
        ...prevState.numElements,
        {
          top: `${this.lastTop}rem`, // 初始位置为上一个元素的 top 位置
          number: this.currentNumber,
          ref: newElementRef // 存储 ref
        }
      ]
    }), () => {
      // 在 setState 回调中执行动画
      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);
      }
    });
    // this.setState({
    //   numElements: [
    //     ...numElements,
    //     {
    //       top: 3.71 - 0.02 * this.divNum + 'rem',
    //       number: this.currentNumber
    //     }
    //   ]
    // });
    // this.divNum++;
  }


  render() {
    const { addition, symbolInfo1, symbolInfo2, selectIndex, currentNum, numElements } = 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">{currentNum}</div>
        </div>
        {/* <div className="numPaper">
          <div className="number">${currentNum}</div>
        </div> */}
        {/* 渲染新创建的元素 */}
        {numElements.map((element, index) => (
          <div key={index} className="numPaper" ref={element.ref} style={{ top: element.top }}>
            {index == numElements.length - 1 && <div className="number">${currentNum}</div>}
          </div>
        ))}
        <div className="leftNum" onClick={() => this.chooseNumber(-1)}>
          {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">{symbolInfo2?.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)}>
          {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>
      </div>
    );
  }
}

export default GamePage;
