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 Finish_task from '../../../components/finish_task/finish_task';
import Consume_qg from '../../../components/consume_qg/consume_qg';
import Consume_credits from '../../../components/consume_credits/consume_credits';
import Renewmodule from '../../../components/renewmodule/renewmodule';
import { unwatchPageVisibility, watchPageVisibility } from '@/core/page-visibility-notify';
import { initWx } from '@/built-in/share/weixin/weixin';
import { handleLogExposure, handleLogClick } from "@/MD";

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

  constructor(props) {
    super(props);
  }

  componentDidMount() {
    watchPageVisibility(this.onPageVisibilityChange)
  }

  componentWillUnmount() {
    unwatchPageVisibility(this.onPageVisibilityChange);
  }

  /** 页面显隐行 */
  onPageVisibilityChange = (visible) => {
    console.log('页面' + visible ? '可见' : '不可见')
    if (visible) {
      store.getTaskInfo();  //跳转回来，刷接口
    }
  }

  // 按钮
  handlegofinish = async (type, n, code, title, jumpUrl, id) => {
    handleLogClick(4, id)
    const { jfNum = 0, qgNum = 0 } = store?.baseInfo || {};
    if (type === "xhqg") {
      if (n <= qgNum) {
        ModalCtrl.showModal(Consume_qg, { n, code, title });
      } else {
        Toast.show("青果不足！");
      }
    } else if (type === "xhjf") {
      if (n <= jfNum) {
        ModalCtrl.showModal(Consume_credits, { n, code, title });
      } else {
        Toast.show("积分不足！");
      }
    } else if (type === "yqzl" || type === "yqzl_new") {
      store.doInvite(code)
    } else if (type === "scan") {
      // await API.getChallenegeComplete({ taskCode: code });
      wx.miniProgram.switchTab({ url: jumpUrl });
    } else if (type === "browse") {
      await API.getChallenegeComplete({ taskCode: code });
      window.location.href = jumpUrl;
    } else if (type === "sign") {
      Toast.show("快去签到吧");
    }
  };


  handlegosign = _asyncThrottle((hasChallengeDay, resignJf, resignQg, type) => {
    if (type === 'task') handleLogClick(5)
    // else if (type === 'calendar') handleLogClick(6)
    ModalCtrl.showModal(Renewmodule, { hasChallengeDay, resignJf, resignQg });
  });

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

  handlesubscribe = _asyncThrottle(() => {
    // if (store?.homeInfo?.subscribe) return console.log('buxing');
    // @ts-ignore
    wx.miniProgram.reLaunch({ url: CFG.subUrl })
  })

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

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

    // 当前挑战信息
    const {
      challengeTotalDay = 0,
      prizeName = '',
      prizeImg = '',
      resignJf = 0,
      resignQg = 0,
    } = 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" />

        {challengeStartTime && challengeEndTime && (
          <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">
            {hasChallengeDay !== challengeTotalDay && (
              <div className="task-plan">打卡任务 |  {completedTasks} / {taskCount}</div>
            )}
            {hasChallengeDay !== challengeTotalDay && Array.isArray(taskInfoList) &&
                taskInfoList.length > 0 &&
                taskInfoList?.map((v, i) => {
                const { title, subTitle, icon, code, completedSize, intervalLimitSize, jumpUrl, id, } = v || {};

                // 获取按钮状态
                const renderActionButton = (code, completedSize, intervalLimitSize) => {
                  // 先判断是否为续签状态
                  if (boolNeedResign) {
                    handleLogExposure(5)
                    return <Button className="gosign" onClick={() => this.handlegosign(hasChallengeDay, resignJf, resignQg, 'task')} />
                  } else if (completedSize < intervalLimitSize) {
                    handleLogExposure(4, id)
                    switch (true) {
                      // 签到
                      case code.startsWith("sign"): {
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("sign", '', code, title, '', id)}
                          />
                        );
                      }
                      // 消耗青果
                      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, code, title, '', id)}
                          />
                        );
                      }
                      // 消耗积分
                      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, code, title, '', id)}
                          />
                        );
                      }
                      // 邀请用户助力
                      case code.startsWith("yqzl"): {
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("yqzl", '', code, title, '', id)}
                          />
                        )
                      }
                      // 邀请新用户
                      case code.startsWith("yqzl_new"): {
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("yqzl_new", '', code, title, '', id)}
                          />
                        )
                      }
                      // 扫码
                      case code.startsWith("scan"): {
                        // const number = (code.split("_")[1]);
                        // const n = parseInt(number.replace(/[{}]/g, ''), 10);
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("scan", '', code, title, jumpUrl, id)}
                          />
                        );
                      }
                      // 浏览
                      case code.startsWith("browse"): {
                        return (
                          <Button
                            className="gofinish"
                            onClick={() => this.handlegofinish("browse", '', code, title, jumpUrl, id)}
                          />
                        );
                      }

                      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">
                      {(code.startsWith("yqzl") || code.startsWith("yqzl_new") || code.startsWith("scan")) ?
                        <span className="item-title">{title}({completedSize}/{intervalLimitSize}) </span> :
                        <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>
          <Button className="subcribe" onClick={this.handlesubscribe} />
          <div className="list">
            {Array.from({ length: challengeTotalDay }).map((_, dayIndex) => (
              <div
                className={`sample ${dayIndex + 1 === challengeTotalDay && !(boolNeedResign && dayIndex === hasChallengeDay)
                  ? 'new-style'
                  : ''
                  }`}
                key={dayIndex}
              >
                {dayIndex <= hasChallengeDay - 1 && dayIndex + 1 !== challengeTotalDay && (
                  <>
                    <span className="done"></span>
                    <span className="duigou"></span>
                  </>
                )}
                {(boolNeedResign && dayIndex === hasChallengeDay) && (
                  <Button className="renew md6" onClick={() => this.handlegosign(hasChallengeDay, resignJf, resignQg, 'calendar')} />
                )}
                {dayIndex !== challengeTotalDay - 1 && (
                  <span className="day-number">{dayIndex + 1}</span>
                )}
              </div>
            ))}
          </div>
        </div>




      </div>;
    }
  }
}

export default Check;
