import Taro, { Component } from '@tarojs/taro'
import { View, Image, Text, Navigator } from '@tarojs/components'
import LoginPopup from '@/c/login/Popup'
import PopupAd from './components/discountGroup/popup'
import './discountGroup.scss'

class Index extends Component {
  onShareAppMessage() {
    const { eId, eName } = this.$router.params
    const { launchObj } = this.state
    if (launchObj.hash) {
      return {
        title: `我想参加${eName}的洪楼团购，快来帮我助力下`,
        path: `/pagesPlan/discountGroup?eId=${eId}&eName=${eName}&hash=${launchObj.hash}`,
      }
    } else {
      return {
        title: '南昌买房，来洪楼领取专属优惠',
        path: `/pagesPlan/discountGroup?eId=${eId}`,
      }
    }
  }
  onShareTimeline () {
    const { eId, eName } = this.$router.params
    const { launchObj } = this.state
    if (launchObj.hash) {
      return {
        title: `我想参加${eName}的洪楼团购，快来帮我助力下`,
        path: `/pagesPlan/discountGroup?eId=${eId}&eName=${eName}&hash=${launchObj.hash}`,
      }
    } else {
      return {
        title: '南昌买房，来洪楼领取专属优惠',
        path: `/pagesPlan/discountGroup?eId=${eId}`,
      }
    }
  }



  constructor (props) {
    super(props)
    this.state = {
      searchKey: '',
      page_size: 10,
      page: 1,
      isListEnd: false,
      isListLoading: false,
      isListEmpty: false,
      dataList: [],
      isRuleShow: false,
      isSharePopup: false,
      launchObj: {},
      joinArr: [],
      userInfo: '',
      token: '',
      isLoginPopupShow: false,
      activityObj: {},
      isJoin: false,
      isGetShow: false,
    }
  }

  config = {
    navigationStyle: 'custom',
    navigationBarTextStyle: 'white'
  }

  componentWillMount () {
    Taro.$AHU(this)
    const { eId, hash } = this.$router.params
    if (hash) {
      this.getDtl()
    } else {
      this.getMyDtl()
    }
  }

  getMyDtl () {
    const { eId } = this.$router.params
    this.setState({
      userInfo: Taro.getStorageSync('APP_userInfo') || {},
      token: Taro.getStorageSync('APP_token') || ''
    })
    Taro.api.other.apiactivitybuyinginfo({estate_id: eId}).then(res => {
      if (res.launch) {
        this.setState({
          joinArr: res.join || [],
          launchObj: res.launch || {},
          activityObj: res.activity || {},
          isJoin: res.is_join || false
        }, () => {
          if (res.launch.status === 3 || res.launch.status === 4 || res.launch.status === 5 || res.launch.status === 6) {
            this.openGetPopup()
          }
          // this.showQrCode()
        })
      } else {
        this.setState({
          activityObj: res.activity || {},
          isRuleShow: true
        })
      }
    })
  }

  getDtl () {
    this.setState({
      userInfo: Taro.getStorageSync('APP_userInfo') || {},
      token: Taro.getStorageSync('APP_token') || ''
    })
    const { hash } = this.$router.params
    Taro.api.other.apiactivitybuyinghash({hash}).then(res => {
      if (res.launch) {
        this.setState({
          joinArr: res.join || [],
          launchObj: res.launch || {},
          activityObj: res.activity || {},
          isJoin: res.is_join || false
        }, () => {
          if (this.subPopup) this.subPopup.getData({poster_img: res.activity.poster_img})
          const { joinArr, activityObj } = this.state
          if (joinArr.length === activityObj.option_req) {
            Taro.$msgConfirm('你的好友已领取团购优惠，看看这个楼盘？', () => {
              this.linkHouseDtl()
            })
          }
        })
      } else {
        Taro.$msgConfirm('没有查到助力数据，看看这个楼盘？', () => {
          this.linkHouseDtl()
        })
      }
    })
  }

  componentDidShow () { }

  componentDidHide () { }

  renderRule () {
    const { isRuleShow, launchObj, activityObj } = this.state
    // console.log(activityObj.rule_img)
    // const bg = require('./img/discountGroup/ex_rule.png')
    const bgClose = require('@img/icon_g_close2.png')
    return (
      <View className={isRuleShow ? 'l-modal-box' : 'l-modal-box hide'}>
        <View className='lmb-bg'></View>
        <View className='lmb-body'>
          <View className="scoped-rule">
            <Image src={activityObj.rule_img} className="bg" />
            <View className="ops">
              <View className="op t2" onClick={this.backPrevPage.bind(this)}>返回上一页</View>
              {
                launchObj.id
                ?
                <View className="op" onClick={this.closeRulePopup.bind(this)}>我知道了</View>
                :
                <View className="op" onClick={this.toHelpMe.bind(this)}>我已阅读,发起助力</View>
              }
            </View>
            {
              launchObj.id
              ?
              <Image src={bgClose} className="close" onClick={this.closeRulePopup.bind(this)} />
              :
              <Image src={bgClose} className="close" onClick={this.backPrevPage.bind(this)} />
            }
          </View>
        </View>
      </View>
    )
  }
  backPrevPage () {
    let pages = getCurrentPages()
    if (pages.length < 2) {
      Taro.reLaunch({
        url: '/pages/index/index'
      })
    } else {
      Taro.navigateBack({
        delta: 1
      })
    }
  }
  toHelpMe () {
    const { eId } = this.$router.params
    Taro.api.other.apiactivitybuyinglaunch({estate_id: eId}).then(res => {
      this.setState({
        launchObj: res || {},
        isRuleShow: false,
        isSharePopup: true,
      })
    })
  }
  dealPopup (str) {
    const { bc } = this.props
    const { formObj } = this.state
    if (bc) {
      if (str === 'confirm') {
        bc('confirm', formObj)
      } else {
        bc()
      }
    }
  }
  openRulePopup () {
    this.setState({
      isRuleShow: true
    })
  }
  closeRulePopup () {
    this.setState({
      isRuleShow: false
    })
  }

  closeSharePopup () {
    this.setState({
      isRuleShow: false,
      isSharePopup: false
    }, () => {
      this.getMyDtl()
    })
  }

  helpHandle () {
    const { hash } = this.$router.params
    Taro.api.other.apiactivitybuyingjoin({hash}).then(res => {
      Taro.$msgConfirm('助力成功', () => {
        this.linkHouseDtl()
      }, () => {
        this.linkHouseDtl()
      })
    })
  }

  getUserProfile (e) {
    wx.getUserProfile({
      desc: '用于完善头像和昵称资料',
      success: (res) => {
        const dtlObj = res || {}
        this.setState({
          userInfo: dtlObj.userInfo
        })
        Taro.setStorageSync('APP_userInfo', dtlObj.userInfo)
      }
    })
  }
  openLoginPopup (obj) {
    this.setState({
      isLoginPopupShow: true
    })
  }
  closeLoginPopup (str) {
    this.setState({
      isLoginPopupShow: false
    })
    if (str && str === 'success') {
      this.getDtl()
    }
  }



  linkHome () {
    Taro.reLaunch({
      url: '/pages/index/index'
    })
  }
  renderGoHome () {
    const icon = require('@img/images/icon_go_home.png')
    return (
      <Image className="g-go-home" src={icon} onClick={this.linkHome.bind(this)}/>
    )
  }

  linkHouseDtl () {
    const { eId } = this.$router.params
    Taro.navigateTo({
      url: `/pagesHouse/indexDtl?id=${eId}`
    })
  }

  showQrCode () {
    const { userInfo } = this.state
    const { joinArr, activityObj, launchObj } = this.state
    if (joinArr.length === activityObj.option_req) {
      Taro.$msgConfirm(`恭喜您，获得团购优惠~优惠码：${userInfo.phone}-${launchObj.hash}`)
    }
  }
  openGetPopup () {
    this.setState({
      isGetShow: true
    })
  }
  closeGetPopup () {
    this.setState({
      isGetShow: false
    })
  }

  renderGetSuccess () {
    const { userInfo } = this.state
    const { launchObj } = this.state
    const bg = require('./img/discountGroup/bg_s.png')
    const bg1 = require('./img/discountGroup/bg_s1.png')
    const bg2 = require('./img/discountGroup/bg_s2.png')
    const bged = require('./img/discountGroup/bg_sed.png')
    const bged1 = require('./img/discountGroup/bg_sed1.png')
    const bged2 = require('./img/discountGroup/bg_sed2.png')
    const { eId } = this.$router.params
    const { eName } = this.$router.params
    return (
      <View className="get-success">
        <View className="bg"></View>
        {
          launchObj.status === 3
          &&
          <Image src={bg1} className="bgImg" />
        }
        {
          launchObj.status === 4
          &&
          <Image src={bg2} className="bgImg" />
        }
        {
          launchObj.status === 5
          &&
          <Image src={bg} className="bgImg" />
        }
        {
          launchObj.status === 6
          &&
          <Image src={bg} className="bgImg" />
        }
        <View className="gs-wrap">
          <View className={launchObj.status === 5 ? 'gs-code' : 'gs-code t2'}>
            <View className="p1">优惠码</View>
            <View className="p2">{userInfo.phone}-{launchObj.hash}</View>
          </View>
          <View className="gs-footer">
            <View className="b t2" onClick={this.closeGetPopup.bind(this)}>关闭</View>
            <Navigator url={`/pagesPlan/apply2?eId=${eId}&eName=${eName}`} className="b">去填写意向</Navigator>
          </View>
          {
            launchObj.status === 3
            &&
            <Image src={bged1} className="gs-ed" />
          }
          {
            launchObj.status === 4
            &&
            <Image src={bged2} className="gs-ed" />
          }
          {
            launchObj.status === 6
            &&
            <Image src={bged} className="gs-ed" />
          }
        </View>
      </View>
    )
  }


  onPopupRef = (ref) => {
    this.subPopup = ref
  }

  render () {
    const bg = require('./img/discountGroup/bg_full.jpg')
    const bgRule = require('./img/discountGroup/icon_rule.png')
    const bg2 = require('./img/discountGroup/share_popup.png')
    const bgLine = require('./img/discountGroup/bg_line.png')
    const exUser = require('./img/discountGroup/ex_user.png')
    const { isSharePopup, launchObj, activityObj, joinArr } = this.state
    const cArr = new Array(activityObj.option_req).fill({name: '待助力'})
    const joinItems = cArr.map((item, index) => {
      let tag = '待助力'
      if (joinArr[index] && joinArr[index].id) tag = '已助力'
      return (
        <View className={tag === '已助力' ? 'dgs-item t2' : 'dgs-item'} key={index}>
          <View className="dgs-img">
            <Image src={tag === '已助力' ? joinArr[index].avatar : exUser} className="img" />
          </View>
          <View className="dgs-text">{tag}</View>
        </View>
      )
    })
    const { hash } = this.$router.params
    const { userInfo, token } = this.state
    const uInfo = userInfo || Taro.getStorageSync('APP_userInfo')
    const { isLoginPopupShow } = this.state
    const { eName } = this.$router.params
    const { isGetShow } = this.state
    return (
      <View className="l-box">
        <PopupAd onRef={this.onPopupRef} />
        {this.renderGoHome()}
        {
          uInfo && uInfo.avatarUrl
          ? token || isLoginPopupShow
          ? ''
          : <Button className="g-u-btn" onClick={this.openLoginPopup.bind(this)}></Button>
          : <Button className="g-u-btn" onClick={this.getUserProfile.bind(this)}></Button>
        }
        <LoginPopup show={isLoginPopupShow} close={this.closeLoginPopup.bind(this)} />
        {this.renderRule()}
        <View className="discount-group">
          <Image src={bg} className="dg-bg" />
          <Image src={bgRule} className="dg-rule-btn" onClick={this.openRulePopup.bind(this)} />
          <View className="dg-wrap">
            <View className="dg-top">
              <View className="dgt-img">
                <Image src={launchObj.avatar || exUser} className="img" />
              </View>
              <View className="dgt-text">{hash ? '好友': '我'}的助力</View>
            </View>
            <View className="dg-info">
              <View className="p1">{hash ? `你的好友${launchObj.nickname}想买${eName}` : `领${eName}专属优惠`}</View>
              <View className="p2">{activityObj.rule}</View>
              <View className="p3">截止时间：{activityObj.end_at}</View>
              <View className="p4" onClick={this.openRulePopup.bind(this)}>查看详细规则</View>
            </View>
            {
              hash
              ?
              <View className="dg-btn">
                {
                  isJoin
                  ?
                  <View className="text" onClick={this.linkHouseDtl.bind(this)}>已助力,去看看这个楼盘</View>
                  :
                  <View className="text" onClick={this.helpHandle.bind(this)}>帮他助力</View>
                }
              </View>
              :
              <View className="dg-btn">
                {
                  joinArr.length === activityObj.option_req
                  ?
                  <Button className="text" onClick={this.openGetPopup.bind(this)}>恭喜您，助力成功，查看凭证</Button>
                  :
                  <Button className="text btn-to-div" openType="share">喊好友助力</Button>
                }
              </View>
            }
            <View className="dg-share">
              <View className="dgs-header">
                <Image className="bg" src={bgLine} />
                <View className="t">好友助力进度{joinArr.length}/{activityObj.option_req}人</View>
              </View>
              <View className="dgs-content">
                {joinItems}
              </View>
            </View>
          </View>
          {
            isSharePopup
            &&
            <View className="dg-popup">
              <View className="bg"></View>
              <Image src={bg2} className="img" />
              {/* <Button className="yes btn-to-div" openType="share"></Button> */}
              <View className="no" onClick={this.closeSharePopup.bind(this)}></View>
            </View>
          }
          {
            isGetShow
            &&
            this.renderGetSuccess()
          }
        </View>
      </View>
    )
  }
}

export default Index
