import React, { Component } from 'react';
import { connect } from 'react-redux';
import { HeaderBar, Popup } from '@common';
import AddressPopup from '@common/addressPopup/index';
import BindPhone from '@common/bindPhone/index';
import ConfirmPhone from '@common/confirmPhone/index';
import TreasureTeam from './team';
import PrizeStatus from './prize';
import SplitSuccess from './../common/splitSuccess/index';
import { http, getParam } from '@/utils';
import './index.scss';

@connect(({country, user}) => ({
  country,
  userInfo: user.data
}))
class MyTreasure extends Component {
  popupInstance = null;

  constructor(props) {
    super(props);
    this.state = {
      isEnd: false,
      isEmpty: false,
      seconds: 3,
      teams: [],
      ids: [], // 未拆宝箱统计
      bindInfo: {}, // 绑定手机号冲突信息
    };
  }

  componentDidMount() {
    const { isEnd, bindInfo } = this.state;
    if (isEnd) {
      this.startCountDown();
    }
    this.fetchMyTreasure();
    this.fetchActivityStatus();
  }

  componentWillUnmount() {
    if(this.phoneInstance) {
      this.phoneInstance.close();
    }
    if(this.confrimInstance) {
      this.confrimInstance.close();
    }
    if(this.splitInstance) {
      this.splitInstance.close();
    }
    if(this.addressInstance) {
      this.addressInstance.close();
    }
  }

  // 页面加载时，是否需要拆宝箱
  judgeIsHaveId = (data) => {
    const id = getParam('id');
    if(id) {
      const newData = data.filter(item => item.id == id);
      if(newData.length > 0) {
        const params = {
          team_num: newData[0]['team_num'],
          owner_uid: newData[0]['captain_uid']
        };
        this.toSplitTreasure(params);
      }
    }
  }

  // 绑定手机号--展示
  handleToBindPhone = (id) => {
    const { history, country } = this.props;
    this.phoneInstance = Popup({
      title: '绑定手机号',
      content: <BindPhone
        history={history}
        country={country}
        hideBindPhone={this.hideBindPhone.bind(this)}
        handleToConfirmPhone={this.handleToConfirmPhone}
        successBindPhone={() => this.successBindPhone(id)}
        desc={
          <>
            <p className="phone-treasure__desc">恭喜您获得 奖品名称（现金）</p>
            <p className="phone-treasure__notice">为了您的账户安全，请于2019年12月31日前绑定手机号，过期将失效</p>
          </>
        }
      />,
      close: () => new Promise(resolve => {
        this.phoneInstance = null;
        resolve()
      })
    });
  }

  // 绑定手机号--隐藏
  hideBindPhone() {
    if (this.phoneInstance) {
      this.phoneInstance.close();
    }
  }

  // 绑定手机号--确认
  handleToConfirmPhone = (params, bindInfo) => {
    this.confrimInstance = Popup({
      title: '绑定确认',
      content: <ConfirmPhone 
        data={params} 
        bindInfo={bindInfo} 
        successBindPhone={this.successBindPhone}
      />,
      close: () => new Promise(resolve => {
        this.confrimInstance = null;
        resolve()
      })
    });
  }

  // 绑定手机号--成功
  successBindPhone = (id) => {
    const { teams } = this.state;
    const data = teams.map(item => {
      if(item.id == id) {
        if(item.bind_address) {
          this.handleToBindAddress();
        }
        return Object.assign({}, item, {
          bind_phone: false,
        });
      }
      return item;
    })
    this.setState({
      teams: data
    });
  }

  // 拆宝箱--拆
  toSplitTreasure = (params) => {
    const { ids } = this.state;
    http.post(`${API.home}/sys/split_treasure`, params).then(res => {
      const { code, data } = res.data;
      if(code === 200) {
        // 拆宝箱弹窗--成功
        this.splitInstance = Popup({
          title: '恭喜你获得',
          skip: 'year',
          content: <SplitSuccess 
            ids={ids}
            data={data}
            handleToInvite={this.handleToInvite}
            successSplitTreasure={() => this.successSplitTreasure(data)}
          >
            <PrizeStatus 
              data={data}
              handleToBindPhone={this.handleToBindPhone}
              handleToBindAddress={this.handleToBindAddress}
              toComposeCoupon={this.toComposeCoupon}
              toUseCoupon={this.toUseCoupon}
              toCourseList={this.toCourseList}
              toFecthMoney={this.toFecthMoney}
            />
          </SplitSuccess>,
          close: () => new Promise(resolve => {
            this.splitInstance = null;
            resolve()
          })
        });

        // 跟新队伍状态
        this.successSplitTreasure(data);
        if(data.bind_phone) {
          setTimeout(() => {
            this.handleToBindPhone();
          }, 500);
        }else if(data.bind_address) {
          setTimeout(() => {
            this.handleToBindAddress();
          }, 500);
        }
      }else if(code === 12000) {
        // 绑定手机号
        this.handleToBindPhone();
      }else if(code === 12001) {
        // 绑定地址
        this.handleToBindAddress();
      }
    });
  }

  // 拆宝箱--成功
  successSplitTreasure = (params) => {
    const { userInfo } = this.props;
    const { teams } = this.state;
    const data = teams.map(item => {
      if(item.id == params.id) {
        return Object.assign({}, item, {
          bind_phone: params.bind_phone,
          bind_address: params.bind_address,
          is_open: true,
          member: item.member.map(val => {
            if(val.uid == userInfo.uid) {
              return Object.assign({}, val, {
                is_open: true,
                prize_name: params.prize_name
              });
            }
            return val;
          })
        });
      }else {
        return item;
      }
    });
    this.initNoSplitInfo(data);
    this.setState({
      teams: data
    });
  }

  // 绑定地址--展示
  handleToBindAddress = () => {
    this.addressInstance = Popup({
      title: '收货信息',
      skip: 'year',
      content: <AddressPopup
        skip="year"
        tip={
          <>
            <p className="address-treasure__desc">恭喜您获得 奖品名称奖品名称奖品名称</p>
            <p className="address-treasure__notice">请及时填写/确认收货信息，活动结束后统一邮寄</p>
          </>
        }
        handleToHide={() => this.addressInstance.close()}
      />,
      close: () => new Promise(resolve => {
        this.addressInstance = null;
        resolve()
      })
    });
  }

  // 获取我的宝箱信息
  fetchMyTreasure = () => {
    http.get(`${API.home}/sys/treasure/my`).then(res => {
      const { code, data } = res.data;
      if (code === 200) {
        this.rule = data.rule;
        if (Array.isArray(data.team) && data.team.length > 0) {
          this.initNoSplitInfo(data.team);
          this.judgeIsHaveId(data.team);
          this.setState({
            isEmpty: false,
            teams: data.team,
          });
        } else {
          this.setState({
            isEmpty: true,
          });
        }
      } else if (code === 4030 || code === 4040) {
        this.setState({
          isEmpty: true,
        });
      }
    });
  }

  // 统计未拆的宝箱信息
  initNoSplitInfo = (data = []) => {
    if(data.length > 0) {
      this.setState({
        ids: data.filter(item => !item.is_open && item.status === 2).map(val => {
          return {
            team_num: val.team_num,
            owner_uid: val.captain_uid
          }
        })
      });
    }
  }

  // 获取宝箱活动状态
  fetchActivityStatus = () => {
    http.get(`${API.home}/activity/stage`).then(res => {
      const { code, data } = res.data;
      if (code === 200) {

        // treasure_stage，宝箱阶段，0-不在活动时间，1-活动时间内
        this.setState({
          isEnd: data.treasure_stage === 0
        });
      }
    });
  }

  startCountDown = () => {
    const { history } = this.props;
    let { seconds } = this.state;
    if (this.timer) {
      clearInterval(this.timer);
    }
    this.setState({
      seconds: seconds--
    });
    this.timer = setInterval(() => {
      this.setState({
        seconds: seconds--
      });
      if (seconds === 0) {
        this.setState({
          seconds: 0
        });
        clearInterval(this.timer);
        history.push('/year/yearIndex');
      }
    }, 1000);
  }

  updatedTreasureStatus = (id) => {
    console.log(id);
  }

  // 邀请好友
  handleToInvite = () => {
    const { history } = this.props;
    const { team } = this.state;
    history.push(`/activity/newyear-2019/landing?treasure_code=${team.treasure_code}&origin=1`);
    if(this.splitInstance) {
      this.splitInstance.close();
    }
  }

  // 奖品，代金券碎片--合成
  toComposeCoupon = () => {
    const { history } = this.props;
    history.push('/coupons/my-patch');
  }

  // 奖品，指定课程代金券--使用
  toUseCoupon = () => {
    const { history } = this.props;
    history.push(`/detail?id=${coupon['limit_course']}`);
  }

  // 第三：奖品，通用课程代金券--使用
  toCourseList = () => {
    const { history } = this.props;
    history.push('/classify');
  }

  // 第三：奖品，现金红包--提现
  toFecthMoney = () => {
    const { history } = this.props;
    history.push('/scholarship');
  }

  render() {
    const { history, userInfo } = this.props;
    const { isEnd, isEmpty, seconds, teams, ids } = this.state;
    return (
      <div data-skip="treasure">
        <HeaderBar title="我的宝箱" arrow={true} />
        {
          isEnd &&
          <p className="activity-end__desc">
            活动已结束<br />
            {seconds}s后将自动返回首页
          </p>
        }
        {
          (!isEnd && isEmpty) &&
          <>
            <i className="team-empty__icon"></i>
            <p className="team-empty__desc">您当前还没有宝箱哦~</p>
            <p className="team-empty__desc">快去组队邀请好友一起开宝箱吧！</p>
            <button className="team-empty__button">组队开宝箱</button>
          </>
        }
        {
          (!isEnd && !isEmpty) &&
          <div className="treasure-content">
            {
              teams.map((item, index) => (
                <TreasureTeam
                  data={item}
                  key={index}
                  userInfo={userInfo}
                  history={history}
                  splitInstance={this.splitInstance}
                  toSplitTreasure={() => this.toSplitTreasure({
                    team_num: item.team_num,
                    owner_uid: item.captain_uid
                  })}
                >
                  <PrizeStatus 
                    data={{
                      bind_phone: item.bind_phone,
                      bind_address: item.bind_address,
                      prize_type: item.prize_type,
                    }}
                    handleToBindPhone={this.handleToBindPhone}
                    handleToBindAddress={this.handleToBindAddress}
                    toComposeCoupon={this.toComposeCoupon}
                    toUseCoupon={this.toUseCoupon}
                    toCourseList={this.toCourseList}
                    toFecthMoney={this.toFecthMoney}
                  />
                </TreasureTeam>
              ))
            }
          </div>
        }
      </div>
    )
  }
}

export default MyTreasure;