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, formatThousand } from '@/utils/utils';
import RecordPage from '../RecordPage/RecordPage';
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";

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

  root: HTMLDivElement;

  state = {
    curTab: 1, // 1-产品列表 2-我的持仓
  }

  async componentDidMount() {
    await store.judgeIsWhiteUser();

  }

  /** 跳转模拟交易记录 */
  recordHadnle = _asyncThrottle(() => {
    if (!store.judgeActTime()) return
    PageCtrl.changePage(RecordPage)
  })

  /** 真实买入 */
  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)
  })

  /** 跳转结果页 */
  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 {
  }
  render() {
    const { curTab } = this.state;
    const { bigStartConfig, virtualAssets, checkIn, recommendProductConfig, productEnd, endPoint, currentTime } = store.indexData
    // 推荐产品
    const rProductList = recommendProductConfig?.filter((item) => +item.status === 0)
    // 我的持仓
    const mProductList = recommendProductConfig?.filter((item) => item.mineProduct)
    // 当前tab的产品列表
    const curTabProductList = curTab == 1 ? recommendProductConfig : mProductList

    return (
      <div className="com_Container" ref={(el) => this.root = el}>
        <div className="homePage md4">
          <span className="bg"></span>
          <span className="title"></span>
          {/* 理财大明星 */}
          {productEnd ? null : <div className="lc_bigstar">
            <span className="lc_bigstar_bg"></span>
            <div className="hongBao">
              {bigStartConfig?.map((item, index) => (
                <div className="bigstar_item" key={`bigStart_${index}`}>
                  <img className="redpacket_img" src={item.prizeImg}></img>
                  <img className="redpacket_tag" src={item.titleImg}></img>
                </div>
              ))}
            </div>
          </div>}
          {/* 领奖banner */}
          {productEnd && <div className="prize_banner">
            <span className="prize_btn md16" onClick={this.prizeHandle}></span>
          </div>}
          {/* 模拟资产 */}
          {/* <div className={`virtual_assets ${!virtualAssets?.realBuyJumpUrl ? 'short_height' : ''}`}> */}
          <div className="virtual_assets">
            {
              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>
            }
            <span className="yesterday_label">累计收益(元)</span>
            <span className="yesterday_amount">{this.settleMoney(virtualAssets?.totalIncome || 0)}</span>
            <div className="record_btn md6" 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 md7" onClick={this.realBuyHandle}>真实买入</Button>
          </div>
          {/* 签到区 */}
          {productEnd ? null : <div className="sign_section">
            <span className="sign_section_bg"></span>
            <span className="sign_tips">累计签到，最高可得{((checkIn?.totalExperienceNum || 0) / 10000).toFixed(0)}万资金</span>
            {checkIn?.todayCheckIn
              ? <Button className="signed_btn md8" onClick={this.signedHandle}>已签到</Button>
              : <Button className="sign_btn md8" onClick={this.signHandle}>签到得1万资金</Button>
            }
            <div className="sign_progress">
              <span className="progress_bg"></span>
              <div className="progress_bar_box">
                <div className="progress_bar" style={{ width: `${store.percent}%` }}></div>
              </div>
              {checkIn?.checkInConfig?.map((item, index) => {
                return (
                  <div
                    className={`step_item step_item${index + 1} ${item.days > checkIn?.totalCheckIn ? 'locked' : item.status ? 'received' : 'signed'}`}
                    key={`sign_${index}`}
                    onClick={() => this.signPrizeHandle(item)}
                  >
                    <span className="prize_bg"></span>
                    <div className="prize_amount">{((item.experienceNum || 0) / 10000).toFixed(0)}<span className="unit">万</span></div>
                    <span className="prize_day">累计{item.days}天</span>
                  </div>
                )
              })}
            </div>
          </div>}
          {/* 推荐产品 */}
          {!!rProductList?.length && <div className="recommend_products">
            <span className="r_products_title"></span>
            <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>
          </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>
                  <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" onClick={this.reallyPrizeHandle}/>
        </div>
      </div>
    );
  }
}
export default HomePage;
