import React, { Component } from 'react';
import QRCode from 'qrcode';
import { http } from '@/utils';
import RulePopup from './rulePopup/index'
import CoursePopup from './coursePopup/index'
import RecordPopup from './recordPopup/index'
import CourseList from './courseList/index';
import SharePopup from './sharePopup/index';
import LuckDraw from './luckDraw/index';
import CollectBlessing from './collectBlessing/index';
import ReserveCourse from './ReserveCourse/index';
import ListHeader from './listHeader/index';
import LevelTest from './levelTest/index';
import RankList from './rankList/index';
import './index.scss'
import { Popup } from '@/common'
import {CopyToClipboard} from 'react-copy-to-clipboard'
import { Toast } from "antd-mobile"
import Live from './live'
import Banner from './banner'


class BlessingPreheat extends Component {
  constructor(props) {
    super(props)
    this.state = {
      isRule: false,
      isCourse: false,
      inviteUrl: '',
      inviteVisible: false,
      joinLotteryVisible: false,
      timelineShareVisible: false,
      showRecordList: false,
      isFormal: false, // 1正式 0 预热
      isServer: false,
      serverUrl: '',
      shareMark: false,
      userInfo: {},
      isSign: false,
    }
  }

  componentDidMount() {
    this.fetchUserBlessing();
  }

  fetchUserBlessing() {
    const { userInfo } = this.state;
    http.get(`${API.home}/sys/user/blessing`).then(res => {
      const { code, data } = res.data;
      if(code === 200) {
        this.setState({
          isFormal: data.is_activity,
          userInfo: Object.assign({}, userInfo, {
            isLogin: !!data.is_login,
            blessingVal: data.user_blessing_value,
          })
        });
        if(data.is_login === 1) {
          this.handleToSign();
        }
      }
    });
  }

  handleToSign = () => {
    console.log(2,2);
    http.post(`${API.home}/sys/add/blessing`, {
      type: 1 // 1：签到；3：分享；4：浏览课程；
    }).then(res => {
      const {code } = res.data;
      if (code === 200) {
        this.setState({
          isSign: true,
        });
        Toast.info('+5点福气值~', 2, null, false);
      }
    });
  }

  handleToHide = (key) => {
    let obj = {}
    obj[key] = false;
    this.setState({
      ...obj
    })
  }

  handleToShow = (key, isLogin = false) => {
    const { history } = this.props;
    if(isLogin) {
      history.push('/passport')
    }else {
      let obj = {};
      obj[key] = true;
      this.setState({
        ...obj
      });
    }
  }

  handleToShowInvite = () => {
    QRCode.toDataURL('http://m.julyedu.com/invite', {
      width: 120,
      height: 120,
      margin: 1
    })
    .then(url => {
      this.setState({
        inviteUrl: url,
        inviteVisible: true
      });
    })
    .catch(err => {
      console.error(err)
    });
  }

  handleToShowNotice = () => {
    http.get(`${API['base-api']}/sys/activity/create_blessing_qrcode`).then(res => {
      const {errno, data} = res.data;
      if (errno === 200) {
        QRCode.toDataURL(data.url, {
          width: 120,
          height: 120,
          margin: 1
        })
        .then(url => {
          this.setState({
            isServer: true,
            serverUrl: url,
          });
        })
        .catch(err => {
          console.error(err)
        });
      }else if(errno === 4030 || errno === 4040) {
        location.href = `http://passport.julyedu.com/login?redirect=${encodeURI(document.URL)}`;
      }
    });
  }

  onCopy = () => {
    Toast.info('复制成功', 2,null,false)
  }

  render() {
    const { userInfo, isRule, isCourse, inviteUrl, inviteVisible, isFormal, isServer, serverUrl, isSign, showRecordList, shareMark} = this.state
    return (
      <div id={'blessing-preheat'}>
        <Banner/>
        {/* 积福气 */}
        <ListHeader text="积福气，享受更多福利" styles={{margin: '0 0 15px'}} />
        <CollectBlessing
          isSign={isSign}
          userInfo={userInfo}
          handleToShowList={() => this.handleToShow('isCourse')}
          handleToShowInvite={this.handleToShowInvite}
          handleToShowNotice={this.handleToShowNotice}
          handleToShow={this.handleToShow}
        />

        {/* 幸运大抽奖--预热 */}
        <ListHeader text="幸运大抽奖" styles={{margin: '30px 0 10px'}} />
        <p className="luck-draw__tip">- 将于11月11日10点开启 -</p>
        <button className="luck-draw__button" onClick={() => this.handleToShow('isRule')}>活动规则></button>
        <LuckDraw />

        {/*定金--只在预热期间显示*/}
        {
          isFormal === 0 &&
          <>
            <ListHeader text="预付1元定金，最高可省100元" styles={{margin: '30px 0 15px'}} />
            <ReserveCourse />
          </>
        }

        {/* 精品课程特惠专区 */}
        <ListHeader text="精品课程特惠专区" styles={{margin: '30px 0 15px'}} />
        <CourseList isFormal={isFormal} />

        {
          isRule &&
          <RulePopup handleToHide={() => this.handleToHide('isRule')}/>
        }
        {
          isCourse &&
          <CoursePopup handleToHide={() => this.handleToHide('isCourse')}/>
        }
        {
          showRecordList &&
          <RecordPopup handleToHide={() => this.handleToHide('showRecordList')}/>
        }
        {
          shareMark &&
          <SharePopup handleToHide={() => this.handleToHide('shareMark')}/>
        }
        <Popup
          visible={inviteVisible}
          title={'扫码邀请好友注册+10点福气值'}
          className={'invite-popup'}
        >
          <img src={inviteUrl} alt="barcode" className="qr-code"/>
          <CopyToClipboard text="http://m.julyedu.com/invite" onCopy={this.onCopy}>
            <button>一键复制网址</button>
          </CopyToClipboard>
        </Popup>
        <Popup
          visible={isServer}
          title="扫码关注“七月在线”服务号"
          className={'invite-popup'}
        >
          <img src={serverUrl} alt="barcode" className="qr-code"/>
        </Popup>


        <Popup visible={this.state.joinLotteryVisible}
               title={'你已成功参与本时段抽奖'}
               className={'join-lottery'}
        >
          <div className="text">
            <div className="code">抽奖码为：99999999</div>
            <div className="time">本时段的中奖结果将在xx:xx公布</div>
            <div className="hint">你可关注‘七月在线’服务号第一时间获得中奖信息。</div>
            <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/tinypng-common/right_weixin.png" className='qr-code' alt=""/>
          </div>

          <button onClick={() => {this.setState({joinLottery: false})}}>知道了</button>
        </Popup>
        <Popup title={'微信扫码分享到微信朋友圈'}
               visible={this.state.timelineShareVisible}
               className={'timeline-share'}
        >
          <img src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/tinypng-common/right_weixin.png" alt="" className="qr-code"/>
        </Popup>


        <ListHeader text="全国AI工程师水平测试" styles={{margin: '30px 0 15px'}} />
        <div className="test__record" onClick={() => this.handleToShow('showRecordList')}>
          测试记录>
        </div>
        <LevelTest></LevelTest>


        <RankList></RankList>

        <Live></Live>
      </div>
    )
  }
}

export default BlessingPreheat
