import React, { Component } from 'react';
import './team.scss'
import { getParam, http, SendMessageToApp } from "@/utils"
import { Toast } from 'antd-mobile';
import {withRouter} from 'react-router-dom';
import {compose} from "redux"
import { connect } from "react-redux";
import jsCookie from 'js-cookie'

class TeamInfo extends Component {
  constructor(props) {
    super(props);
    this.state = {
      is_my_team: false, // 是否有自己的队伍
      prize_info: [],
      info: {
        removable: 0,
        total: 0
      },
      member: [],
      removable_data: [],
      my_team: {},
    }
  }

  componentDidMount() {
    this.getTeamInfo();
  }

  // 获取队伍信息
  getTeamInfo = () => {
    http.get(`${API.home}/sys/treasure/teamInfo`).then(res => {
      const { code, data, msg } = res.data;
      if (code === 200) {
        const { prize_info, is_my_team, info, member, removable_data, my_team } = data;
        this.setState({
          prize_info,
          is_my_team,
          info,
          member: this.fillTeam(member, is_my_team),
          removable_data,
          my_team
        })
        let currentId = null;
        if(info.removable > 0) {
          currentId = removable_data[0].id;
        }
        this.props.getRemovable(info.removable, currentId);
      } else {
        Toast.info(msg);
      }
    })
  }

  // 跳转到我的宝箱页
  toYearTreasure = (close) => {
    if(this.props.user.hasError) {
      this.toLogin();
    } else {
      let search = '';
      if(close) {
        const {removable_data, info: {removable}} = this.state;
        if(removable > 0) {
          let current = removable_data[0];
          search = `?id=${current.id}`;
        }
      }
      if (!getParam('version')) {
        this.props.history.push(`/year/yearTreasure${search}`);
      } else {
        this.props.history.push(`/year/yearTreasure${search}?version=${getParam('version')}`);
      }
    }

  }

  // 去登录
  toLogin = () => {
    if (!getParam('version')) {
        this.props.history.push('/passport/login')
    } else {
        SendMessageToApp("toLogin")
    }
  }

  // 邀请好友组队
  createTeam = () => {
    if(this.props.user.hasError) {
      this.toLogin();
    } else {
      const {is_my_team, my_team: {treasure_code}} = this.state;
      if(is_my_team) { // 有自己的队伍
        // 直接跳转

        if (!getParam('version')) {
          this.props.history.push('/activity/newyear-2019/landing?origin=1&treasure_code=' + treasure_code);
        } else {
          this.props.history.push('/activity/newyear-2019/landing?origin=1&treasure_code=' + treasure_code + '&version='+ getParam('version'));
        }

      }else{ // 没自己的队伍
        // 请求创建队伍的接口
        http.get(`${API.home}/sys/treasure/createMyTeam`).then(res => {
          const { code, data, msg } = res.data;
          if (code === 200) {
            const { treasure_code } = data;
            if (!getParam('version')) {
              this.props.history.push('/activity/newyear-2019/landing?origin=1&treasure_code=' + treasure_code);
            } else {
              this.props.history.push('/activity/newyear-2019/landing?origin=1&treasure_code=' + treasure_code + '&version='+ getParam('version'));
            }
          } else {
            Toast.info(msg);
          }
        });
      }
    }
  }

  // 队伍成员信息必须满五个 不满的需要填充
  fillTeam = (list, is_my_team) => {
    let len = list.length;
    // 没有创建队伍 并且没有加入他人队伍
    if(this.props.user.hasError) {
      for(let i=0;i<5-len;i++) {
        list.push({
          head_img: '',
          user_name: '',
          nobody: true,
        })
      }
    } else {
      if(len === 0 && !is_my_team) {
        list.push({
          head_img: jsCookie.get('avatar_file'),
          user_name: jsCookie.get('user_name'),
        })
        for(let i=0;i<4;i++) {
          list.push({
            head_img: '',
            user_name: '',
            nobody: true,
          })
        }
      }else{
        for(let i=0;i<5-len;i++) {
          list.push({
            head_img: '',
            user_name: '',
            nobody: true,
          })
        }
      }
    }

    return list;
  }

  render() {
    const { prize_info, is_my_team, info: {removable, total}, member } = this.state;
    let name = '', stage_no = 0;
    if(prize_info.length > 0) {
      name = prize_info[0].name;
      stage_no = prize_info[0].stage_no;
    }
    // 显示文案控制
    let Text = '';
    if(total === 0) {
      Text = `我的宝箱`;
    } else if (removable === 0) {
      Text = `共${total}个宝箱`;
    } else {
      Text = `共${total}个宝箱/${removable}个未开`;
    }

    return (
      <div className='team_info__container'>
        <div className='team__member'>
          <ul className='member__list'>
            {
              member && member.length > 0 && (
                member.map((item, index) => {
                  return <li key={index} className='member__item'>
                    <div className='avatar__container'>
                      {
                        item.nobody ? (
                          <img className='head__image' src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/default-member-avatar.png" alt=""/>
                        ) : (
                          <img className='head__image' src={item.head_img} alt=""/>
                        )
                      }
                      {
                        index === 0 ? (
                          <img className='caption__flag' src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/caption.png" alt=""/>
                        ) : (null)
                      }
                      <div className='shadow'></div>
                    </div>
                    <div className={`member__join ${item.nobody ? '' : 'join'}`}></div>
                  </li>
                })
              )
            }
          </ul>

          <div className='box__number'>
            <img onClick={() => this.toYearTreasure(true)} src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/treasure-box-icon.png" alt="" />
            <p onClick={() => this.toYearTreasure(false)} className='box__text'>
              {Text}
            </p>
            <img className='position__arrow' src="https://julyedu-cdn.oss-cn-beijing.aliyuncs.com/newyear20/H5/arrow_jinzhan.png" alt=""/>
            {
              removable > 0 && (
                <div className='position__number'>{removable}</div>
              )
            }
          </div>
        </div>
        <div onClick={this.createTeam} className='invite__btn'>
          {
            is_my_team ? ('继续组队') : ('组队开宝箱')
          }
        </div>
        {
          stage_no > 0 && name && <p className='stage_prize'>{`第${stage_no}次必中${name}`}</p>
        }
      </div>
    )
  }
}
export default compose(
  connect(
      state => ({user: state.user}),
      null
  ),
  withRouter
)(TeamInfo)
