import React, { Component } from 'react';
import { connect } from 'react-redux';
import DocumentTitle from 'react-document-title';
import 'antd-mobile/dist/antd-mobile.less';
import styles from './index.less';
import router from 'umi/router';
import PlayMusic from '../components/playMusic/index';
import { onPlay, getPlayFlag, setImg } from '../common/common';
import { sysMobileNum } from '../../../utils/helper';

import icon03 from '../assets/detail/icon03.png';
import icon04 from '../assets/detail/icon04.png';
import * as Service from '../services/index';
import { Toast } from 'antd-mobile';
@connect(() => ({}))
class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      playFlag: getPlayFlag(),
      popFlag: false,
      numflag: true,
      number: null,
      numberT: null,
      catFoodList: [],
      schoolDetail: {},

      votes: 0, //总的投票数
      loading: false, //请求中
    };
  }
  componentWillMount = () => {};
  componentDidMount = () => {
    this.getSchoolDetail();
  };

  //获取学校信息详情
  getSchoolDetail = () => {
    const detailStr = window.sessionStorage.getItem('selectSchool');
    const schoolDetail = JSON.parse(detailStr);
    this.setState({
      schoolDetail,
      votes: schoolDetail && schoolDetail.votes ? schoolDetail.votes : '0',
    });
  };

  onClick = () => {
    const { number, loading } = this.state;
    if (number || loading) {
      return;
    }

    this.feed();

    // this.feeding();
    // this.raise(70);
    // this.popFlag(true);
  };

  //喂养
  feed = async () => {
    const { schoolDetail } = this.state;

    var openId = window.localStorage.getItem('openId');

    //makeOpenId
    if (!openId) {
      openId = sysMobileNum;
      window.localStorage.setItem('openId', sysMobileNum);
    }
    if (!schoolDetail.schoolCode || !openId) {
      return;
    }

    const params = {
      id: schoolDetail.schoolCode,
      wxOpenId: openId,
      subscribe: 0,
    };

    const { rc, data, msg } = await Service.feed(params);

    try {
      if (!rc) {
        // alert(JSON.stringify(data));
        if (data && data.type === '1' && data.thisVotes === '0' && data.totalVotes === '100') {
          //弹出100内容提示框
          this.popFlag(true, true);
        } else if (data && data.thisVotes) {
          //播放喂养动画
          this.raise(data.thisVotes ? parseInt(data.thisVotes) : 10);
          this.feeding();
          this.setState({
            votes: data.votes,
          });
        }
      } else {
        Toast.info(msg, 2);
      }
    } catch (e) {}

    //修改加载状态
    this.setState({
      loading: false,
    });
  };
  /****
   * 猫数字和文案动画
   */
  raise = number => {
    const _this = this;
    _this.setState({
      number,
      numberT: number,
    });
    setTimeout(function() {
      _this.setState({
        number: null,
      });
    }, 2000);
  };
  /****
   * 撒猫粮动画
   */
  feeding = () => {
    const _this = this;
    const catFoodList = new Array(30);
    for (var i = 0; i < catFoodList.length; i++) {
      const x = 6.66 * Math.random().toFixed(2);
      const animationDuration = Math.random().toFixed(2) * 0.5 + 0.8;
      const animationDelay = Math.random().toFixed(2) * 0.6;
      const rotate = 360 * Math.random().toFixed(2);
      const scale = Math.random().toFixed(2) * 0.5 + 0.5;
      const style = {
        left: `${x}rem`,
        animationDuration: `${animationDuration}s`,
        animationDelay: `${animationDelay}s`,
        transform: `rotate(${rotate}deg) scale(${scale})`,
      };
      catFoodList[i] = { style };
    }
    _this.setState({
      catFoodList,
    });
    setTimeout(function() {
      _this.setState({
        catFoodList: [],
      });
    }, 2000);
  };

  /****
   * 弹窗提示
   * flag 弹窗开启
   * numflag true弹出100的内容框  false弹出150的内容框
   */
  popFlag = (flag, numflag) => {
    this.setState({
      numflag: numflag,
      popFlag: flag,
    });
  };

  render() {
    const {
      popFlag,
      numflag,
      playFlag,
      number,
      numberT,
      catFoodList,
      schoolDetail,
      votes,
    } = this.state;
    return (
      <DocumentTitle title="校宠开饭啦">
        <div>
          <PlayMusic
            play={playFlag}
            onPlay={() => {
              onPlay(playFlag, flag => {
                this.setState({
                  playFlag: flag,
                });
              });
            }}
          ></PlayMusic>
          <div className={styles.body}>
            <div>
              <div className={styles.top_n}>
                <span>投喂总量：{votes ? votes : ''}</span>
              </div>

              <div className={styles.top_d}>
                {schoolDetail && schoolDetail.catDescription ? schoolDetail.catDescription : ''}
              </div>
              <div className={styles.top_bg}>
                <div className={styles.top_bg_l}>
                  {schoolDetail && schoolDetail.schoolName ? schoolDetail.schoolName : ''}
                  <span> {schoolDetail && schoolDetail.catName ? schoolDetail.catName : ''}</span>
                </div>
                {/* <img
                  src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1589271335573&di=84ebb7c94a33f8c40d546030a7666171&imgtype=0&src=http%3A%2F%2Fc.hiphotos.baidu.com%2Fbaike%2Fpic%2Fitem%2F6a63f6246b600c33d5a41de31b4c510fd9f9a138.jpg"
                  alt="icon"
                /> */}
                <img
                  src={schoolDetail && schoolDetail.catImg ? setImg(schoolDetail.catImg) : ''}
                  alt="校宠美照"
                />
              </div>
              <div className={styles.btn} onClick={this.onClick}></div>
            </div>
            <div className={styles.cat}>
              <div
                className={`${styles.raise} ${number ? styles.animation : null} ${
                  number === 10
                    ? styles.raise_10
                    : number === 30
                    ? styles.raise_30
                    : number === 70
                    ? styles.raise_70
                    : number === 100
                    ? styles.raise_100
                    : null
                }`}
              >
                <div></div>
                <div></div>
                <div></div>
                <div></div>
                <div></div>
              </div>
              <div
                className={`${styles.raise_t} ${
                  numberT === 10
                    ? styles.raise_10_t
                    : numberT === 30
                    ? styles.raise_30_t
                    : numberT === 70
                    ? styles.raise_70_t
                    : numberT === 100
                    ? styles.raise_100_t
                    : null
                }`}
              ></div>
            </div>
            {catFoodList.map((food, i) => (
              <div key={i} className={styles.cat_food} style={food.style}></div>
            ))}
          </div>
          <div className={`${styles.pop_w} ${popFlag ? styles.pop_w_a : null}`}>
            <div className={styles.pop_c}>
              {numflag ? <img src={icon03} alt="100" /> : <img src={icon04} alt="150" />}
              <div
                className={styles.pop_closed}
                onClick={() => {
                  router.push('share');
                }}
              ></div>
            </div>
          </div>
        </div>
      </DocumentTitle>
    );
  }
}

export default Index;
