import React, { useState, useEffect } from "react";
import styles from "./index.module.scss";
import { useNavigate } from "react-router-dom";
import { getRankList, RankItem, RankDescItem, saveScore } from "../../../utils/API";
interface ResultProps {
  timeLeft: number;
  rightCount: number;
}

// 对数据进行排序
const getRankDesc = (rankList: RankItem[], rightCount: number, exhauseTime: number) => {
  const rankArr: RankDescItem[] = rankList.map(item => {
    return { score: item.score, time: item.time, rank: -1, isCurrentUser: false }
  })
  rankArr.push({ score: rightCount, time: exhauseTime, rank: -1, isCurrentUser: true })
  rankArr.sort((a, b) => {
    if (a.score !== b.score) {
      // 得分不同时，得分高的排在前面
      return b.score - a.score;
    } else {
      // 得分相同时，花费时间少的排在前面
      return a.time - b.time;
    }
  });
  // 为排序后的数据添加排名信息
  rankArr.forEach((item, index) => {
    item.rank = index + 1;
  });

  return rankArr
}

const Result = ({ timeLeft, rightCount }: ResultProps) => {
  const navigate = useNavigate()
  const [nickname, setNickname] = useState("")
  const [phone, setPhone] = useState("")
  const [isShowTips, setIsShowTips] = useState(true)
  const exhausetime = 180 - timeLeft
  const [rankDesc, setRankDesc] = useState<RankDescItem[]>([])

  const handleInputChange = () => {
    if ((nickname.length > 5 || nickname.length === 0) || (phone.length > 20 || phone.length === 0)) {
      setIsShowTips(true)
    } else {
      setIsShowTips(false)
    }
  }

  const handleRank = () => {
    if (!isShowTips) {
      saveScore({
        name: nickname,
        phone: phone,
        score: rightCount * 10,
        time: exhausetime
      }).then(() => {
        navigate("/rank", { state: { noRank: false } })
      })
      return
    }
    if (isShowRank) {
      navigate("/rank", { state: { noRank: true } })
      return
    }
  }
  const [isShowRank, setIsShowRank] = useState(true)
  useEffect(() => {
    getRankList().then(res => {
      setRankDesc(res.data.data)
      let rankData = res.data.data
      setIsShowRank((rankData[rankData.length - 1].score > rightCount * 10) || (rankData[rankData.length - 1].score === rightCount * 10 && rankData[rankData.length - 1].time < exhausetime) ? true
        : false)
    })
  }, [exhausetime, rightCount])
  console.log(rankDesc)
  return (
    <div className={styles.infomation}>
      <div className="title">恭喜您！
      </div>
      <div className="content">
        共答对 <span>{rightCount}</span> 道题，耗时 <span>{exhausetime}</span> 秒。{isShowRank ? "未进入排行榜" : "恭喜您进入当前答题排行榜前十名！"}
      </div>
      <div className="from" style={{ display: isShowRank ? "none" : "flex" }}>
        <input value={nickname} onChange={(e) => setNickname(e.target.value)} onBlur={handleInputChange} type="text" placeholder="请输入昵称，不超过5个字" />
        <input value={phone} onChange={(e) => setPhone(e.target.value)} onBlur={handleInputChange} type="text" placeholder="请输入联系方式，不超过20个字" />
      </div>
      <div className="content2">
        游戏规则：答对更多题目耗时更少的前五名 将在展览结束后赠送文创书签纪念品。
      </div>
      <div className="tips" style={{ display: isShowTips && !isShowRank ? "block" : "none" }}>您未填写昵称和联系方式，无法参与此次活动</div>
      <div className="tips" style={{ display: !isShowTips && !isShowRank ? "block" : "none" }}>点击查看排行榜参与排名</div>
      <div className="btn-group">
        <div className={isShowRank ? "item" : "backHome"} onClick={() => navigate("/")}>返回首页</div>
        <div className="item" onClick={handleRank}>查看排行榜</div>
      </div>
      <div className="back" onClick={() => navigate("/")}><img src={require("../../../assets/img/back.png")} alt="" /></div>

    </div >
  );
};

export default Result;
