import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import Notice from '@components/Notice'
import BackHomeBtn from '@components/BackHomeBtn'
import Poster from './poster'
import dayjs from 'dayjs'
import WxParse from '@components/wxParse/wxParse'
import getUserPhone from '@utils/getUserPhone'
import ready from '@utils/ready'
import { getDownloadURL, times, getThumbnail } from '@utils/tools'
import {
  addActivityShareNum,
  signupActivity,
  favorActivity,
  cancelFavorActivity,
  queryActivityDetail
} from '@services/activity'
import {
  getMiniQrcode,
  savePoint,
  updatePoint
} from '@services/common'
import { connect } from '@tarojs/redux'

@connect(state => state.user)
export default class Detail extends Component {
  config = {
    navigationBarTitleText: '活动详情'
  }

  state = {
    id: null,
    loaded: false,
    detail: {},
    recordId: null,
    isSaved: false,
    isSign: false,
    posterShow: false,
    posterData: {},
    posterVisible: false,
    selector: [],
    selectorChecked: '1',
    canChoose: 'none',
    inputName: ''
  }

  componentWillMount() {
    ready.queue(() => {
      const router = Taro.getStorageSync('router')
      const id = this.$router.params.id || router.query.id || '2fe920719b8b0db50011441462e647ad'
      this.setState({ id }, () => {
        this.loadDetail()
      })
    })
  }
  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)
  }

  loadDetail() {
    const { id } = this.state
    Taro.showLoading()
    queryActivityDetail(id).then(res => {
      Taro.hideLoading()
      const { isSaved, isSign } = res
      this.setState({
        detail: res,
        isSaved,
        isSign,
        loaded: true,
        selector: times(res.maxEnlistByPerson || 1).map((_, i) => `${i + 1}`),
      }, () => {

        const { detail } = this.state
        if (detail.posters && detail.posters.length && detail.posters[0].posterImg) {
          this.setState({
            posterShow: true
          })
        }
      })
      WxParse.wxParse('article', 'html', res.desc, this.$scope, 0)

      savePoint({
        event: 'detail',
        eventType: 'activity',
        propertyName: '活动详情',
        buildingId: res.buildingId,
        targetId: res.dynamicId,
        data: '{}'
      }).then(res1 => {
        this.setState({
          recordId: res1.recordId
        })
        console.log('活动详情')
      })
    })
  }
  onShareAppMessage = () => {
    const { detail: { shareContents, title, dynamicId, url } } = this.state
    const { userInfo: { person: { personId } } } = this.props
    console.log(dynamicId, "path")
    console.log(personId, "personId")

    addActivityShareNum(dynamicId)


    savePoint({
      event: 'share',
      eventType: 'activity',
      propertyName: '活动详情分享',
      data: '{}'
    }).then(res => {
      console.log('活动详情分享')
    })

    return {
      title: shareContents[0].shareContentTitle,
      path: `/pages/activity/detail/index?id=${dynamicId}&from=dynamic_share&recommender=${personId}`,//分享地址
      imageUrl: shareContents[0].shareContentImg
    }

  }

  handleSignup() {
    const { detail: { buildingId, dynamicId }, isSign } = this.state
    const { userInfo: { person: { phone, name, nickname } } } = this.props

    if (isSign) {
      Taro.showToast({
        icon: 'none',
        title: '你已报名成功'
      })
      return
    }

    this.setState({
      canChoose: 'block'
    })
  }

  handleFavor() {
    const { detail: { dynamicId }, isSaved } = this.state
    if (isSaved) {
      cancelFavorActivity(dynamicId).then(res => {
        Taro.showToast({
          title: '已取消收藏'
        })
        this.setState({
          isSaved: false
        })
      })
    } else {
      favorActivity(dynamicId).then(res => {
        Taro.showToast({
          title: '收藏成功'
        })
        this.setState({
          isSaved: true
        })
      })
    }
    savePoint({
      event: 'save',
      eventType: 'activity',
      propertyName: '活动详情收藏',
      data: '{}'
    }).then(res => {
      console.log('活动详情收藏')
    })
  }

  handleGetPhone(e) {
    getUserPhone(e, (phoneNumber) => {
      if (phoneNumber) {
        this.handleSignup()
      } else {
        Taro.showToast({
          title: '报名失败',
          icon: 'none'
        })
      }
    })
  }
  getPosterData = () => {
    return new Promise(resolve => {
      const { posterData } = this.state
      if (posterData.qrcode) {
        resolve(posterData)
        return
      }

      const { userInfo: { person } } = this.props
      const { avatarurl, nickname, personId } = person
      const { detail: { dynamicId, posters, createDate } } = this.state
      const payload = {
        "scene": `id=${dynamicId}&from=dynamic_share&recommender=${personId}`,
        "page": 'pages/activity/detail/index',
      }
      // debugger
      const _avatarurl = getDownloadURL(avatarurl, 'avatar');
      getMiniQrcode(payload).then(qrcode => {
        let data = {
          qrcode,//小程序二维码
          nickname,//访问者名字
          avatarurl: _avatarurl,//访问者头像
          poster: posters[0].posterImg,
          title: posters[0].posterTitle,//海报标题
          posterDescription: posters[0].posterDescription,//海报标题
          createDate: createDate,//时间
        }
        resolve(data)
      })
    })
  }
  // 开始生成海报
  togglePosterStatus = (flag) => {
    if (flag) {
      this.getPosterData().then(posterData => {
        this.setState({
          posterVisible: !!flag,
          posterData
        })
      })
      // App.zhuge.track('生成活动详情海报')
    } else {
      this.setState({
        posterVisible: !!flag
      })
    }
    savePoint({
      event: 'poster',
      eventType: 'activity',
      propertyName: '生成活动详情海报',
      data: '{}'
    }).then(res => {
      console.log('生成活动详情海报')
    })
  }

  handleMoreClick() {
    // App.zhuge.track('查看置业顾问列表')
    console.log()
    Taro.navigateTo({
      url: `/pages/card/list/index?buildingId=${this.state.detail.buildingId}`
    })
  }

  onChange = e => {
    this.setState({
      selectorChecked: this.state.selector[e.detail.value]
    })
  }

  onInputText = e => {
    this.setState({
      inputName: e.detail.value
    })
  }

  comfire = e => {

    const { detail: { buildingId, dynamicId }, isSign, selectorChecked, inputName } = this.state
    const { userInfo: { person: { phone, name, nickname, tel } } } = this.props

    if (inputName == '') {
      Taro.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return
    }

    const payload = {
      buildingId,
      dynamicId,
      name: inputName,
      phone: phone ? phone : tel,
      attendNum: selectorChecked
    }

    signupActivity(payload).then(res => {
      Taro.showToast({
        title: '报名成功'
      })
      this.setState({
        isSign: true,
        canChoose: 'none'
      })
    })

    savePoint({
      event: 'enlist',
      eventType: 'activity',
      propertyName: '活动详情报名',
      data: '{}'
    }).then(res => {
      console.log('活动详情报名 ')
    })
  }

  hideModal() {
    this.setState({
      canChoose: 'none'
    })
  }

  render() {
    const { detail, loaded, isSaved, isSign, posterVisible, posterData, posterShow } = this.state
    const { userInfo: { person: { phone } } } = this.props
    return (
      <Block>
        {/* 生成海报 */}
        {posterVisible && (<Poster data={posterData} toggle={this.togglePosterStatus}></Poster>)}

        {
          loaded && (
            <View>
              <Notice></Notice>
              <View className="detail-banner">
                <Image mode="aspectFill" src={getThumbnail(detail.imgUrl)} className="detail-banner__img"></Image>
              </View>
              <ScrollView
                scrollY
                className="detail-wrap">
                <View className="detail bottom-box">
                  {detail.isEnlist == 0 &&
                    <View className="detail-sign__num">不需要报名</View>
                  }
                  {detail.isEnlist != 0 &&
                    <View className="detail-sign__num">{detail.enlisted || 0}人已报名</View>
                  }
                  <View class="detail-title">{detail.title}</View>
                  <View className="detail-top">
                    <View className="detail-top__row">
                      <Text className="row-label">活动时间：</Text>
                      <Text className="row-content">{dayjs(detail.startDate).format('YYYY-MM-DD HH:mm:ss')}</Text>
                    </View>
                    <View className="detail-top__row">
                      <Text className="row-label">活动地址：</Text>
                      <Text className="row-content">{detail.address}</Text>
                    </View>
                    {detail.isEnlist != 0 &&
                      <View className="detail-top__row">
                        <Text className="row-label">报名截止：</Text>
                        {detail.enlistEnd &&
                          <Text className="row-content">{dayjs(detail.enlistEnd).format('YYYY-MM-DD HH:mm:ss')}</Text>
                        }
                      </View>
                    }
                  </View>
                  <View className="detail-con">
                    <View className="detail-con__title">活动详情</View>
                    <import src='../../../components/wxParse/wxParse.wxml' />
                    <template is='wxParse' data='{{wxParseData:article.nodes}}' />
                  </View>
                  <View style="color:#999;font-size:15px;margin:0 auto 90px auto;text-align:center">已经到底了~</View>

                </View>
              </ScrollView>

              <View className="chat-entrance" onClick={this.handleMoreClick}>
                <Text className="iconfont icon-chat"></Text>
              </View>

              <BackHomeBtn></BackHomeBtn>

              <View className="bot-nav flex">
                {
                  posterShow && (
                    <Button className='btn poster-btn' onClick={() => { this.togglePosterStatus(true) }}>
                      <Image mode="aspectFill" src={require('@assets/tupian_3@3x.png')} className="btn-icon"></Image>
                      <Text className="txt">海报</Text>
                    </Button>
                  )
                }
                <Button className="btn share-btn" open-type="share">
                  <Image mode="aspectFill" src={require('@assets/fasong@3x.png')} className="btn-icon"></Image>
                  <Text className="txt">分享</Text>
                </Button>

                <Button className="btn" onClick={this.handleFavor}>
                  <Text className={`iconfont ${isSaved ? 'icon-shoucang selected' : 'icon-shoucang1'}`}></Text>
                  <Text className="txt">收藏</Text>
                </Button>
                {
                  parseInt(detail.isEnlist) != 0 && detail.activityStatus != 2 && (parseInt(detail.isEnlist) == 2 ? (<Button disabled='true' className='submit-btn hasSigned'>报名人数已满</Button>) : ((phone ? (
                    <Button disabled={isSign} className={`submit-btn ${isSign ? 'hasSigned' : ''}`} onClick={this.handleSignup}>{isSign ? '已报名' : '立即报名'}</Button>
                  ) : (
                      <Button disabled={isSign} className='submit-btn' open-type="getPhoneNumber" onGetphonenumber={this.handleGetPhone}>{isSign ? '已报名' : '立即报名'}</Button>
                    ))))
                }
                {detail.activityStatus == 2 &&
                  <Button disabled='true' className='submit-btn hasSigned' >立即报名</Button>
                }

                {/* {phone ? (
                  <Button disabled={isSign} className={`submit-btn ${isSign ? 'hasSigned' : ''}`} onClick={this.handleSignup}>{isSign ? '已报名' : '立即报名'}</Button>
                ) : (
                    <Button disabled={isSign} className='submit-btn' open-type="getPhoneNumber" onGetphonenumber={this.handleGetPhone}>{isSign ? '已报名' : '立即报名'}</Button>
                  )} */}
              </View>

              <View className='page-body' style={{ display: this.state.canChoose }}>
                <View className="mask" onClick={this.hideModal}></View>
                <View className='page-section'>
                  <Text className="page-section__title">报名信息</Text>
                  <View className='page-content'>
                    <Input className='inputName' onInput={this.onInputText.bind(this)} type='text' placeholder='请输入姓名' />
                    <Picker mode='aspectFill' range={this.state.selector} onChange={this.onChange}>
                      <View className='picker'>
                        <Text>参加人数</Text>
                        <Text className='content'>{this.state.selectorChecked}</Text>
                        <Text>人</Text>
                      </View>
                    </Picker>
                    <View onClick={this.comfire} className='comfire'>确认</View>
                  </View>
                </View>
              </View>
            </View>
          )
        }
      </Block>
    )
  }
}