import React from 'react';
import { observer } from 'mobx-react';
import './Check.less';
import store from "@/store/store.ts";
import { Button, Toast } from '@grace/ui';
import API from '@/api';
import { _asyncThrottle, dateFormatter } from '@/utils/utils';
import { PageCtrl } from '@/core/ctrls/PageCtrl';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import Consume_qg from '../../../components/consume_qg/consume_qg';
import Consume_credits from '../../../components/consume_credits/consume_credits';

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

  constructor(props) {
    super(props);
    this.state = {
      baseInfo: {}
    };
  }

  componentDidMount() {
    store.getTaskInfo()
    this.getBaseIndex()
  }

  async getBaseIndex() {
    const { success, data } = await API.getChallengeBaseIndex()
    if (!success) return;
    this.setState({
      baseInfo: data
    });
  }

  // 按钮
  handlegofinish = (type, n) => {
    console.log(this.state?.baseInfo)
    const { jfNum = 0, qgNum = 0 } = this.state?.baseInfo || {};
    if (type === "xhqg") {
      if (n <= qgNum) {
        ModalCtrl.showModal(Consume_qg, { n });
      } else {
        console.log("青果不足", qgNum);
        Toast.show("很抱歉，您的青果不足");
      }
    } else if (type === "xhjf") {
      if (n <= jfNum) {
        ModalCtrl.showModal(Consume_credits, { n });
      } else {
        Toast.show("很抱歉，您的积分不足");
      }
    }
    else {
      // todo
    }
  };


  handlegosign = _asyncThrottle(() => {
    //todo
  })

  handlefinish = _asyncThrottle(() => {
    Toast.show("该任务已完成");
  })

  render() {
    const { boolOpenChallenge,
      challengeStartTime,
      challengeEndTime,
      choosedChallengeId,
      hasChallengeDay,
      boolNeedResign,
      challengeConfigList = [],
      taskInfoList = [],
    } = store?.taskInfo || {};

    // 找到当前挑战信息项
    const currentChallenge = challengeConfigList.find(
      item => item.challengeId === choosedChallengeId
    );

    // 当前挑战信息
    const { challengeTotalDay,
      prizeName,
      prizeImg,
      resignJf,
      resignQg,
    } = currentChallenge || {};

    // 进度显示
    const progress = ((hasChallengeDay / challengeTotalDay) * 100).toFixed(0);
    // 还差多少天
    const remainingDays = challengeTotalDay - hasChallengeDay;

    // 当前任务总数
    const taskCount = (taskInfoList || []).length;
    // 已完成任务数
    const completedTasks = (taskInfoList || []).filter(
      task => task.completedSize >= task.intervalLimitSize
    ).length;



    if (boolOpenChallenge) {
      return <div className="check">
        <div style={{ height: 0 }}>
          <div className="check-bg" />
        </div>
        <div className="check-color" />

        <div className="actTime">活动时间{dateFormatter(challengeStartTime, "yyyy.MM.dd")}-{dateFormatter(challengeEndTime, "MM.dd")}</div>

        <div className="title-line"></div>
        <div className="check-title">累计打卡挑战{challengeTotalDay || 0}天</div>

        <div className="prize-name">{prizeName}奖励</div>

        <img className="prize-img"
          src={prizeImg}
          alt={prizeName}
        />

        <div className="insist-bg"></div>
        <div className="insist-day">已坚持 <span className="special">{hasChallengeDay || 0}</span> 天</div>

        <div className="process-tip">挑战进度<span className='process1'>{progress || 0}%</span> 距离拿奖还差<span className='process2'>{remainingDays || 0}天</span></div>

        <div className="task">
          <div className="task-bg">
            <div className="task-plan">打卡任务 {completedTasks} ｜ {taskCount}</div>
            {Array.isArray(taskInfoList) &&
              taskInfoList.length > 0 &&
              taskInfoList?.map((v, i) => {
                const { title, subTitle, icon, code, completedSize, intervalLimitSize } = v || {};

                // 获取按钮状态
                const renderActionButton = (code, completedSize, intervalLimitSize) => {
                  // 先判断是否为续签状态
                  if (boolNeedResign) {
                    return <Button className="gosign" onClick={this.handlegosign} />
                  } else if (completedSize < intervalLimitSize) {
                    switch (true) {
                      case code.startsWith("xhqg_"): {
                        const number = (code.split("_")[1]);
                        const n = parseInt(number.replace(/[{}]/g, ''), 10);
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("xhqg", n)}
                          />
                        );
                      }
                      case code.startsWith("xhjf_"): {
                        const number = (code.split("_")[1]);
                        const n = parseInt(number.replace(/[{}]/g, ''), 10);
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("xhjf", n)}
                          />
                        );
                      }
                      case code.startsWith("yqzl"): {
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("yqzl", '')}
                          />
                        )
                      }
                      case code.startsWith("yqzl_new"): {
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("yqzl_new", '')}
                          />
                        )
                      }
                      case code.startsWith("scan_"): {
                        const number = (code.split("_")[1]);
                        const n = parseInt(number.replace(/[{}]/g, ''), 10);
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("scan", n)}
                          />
                        );
                      }
                      case code.startsWith("browse_"): {
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("browse", '')}
                          />
                        );
                      }

                      default:
                        return <Button className="gofinish" onClick={this.handlefinish} />;
                    }
                  }
                  else if (completedSize >= intervalLimitSize) {
                    return <Button className="finish" onClick={this.handlefinish} />
                  }
                };

                return (
                  <div className="task-item" key={i}>
                    {/* <span className="item-bg"></span> */}
                    <img className="item-icon" src={icon} alt="" />
                    <div className="item-name">
                      <span className="item-title">{title}</span>
                      <span className="item-tip">{subTitle}</span>
                    </div>
                    {renderActionButton(code, completedSize, intervalLimitSize)}
                  </div>
                );
              })}
          </div>
        </div>



        <div className="calendar">
          <span className="remind">提醒我签到 挑战失败重新开始</span>
          <div className="list">
            {Array.from({ length: challengeTotalDay }).map((_, dayIndex) => (
              <div className="sample" key={dayIndex}>
                <span className="day-number">{dayIndex + 1}</span>
              </div>
            ))}
          </div>
        </div>


      </div>;
    }
  }
}

export default Check;
