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 TaskPanel from '@/panels/taskPanel/index.jsx';

import { PageCtrl } from '@/core/ctrls/PageCtrl';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import { _asyncThrottle, dateFormatter, formatThousand } from '@/utils/utils';
import NewRecordPage from '../newRecordPage/index.jsx';
import { diffJump, RATE_NAME } from '@/AppTools';
import API from '@/api';
import DetailPage from '../DetailPage/DetailPage';
import MyQradesPage from '../myQradesPage/myqradespage';
import Countdown from '@/core/components/ComCountdown/index.jsx';
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()
    const { canJoinCurrentRank } = store.indexData
    // canJoinCurrentRank true-可以参与当前月度排行榜
    if(canJoinCurrentRank){
      this.setState({
        rankingTab: 0,
      })
      this.getQueryRankInfo(0)
    } else{
      this.setState({
        rankingTab: 1,
      })
      this.getQueryRankInfo(1);
    }
    // 分享页
    // PageCtrl.changePage(SharePage)
    
  }
  // 获取排行榜信息
  getQueryRankInfo = async (type) => { 
    console.log("🚀 ~ HomePage ~ type:", type)
    const {success, code , data , message } = await API.queryRankInfo({type: type});
    if (data) {
      // 格式化收益率
      data.rankInfos.forEach(item => {
        item.score = this.formatProfit(item.score)
      })
      // 格式化我的排名收益率
      data.myRank.score = this.formatProfit(data.myRank.score)
      this.setState({
        rankOptions: data?.rankOptions || [],
        rankInfos: data?.rankInfos || [],
        myRank: data?.myRank || {},
      })
    }
  }

  /** 跳转模拟交易记录 */
  recordHadnle = _asyncThrottle(() => {
    if (!store.judgeActTime()) return
    PageCtrl.changePage(NewRecordPage, { tab: 1 });
  })

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

  /** 规则 */
  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) => {
    const { canJoinCurrentRank } = store.indexData
    if(canJoinCurrentRank == false && type == 0){
      Toast.show('本月不可参与哦～')
      return
    }
    this.setState({ rankingTab: type })
    // 获取排行榜信息
    this.getQueryRankInfo(type);

  }
  // 查看分布按钮
  viewDistribution = (item) => {
   console.log("🚀 ~ HomePage ~ item:", item)
   if(!item || (Object.keys(item).length === 0 && item.constructor === Object)) return
   // 新增 type 0-月榜 1-总榜 
   item.type = this.state.rankingTab
   ModalCtrl.showModal(Positionpop, { item })
  }
  // 赚取模拟理财金
  lcGradeHandle = _asyncThrottle(() => {
    if (!store.judgeActTime()) return
    ModalCtrl.showModal(TaskPanel)
  })
  // 格式化收益率，将原始值除以100
  formatProfit(profit) {
    const num = Number(profit);
    if (num == null) return;
    return (num / 100).toFixed(2);
  }
  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, endPoint, currentTime, productEnd } = 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' : ''}`}>
                {(() => {
                  const filteredRanks = rankInfos.filter(item => item.index && item.index >= 4 && item.index <= 100);
                  return filteredRanks.length > 0 ? (
                    filteredRanks.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}%</span> */}
                        <span className='span-3'>{item.score != null ? (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 className="no_data_hint">暂无数据</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.score}%</span> */}
                <span className='span-3'>{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>
              {/* 展开 */}
              {
                rankInfos.length > 3 &&  <div className='postRanking_expand'>
                 <span className={this.state.isExpand ? 'expandSty-1' : 'expandSty-2'} onClick={() => this.setState({isExpand: !this.state.isExpand})}></span>
              </div>
              }
             
            </div>
          </div>

          {/* 模拟资产 */}
          {!productEnd &&<div className="actual_assets">
            <div className='exchange_record md10' onClick={this.recordHadnle}></div>
            <div className="rate_wrap">
              <div className="yield_rate">
                <div className="yield_rate_label">收益率</div>
                <div className="yield_rate_value">{virtualAssets?.profit ? (+virtualAssets?.profit / 100) : 0}%</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>

            {
              endPoint > currentTime
                ? <Countdown
                  leftT={endPoint - currentTime}
                  renderText={data => {
                    const { day, hour, minute, second } = data
                    return <div className="time_box">
                      理财体验金
                      <span className="time_item">{day}</span>天
                      <span className="time_item">{hour}</span>时
                      <span className="time_item">{minute}</span>分
                      <span className="time_item">{second}</span>秒后到期
                    </div>
                  }}
                  countdownOver={() => store.updateIndex()}
                />
                : <div className="time_box">理财体验金已失效</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>}

          {/* 签到区 */}
          {!productEnd && <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 md9" onClick={this.prizeHandle}></Button>}
          {!productEnd && <Button className='mnlcj-icon md8' onClick={this.lcGradeHandle}></Button>}
        </div>
      </div>
    );
  }
}
export default HomePage;
