'use strict';

import React from 'react';
import { observer } from 'mobx-react';
import './signCom.less';
import { ModalCtrl } from '@/core/ctrls/ModalCtrl';
import { Button, Toast } from '@grace/ui';
import { _asyncThrottle, formatThousand } from '@/utils/utils';
import store from '@/store/store';
import API from '@/api';
import SignTaskPop from '@/panels/signTaskPop';
import { weekList } from "@/contants"
import classNames from 'classnames';
import SignSuccessPop from '@/panels/signSuccessPop';

@observer
class SignCom extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentWeek: new Date().getDay(), // 当前周几
      signInfo: {},
      isJump: false,
    }
  }

  componentDidMount() {
    this.getSignInfo();
    window.addEventListener('visibilitychange', this.handleVisibilityChange);
  }

  componentWillUnmount() {
    window.removeEventListener('visibilitychange', this.handleVisibilityChange);
  }

  handleVisibilityChange = () => {
    if (document.visibilityState === 'visible') {
      console.log('页面可见');
      if (this.state.isJump) {
        this.signPrizeHandle()
      }
    } 
  }

  /** 获取签到信息 */
  async getSignInfo() {
    try {
      const { success, data } = await API.querySign();
      if (success) {
        this.setState({
          signInfo: data || {},
        })
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 跳转前进行打标
  jumpToSing = () => {
    this.setState({
      isJump: true,
    })
  }

  /** 签到 */
  signHandle = _asyncThrottle(async () => {
    if (!store.judgeActTime()) return
    const { success, data } = await API.doSign();
    if (success) {
      Toast.show(`签到成功，获得${data?.options?.[0]?.sendCount || 0}模拟理财金`)
    }

    await this.getSignInfo();
    await store.updateIndex();

    // 浏览任务
    const {signInfo, currentWeek} = this.state
    if(signInfo?.prizeDays?.includes(`${currentWeek}`)) {
      ModalCtrl.showModal(SignTaskPop, {
        otherPrizeInfo: data.otherPrizeInfo || {},
        callback: () => {
          this.jumpToSing();
        }
      })
    }
  })

  /** 签到-领奖 */
  signPrizeHandle = _asyncThrottle(async () => {
    if (!store.judgeActTime()) return
    const  { success, data } = await API.completeSignView();
    if(success) {
      store.updateIndex();
      this.setState({ isJump: false })
      ModalCtrl.showModal(SignSuccessPop, {
        prizeInfo: data || {},
      })
    }
  })

  render() {
    const {currentWeek, signInfo} = this.state
    return (
      <div className="no-center-qes">
        <div className="sign-module">
          <div className="week-list-box">
            {
              weekList.map((item, index) => (
                <Button className={classNames("week-item", {
                  'week-item-ok': signInfo?.signDays?.includes(`${index +1}`),
                  'week-item-task': signInfo?.prizeDays?.includes(`${index +1}`),
                  'week-item-nosign': index + 1 < currentWeek && !signInfo?.signDays?.includes(`${index +1}`)
                })} key={index}>
                  <div className="week-item-text">周{item}</div>
                  {signInfo?.prizeDays?.includes(`${index +1}`) ? <div className="task-title"></div> : null}
                </Button>
              ))
            }
          </div>
          {signInfo?.todaySign ? <div className="sign_btn sign_btn_yes"></div> : <Button className="sign_btn md11" onClick={this.signHandle}></Button>}
        </div>
      </div>
    );
  }
}
export default SignCom;
