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 { 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 mainPageTitle from '../../assets/svga/mainPageTitle.svga';
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 = {
    curTab: 1, // 1-产品列表 2-我的持仓
    unlockObj: {
      prizeImg: '',
      unlockedPrizeImg: ''
    },
    order: 0,
    backOrder: 1,
  };
  lockArr = [];

  async componentDidMount() {
    await store.updateIndex();
    // 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 })
  }


  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 } = 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 md4"></span>

          <span className="title"></span>
          {/* <SvgaPlayer className="title" src={mainPageTitle}></SvgaPlayer> */}

          {/* 红包区域 */}
          <div className='red-pack-con'>
            {
              lockArr.length > 0 ? <div className='left-right'>
                <div className='left'>
                  {lockArr.length === 1 && <div className={`red-pack-item`}>
                    <img src={lockArr[0].prizeImg}></img>
                  </div>}
                  {
                    lockArr.length > 1 && lockArr.map((el, index) => {
                      if (index === backOrder) {
                        return <div className={`red-pack-item backAniItem`} key={index}>
                          <img src={el.prizeImg}></img>
                        </div>
                      }
                      if (index === order) {
                        return <div
                          className={`red-pack-item frontAniItem`} key={index}>
                          <SvgaPlayer loop={1} className='redpackAni' src={redFenwei}></SvgaPlayer>
                          <img src={el.prizeImg}></img>
                        </div>
                      }
                      return <div className={`red-pack-item hide-red-pack-item`} key={index}>
                        <img src={el.prizeImg}></img>
                      </div>
                    })
                  }
                </div>
                <div className='right'>
                  <div className='red-pack-item'><img src={unlockObj?.unlockedPrizeImg}></img></div>
                </div>
              </div> : <div className='one-middle'>
                {unlockObj?.unlockedPrizeImg && <div className='red-pack-item'><img src={unlockObj?.unlockedPrizeImg}></img></div>}
              </div>
            }
          </div>
          {productEnd && <div className="prize_banner">
            <span className="prize_btn md31" 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}>
              {/* <span className="record_btn_text">模拟交易记录</span>
              <span className="arrow_right"></span> */}
            </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>
            {/* <Button className="realbuy_btn md11" onClick={this.realBuyHandle}></Button> */}
          </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 md5" onClick={this.ruleHandle} />
          <Button className="prize_btn md6" onClick={this.reallyPrizeHandle} />
          {giftPop && <Button className="newUser_btn md7" onClick={this.newUserFun} />}
          {redDownTime > 0 && <Button className="redpack_btn md8" onClick={this.countDownFun} >
            <Countdown
              leftT={redDownTime}
              renderText={data => {
                const { day, hour, minute, second } = data
                let hourNum: any = Number(day) * 24 + Number(hour);
                hourNum = hourNum >= 10 ? hourNum : '0' + hourNum;
                return <div className="redpack_time_box">
                  <span className="redpack_time_item">{`${hourNum}:${minute}:${second}`}</span>
                </div>
              }}
              countdownOver={() => store.updateIndex()}
            />
          </Button>}
        </div>
      </div>
    );
  }
}
export default HomePage;
