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;

  plusNum = 0;

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

  }
  newNumber1 = 0;
  newNumber2 = 0;
  // 生成加减
  createAddition = () => {

    this.leftSymbol = ''
    // 随机生成加减
    let addition = this.plusNum > 7 ? (Math.random() > 0.5 ? 'minus' : 'plus') : 'plus';
    if(this.firstInFlag) {
      this.firstInFlag = false;
      addition = 'plus';
    }

    if(this.currentNumber == 0 || this.currentNumber < 100) {
      addition = 'plus';
    }

    if(this.divNum >= 10) {
      addition = 'minus';
    }

    if(this.currentNumber > 99999) {
      addition ='minus';
    }

    if(addition == 'plus') {
      this.plusNum += 1;
    }


    // console.error("addition", addition, this.plusNum)

    this.currentOpt = addition;
    let symbolInfo1 = this.createSymbol(addition, -1);
    this.leftSymbol = symbolInfo1.symbolName;
    let symbolInfo2 = this.createSymbol(addition, 1);

    // this.newNumber1 = this.calcNum(symbolInfo1.symbolName, -1);
    // this.newNumber2 = this.calcNum(symbolInfo2.symbolName, 1);
    // while (this.newNumber1 === this.newNumber2) {
    //   symbolInfo2 = this.createSymbol(addition, 1);
    //   this.newNumber2 = this.calcNum(symbolInfo2.symbolName, 1);
    // }
    // console.error(symbolInfo1, symbolInfo2);

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

  }

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

    if(this.currentNumber < 20) {
      probabilityList = probabilityList.filter(item => item.name!='division')
    }

    if(this.currentNumber < 600) {
      probabilityList = probabilityList.filter(item => (item.name!='minus' && item.name!='minusDouble'))
    }

    if(pos == 1) {
      probabilityList = probabilityList.filter(item => item.name != this.leftSymbol)
      if(this.leftSymbol == 'division') {
        probabilityList = probabilityList.filter(item => item.name!= 'multiplyFen')
      }

      if(this.leftSymbol == 'multiplyFen') {
        probabilityList = probabilityList.filter(item => item.name!='division')
      }
    }

    // console.error("看看可选的列表", probabilityList, addition, this.leftSymbol, pos == 1 ? '右' : '左');

    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;
        // if(pos == -1) this.leftSymbol = symbolName;
        // console.error("leftSymbol", this.leftSymbol)
        // if(pos == 1 && symbolName == this.leftSymbol) {
        //   if(i == probabilityList.length - 1) {
        //     symbolText = probabilityList[0].symbolText;
        //     symbolName = probabilityList[0].name;
        //   } else {
        //     symbolText = probabilityList[i + 1].symbolText;
        //     symbolName = probabilityList[i + 1].name;
        //   }
        // }
        break;
      }
    }


    // 测试某一种符号
    // if(pos == -1) {
    //  return this.createNum({symbolName: 'percent', symbolText: '%'}, pos);
    // } else {
    //   return this.createNum({symbolName: 'multiplyFen', symbolText: 'x'}, pos);
    // }
   
    return this.createNum({symbolName, symbolText}, pos);

    

  }

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

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

    const symbolName = symbolInfo?.symbolName;
    const symbolText = symbolInfo?.symbolText;
    const operate = this.currentOpt == 'plus' ? 1 : -1;

    const newNum1 = this.calcNum(symbolName, -1);

    let number = 1;

    let fen1 = 2;
    let fen2 = 1;
    switch(symbolName) {
      case 'plus':
      case 'doublePlus':
        number = this.createSpecialNum(this.min, this.max);
        if(pos == 1) {
          let newNum2 = this.currentNumber + number * operate;
          if(symbolName == 'doublePlus') {
            newNum2 = this.currentNumber + number * 2 * operate;
          }
          if(newNum1 == newNum2) {
            number = this.createSpecialNum(this.min, number);
          }
        }
        break;
      case 'minus':
        // const _max = Math.floor(currentNum / 2);
        number = this.createSpecialNum(this.min, Math.min(this.max, this.currentNumber));
        if(pos == 1) {
          let newNum2 = this.currentNumber - number;
          if(newNum1 == newNum2) {
            number = this.createSpecialNum(this.min, number);
          }
        }
        break;
      case 'multiplyZheng':
        number = this.createSpecialNum(2, 4);
        if(pos == 1) {
          let newNum2 = this.currentNumber * number;
          if(newNum1 == newNum2) {
            number = number + 1;
          }
        }
        break;
      case 'multiplyFen':
        if(this.currentOpt == 'plus') {
          fen1 = this.createSpecialNum(2, 7);
          if(fen1 == 7) {
            fen2 = 8
          } 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);

        if(pos == 1) {
          let newNum2 = Math.floor(this.currentNumber * fen2 / fen1);
          if(newNum1 == newNum2) {
            let found1 = false
            if(this.currentOpt == 'plus') {
              for (let f1 = 2; f1 <= 8; f1++) {
                for (let f2 = 3; f2 <= 9; f2++) {
                  const newNum1 = Math.floor(this.currentNumber * f2 / f1);
                  if (newNum2 !== newNum1) {
                    fen1 = f1;
                    fen2 = f2;
                    found1 = true;
                    break;
                  }
                }
                if (found1) break;
              }
            } else {
              let found2 = false
              let newNum2 = Math.floor(this.currentNumber * fen2 / fen1);
              for (let f1 = 2; f1 <= 9; f1++) {
                for (let f2 = 1; f2 < f1; f2++) {
                  const temNum = Math.floor(this.currentNumber * f2 / f1);
                  if (temNum !== newNum2) {
                    fen1 = f1;
                    fen2 = f2;
                    found2 = true;
                    break;
                  }
                }
                if (found2) break;
              }
            }
          }
        }
        break;
      case 'percent':
        number = this.createSpecialNum(1, 100);
        if(pos == 1) {
          let newNum2 = Math.round(this.currentNumber + 1 * operate * number * this.currentNumber / 100);
          if(newNum1 == newNum2) {
            if(number + 10 < 100) {
              number = number + 10;
            } else {
              number = 10
            }
          }
        }

        break;
      case 'division':
        number = 2
        if(pos == 1) {
          let newNum2 = this.currentNumber * number;
          if(newNum1 == newNum2) {
            if(number + 4 < Math.floor(this.currentNumber / 2)) {
              number = number + 4;
            } else {
              number = Math.floor(this.currentNumber / 4)
            }
            
          }
        }
        break;
      case 'minusDouble':
        number = this.createSpecialNum(0, Math.min(99, Math.floor(this.currentNumber / 2)));
        if(pos == 1) {
          let newNum2 = this.currentNumber - number * 2;
          if(newNum1 == newNum2) {
            number = this.createSpecialNum(0, number);
          }
        }
        break;
    }

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

  }

  currentNumber = 1;
  currentOpt = 'plus'
  // 计算数字
  calcNum(symbolName, index, yansuan) {
    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(newNumber1 + 1 * operate * symbolInfo?.number * newNumber1 / 100);
        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;

    let newNumber1 = this.calcNum(symbolName1, -1);
    let newNumber2 = this.calcNum(symbolName2, 1);
    // const newNumber1 = this.newNumber1;
    // const newNumber2 = this.newNumber2;

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

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

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

        }, 500)

        return
      }
      
    } else {
      correctIndex = index == 1 ? -1 : 1;
      store.playWrongSound();
    }


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

    // console.error("newNumber+++", this.currentNumber != this.state.currentNum)

    if(this.currentOpt == 'plus' && this.currentNumber > 0 && this.currentNumber != this.state.currentNum) {
      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);

    if(correctIndex === index) store.playRightSound();
    // 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;
