'use strict';

import React from 'react';
import { observer } from 'mobx-react';
import './prizepage.less';
import { Button } from '@src/components/Button';
import store from '@src/store'
import { _asyncThrottle, getUrlParam, windowJumpUrl } from '@src/utils/utils'
import modalStore from '@src/store/modal'
import { unwatchPageVisibility, watchPageVisibility } from '@spark/utils';
import API from '@src/api'
import { sensorMdClick, sensorMdExpouse } from '@src/utils/sensorMd'

@observer
class Prizepage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      prizeInfo: {},
    }
  }

  async componentDidMount() {
    // 初始化神策埋点
    await store.initSensorsMd()
    sensorMdExpouse("activityPage", { pageName: "我的奖品页", activityName: CFG.activityName, follow_action: 2 })
    await this.getPrizeInfo()

    // 关注回来 刷新首页
    watchPageVisibility(this.pageVChange)
  }

  componentWillUnmount() {
    unwatchPageVisibility(this.pageVChange)
  }

  /** 页面显示 */
  pageVChange = (visible) => {
    console.log('页面', visible ? '可见' : '不可见')
    if (visible) {
      this.getPrizeInfo()
    }
  }

  /** 获取奖品信息 */
  getPrizeInfo = async () => {
    const res = await API.getPrizePageInfo();
    if (res?.success) {
      this.setState({
        prizeInfo: res.data || {},
      });
    }
  };

  navigateToPrize = (item) => {
    return _asyncThrottle(async () => {
      sensorMdClick("activityClick", { pageName: "我的奖品页点击", activityName: CFG.activityName, buttonName: `点击奖品` });
      // sensorMdClick("activityClick", { pageName: "我的奖品页", buttonName: `去看看-${item.prizeName}` });
      const {
        focusStatus, // 是否关注公众号（true-关注，false-未关注）
        bindStatus, // 是否绑定（true-已绑定，false-未绑定）
        activityCode,
      } = this.state.prizeInfo;
      if (!focusStatus) {
        modalStore.pushPop("Focuspop");
        return false;
      } else if (!bindStatus) {
        modalStore.pushPop("Bindpop");
        return false;
      }

      const { id, prizeId, userRecordId } = item;

      if (prizeId?.indexOf("sp_object_gw") == -1 && prizeId?.indexOf("sp_virtual") == -1) {
        //非官微奖品
        setTimeout(() => {
          location.href = `/aaw/projectx/takePrize?projectOrderNo=${id}`;
        }, 300)
      } else {
        if (prizeId?.indexOf("sp_virtual") > -1 && userRecordId) {
          location.href = `/aaw/projectx/takePrize?projectOrderNo=${userRecordId}`;
          return
        }
        if (item.gwObjectStatus == 1) return;

        const { success, data } = await API.createCode({ recordId: id, newActivityCode: activityCode });
        if (!success) return;
        const { enParamStr } = data;

        setTimeout(() => {
          location.href = CFG.prizeJumpUrl + `?enParamStr=${enParamStr}&activityCode=${data.activityCode}`;
        }, 300)
      }
    });
  }
  backHome() {
    sensorMdClick("activityClick", { pageName: "我的奖品页点击", buttonName: "返回", activityName: CFG.activityName })
    const fromPage = getUrlParam('fromPage')
    if (fromPage == 'home') {
      history.go(-1)
    } else {
      const indexUrl = 'index.html?appID=' + CFG.appID + '&channel=' + getUrlParam("channel")
      //留资跳转回来
      windowJumpUrl(indexUrl)
    }
  }

  render() {
    const { prizeInfo } = this.state
    return (
      <div className="prizepage modal_center">
        <span className="bg"></span>
        <span className="title"></span>
        <div className="prize_list">
          {prizeInfo?.list?.map((item, index) => (
            <div className="prize_item" key={index} onClick={this.navigateToPrize(item)}>
              <img className="prize_img" src={item.prizeImg} />
              <span className="prize_name">{item.prizeName}</span>
              <span className="prize_btn"></span>
            </div>
          ))}
        </div>
        <Button className="back" onClick={this.backHome}></Button>
      </div>
    );
  }
}
export default Prizepage;
