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 RecordPage from '../RecordPage/RecordPage';
import NewRecordPage from '../newRecordPage/index.jsx';
import { diffJump, RATE_NAME } from '@/AppTools';
import API from '@/api';
import DetailPage from '../DetailPage/DetailPage';
import ResPage from '../ResPage/ResPage';
import Countdown from '@/core/components/ComCountdown/index.jsx';
import ProductListPage from '../productListPage/productListPage';
import PrizePage from "@/pages/PrizePage/PrizePage.tsx";
import { NewbieModal } from '@/panels/newbieModal/newbieModal';
import SignCom from '@/panels/signCom/signCom.jsx';
import { SvgaPlayer } from '@grace/svgaplayer';
import redFenwei from '../../assets/svga/redFenwei.svga';
import RedPackCountPanel from '@/panels/redPackCountPanel/index.jsx';

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

  root: HTMLDivElement;

  state = {
    rankingTab: 1,
    curTab: 1, // 1-产品列表 2-我的持仓
    unlockObj: {
      prizeImg: '',
      unlockedPrizeImg: ''
    },
    order: 0,
    backOrder: 1,
    // 理财排行榜-奖品列表
    rankOptions: [
       {
        ranking: 1, //排名	
        name: '100元', //奖品名称	
        image: '', //图片	
       },
        {
        ranking: 2, //排名	
        name: '100元', //奖品名称	
        image: '', //图片	
       },
        {
        ranking: 3, //排名	
        name: '100元', //奖品名称	
        image: '', //图片	
       }, {
        ranking: 4, //排名	
        name: '100元', //奖品名称	
        image: '', //图片	
       }
    ],
    // 理财排行榜-用户信息
    rankInfos:[
        {
          index: 1, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId: 1, //用户id	
          score: 43.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 2, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 33.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 3, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 23.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 4, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 13.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 5, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 3.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 6, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 43.18, //收益率	
          meFlag: false //是否是我，为true是
        },
        {
          index: 7, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 43.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 8, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 43.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 9, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 43.18, //收益率	
          meFlag: false //是否是我，为true是
        },
         {
          index: 10, //排名,null表示未上榜，前端判断大于等于100，展示99+	
          userName:'136xxxx7894', // 用户名	
          userId:1, //用户id	
          score: 43.18, //收益率	
          meFlag: false //是否是我，为true是
        }
    ],
    // 理财排行榜-我的排名
    myRank:{
      index: 99, //排名,null表示未上榜，前端判断大于等于100，展示99+	
      userName:'136xxxx7894', // 用户名	
      userId:1, //用户id	
      score: 43.18, //收益率	
    },
    isExpand: false,
  };
  lockArr = [];

  async componentDidMount() {
    await store.judgeIsWhiteUser();
    const { bigStartConfig, virtualAssets } = store.indexData;

    const lockArr = (bigStartConfig || []).filter(el => {
      // 待解锁
      return Number((virtualAssets?.totalIncome || 0) / 100) < el.min;
    });
    const unlockArr = (bigStartConfig || []).filter(el => {
      // 已解锁
      return !(Number((virtualAssets?.totalIncome || 0) / 100) < el.min);
    });

    lockArr.sort((a, b) => {
      return a.max - b.max
    })
    unlockArr.sort((a, b) => {
      return b.max - a.max
    })
    this.lockArr = lockArr;

    this.setState({
      unlockObj: unlockArr[0],
      order: lockArr.length - 1,
      backOrder: lockArr.length - 2,
    })
    this.updateIndex();
  }
  // 更新红包轮播索引
  timer = null;
  updateIndex = () => {
    this.timer = setTimeout(() => {
      this.timer && clearTimeout(this.timer)
      const len = this.lockArr.length;
      let num = this.state.order - 1;
      num = num < 0 ? len - 1 : num;
      const backNum = num - 1 < 0 ? len - 1 : num - 1;
      this.setState({
        order: num,
        backOrder: backNum,
      })
      this.updateIndex();
    }, 3000)
  }
  /** 跳转模拟交易记录 */
  recordHadnle = _asyncThrottle(() => {
    if (!store.judgeActTime()) return
    PageCtrl.changePage(NewRecordPage, { tab: 1 });
  })


  /** 真实买入 */
  realBuyHandle = _asyncThrottle(() => {
    if (!store.judgeActTime()) return
    const { realBuyJumpUrl } = store.indexData?.virtualAssets || {}
    if (realBuyJumpUrl) {
      diffJump(realBuyJumpUrl)
    } else {
      // 没有链接 就跳产品列表页
      PageCtrl.changePage(ProductListPage)
    }
  })

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

  /** 跳转“真实”产品详情页 */
  jumpRealDetailHandle = _asyncThrottle((item) => {
    if (!store.judgeActTime()) return
    const { curTab } = this.state
    if (curTab != 2) return false
    // 我的持仓才可以跳转
    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(true, false)) return
    // TODO
    const { giftPop } = store.indexData;
    ModalCtrl.showModal(NewbieModal, { type: giftPop?.type, actPrizeVO: giftPop?.actPrizeVO })
  })
  // 倒计时
  countDownFun = _asyncThrottle(() => {
    if (!store.judgeActTime(true, false)) return
    ModalCtrl.showModal(RedPackCountPanel)
  })
  /** 跳转结果页 */
  prizeHandle = _asyncThrottle(() => {
    if (!store.judgeActTime(true, false)) return
    PageCtrl.changePage(ResPage)
  })

  /** 已签到 */
  signedHandle = _asyncThrottle(async () => {
    if (!store.judgeActTime()) return
    Toast.show("今日已签到")
  })

  /** 签到 */
  signHandle = _asyncThrottle(async () => {
    if (!store.judgeActTime()) return
    const { success } = await API.doCheckIn();
    if (success) {
      Toast.show("签到成功")
    }
    await store.updateIndex();
  })

  /** 签到-领奖 */
  signPrizeHandle = _asyncThrottle(async (item) => {
    // 已领奖
    if (item.status) return false

    // 未签到
    const { checkIn } = store.indexData
    if (item.days > checkIn?.totalCheckIn) return false

    if (!store.judgeActTime()) return
    const { endPoint, currentTime } = store.indexData || {}
    if (endPoint <= currentTime) {
      Toast.show("模拟理财已结束～")
      return false
    }
    const { success } = await API.doRewards({ checkInConfigId: item.id });
    if (success) {
      Toast.show("领取成功")
    }
    await store.updateIndex();
  })

  /** 切换tab */
  toggleTab = async (type) => {
    this.setState({ curTab: type })
  }
  // 理财排行榜切换
  rankingTab_click = async (type) => {
    this.setState({ rankingTab: type })
  }
  // 查看分布按钮
  viewDistribution = (item) => {
   console.log("🚀 ~ HomePage ~ item:", item)
   ModalCtrl.showModal(Positionpop, { item })
  }
  settleMoney = (num) => {
    return formatThousand((num / 100).toFixed(2))
  }
 
  componentWillUnmount(): void {
    clearTimeout(this.timer);
    /*
    clearTimeout(store.leftOpenId);
    store.leftOpenId = null;
    store.leftOpenTime = 0;
    */
  }

  /*
  getRedCountDown(redRainConfig) {
    const now = new Date().getTime();
    const today = dateFormatter(new Date(), 'yyyy-MM-dd');
    const timeArr = redRainConfig.map(el => {
      return {
        ...el,
        start: new Date(today + " " + el.startTime).getTime(),
        end: new Date(today + " " + el.endTime).getTime(),
      }
    })
    // 按照开始时间排序
    timeArr.sort((a, b) => {
      return a.start - b.start;
    })
    const el = timeArr.find(el => {
      return now >= el.start && now <= el.end;
    })
    if (el && !el.joinStatus) {
      return 0;
    } else {
      const next = timeArr.find(el => {
        return now < el.start;
      });
      if (!next) {
        return 0
      } else {
        return next.start - now
      }
    }
  }
  */
  render() {
    const { curTab, rankingTab, rankOptions, rankInfos, myRank } = this.state;
    const { bigStartConfig, virtualAssets, checkIn, recommendProductConfig, productEnd, endPoint, currentTime, redRainConfig, giftPop } = store.indexData
    /*
    const redDownTime = this.getRedCountDown(redRainConfig || []);
    */
    const redDownTime = redRainConfig?.haveNext ? redRainConfig?.nextRainBeginTime - currentTime : 0;
    // 推荐产品
    const rProductList = recommendProductConfig?.filter((item) => +item.status === 0)
    // 我的持仓
    const mProductList = recommendProductConfig?.filter((item) => item.mineProduct)
    // 当前tab的产品列表
    const curTabProductList = curTab == 1 ? recommendProductConfig : mProductList


    const { unlockObj, order, backOrder } = this.state;
    const lockArr = this.lockArr;

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

          {/* {productEnd && <div className="prize_banner">
            <span className="prize_btn" onClick={this.prizeHandle}></span>
          </div>} */}

          {/* 签到区 */}
          {/* {!productEnd && <SignCom></SignCom>} */}
          {/* 模拟资产 */}
          {/* <div className="virtual_assets short_height">
            {
              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_over">理财体验金已失效</div>
            }
            <span className="yesterday_label">累计收益(元)</span>
            <span className="yesterday_amount">{this.settleMoney(virtualAssets?.totalIncome || 0)}</span>
            <div className="record_btn" onClick={this.recordHadnle}>
            </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_assets2">
                <span className="other_assets_label">可用资金</span>
                <span className="other_assets_value">{this.settleMoney(virtualAssets?.availableFunds || 0)}</span>
              </div>
              <div className="other_assets3">
                <span className="other_assets_label">昨日收益</span>
                <span className="other_assets_value">{this.settleMoney(virtualAssets?.preDayIncome || 0)}</span>
              </div>
            </div>
            <div className="canuse_popover">
              <span className="canuse_popover_bg"></span>
              <span className="canuse_popover_text"></span>
            </div>
          </div> */}
          {/* 理财排行榜 */}
          <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 == 1 ? "rankingActive" : ""} onClick={() => this.rankingTab_click(1)}>月榜</span>
                <span className={rankingTab == 2 ? "rankingActive" : ""} onClick={() => this.rankingTab_click(2)}>总榜</span>
            </div>
            {/* 月榜奖品列表 */}
            { rankingTab == 1 && <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 == 2 && <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}%</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}%</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}%</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)
                  .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-4' onClick={() => this.viewDistribution(item)}></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.score}%</span>
                <span className='span-4' onClick={() => this.viewDistribution(myRank)}></span>
              </div>
              {/* 展开 */}
              <div className='postRanking_expand'>
                 <span 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">3.5%</div>
              </div>
              <div className="yesterday_amount">
                <div className="yesterday_amount_label">昨日收益</div>
                <div className="yesterday_amount_value">102.32</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?.preDayIncome || 0)}</span>
              </div>
            </div>
            <div className="canuse_popover">
              <span className="canuse_popover_bg"></span>
            </div>
          </div>

          {/* 推荐产品 */}
          {!!rProductList?.length && <div className="recommend_products">
            <span className="recommend_products_bg">
              <div className="r_products_list">
                {rProductList?.map((item, index) => (
                  <div className="r_products_item" key={`r_prdct_${index}`}>
                    <span className="r_product_bg"></span>
                    <span className="r_product_name">{item.name}</span>
                    {!!item.rate && <span className="r_product_risk">{(item.rate / 100).toFixed(2)}%</span>}
                    <span className="r_product_rate">{RATE_NAME[item.type] || '年化收益率'}</span>
                    <Button className="detail_btn" onClick={() => this.jumpVirtualDetailHandle(item)}></Button>
                    <div className="r_product_like">
                      <span className="r_product_like_text">{item.baiFenBiText}</span>
                    </div>
                  </div>
                ))}
              </div>
            </span>
            {/* <span className="r_products_title"></span> */}

          </div>}
          <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" onClick={this.ruleHandle} />
          <Button className="prize_btn" onClick={this.reallyPrizeHandle} />
          {/* 其他icon */}
          <Button className="new-user-gift-icon"></Button>
          <Button className="finance-achievement-icon"></Button>
          {giftPop && <Button className="newUser_btn" onClick={this.newUserFun} />}
        </div>
      </div>
    );
  }
}
export default HomePage;
