import React, { Component } from 'react'
import { connect } from 'react-redux'
import { HeaderBar } from '@common'
import AddressPopup from '@common/addressPopup/index'
import BindPhone from '@common/bindPhone/index'
import ConfirmPhone from '@common/confirmPhone/index'
import CreateSuccess from './../common/createSuccess/index'
import TreasureTeam from './team'
import PrizeStatus from './prize'
import SplitSuccess from './../common/splitSuccess/index'
import { http, getParam, SendMessageToApp, browser } from '@/utils'
import Mask from './mask'
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: {}, // 绑定手机号冲突信息
      isPhone: false,
      isAddress: false,
      isConfirm: false,
      confirmInfo: {},
      isSplit: false,
      isCreate: false,
      createInfo: {},
      prizeName: '', // 当前商品的名字
      treasureTime: '', // 宝箱活动结束时间
    }
  }

  componentDidMount() {
    this.fetchMyTreasure()
    this.fetchActivityStatus()
    document.title = '七月在线新春献礼，幸运宝箱随你开，100%有奖！“薪”年好课免费学，精品课程1分秒！';
  }

  componentWillReceiveProps(nextProp) {
    const {history} = this.props
    const {userInfo} = nextProp
    if (!userInfo.uid) {
      history.push('/passport')
    }else {
      this.fetchMyTreasure();
    }
  }

  // 页面加载时，初始化当前需要绑定手机号的奖品名字
  initPrizeName = (params) => {
    const key = this.fetchCurrentTeamId(params)
    const data = params.filter(item => item.id == key)
    if (data.length > 0) {
      this.setState({
        prizeName: data[0]['prize_name']
      })
    }
  }

  // 页面加载时，是否需要拆宝箱
  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)
      }
    }
  }

  // 获取当前需要绑定手机的队伍id，当拆到需要绑定手机号/地址的宝箱时，如果不进行绑定则无法拆下一个
  fetchCurrentTeamId = (data = []) => {
    const arr = data.filter(item => item.is_open && (item.bind_phone || item.bind_address))
    if (arr.length > 0) {
      return arr[0]['id']
    } else {
      return ''
    }
  }

  // 页面加载时，是否是从选择区号页面过来的
  // TODO,当同时展示拆宝箱成功弹窗和绑定手机号弹窗时，选择区号返回时未展示拆宝箱成功弹窗（和产品确认，后续优化）
  isShowBindPhone = (data) => {
    const {country} = this.props
    if (country.from) {
      const id = this.fetchCurrentTeamId(data)
      this.handleToBindPhone(id)
    }
  }

  // 绑定手机号--展示
  handleToBindPhone = (id) => {
    this.setState({
      isPhone: true,
    })
  }

  // 绑定手机号--确认
  handleToConfirmPhone = (params, bindInfo) => {
    this.handleToHideWindow('isPhone')
    this.setState({
      confirmInfo: {
        params,
        bindInfo,
      },
      isConfirm: true,
    })
  }

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

  // 拆宝箱--拆
  toSplitTreasure = (params) => {
    http.post(`${API.home}/sys/split_treasure`, params).then(res => {
      const {code, data} = res.data
      if (code === 200) {
        // 拆宝箱弹窗--成功
        this.showSuccessSplit(data)

        // 更新队伍状态
        this.successSplitTreasure(data)
        if (data.bind_phone) {
          setTimeout(() => {
            this.handleToBindPhone(data.id)
          }, 500)
        } else if (data.bind_address) {
          setTimeout(() => {
            this.handleToBindAddress(data.id, data.prize_name)
          }, 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,
          prize_type: params.prize_type,
          prize_data: params.prize_data,
          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,
      splitInfo: params,
      prizeName: params.prize_name
    })
  }

  // 拆宝箱--成功，展示弹窗
  showSuccessSplit = (data) => {
    this.setState({
      isSplit: true,
      splitInfo: data
    })
  }

  // 绑定地址--展示
  handleToBindAddress = (id, prizeName = '') => {
    if (id) {
      if(prizeName) {
        this.setState({
          prizeName
        })
      }else {
        const {teams} = this.state
        const data = teams.filter(item => item.id == id)
        if (data.length > 0) {
          this.setState({
            prizeName: data[0]['prize_name']
          })
        }
      }
    }
    this.setState({
      isAddress: true
    })
  }

  // 绑定地址--成功
  successBindAddress = () => {
    this.setState({
      isAddress: false,
    })
    const {teams, splitInfo} = this.state
    const teamId = this.fetchCurrentTeamId(teams)
    const data = teams.map(item => {
      if (item.id == teamId) {
        return Object.assign({}, item, {
          bind_address: false,
        })
      }
      return item
    })
    this.setState({
      teams: data,
      splitInfo: Object.assign({}, splitInfo, {
        bind_address: false
      })
    })
  }

  // 获取我的宝箱信息
  fetchMyTreasure = () => {
    http.get(`${API.home}/sys/treasure/my`).then(res => {
      const {code, data} = res.data
      if (code === 200) {
        this.setState({
          rule: data.rule
        })
        if (Array.isArray(data.team) && data.team.length > 0) {
          this.initNoSplitInfo(data.team)
          this.judgeIsHaveId(data.team)
          this.isShowBindPhone(data.team)
          this.initPrizeName(data.team)
          this.setState({
            isEmpty: false,
            teams: data.team,
          })
        } else {
          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) {
        if(Number(data.activity_stage) === 0) {
          this.props.history.push('/');
          return;
        }
        // treasure_stage，宝箱阶段，0-不在活动时间，1-活动时间内
        if (data.treasure_stage === 0) {
          this.startCountDown()
        }
        this.setState({
          isEnd: data.treasure_stage === 0,
          treasureTime: data.treasure_stop_date
        })
      }
    })
  }

  // 活动结束--倒计时
  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)
        if (getParam('version')) {
          history.push(`/year/yearIndex?version=${getParam('version')}`)
        } else {
          history.push('/year/yearIndex')
        }
      }
    }, 1000)
  }

  // 邀请好友
  handleToInvite = (treasure_code) => {
    const {history} = this.props
    if (getParam('version')) {
      window.location.assign(`https://h5.julyedu.com/activity/newyear-2019/landing?treasure_code=${treasure_code}&origin=1&version=${getParam('version')}`)
    } else {
      window.location.assign(`https://h5.julyedu.com/activity/newyear-2019/landing?treasure_code=${treasure_code}&origin=1`)
    }
  }

  // 组队开宝箱
  toOrganizeTeam = () => {
    const {history, userInfo: {uid = ''}} = this.props
    if (uid === '') {
      history.push('/passport')
    } else {
      http.get(`${API.home}/sys/treasure/createMyTeam`).then(res => {
        const {code, data} = res.data
        if (code === 200) {
          const teams = []
          teams[0] = data
          this.setState({
            isEmpty: false,
            teams,
            isCreate: true,
            createInfo: data
          })
        }
      })
    }
  }

  // 奖品，代金券碎片--合成
  toComposeCoupon = () => {
    const {history} = this.props
    if (getParam('version')) {
      SendMessageToApp("toCoupon")
    } else {
      history.push('/coupons/my-patch')
    }
  }

  // 奖品，指定课程代金券--使用
  toUseCoupon = (id) => {
    const {history} = this.props
    if (getParam('version')) {
      SendMessageToApp("toCourse", id)
    } else {
      history.push(`/detail?id=${id}`)
    }
  }

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

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

  // 弹窗--隐藏
  handleToHideWindow = (key) => {
    const param = {}
    param[key] = false
    this.setState(param)
  }

  render() {
    const {history, userInfo, country} = this.props
    const {
      isEnd,
      isEmpty,
      seconds,
      teams,
      ids,
      isPhone,
      isAddress,
      isConfirm,
      isSplit,
      splitInfo = {},
      confirmInfo: {
        params = {},
        bindInfo = {}
      },
      isCreate,
      createInfo,
      prizeName,
      rule,
      treasureTime,
    } = this.state
    return (
      <div data-skip="treasure">
        {(!browser.isAndroidApp && !browser.isIOSApp) && <HeaderBar title="我的宝箱" arrow={true}/>}
        {
          isEnd &&
          <div className="team-empty">
            <p className="activity-end__desc">
              活动已结束<br/>
              {seconds}s后将自动返回首页
            </p>
          </div>
        }
        {
          (!isEnd && isEmpty) &&
          <div className="team-empty">
            <i className="team-empty__icon"></i>
            <p className="team-empty__desc">您当前还没有宝箱哦~</p>
            <p className="team-empty__desc">快去组队邀请好友一起开宝箱吧！</p>
            <button className="team-empty__button" onClick={this.toOrganizeTeam}>组队开宝箱</button>
          </div>
        }
        {
          (!isEnd && !isEmpty && userInfo.uid) &&
          <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(item.id)}
                    toComposeCoupon={this.toComposeCoupon}
                    toUseCoupon={() => this.toUseCoupon(item.prize_data)}
                    toCourseList={this.toCourseList}
                    toFecthMoney={this.toFecthMoney}
                  />
                </TreasureTeam>
              ))
            }

            {/* 拆宝箱--弹窗，成功 */}
            <Mask visible={isSplit} handleToHide={() => this.handleToHideWindow('isSplit')}>
              <SplitSuccess
                ids={ids}
                data={splitInfo}
                handleToInvite={() => this.handleToInvite(splitInfo.treasure_code)}
                handleToBindPhone={this.handleToBindPhone}
                handleToBindAddress={this.handleToBindAddress}
                successSplitTreasure={this.successSplitTreasure}
              >
                <PrizeStatus
                  data={splitInfo}
                  handleToBindPhone={this.handleToBindPhone}
                  handleToBindAddress={this.handleToBindAddress}
                  toComposeCoupon={this.toComposeCoupon}
                  toUseCoupon={() => this.toUseCoupon(splitInfo.prize_data)}
                  toCourseList={this.toCourseList}
                  toFecthMoney={this.toFecthMoney}
                />
              </SplitSuccess>
            </Mask>

            {/*绑定手机号--弹窗 */}
            <Mask visible={isPhone} className="popup-bind-phone" handleToHide={() => this.handleToHideWindow('isPhone')}>
              <BindPhone
                history={history}
                country={country}
                hideBindPhone={() => this.handleToHideWindow('isPhone')}
                handleToConfirmPhone={this.handleToConfirmPhone}
                successBindPhone={this.successBindPhone}
                desc={
                  <>
                    <p className="phone-treasure__desc">恭喜您获得 {prizeName}</p>
                    <p className="phone-treasure__notice">为了您的账户安全，请于{treasureTime}前绑定手机号，过期将失效</p>
                  </>
                }
              />
            </Mask>

            {/* 绑定手机号--弹窗，确认 */}
            <Mask visible={isConfirm} handleToHide={() => this.handleToHideWindow('isConfirm')}>
              <ConfirmPhone
                data={params}
                bindInfo={bindInfo}
                handleToCancle={() => this.handleToHideWindow('isConfirm')}
                successBindPhone={this.successBindPhone}
              />
            </Mask>

            {/* 绑定地址--弹窗 */}
            <Mask visible={isAddress} className="popup-bind-address" handleToHide={() => this.handleToHideWindow('isAddress')}>
              <AddressPopup
                skip="year"
                tip={
                  <>
                    <p className="address-treasure__desc">恭喜您获得 {prizeName}</p>
                    <p className="address-treasure__notice">请及时填写/确认收货信息，活动结束后统一邮寄</p>
                  </>
                }
                successBindAddress={this.successBindAddress}
              />
            </Mask>

            {/* 组队成功 */}
            <Mask visible={isCreate} handleToHide={() => this.handleToHideWindow('isCreate')}>
              <CreateSuccess
                data={createInfo}
                handleToInvite={() => {
                  this.handleToInvite(createInfo.treasure_code)
                  this.handleToHideWindow('isCreate')
                }}
              />
            </Mask>
          </div>
        }
        {
          rule &&
          <>
            <div className="activity-rule__header">
              <i className="activity-rule__decorate"></i>
              <h2 className="activity-rule__title">活动规则</h2>
              <i className="activity-rule__decorate"></i>
            </div>
            <div className="activity-rule__body" dangerouslySetInnerHTML={{__html: rule}}></div>
          </>
        }
      </div>
    )
  }
}

export default MyTreasure
