import React from 'react';
import { observer } from 'mobx-react';
import './HomePage.less';
import store from "@/store/store.ts";
import { Button, Toast } from "@grace/ui";
import Rulepop from '@/panels/rulepop/rulepop';
import Positionpop from '@/panels/positionpop/positionpop';
import { PageCtrl } from '@/core/ctrls/PageCtrl';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import { _asyncThrottle, dateFormatter, formatThousand } from '@/utils/utils';
import { diffJump, RATE_NAME } from '@/AppTools';
import API from '@/api';
import MyQradesPage from '../myQradesPage/myqradespage';
import PrizePage from "@/pages/PrizePage/PrizePage.tsx";
import SignCom from '@/panels/signCom/signCom.jsx';
import SetupSuccessPop from '@/panels/setupSuccessPop';

@observer
class HomePage extends React.Component<any, any> {

  root: HTMLDivElement;

  state = {
    rankingTab: 0,   // 0-月榜 1-总榜 
    curTab: 1, // 1-产品列表 2-我的持仓
    unlockObj: {
      prizeImg: '',
      unlockedPrizeImg: ''
    },
    order: 0,
    backOrder: 1,
    // 理财排行榜-奖品列表
    rankOptions: [],
    // 理财排行榜-用户信息
    rankInfos:[],
    // 理财排行榜-我的排名
    myRank:{
      index: 0,
      userName: '',
      score: 0,
    },
    isExpand: false,
  };

  async componentDidMount() {
    // 确保索引数据更新完成后再获取排行榜信息
    await store.updateIndex();
    // 获取排行榜信息
    this.getQueryRankInfo(this.state.rankingTab);
  }
  // 获取排行榜信息
  getQueryRankInfo = async (type) => { 
    console.log("🚀 ~ HomePage ~ type:", type);
    try {
      // 先重置数据，避免切换时显示旧数据
      this.setState({
        rankOptions: [],
        rankInfos: [],
        myRank: {},
      });
      
      const {success, code , data , message } = await API.queryRankInfo({type: type});
      
      // 检查API调用是否成功且有数据
      if (success && data) {
        this.setState({
          rankOptions: data?.rankOptions || [],
          rankInfos: data?.rankInfos || [],
          myRank: data?.myRank || {},
        });
      } else {
        console.warn("获取排行榜数据失败:", message || "未知错误");
      }
    } catch (error) {
      console.error("查询排行榜信息时发生错误:", error);
    }
  }

  /** 跳转“模拟”产品详情页 */
  jumpVirtualDetailHandle = _asyncThrottle((item) => {
    if (!store.judgeActTime()) return
    // PageCtrl.changePage(DetailPage, item)
    diffJump(item.realBuyJumpUrl)
  })

  /** 规则 */
  ruleHandle = _asyncThrottle(() => {
    if (!store.judgeActTime(true, false)) return
    ModalCtrl.showModal(Rulepop)
  })

  reallyPrizeHandle = _asyncThrottle(() => {
    if (!store.judgeActTime(true, false)) return
    PageCtrl.changePage(PrizePage)
  })

  // 新手礼包
  newUserFun = _asyncThrottle(() => {
    if (!store.judgeActTime()) return
    ModalCtrl.showModal(SetupSuccessPop)
  })
  /** 跳转结果页 */
  prizeHandle = _asyncThrottle(() => {
    if (!store.judgeActTime(true, false)) return
    PageCtrl.changePage(MyQradesPage)
  })

  /** 切换tab */
  toggleTab = async (type) => {
    this.setState({ curTab: type })
  }
  // 理财排行榜切换
  rankingTab_click = async (type) => {
    this.setState({ rankingTab: type })
    // 获取排行榜信息
    this.getQueryRankInfo(type);
  }
  // 查看分布按钮
  viewDistribution = (item) => {
   console.log("🚀 ~ HomePage ~ item:", item)
  if (!store.judgeActTime()) return
   // 新增 type 0-月榜 1-总榜 
   item.type = this.state.rankingTab
   ModalCtrl.showModal(Positionpop, { item })
  }

  settleMoney = (num) => {
    return formatThousand((num / 100).toFixed(2))
  }

  handleClickBanner = _asyncThrottle((item) => { 
    if (!store.judgeActTime()) return
    location.href = item.bannerLink;
  })

  componentWillUnmount(): void {
  }

  render() {
    const { curTab, rankingTab, rankOptions, rankInfos, myRank } = this.state;
    const { virtualAssets, recommendProductConfig, giftPop, bannerInfo, lcGradeIcon } = store.indexData
    // 我的持仓
    const mProductList = recommendProductConfig?.filter((item) => item.mineProduct)
    // 当前tab的产品列表
    const curTabProductList = curTab == 1 ? recommendProductConfig : mProductList

    return (
      <div className="com_Container" ref={(el) => this.root = store.homeRoot = el}>
        <div className="homePage md4">
          <span className="bg"></span>

          {/* 理财排行榜 */}
          <div  className={`ranking_list ${this.state.isExpand ? 'expandSty1' : ''}`}>
            <div className="ranking_list_title">
              <span></span>
            </div>
            {/* tab切换 */}
            <div className="ranking_list_tab">
                <span className={rankingTab == 0 ? "rankingActive" : ""} onClick={() => this.rankingTab_click(0)}>月榜</span>
                <span className={rankingTab == 1 ? "rankingActive" : ""} onClick={() => this.rankingTab_click(1)}>总榜</span>
            </div>
            {/* 月榜奖品列表 */}
            { rankingTab == 0 && <div className='ranking_list_prize'>
                 {
                  rankOptions?.map((item, index) => (
                    <div className="ranking_list_prize_item" key={`ranking_prize_${index}`}>
                      <div className="item_img">
                        <img className="img" src={item.image}/>
                        <span className="item_img_rank">
                          第{item.ranking}名
                        </span>
                      </div>
                     
                      <div className="item_name">
                        {item.name}
                      </div>
                    </div>
                  ))
                 }
               </div>
            }
            {/* 总榜奖品列表 */}
            { rankingTab == 1 && <div className='ranking_list_prizeT'>
                  {
                    rankOptions?.map((item, index) => (
                      <div className="ranking_list_prize_item" key={`ranking_prize_${index}`}>
                        <div className="item_img">
                          <img className="img" src={item.image}/>
                          <span className="item_img_rank">
                            第{item.ranking}名
                          </span>
                        </div>
                      
                        <div className="item_name">
                          {item.name}
                        </div>
                      </div>
                    ))
                  }
              </div>
            }
            {/* 前三名 */}
            <div className='ranking_list_topThree'>
               {/* 第二名 */}
               <div className='topThree-2'>
                   <span className='userName'>{rankInfos?.[1]?.userName || '-'} </span>
                   <span className='score'>{rankInfos?.[1]?.score != null ? (rankInfos[1].score > 0 ? `+${rankInfos[1].score}` : rankInfos[1].score) : '-'}%</span>
                  <span className='topThree-2_btn btn-bg2' onClick={() => this.viewDistribution(rankInfos?.[1] || {})}></span>
               </div>
              
               {/* 第三名 */}
               <div className='topThree-3'>
                 <span className='userName'>{rankInfos?.[2]?.userName || '-'} </span>
                  <span className='score'>{rankInfos?.[2]?.score != null ? (rankInfos[2].score > 0 ? `+${rankInfos[2].score}` : rankInfos[2].score) : '-'}%</span>    
                 <span className='topThree-3_btn btn-bg2' onClick={() => this.viewDistribution(rankInfos?.[2] || {})}></span>
               </div>
                {/* 第一名 */}
               <div className='topThree-1'>
                 <span className='userName'>{rankInfos?.[0]?.userName || '-'} </span>
                 <span className='score'>{rankInfos?.[0]?.score != null ? (rankInfos[0].score > 0 ? `+${rankInfos[0].score}` : rankInfos[0].score) : '-'}%</span>
                 <span className='topThree-1_btn btn-bg1' onClick={() => this.viewDistribution(rankInfos?.[0] || {})}></span>
               </div>
            </div>
            {/* 第四名以后以及我的排名 */}
            <div className={`ranking_list_postRanking ${this.state.isExpand ? 'expandSty2' : ''}`}>
              <div className='postRanking_title'>
                <span className='span-1'>排名</span>
                <span className='span-2'>用户信息</span>
                <span className='span-3'>收益率</span>
                <span className='span-4'>持仓分布</span>
              </div>
              <div className={`postRanking_item_box ${this.state.isExpand ? 'expandSty3' : ''}`}>
                {rankInfos
                  .filter(item => item.index && item.index >= 4 && item.index <= 100)
                  .filter(item => this.state.isExpand || item.index === 4 || item.index === 5) // 收起状态下显示第4名和第5名
                  .map((item, index) => (
                    <div key={`rank_${item.index}`} className={`postRanking_item`}>
                      <span className='span-1'>{item.index}</span>
                      <span className='span-2'>{item.userName}</span>
                      <span className='span-3'>{item.score > 0 ? `+${item.score}` : item.score}%</span>
                      <span className='span-4' onClick={() => this.viewDistribution(item)}>
                        <span className='span-4-1'></span>
                      </span>
                    </div>
                  ))
                }
              </div>
              {/* 我的排名 */}
              <div className='postRanking_myRanking'>
                <span className='span-1'>{myRank.index == null ? '未上榜' : myRank.index > 100 ? '99+' : myRank.index}</span>
                <span className='span-2'>{myRank.userName}（我）</span>
                <span className='span-3'>{myRank && myRank.score != null ? (myRank.score > 0 ? `+${myRank.score}` : myRank.score) : '-'}%</span>
                <span className='span-4' onClick={() => this.viewDistribution(myRank)}>
                   <span className='span-4-1'></span>
                </span>
              </div>
              {/* 展开 */}
              <div className='postRanking_expand'>
                 <span className={this.state.isExpand ? 'expandSty-1' : 'expandSty-2'} onClick={() => this.setState({isExpand: !this.state.isExpand})}></span>
              </div>
            </div>

          </div>

          {/* 真实持仓 */}
          <div className="actual_assets">
            <div className="rate_wrap">
              <div className="yield_rate">
                <div className="yield_rate_label">收益率</div>
                <div className="yield_rate_value">{virtualAssets?.profit || '-'}%</div>
              </div>
              <div className="yesterday_amount">
                <div className="yesterday_amount_label">昨日收益</div>
                <div className="yesterday_amount_value">{this.settleMoney(virtualAssets?.preDayIncome || 0)}</div>
              </div>
            </div>
            <div className="other_assets">
              <div className="other_assets1">
                <span className="other_assets_label">总资产</span>
                <span className="other_assets_value">{this.settleMoney(virtualAssets?.totalMoney || 0)}</span>
              </div>
              {/* <div className='other_line1'></div> */}
              {/* <div className="other_assets2">
                <span className="other_assets_label">可用资金</span>
                <span className="other_assets_value">{this.settleMoney(virtualAssets?.availableFunds || 0)}</span>
              </div> */}
              <div className='other_line2'></div>
              <div className="other_assets3">
                <span className="other_assets_label">累计收益</span>
                <span className="other_assets_value">{this.settleMoney(virtualAssets?.totalIncome || 0)}</span>
              </div>
            </div>
            <div className="canuse_popover">
              <span className="canuse_popover_bg"></span>
            </div>
          </div>

          {/* banner */}
          {!!bannerInfo?.length && <div className="recommend_products">
            <span className="recommend_products_bg">
              <div className="r_products_list">
                {bannerInfo?.map((item, index) => (
                  <div className="r_products_item" key={`r_prdct_${index}`} onClick={() => this.handleClickBanner(item)}>
                    <img className="r_product_bg" src={item.bannerImg} alt="" />
                  </div>
                ))}
              </div>
            </span>
          </div>}

          {/* 签到区 */}
          <SignCom></SignCom>

          {/* 产品列表 */}
          <div className="bottom_products">
            {curTab == 1 && <span className="tab1_bg"></span>}
            {curTab == 2 && <span className="tab2_bg"></span>}
            <span className="tab1_btn" onClick={() => this.toggleTab(1)}></span>
            <span className="tab2_btn" onClick={() => this.toggleTab(2)}></span>
            <div className="products_list">
              {curTabProductList?.map((item, index) => (
                <div className="b_product_item" key={`r_prdct_${index}`}>
                  <span className="b_product_name">{item.name}</span>
                  {curTab == 2
                    ? <>
                      <div className="b_product_rate">
                        <span className="b_product_rate_value">{this.settleMoney(item.totalProfit || 0)}</span>
                        <span className="b_product_rate_label">累计收益</span>
                      </div>
                      <div className="b_product_shu">
                        <span className="b_product_shu_value">{this.settleMoney(item.positionMoney || 0)}</span>
                        <span className="b_product_shu_label">持仓金额</span>
                      </div>
                    </>
                    : <>
                      <div className="b_product_rate">
                        {!!item.rate && <span className="b_product_rate_value">{(item.rate / 100).toFixed(2)}%</span>}
                        <span className="b_product_rate_label">{RATE_NAME[item.type] || '年化收益率'}</span>
                      </div>
                      <div className="b_product_shu">
                        <span className="b_product_shu_value">{item.shenShuGuiZei}</span>
                        <span className="b_product_shu_label">{item.fengXian} ｜ {item.qigouText}</span>
                      </div>
                    </>
                  }
                  <Button className="detail_btn_1" onClick={() => this.jumpVirtualDetailHandle(item)}></Button>
                  <span className="b_product_line"></span>
                </div>
              ))}
            </div>
            {!curTabProductList?.length && curTab == 2 && <div className="empty">暂无持仓产品哦</div>}
          </div>

          <Button className="rule_btn md5" onClick={this.ruleHandle} />
          <Button className="prize_btn md6" onClick={this.reallyPrizeHandle} />
          {/* 其他icon */}
          {giftPop?.show && <Button className="new-user-gift-icon md7" onClick={this.newUserFun}></Button>}
          {lcGradeIcon &&<Button className="finance-achievement-icon md8" onClick={this.prizeHandle}></Button>}
        </div>
      </div>
    );
  }
}
export default HomePage;