'use strict';

import React from 'react';
import { observer } from 'mobx-react';
import { PageCtrl } from "@/core/ctrls/PageCtrl.tsx";
import HomePage from "@/pages/HomePage/HomePage.tsx";
import { _asyncThrottle, dateFormatter, formatThousand } from '@/utils/utils';
import { Button, Toast } from "@grace/ui";
import API from '@/api';
import './myqradespage.less';

@observer
class Myqradespage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        monthInfo:[],   // 月份信息
        selectIndex: 0,
        selectId: {},
        info:{},
        actStartTime: 0,  // 活动开始时间戳	
        actEndTime: 0,  //活动结束时间戳	
        currentTime: 0,  //当前时间戳
    };
    this.monthContainerRef = React.createRef();
  }
  componentDidMount() {
    this.getMonthInfo();
  }
  // 提取月份匹配辅助函数
  findMatchingMonth = (monthInfo, targetMonth) => {
    return monthInfo.find(item => {
      // 提取yyyy-MM部分进行匹配
      const itemMonthKey = item.monthId.split('-').slice(0, 2).join('-');
      return itemMonthKey === targetMonth;
    });
  };
  // 提取月份范围生成辅助函数
  generateMonthList = (startTime, endTime) => {
    const monthList = [];
    const startDate = new Date(startTime);
    const endDate = new Date(endTime);
    const currentDate = new Date(startDate);
    
    // 从开始日期到结束日期，逐月添加
    while (currentDate <= endDate) {
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const monthStr = `${year}-${month}`;
      
      monthList.push({
        monthId: monthStr,
        month: monthStr
      });
      
      // 移动到下个月第一天
      currentDate.setMonth(currentDate.getMonth() + 1);
      currentDate.setDate(1);
    }
    
    return monthList;
  };
  // 获取月份信息
  getMonthInfo = async () => {
    const {code, data, message, success} = await API.drawQuery();
    if (success) {
      // 初始化状态
      this.setState({ monthInfo: data.monthInfo }, () => {
        // 生成完整月份列表
        const monthList = this.generateMonthList(data.actStartTime, data.actEndTime);
        console.log("🚀 ~ Myqradespage ~ monthList:", monthList);
        
        // 合并月份信息
        const mergedMonthInfo = monthList.map(month => {
          const existing = this.findMatchingMonth(this.state.monthInfo, month.monthId);
          return existing ? { ...month, ...existing } : month;
        });
        
        // 找到第一个包含receiveStatus属性的元素索引
        const firstReceiveStatusIndex = mergedMonthInfo.findIndex(item => item.hasOwnProperty('receiveStatus'));
        // 如果找到符合条件的元素，则使用其索引，否则使用默认索引0
        const targetIndex = firstReceiveStatusIndex !== -1 ? firstReceiveStatusIndex : 0;
        
        // 更新状态并在回调中执行后续操作
        this.setState({ 
          monthInfo: mergedMonthInfo,
          selectIndex: targetIndex
        }, () => {
          console.log("🚀 ~ Myqradespage ~ monthInfo:", this.state.monthInfo);
          // 确保monthInfo数组非空再调用getdrawIndex
          if (this.state.monthInfo && this.state.monthInfo.length > 0) {
            this.getdrawIndex(this.state.monthInfo[targetIndex].monthId);
            // 组件挂载后，自动滚动到选中的月份
            this.scrollToSelectedMonth(targetIndex);
          }
        });
      });
    }
  }
  // 获取理财成绩-首页
  getdrawIndex = async (monthId) => {
    const {code, data, message, success} = await API.drawIndex({monthId});
    if (success) {
      this.setState({
        info: data
      });
    }
  }
  // 格式化分转换为元并添加千分位分隔符
  formatMoney = (amount) => {
    return formatThousand((amount / 100).toFixed(2))
  }
  // 返回
  clickBack = _asyncThrottle(() => {
    PageCtrl.changePage(HomePage);
  })
  // 点击查看
  clickView = _asyncThrottle(() => {
    const {url, recordId } = this.state.info.prizeInfo || {};
    if(url){
        location.href = url
    }else {
        location.href = `/aaw/projectx/takePrize?projectOrderNo=${recordId}`
    }
  })
  // 滚动到选中的月份
  scrollToSelectedMonth = (index) => {
    if (this.monthContainerRef.current) {
      const container = this.monthContainerRef.current;
      const monthElements = container.querySelectorAll('.yue');
      if (monthElements && monthElements[index]) {
        const targetElement = monthElements[index];
        // 使用scrollLeft代替scrollIntoView，避免影响页面布局
        // 计算元素相对于容器左侧的偏移量
        const targetLeft = targetElement.offsetLeft;
        // 平滑滚动到目标位置
        container.scrollTo({
          left: targetLeft,
          behavior: 'smooth'
        });
      }
    }
  }
  // 点击月份
  clickMonth = _asyncThrottle((item, index) => {
    console.log("🚀 ~ Myqradespage ~ item, index:", item, index)
    if(item.hasOwnProperty('receiveStatus')){  // 检查字段是否存在
       this.setState({
        selectIndex: index,
        selectId: item.monthId,
      }, () => {
        // 状态更新后，滚动到选中的月份
        this.scrollToSelectedMonth(index);
      })
      this.getdrawIndex(item.monthId)
    } else {
      Toast.show("本月未参与哦～");
    }
  })
  // 点击立即领取
  clickClaim = _asyncThrottle(() => {
    const { selectId } = this.state;
    console.log("🚀 ~ Myqradespage ~ selectId:", selectId)
    this.getdrawJoin(selectId);
    // Toast.show("领取成功");
  })
  // 领取奖品
  getdrawJoin = async (monthId) => {
    const {code, data, message, success} = await API.drawJoin({monthId});
    if (success) {
      Toast.show("领取成功");
      this.getdrawIndex(monthId);
    }
  }
  render() {
    const { monthInfo, selectIndex } = this.state;
    return (
      <div className="myqradespage">
        <span className="bg"></span>
        <span className="back" onClick={() => this.clickBack()}></span>
        {
          this.state.info?.drawStatus != 1 ? (
            <div className="lottery">
              <span className="icon3">
                <img src={this.state.info.prizeInfo?.prizeImg} alt="" />
              </span>
              <span className="jiangPinMingCheng">{this.state.info.prizeInfo?.prizeName}</span>
              {
                this.state.info.drawStatus == 0 && (
                  <span className="btn1 md13" onClick={() => this.clickClaim()}></span>
                )
              }
              {
                this.state.info.drawStatus == 2 && (
                  <span className="btn2" onClick={() => this.clickView()}></span>
                )
              }
            </div>
          ) : (
            <div className="lottery2">
            </div>
          )
        }
      
        
        <div className="ranking">
          <span className="rankingbg"></span>
          <div className="badge">
              <span className="xxx">{this.state.info.rank == null ? '未上榜' : this.state.info.rank > 100 ? '99+' : this.state.info.rank}</span>
            
          </div>
          <div className="ranking1">
            <span className="woDeShouYiLuPaiMing">我的收益率排名</span>
            <span className="diXxx">{this.state.info.rank == null ? '未上榜' : this.state.info.rank > 100 ? '第99+' : '第' + this.state.info.rank}</span>
          </div>
          <div className="ranking2">
            <span className="juXing880"></span>
            <span className="liCaiZiJin">理财资金</span>
            <span className="_334556675yuan">{this.formatMoney(this.state.info.totalAmount)}元</span>
          </div>
          <div className="ranking3">
            <span className="juXing880_1"></span>
            <span className="leiJiShouYi">累计收益</span>
            <span className="_2213yuan">{this.formatMoney(this.state.info.totalProfit)}元</span>
          </div>
          <div className="ranking4">
            <span className="juXing880_2"></span>
            <span className="liCaiZhouQi">收益率</span>
            <span className="_2025062220250722">{this.state.info.profitRatio}%</span>
          </div>
        </div>
        <span className="woDeChengJi">我的成绩</span>
        <div className="month" ref={this.monthContainerRef}>
          {
            monthInfo.map((item, index) => (
              <div className="yue" key={item.monthId} onClick={() => this.clickMonth(item,index)}>
                    {
                      selectIndex === index && (
                      <span className="line"></span>
                      )
                    }
                    
                    {
                      item.receiveStatus == 0 && (
                        <span className="icon1"></span>
                      )
                    }
                    {item.monthId.split('-')[1] + '月'}
                 </div>
            ))
          }
         
        </div>
      </div>
    );
  }
}
export default Myqradespage;