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 MyPrize from '../MyPrize/MyPrize';
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 } from '@/AppTools';
import API from '@/api';
import DetailPage from '../DetailPage/DetailPage';

@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 || {}
    diffJump(realBuyJumpUrl)
  })

  /** 跳转“模拟”产品详情页 */
  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)
  })

  /** 已签到 */
  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 (!store.judgeActTime()) return
    const { myEndTime, currentTime } = store.indexData || {}
    if (myEndTime <= currentTime) {
      Toast.show("模拟理财已结束～")
      return false
    }
    const { success } = await API.doRewards({ checkInConfigId: item.id });
    if (success) {
      Toast.show("领取成功")
    }
    await store.updateIndex();
  })

  /** 切换tab */
  toggleTab = _asyncThrottle(async (type) => {
    if (!store.judgeActTime()) return
    this.setState({ curTab: type })
  })


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

  componentWillUnmount(): void {
  }
  render() {
    const { curTab } = this.state;
    const { bigStartConfig, virtualAssets, checkIn, recommendProductConfig } = store.indexData
    return (
      <div className="com_Container" ref={(el) => this.root = el}>
        <div className="homePage">
          <span className="bg"></span>
          <span className="title"></span>
          {/* 理财大明星 */}
          <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>
          {/* 模拟资产 */}
          <div className={`virtual_assets ${!virtualAssets?.realBuyJumpUrl ? 'short_height' : ''}`}>
            <span className="yesterday_label">昨日收益(元)</span>
            <span className="yesterday_amount">{this.settleMoney(virtualAssets?.preDayIncome || 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?.totalIncome || 0)}</span>
              </div>
            </div>
            <div className="canuse_popover">
              <span className="canuse_popover_bg"></span>
              <span className="canuse_popover_text">可用资金去购买理财</span>
            </div>
            {!!virtualAssets?.realBuyJumpUrl && <Button className="realbuy_btn" onClick={this.realBuyHandle}>真实买入</Button>}
          </div>
          {/* 签到区 */}
          <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" onClick={this.signedHandle}>已签到</Button>
              : <Button className="sign_btn" onClick={this.signHandle}>签到得1万资金</Button>
            }
            <div className="sign_progress">
              <span className="progress_bg"></span>
              <div className="progress_bar_box">
                {/* TODO 百分比计算 */}
                <div className="progress_bar" style={{ width: `${87}%` }}></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>
          <div className="recommend_products">
            <span className="r_products_title"></span>
            <div className="r_products_list">
              {recommendProductConfig?.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>
                  <span className="r_product_risk">{item.fengXian}</span>
                  <span className="r_product_rate">{item.touZiQiXianText}</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">
              {/* TODO 字段 */}
              {recommendProductConfig?.map((item, index) => (
                <div className="b_product_item" key={`r_prdct_${index}`} onClick={() => this.jumpRealDetailHandle(item.realBuyJumpUrl)}>
                  <span className="b_product_name">{item.name}</span>
                  <div className="b_product_rate">
                    <span className="b_product_rate_label">年化收益率</span>
                    {/* TODO */}
                    <span className="b_product_rate_value">1.97%</span>
                  </div>
                  <div className="b_product_shu">
                    <span className="b_product_shu_label">{item.fengXian} ｜ {item.qigouText}</span>
                    <span className="b_product_shu_value">{item.shenShuGuiZei}</span>
                  </div>
                  <Button className="detail_btn_1" onClick={() => this.jumpVirtualDetailHandle(item)}></Button>
                  <span className="b_product_line"></span>
                </div>
              ))}
            </div>
            {/* TODO 字段 */}
            {!recommendProductConfig?.length && curTab == 2 && <div className="empty">暂无持仓产品哦</div>}
          </div>
          <Button className="rule_btn" onClick={this.ruleHandle} />
        </div>
      </div>
    );
  }
}
export default HomePage;
