import React, { Component } from 'react';
import classnames from 'classnames';
import { withRouter, Link } from 'react-router-dom';
import { http } from '@/utils';
import { Popup } from '@common';
import SplitSuccess from './../common/splitSuccess/index';
import './team.scss';

class TreasureTeam extends Component {
  constructor(props) {
    super(props);
    this.state = {
      team: {},
      currentMember: {}
    };
  }

  componentDidMount() {
    this.initMemberInfo();
  }

  handleToInvite = () => {
    const { history } = this.props;
    history.push('/activity/newyear-2019/landing');
    if(this.splitInstance) {
      this.splitInstance.close();
    }
  }

  initMemberInfo = () => {
    const { data } = this.props;
    let members = data.members;
    let len = members.length - 5;
    for(; len < 0; len++) {
      members.push({});
    }
    this.setState({
      team: Object.assign({}, data, {
        members
      }),
      currentMember: members[0]
    });
  }

  computedClass = (id) => {
    const { data: { is_open } } = this.props;
    const { currentMember } = this.state;
    return classnames(
      'team-member__item',
      {
        'active': id === currentMember.uid && is_open,
      }
    );
  }

  computedBg = (val) => {
    return val? {
      backgroundImage: `url(${val})`
    } : {};
  }

  // 查看队友的奖品，条件：宝箱已拆
  toCheckPrize = (id) => {
    const { team: { is_open, members = []} } = this.state;
    if(is_open) {
      const data = members.filter(item => item.uid === id);
      this.setState({
        currentMember: data[0]
      });
    }
  }

  toSplitTreasure = () => {
    const { handleToBindPhone, handleToBindAddress } = this.props;
    const { team: {captain_uid, team_num} } = this.state;
    http.post(`${API.home}/sys/split_treasure`, {
      team_num: team_num,
      owner_uid: captain_uid
    }).then(res => {
      const { code, data } = res.data;
      if(code === 200) {
        // 拆宝箱弹窗--成功
        this.splitInstance = Popup({
          title: '恭喜你获得',
          skip: 'year',
          content: <SplitSuccess handleToInvite={this.handleToInvite} />
        });
      }else if(code === 12000) {
        // 绑定手机号
        handleToBindPhone();
      }else if(code === 12001) {
        // 绑定地址
        handleToBindAddress();
      }
    });
  }

  render() {
    const { 
      team: {
        id,
        is_captain,
        status,
        team_num,
        lack_member,
        is_open,
        members = [],
        prize_type,
        bing_phone,
        bing_address,
      },
      currentMember: {
        prize_name
      }
   } = this.state;
    return (
      <div className="team-container" data-skip="team">
        {
          !is_captain &&
          <i className="team-friend">友</i>
        }
        
        {/* 组队状态 */}
        {
          status === 1
          ? <i className="team-status">组队中..</i>
          : <i className="team-decorate"></i>
        }

        {/* 队伍类型 */}
        {
          is_captain
          ? <h2 className="team-title">{team_num}号队伍</h2>
          : <h2 className="team-title">好友队伍</h2>
        }
        

        {/* 队员情况 */}
        {
          status === 1
          ? <p className="team-desc">还差{lack_member}名队员即可获得宝箱哦～</p>
          : <p className="team-desc">组队成功</p>
        }
        <div className="team-member">
          {
            members.map((item, index) => (
              <div 
                className={this.computedClass(item.uid)}
                onClick={() => this.toCheckPrize(item.uid)}
                key={item.id}
                style={this.computedBg(item.head_img)}
              >
                {
                  item.is_captain &&
                  <span className="team-member__captain">队长</span>
                }
              </div>
            ))
          }
        </div>
        <div className="team-footer" data-layout={is_open? 'column': 'row'}>
          {/* 队伍未满 */}
          {
            status === 1 && 
            <>
              {
                is_captain
                ? <Link className="team-button" to="/activity/newyear-2019/landing">继续邀请队友</Link>
                : <Link className="team-button" to="/activity/newyear-2019/landing">帮好友完成组队</Link>
              }
            </>
          }

          {/* 可拆状态 */}
          {
            (status === 2 && !is_open) &&
            <>
              <span className="team-icon" data-direction="left"></span>
              <span className="team-button--split" onClick={this.toSplitTreasure}></span>
              <span className="team-icon" data-direction="right"></span>
            </>
          }

          {/* 已拆状态 */}
          {
            (status === 2 && is_open) &&
            <>
              <p className="team-prize">{prize_name}</p>

              {/* 第一：是否需要绑定手机号 */}
              {
                bing_phone &&
                <a className="treamsure-team__result" onClick="$emit('to-bind-phone', data.bing_address)">
                  <span>绑定手机号</span>
                </a>
              }

              {/* 第二：是否需要填写地址 */}
              {
                (!bing_phone && bing_address) &&
                <a className="treamsure-team__result" onClick="$emit('to-bind-address')">
                  <span>查看/修改收货信息</span>
                </a>
              }

              {/* 第三：奖品，代金券碎片 */}
              {
                (!bing_phone && !bing_address && prize_type === 6) &&
                <a 
                  href="/my/coupon" 
                  target="_blank"
                  className="treamsure-team__result"
                >
                  可合成代金券在购课时使用，
                  <span>去合成</span>
                </a>
              }

              {/* 第三：奖品，指定课程代金券 */}
              {
                (!bing_phone && !bing_address && prize_type === 3) &&
                <a 
                  href="/my/coupon" 
                  target="_blank"
                  className="treamsure-team__result"
                >
                  已发放至您的账户，
                  <span>去使用</span>
                </a>
              }

              {/* 第三：奖品，通用课程代金券 */}
              {
                (!bing_phone && !bing_address && prize_type === 4) &&
                <a 
                  href="/my/coupon" 
                  target="_blank"
                  className="treamsure-team__result"
                >
                  已发放至您的账户，
                  <span>去使用</span>
                </a>
              }

              {/* 第三：奖品，现金红包 */}
              {
                (!bing_phone && !bing_address && prize_type === 7) &&
                <a 
                  href="/my/coupon" 
                  target="_blank"
                  className="treamsure-team__result"
                >
                  已存入您的账户，
                  <span>去提现</span>
                </a>
              }

              {/* 第三：奖品，线上课程 */}
              {
                (!bing_phone && !bing_address && prize_type === 2) &&
                <a 
                  href="/my/coupon" 
                  target="_blank"
                  className="treamsure-team__result"
                >已发放至您的账户</a>
              }
            </>
          }
        </div>
      </div>
    )
  }
}

export default withRouter(TreasureTeam);