import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import Notice from '@components/Notice'
import BackHomeBtn from '@components/BackHomeBtn'
import AchievePhone from '@components/achievePhone'
import Poster from '@components/Poster'
import FormIdCollector from '@components/formIdCollector'
import dayjs from 'dayjs'
// import WxParse from '@components/wxParse/wxParse'
// import getUserPhone from '@utils/getUserPhone'
import ready from '@utils/ready'
import { getDownloadURL, times, formateLeftTime, getCanvasConfig, getThumbnail } from '@utils/tools'
import {
  getGroupDetail,
  createGroupActivity,
  joinGroupBuy,
} from '@services/activity'
import {
  getMiniQrcode,
  savePoint,
  updatePoint
} from '@services/common'
import { connect } from '@tarojs/redux'

const waitImg = require('@assets/helpgroup/wait.png')
const memberImg = require('@assets/helpgroup/group/member.png')
const successImg = require('@assets/helpgroup/group/success.png')
const failImg = require('@assets/helpgroup/group/fail.png')
const quoteImg = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/images/quota.png'

// 活动状态
const ActBeforeStart = 0;
const ActInProcess = 1;
const ActFinished = 2;

// 发起的拼团状态
const GroupInProcess = 1;
const GroupSuccess = 0;
const GroupFailure = 2;

@connect(state => state.user)
export default class Detail extends Component {

  config = {
    navigationBarTitleText: '拼团详情'
  }

  state = {
    id: null, // 活动ID
    recordId: undefined,  // 发起拼团ID
    loaded: false,
    detail: {}, // 活动详情
    recordDetail: {}, // 发团记录
    memberList: [], // 团员记录
    shares: [], // 分享设置
    posters: [],  // 海报设置
    posterTpls: [], // 海报模板
    leftTime: 0,  // 剩余时间
    ltTicker: undefined,  // 剩余时间计时器
    actState: ActBeforeStart,  // 活动本身状态
    groupState: undefined, // 发起拼团活动的状态
    isStarter: true, // 是否发起人
    submitting: false, // 是否提交中
    actionSheetVisible: false, // 底部分享好友
    posterVisible: false, // 海报分享
    grantPhoneVisible: false, // 授权电话
    grantAvatarVisible: false, // 授权头像
    pointRecordId: undefined, // 埋点ID
  }

  componentWillMount() {
    ready.queue(() => {
      // 必须授权电话
      if (this.toggleGrantPhone()) {
        this.initPageData()
      }
    })
  }

  componentWillUnmount() {
    this.stopTicker()
    this.state.pointRecordId && updatePoint(this.state.pointRecordId)
  }

  componentDidShow() {
    this.startTicker()
  }

  componentDidHide() {
    this.stopTicker()
  }

  // 初始化页面数据
  initPageData = () => {
    if (!this.state.detail.groupActivityId) {
      let id = this.$router.params.id
      let recordId = this.$router.params.recordId

      if (!id) {
        const router = Taro.getStorageSync('router')
        id = router.query.id
        recordId = router.query.recordId
      }

      this.setState({ id, recordId }, () => {
        this.loadDetail()
      })
    }
  }

  // 启动 ticker
  startTicker() {
    if (this.state.ltTicker && !this.state.ltTicker.processing) {
      this.state.ltTicker.start()
    }
  }

  // 清除 ticker
  stopTicker() {
    if (this.state.ltTicker) {
      this.state.ltTicker.stop()
    }
  }

  // 调起授权电话
  toggleGrantPhone = () => {
    const { userInfo: { person: { phone, tel } } } = this.props
    if (!phone && !tel) {
      this.setState({ grantPhoneVisible: true })
      return false
    }

    return true
  }

  // 调起授权头像
  toggleGrantAvatar = () => {
    const { userInfo: { person: { avatarurl } } } = this.props
    if (!avatarurl) {
      this.setState({ grantAvatarVisible: true })
      return false
    }

    return true
  }

  // 打开关闭 ActionSheet 面板
  toggleActionVisible = () => {
    const { actionSheetVisible } = this.state

    if (this.state.ltTicker) {
      actionSheetVisible ? this.startTicker() : this.stopTicker()
    }

    this.setState({
      actionSheetVisible: !actionSheetVisible
    })
  }

  // 打开关闭海报面板
  togglePosterVisible = () => {
    const { posterVisible, posters, actionSheetVisible } = this.state

    if (!posters || !posters.length) {
      Taro.showToast({
        title: '未设置海报模板',
        icon: 'none'
      })
      return
    }

    // actionSheet 需要隐藏掉
    const showActionSheet = posterVisible ? actionSheetVisible : false

    this.setState({
      posterVisible: !posterVisible,
      actionSheetVisible: showActionSheet,
    })
  }

  compActState = (startDate, endDate) => {
    const st = dayjs(startDate).valueOf()
    const ed = dayjs(endDate).valueOf()
    const nw = dayjs().valueOf()

    if (st > nw) {
      // 活动未开始
      return [ActBeforeStart, st - nw]
    } else if (ed > nw) {
      // 活动进行中
      return [ActInProcess, ed - nw]
    } else {
      // 活动已结束
      return [ActFinished, 0]
    }
  }

  // 计时器更新剩余时间
  getLeftTimeTicker(startDate, endDate) {
    let processing = false
    let ticker = undefined

    const stop = () => {
      ticker && clearInterval(ticker)
      processing = false
    }

    const fn = () => {
      const [actState, leftTime] = this.compActState(startDate, endDate)
      this.setState({ actState, leftTime })

      if (actState === ActFinished) {
        stop()
      }
    }

    const start = () => {
      ticker = setInterval(fn, 1000)
      processing = true
    }

    return {
      start,
      stop,
      processing,
    }
  }

  loadDetail() {
    let { id, recordId, ltTicker } = this.state
    const { userInfo } = this.props

    Taro.showLoading()
    getGroupDetail(id, recordId).then(res => {
      this.stopTicker()

      const recordDetail = res.taShareRecord || {}
      let [actState, leftTime] = this.compActState(res.taShareActivity.startTime, res.taShareActivity.endTime)

      if (res.taShareActivity.activityStatus === 2) {
        actState = ActFinished
      }

      if (actState != ActFinished) {
        ltTicker = this.getLeftTimeTicker(res.taShareActivity.startTime, res.taShareActivity.endTime)
      }

      Taro.hideLoading()
      this.setState({
        detail: res.taShareActivity,
        recordDetail,
        recordId: recordDetail.recordId,
        groupState: recordDetail.status,
        shares: res.shareContentList || [],
        posters: res.postList || [],
        posterTpls: res.posterTemplateList || [],
        memberList: res.shareChildRecordList || [],
        loaded: true,
        isStarter: userInfo.person.personId === recordDetail.personId,
        actState,
        leftTime,
        ltTicker
      }, () => this.startTicker())

      // Taro.setNavigationBarTitle({ title: res.taShareActivity.activityName })

      // WxParse.wxParse('article', 'html', res.desc, this.$scope, 0)

      savePoint({
        event: 'detail',
        eventType: 'group',
        propertyName: '拼团详情',
        buildingId: res.taShareActivity.buildingId,
        targetId: id,
        data: '{"recordId":"' + recordId + '"}'
      }).then((res) => {
        this.setState({ pointRecordId: res.recordId })
      })
    })
  }

  currentPageAndParams() {
    const { id, recordId } = this.state
    const { userInfo: { person: { personId } } } = this.props

    let queryParams = [
      `id=${id}`,
      `from=group_share`,
      `recommender=${personId}`
    ]
    if (recordId) {
      queryParams.push(`recordId=${recordId}`)
    }

    const res = [
      'pages/activity/detail/assemble',
      queryParams.join('&'),
    ]

    console.log('--page-params->', res)
    return res
  }


  onShareAppMessage = () => {
    const { shares } = this.state
    const currentPage = this.currentPageAndParams().join('?')

    savePoint({
      event: 'share',
      eventType: 'group',
      propertyName: '拼团详情分享',
      data: '{}'
    })

    if (!shares || !shares.length) {
      return {
        title: this.state.detail.activityName,
        path: currentPage,//分享地址
        imageUrl: this.state.detail.mainImg
      }
    }

    return {
      title: shares[0].shareContentTitle,
      path: currentPage,//分享地址
      imageUrl: shares[0].shareContentImg
    }
  }

  // 立即参团
  joinGroup = () => {
    const { submitting, detail, recordDetail, memberList = [] } = this.state
    const person = this.props.userInfo.person
    if (submitting) return

    Taro.showModal({
      content: `是否扣除 ${detail.integral} 积分参与拼团?`,
      success: (res) => {
        if (res.confirm) {
          Taro.showLoading()
          this.setState({ submitting: true }, () => {
            joinGroupBuy({
              recordId: recordDetail.recordId,
              groupActivityId: detail.groupActivityId,
              personId: person.personId,
              nickname: person.name || person.nickname,
              phone: person.tel || person.phone,
              avatarurl: person.avatarurl,
            }).then((res) => {
              Taro.hideLoading()
              memberList.push(res.taShareChildRecord)

              this.setState({
                submitting: false,
                memberList,
                recordDetail: res.taShareRecord,
                recordId: res.taShareRecord.recordId,
                groupState: res.taShareRecord.status,
              })

              Taro.showToast({
                title: '参团成功',
                icon: 'success'
              })
            }).catch(err => {
              console.log('err:', err)
              Taro.hideLoading()

              Taro.showToast({
                title: '失败: ' + err.message,
                icon: 'none'
              })
              // setTimeout(() => {
              //   this.loadDetail()
              // }, 500)

              this.setState({ submitting: false })
            })
          })
        } // if (res.confirm)
      }
    }) // Taro.showModal
  }

  // 发起我的拼团
  startMine = (cb) => {
    const detail = this.state.detail
    const person = this.props.userInfo.person

    Taro.showModal({
      content: `是否扣除 ${detail.integral} 积分参与拼团?`,
      success: (res) => {
        if (res.confirm) {

          // 必须授权头像
          if (this.toggleGrantAvatar()) {            
            createGroupActivity({
              groupActivityId: detail.groupActivityId,
              personId: person.personId,
              nickname: person.name || person.nickname,
              phone: person.tel || person.phone,
              avatarurl: person.avatarurl,
            }).then(res => {
              this.setState({
                recordDetail: res.taShareRecord,
                recordId: res.taShareRecord.recordId,
                memberList: res.shareChildRecordList || [],
                isStarter: true,
                groupState: res.taShareRecord.status,
              }, () => cb && cb())
            }).catch(err => {
              console.log('err:', err)
              Taro.showToast({
                title: '发起失败: ' + err.message,
                icon: 'none'
              })
            })
          }

        } // if (res.confirm)
      }
    }) // Taro.showModal
  }

  // 请求好友参团
  groupBuyInvite = () => {
    // 必须授权头像
    if (this.toggleGrantAvatar()) {
      const recordDetail = this.state.recordDetail
      if (!recordDetail.recordId) {
        // 如果是未发起的拼团, 先以当前人身份发起
        this.startMine(() => {
          this.toggleActionVisible()
        })
      } else {
        this.toggleActionVisible()
      }
    }
  }

  getQRCode() {
    const [page, scene] = this.currentPageAndParams()
    const payload = { page, scene }

    return new Promise((resolve) => {
      getMiniQrcode(payload).then(qrCode => {
        this.setState({ qrCode }, resolve)
      })
    })
  }

  // 发送朋友圈
  shareMoments = () => {
    this.getQRCode().then(() => {
      this.togglePosterVisible()
    })
  }

  transTPLs2Configs(tpls, params) {
    return tpls.map((tpl) => {
      const conf = getCanvasConfig(tpl.configs, params)
      return { ...conf }
    })
  }


  render() {
    const {
      recordId,
      recordDetail,
      detail,
      loaded,
      actState,
      posterVisible,
      isStarter,
      memberList,
      groupState,
      actionSheetVisible,
      grantPhoneVisible,
      posterTpls,
      posters,
      qrCode,
      leftTime,
      ltTicker,
    } = this.state

    const { userInfo } = this.props
    const posterData = {
      title: posters[0] ? posters[0].posterTitle : '',
      desc: posters[0] ? posters[0].posterDescription : '',
      poster: posters[0] ? getDownloadURL(posters[0].posterImg, 'alioss') : '',
      userName: userInfo.person.name || userInfo.person.nickname,
      qrcode: getDownloadURL(qrCode, 'alioss'),
      quote: getDownloadURL(quoteImg, 'alioss'),
      avatar: getDownloadURL(userInfo.person.avatarurl, 'avatar') || '',
      date: dayjs().format('YYYY.MM.DD'),
      appName: (userInfo.miniApp || {}).name,
    }

    // 团长显示团长核销码, 参团的显示参团核销码
    const verificationCode = isStarter ? recordDetail.verificationCode : (memberList.filter(x => x.personId === userInfo.person.personId)[0] || {}).verificationCode

    const joinedNum = detail.groupBuyPeople - (recordDetail.recordId ? 1 : 0) - memberList.length

    const posterConfigs = this.transTPLs2Configs(posterTpls, posterData)

    console.log('------posterData------', posterData)
    console.log('------posterConfigs------', posterConfigs)

    const isJoin = memberList.filter(x => x.personId === userInfo.person.personId)[0] || isStarter

    return (
      <Block>
        {/* 生成海报 */}
        {posterVisible && !ltTicker.processing &&
          (
            <Poster configs={posterConfigs} onCancel={this.togglePosterVisible} onFinish={this.togglePosterVisible}></Poster>
          )
        }

        {
          grantPhoneVisible &&
          <AchievePhone user={userInfo.person} onSuccess={this.initPageData}></AchievePhone>
        }
        <BackHomeBtn></BackHomeBtn>
        {
          loaded && (
            <View className="ass-page">
              <Notice></Notice>
              <View className="detail-banner">
                <Image mode="widthFix" src={getThumbnail(detail.mainImg)} className="detail-banner__img"></Image>

                <View className="rest-time">
                  <Text className="row-label">{actState === ActBeforeStart ? '距活动开始 :' : (actState === ActInProcess ? '活动剩余时间 :' : '')} </Text>
                  <Text className="row-text">{actState != ActFinished ? formateLeftTime(leftTime) : '活动已结束'}</Text>
                </View>
                {detail.successNum > 0 &&
                  <View className="success-num">
                    <View className="triangle"></View>
                    <View className="text">已成功 {detail.successNum}</View>
                  </View>
                }
              </View>
              <ScrollView
                scrollY
                className="detail-wrap">
                <View className="detail">
                  <View class="detail-title">{detail.activityName}</View>
                  <View className="detail-info" >
                    <View style="margin-right:30px">所需<Text style="color:#FF245A">{detail.integral}</Text>积分</View>
                    <Image style="width:20px;height:20px;margin-right:2px" src={memberImg} ></Image>
                    <Text >{detail.groupBuyPeople}人团</Text>
                  </View>
                  {
                    groupState === GroupSuccess &&
                    (
                      <Block>
                        <Image className="status__img" style="margin:12rpx auto 24rpx auto" src={successImg}></Image>
                        <View className="hexiaoma" style="margin:0 auto 40rpx auto">核销码: {verificationCode}</View>
                      </Block>
                    )
                  }

                  {
                    groupState === GroupFailure &&
                    (
                      <View>
                        <Image className="status__img" style="margin:12rpx auto 24rpx auto" src={failImg}></Image>
                        <View className="fail-text" style="margin:0 auto 40rpx auto">活动已超时,拼团失败!</View>
                      </View>
                    )
                  }

                  {isStarter &&
                    <View className="detail-title" >我的拼团</View>
                  }

                  <View className='tools-main'>
                    {
                      recordDetail.recordId &&
                      (
                        <View className='tools-item'>
                          <Image src={recordDetail.avatarurl} className='tools-item-img'></Image>
                          <View className='leader-tip'>团长</View>
                          <Text className='tools-item-txt'>{recordDetail.nickname}</Text>
                        </View>
                      )
                    }
                    {
                      memberList.map((it, inx) => {
                        return (
                          <View className='tools-item' key={`group-${inx}`}>
                            <Image src={it.avatarurl} className='tools-item-img'></Image>
                            <Text className='tools-item-txt'>{it.nickname}</Text>
                          </View>
                        )
                      })
                    }
                    {
                      times(joinedNum).map((_, inx) => {
                        return (
                          <View className='tools-item' key={`un-${inx}`}>
                            <Image src={waitImg} className='tools-item-img'></Image>
                            <Text className='wait-txt'>等待拼团</Text>
                          </View>
                        )
                      })
                    }
                  </View>
                </View>

                <View className="assistance-text"><Text className="acitivty-desc">活动说明</Text>-------------------------------------------------------------- </View>
                <View style="padding:0 40rpx 180rpx 40rpx">
                  <Image src={getThumbnail(detail.descImg)} mode="widthFix" style="width:100%;"></Image>
                </View>
                { (actState === ActBeforeStart||(isStarter && actState === ActInProcess && groupState === GroupInProcess)||(!isStarter && actState === ActInProcess && groupState != GroupInProcess )||(!isStarter && actState === ActInProcess && groupState === GroupInProcess))&&
                <View className="btn-fixed">
                  {
                    actState === ActBeforeStart &&
                    (<View className="nostart-btn"><FormIdCollector><Button className="nostart-btn" style="margin: auto">未开始</Button></FormIdCollector></View>)
                  }
                  {
                    isStarter && actState === ActInProcess && groupState === GroupInProcess &&
                    (<View className="assistance-btn"><FormIdCollector><Button className="assistance-btn" style="margin: auto" onClick={this.groupBuyInvite}>邀请好友拼团</Button></FormIdCollector></View>)
                  }
                  {
                    !isStarter && actState === ActInProcess && groupState != GroupInProcess &&

                    <View className={groupState === GroupInProcess ? "set-btn" : "assistance-btn"}>
                      <FormIdCollector>
                        <Button className={groupState === GroupInProcess ? "set-btn" : "assistance-btn"} onClick={this.startMine}>发起我的拼团</Button>
                      </FormIdCollector>
                    </View>
                  }
                  {
                    !isStarter && actState === ActInProcess && groupState === GroupInProcess &&

                    <View className="btn-box" style="margin: auto; padding: 0;">
                      {
                        (groupState === GroupInProcess && !isJoin) &&
                        (<View className="assistance-btn"><FormIdCollector><Button className="assistance-btn" onClick={this.joinGroup}>立即参团</Button></FormIdCollector></View>)
                      }                      
                      <View className={groupState === GroupInProcess && !isJoin ? "set-btn" : "assistance-btn"}>
                        <FormIdCollector>
                          <Button className={groupState === GroupInProcess && !isJoin ? "set-btn" : "assistance-btn"} onClick={this.startMine}>发起我的拼团</Button>
                        </FormIdCollector>
                      </View>
                    </View>

                  }
                </View>
                }
              </ScrollView>

              <action-sheet hidden={!actionSheetVisible} bindchange={this.toggleActionVisible}>
                <action-sheet-item open-type="share">
                  <Button open-type="share" className='share__friend' onClick={this.toggleActionVisible}>分享给好友</Button>
                </action-sheet-item>
                <action-sheet-item>
                  <Button className='creat__img' onClick={this.shareMoments}>发送朋友圈</Button>
                </action-sheet-item>
                <action-sheet-cancel onClick={this.toggleActionVisible}>取消</action-sheet-cancel>
              </action-sheet>
            </View>
          )
        }
      </Block>
    )
  }
}
