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 {
  getHelpDetail,
  createHelpActivity,
  giveFriendHelp,
} from '@services/activity'
import {
  getMiniQrcode,
  savePoint,
  updatePoint
} from '@services/common'
import { connect } from '@tarojs/redux'

const successImg = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/images/helpgroup/help/success2.png'
const failImg = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/images/helpgroup/help/help%20failure.png'
const quoteImg = 'https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/images/quota.png';
const waitImg = require('@assets/helpgroup/wait.png')

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

// 发起的助力状态
const HelpInProcess = 1;
const HelpSuccess = 0;
const HelpFailure = 2;

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

  state = {
    id: null, // 活动ID
    initiateId: undefined,  // 发起活动
    loaded: false,
    detail: {}, // 活动详情
    initiateDetail: {}, // 发起详情
    helpList: [], // 助力人员列表
    shares: [], // 分享设置
    posters: [],  // 海报设置
    posterTpls: [], // 海报模板
    leftTime: 0,  // 剩余时间
    ltTicker: undefined,  // 剩余时间计时器
    actState: ActBeforeStart,  // 活动本身状态
    helpState: HelpInProcess, // 发起助力活动的状态
    isStarter: true, // 是否发起人
    submitting: false, // 是否提交中
    actionSheetVisible: false, // 底部分享好友
    posterVisible: false, // 海报分享
    grantPhoneVisible: false, // 授权电话
    grantAvatarVisible: false, // 授权头像
    handleHelpBtn: true, // 立即助力好友
    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.helpActivityId) {
      let id = this.$router.params.id
      let initiateId = this.$router.params.initiateId

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

      this.setState({ id, initiateId }, () => {
        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, initiateId, ltTicker } = this.state
    const { userInfo } = this.props

    Taro.showLoading()
    getHelpDetail(id, initiateId).then(res => {
      this.stopTicker()

      const initiateDetail = res.helpInitiateRecord || {}
      let [actState, leftTime] = this.compActState(res.helpActivity.startDate, res.helpActivity.endDate)

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

      if (actState != ActFinished) {
        ltTicker = this.getLeftTimeTicker(res.helpActivity.startDate, res.helpActivity.endDate)
      }

      Taro.hideLoading()
      this.setState({
        detail: res.helpActivity,
        initiateDetail,
        initiateId: initiateDetail.helpRecordInitiateId,
        helpState: initiateDetail.status === undefined ? HelpInProcess : initiateDetail.status,
        shares: res.shareContentList || [],
        posters: res.postList || [],
        posterTpls: res.posterTemplateList || [],
        helpList: res.helpRecordList || [],
        loaded: true,
        isStarter: !initiateDetail.personId || userInfo.person.personId === initiateDetail.personId,
        actState,
        leftTime,
        isJoin: res.isJoin,
        ltTicker
      }, () => this.startTicker())

      // Taro.setNavigationBarTitle({ title: res.helpActivity.title })

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

      savePoint({
        event: 'detail',
        eventType: 'help',
        propertyName: '助力详情',
        buildingId: res.helpActivity.buildingId,
        targetId: id,
        data: '{"initiateId":"' + initiateId + '"}'
      }).then((res) => {
        this.setState({ pointRecordId: res.recordId })
      })
    })
  }

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

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

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

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

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

    savePoint({
      event: 'share',
      eventType: 'help',
      propertyName: '助力详情分享',
      data: '{}'
    })

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

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

  // 助力好友
  handleHelp = () => {
    if (this.state.submitting) return

    Taro.showLoading()
    this.setState({ submitting: true }, () => {
      const { detail, initiateDetail } = this.state
      const person = this.props.userInfo.person

      giveFriendHelp({
        buildingId: detail.buildingId,
        helpActivityId: detail.helpActivityId,
        personId: person.personId,
        name: person.name || person.nickname,
        phone: person.tel || person.phone,
        avatarurl: person.avatarurl,
        helpRecordInitiateId: initiateDetail.helpRecordInitiateId,
      }).then((res) => {
        Taro.hideLoading()
        const helpList = this.state.helpList || []
        helpList.push(res.helpRecord)

        this.setState({
          submitting: false,
          helpList,
          initiateDetail: res.helpInitiateRecord,
          initiateId: res.helpInitiateRecord.helpRecordInitiateId,
          helpState: res.helpInitiateRecord.status === undefined ? HelpInProcess : res.helpInitiateRecord.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 })
      })
    })
  }

  // 发起我的助力
  startMine = () => {
    // 必须授权头像
    if (this.toggleGrantAvatar()) {
      const detail = this.state.detail
      const person = this.props.userInfo.person

      return new Promise((resolve, reject) => {
        createHelpActivity({
          buildingId: detail.buildingId,
          helpActivityId: detail.helpActivityId,
          personId: person.personId,
          name: person.name || person.nickname,
          phone: person.tel || person.phone,
          avatarurl: person.avatarurl,
        }).then(res => {
          this.setState({
            initiateDetail: res.helpInitiateRecord,
            initiateId: res.helpInitiateRecord.helpRecordInitiateId,
            helpList: res.helpRecordList,
            isStarter: true,
            helpState: res.helpInitiateRecord.status === undefined ? HelpInProcess : res.helpInitiateRecord.status,
          }, resolve)
        }).catch(err => {
          console.log('err:', err)
          Taro.showToast({
            title: '发起助力失败',
            icon: 'none'
          })
          reject()
        })
      })
    }

    return Promise.reject()
  }

  // 请求好友助力
  askForHelp = () => {
    // 必须授权头像
    if (this.toggleGrantAvatar()) {
      const initiateDetail = this.state.initiateDetail
      if (!initiateDetail.helpRecordInitiateId) {
        // 如果是未发起的助力, 先以当前人身份发起
        this.startMine().then(() => {
          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 {
      initiateId,
      initiateDetail,
      detail,
      loaded,
      actState,
      posterVisible,
      isStarter,
      helpList,
      helpState,
      actionSheetVisible,
      grantPhoneVisible,
      posterTpls,
      posters,
      qrCode,
      leftTime,
      ltTicker,
    } = this.state

    const { userInfo } = this.props
    const avatar = initiateId ? initiateDetail.avatarurl : userInfo.person.avatarurl
    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 posterConfigs = this.transTPLs2Configs(posterTpls, posterData)

    console.log('------posterData------', posterData)
    console.log('------posterConfigs------', posterConfigs)
    const isJoin = helpList.filter(x => x.personId === userInfo.person.personId)[0] || isStarter

    return (
      <View>
        {/* 生成海报 */}
        { 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="aspectFill" src={getThumbnail(detail.img)} 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.title}</View>
                  {
                    helpState === HelpSuccess &&
                    (
                      <Block>

                        <Image className="status__img" src={successImg}></Image>
                        {
                          isStarter && (<View className="hexiaoma">核销码: {initiateDetail.verification}</View>)
                        }
                      </Block>
                    )
                  }
                  {
                    helpState === HelpFailure &&
                    (
                      <View>
                        <Image className="status__img" src={failImg}></Image>
                        <View className="fail-text">活动已超时,助力失败!</View>
                      </View>
                    )
                  }
                  <View className="my-con">
                    <Image src={avatar} className="my-img"></Image>
                    <View className="my-text">邀请<Text style="color:#FF245A">{detail.personNum}</Text>位好友即可赢取大奖</View>
                    <View className="my-number">{`${initiateDetail.enlistNum || 0}/${detail.personNum}`}</View>
                  </View>

                  <View className='tools-main'>
                    {
                      helpList.map((it, inx) => {
                        return (
                          <View className='tools-item' key={`help-${inx}`}>
                            <Image src={it.avatarurl} className='tools-item-img'></Image>
                            <Text className='tools-item-txt'>{it.name}</Text>
                          </View>
                        )
                      })
                    }
                    {
                      times(detail.personNum - helpList.length).map((_, inx) => {
                        return (
                          <View className='tools-item' key={`un-${inx}`}>
                            <Image src={waitImg} className='tools-item-img'></Image>
                            <Text className='tools-item-wait'>等待助力</Text>
                          </View>
                        )
                      })
                    }
                  </View>
                </View>
                <View style="display:flex;justify-content: space-between;padding:0 15px">
                  {
                    actState === ActBeforeStart &&
                    (<View className="nostart-btn"><FormIdCollector><Button className="nostart-btn">未开始</Button></FormIdCollector></View>)
                  }
                  {
                    isStarter && actState === ActInProcess && helpState === HelpInProcess &&
                    (<View className="assistance-btn"><FormIdCollector><Button className="assistance-btn" onClick={this.askForHelp}>邀请好友助力</Button></FormIdCollector></View>)
                  }
                  {
                    !isStarter && actState === ActInProcess &&

                    (
                      <View className="btn-box" style="padding:25px 0;">

                        {
                          (helpState === HelpInProcess && !isJoin) &&
                          (<View className="assistance-btn"><FormIdCollector><Button className="assistance-btn" onClick={this.handleHelp}>立即助力好友</Button></FormIdCollector></View>)
                        }
                        <View className={(helpState === HelpInProcess && !isJoin) ? "set-btn" : "assistance-btn"}>
                          <FormIdCollector>
                            <Button className={(helpState === HelpInProcess && !isJoin) ? "set-btn" : "assistance-btn"} onClick={this.startMine}>发起我的助力</Button>
                          </FormIdCollector>
                        </View>
                      </View>
                    )
                  }
                </View>
                <View className="assistance-text"><Text className="acitivty-desc">活动说明</Text>-------------------------------------------------------------- </View>
                <View style="padding:0 40rpx">
                  <Image src={getThumbnail(detail.activityInstructions)} mode="aspectFill" style="width:100%;margin-bottom:20px;"></Image>
                </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>
          )
        }
      </View>
    )
  }
}
