import Taro, { Component } from '@tarojs/taro'
import { View, ScrollView, Button, Swiper, Block } from '@tarojs/components'
import ActSheet from '../../components/ActSheet'
import ShareButtons from '../../components/ShareButtons'
import GrantProfile from '../../components/GrantProfile'
import Poster from '@/components/Poster'
import { connect } from '@tarojs/redux'
import ready from '@/utils/ready'
import { queryLiveDetail, addLiveNum } from '@/services/item'
import { getQrCodeParams } from '@/utils/qrcode'
import { withDetail } from '@/utils/page'
import { share as shareSavePoint } from '@/utils/shareSavePoint'
import { ROLE_CODE } from '@/constants/user'
import { report as reportCustomer } from '@/utils/customer'
import { getMiniQrcode, savePoint, updatePoint } from '@/services/common'
import { getCanvasConfig, transferImage } from '@/utils/tools'
import { getCardDetail } from '@/services/card'
import Consultant from '@/components/consultant'
import Blank from '../../components/Blank'
import './index.scss'
const bgImg = "https://njcj.oss-cn-shanghai.aliyuncs.com/miniapp/images/helpgroup/bg.png"

@connect(s => s.user)
@withDetail({
  track: {
    event: 'detail',
    eventType: 'activity',
    targetType: 'live',
    propertyName: '查看直播详情页',
    data: '{}',
  }
})
export default class livePage extends Component {
  config = {
    navigationBarTitleText: '直播活动详情',
  }
  state = {
    showShareMenu: false,
    showPoster: false,
    qrcodeParams: {},
    reportedCustomer: false,
    posterShow: false,
    posterData: {},
    liveDetail: {},
    posterConfig: [],
    consultData: {}, // 分享的置业顾问信息
    consultShow: false,  // 置业顾问悬浮框显示隐藏
    noRecord: false,
  }


  componentDidShow() {
    this.setState({ showShareMenu: false })
    ready.queue(() => {

      this.initPageData()

    })
  }

  componentWillReceiveProps() {
    this.reportClientFn()
  }

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

  // 报备客户
  reportClientFn() {

    const { qrcodeParams } = this.state
    const consultant = this.$router.params.consultant || qrcodeParams.consultant || ""
    const { userInfo: { person } } = this.props

    if (!this.state.reportedCustomer) {
      reportCustomer(person, consultant).then(() => {
        this.setState({ reportedCustomer: true })
      })
    }
  }
  initPageData() {

    Taro.showToast({
      title: '加载中...',
      icon: 'loading'
    })
    const id = this.$router.params.id

    if (this.$router.params.scene) {
      getQrCodeParams(this.$router.params.scene).then((res) => {
        this.setState({ id: res.id, qrcodeParams: res }, () => {
          this.anotherInfo(res.id)
        })
      })
    } else {
      this.anotherInfo(id)
    }
    this._$_dataReady()
  }


  anotherInfo(id) {

    this.reportClientFn()
    let { qrcodeParams } = this.state
    const consultant = this.$router.params.consultant || qrcodeParams.consultant

    if (consultant) {
      getCardDetail(consultant).then(res => {
        this.setState({
          consultData: res,
          consultShow: true
        })
      })
    }

    queryLiveDetail(id).then(res => {
     
      this.setState({
        liveDetail: res || {},
        noRecord: res.status == '1' ? false : true
      })
      Taro.hideToast()
      const { templates = [], posterImg = '' } = (res.posters || [])[0]

      this.setState({
        posterData: { poster: posterImg },
      }, () => {
        this.getPosterData().then(posterData => {
          const posterConfig = this.transTPLs2Configs(templates, posterData)
          this.setState({ posterConfig, posterData })
        })
      })
    }).catch(err => {
      Taro.hideToast()
    })
  }


  goto = url => Taro.navigateTo({ url })


  handleShareBtn = e => {
    this.setState({ showShareMenu: true })
  }

  handleLiveBtn = e => {
    const { liveDetail: { liveAppAppId, liveAppPath } } = this.state
    if (liveAppAppId && liveAppPath) {
      const id = this.$router.params.id || this.state.liveDetail.liveActivityId
      addLiveNum(id).then(res => { })

      Taro.navigateToMiniProgram({
        appId: liveAppAppId,
        path: liveAppPath,
        extraData: {
          foo: 'bar'
        },
        success(res) {
          console.log(res, "navigateToMiniProgram")
        }
      })

    } else {
      Taro.showToast({ title: '后台未配置跳转链接', icon: 'none', duration: 2000 })
    }

  }
  currentPageAndParams() {
    const id = this.$router.params.id || this.state.liveDetail.liveActivityId
    const {
      userInfo: { person: { personId, personType, userId } }
    } = this.props

    const consultant = personType == ROLE_CODE['CONSULTANT'] ? personId : ""
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""

    const queryParams = [
      `id=${id}`,
      'from=live_share',
      `recommender=${personId}`,
      `consultant=${consultant}`,
      `consultantId=${consultantId}`,
    ]

    return [
      'onlineSelling/pages/live/index',
      queryParams.join('&'),
    ]
  }

  onShareAppMessage = () => {
    this.setState({ showShareMenu: false })
    const id = this.$router.params.id || this.state.liveDetail.liveActivityId
    const { userInfo: { person: { personId, personType, userId } } } = this.props
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""
    const { liveDetail: { shareContents } } = this.state
    const shareData = shareContents && shareContents.length ? shareContents[0] : { shareContentTitle: '房源列表', shareContentImg: null };
    // 分享埋点

    shareSavePoint({
      event: 'share',
      eventType: 'activity',
      targetType: 'live',
      propertyName: '直播详情页分享',
      consultantId: consultantId,
      sharePersonId: personId,
      targetId: id,
      data: '{}',
    }, 'liveApp')

    const [page, params] = this.currentPageAndParams()

    console.log(`/${page}?${params}`, "`/${page}?${params}`")
    return {
      title: shareData.shareContentTitle,//分享标题
      path: `/${page}?${params}`,//分享地址
      imageUrl: shareData.shareContentImg
    }
  }

  // 开始生成海报
  togglePosterStatus = (flag) => {
    if (flag) {
      this.getPosterData().then(posterData => {
        this.setState({
          showPoster: !!flag,
          posterData,
          showShareMenu: false
        })
        const id = this.$router.params.id || this.state.liveDetail.liveActivityId
        shareSavePoint({
          event: 'poster',
          eventType: 'activity',
          targetType: 'live',
          propertyName: '生成直播详情海报',
          targetId: id,
          data: '{}'
        }, 'livePoster')
      })


    } else {
      this.setState({
        showPoster: !!flag,
        showShareMenu: false
      })
    }
  }
  getPosterData = () => {
    return new Promise(resolve => {
      const { posterData } = this.state
      if (posterData.qrcode) {
        resolve(posterData)
        return
      }

      const [page, scene] = this.currentPageAndParams()
      const payload = { page, scene, showToast: false }

      getMiniQrcode(payload).then(qrcode => {
        const { posterData = {} } = this.state
        let data = {
          qrcode,//小程序二维码
          ...posterData,
        }
        resolve(data)
      })
    })
  }
  toBuildingDetail = () => {
    const { liveDetail: { buildingId } } = this.state
    this.goto(`/pages/project/detail/index?id=${buildingId}`)
  }

  renderBottom() {
    const { liveDetail: { buildingId } } = this.state
    return (
      <View className="bottombar">
        <View className="bt-nav__left">
          {buildingId &&
            <Button class='bt-nav__item' onClick={this.toBuildingDetail}>
              <Image src={transferImage(require('@/assets/news/property.png'))} style="width:42rpx;height:42rpx"></Image>
              <Text className="text">查看楼盘</Text>
            </Button>
          }
          <Button className='bt-nav__item' onClick={this.handleShareBtn} >
            <Image src={transferImage(require('@/assets/news/fasong.png'))} className='icon-img'></Image>
            <Text className="text">分享</Text>
          </Button>
        </View>
        <Button className="btn tolive" onClick={this.handleLiveBtn}>
          <Image style="width:54rpx;height:40rpx" src={transferImage(require('../../assets/seeding.png'))}></Image>
          <Text className="txt">观看直播</Text>
        </Button>
      </View>
    )
  }


  render() {
    const {
      consultData,
      consultShow,
      showShareMenu,
      showPoster,
      posterData,
      posterConfig,
      liveDetail,
      noRecord
    } = this.state

    const { userInfo: { person } } = this.props
    const showCircleBtn = posterData && posterData.qrcode
    console.log('==============>', posterData, showPoster, posterConfig)
    return (
      <Block>
        {/* 授权电话与头像 */}
        <GrantProfile both person={person} />
        {/* 置业顾问悬框 */}
        {
          consultShow && <Consultant style="bottom:150rpx" smallStyle="bottom:178rpx" personId={person.personId} name={person.name || person.nickname} data={consultData}></Consultant>
        }
        {/* 生成海报 */}
        {showPoster && <Poster data={posterData} configs={posterConfig} onCancel={this.togglePosterStatus} onFinish={this.togglePosterStatus} ></Poster>}
        {!noRecord ?
          <View className="live-page">
            <Image onClick={this.handleLiveBtn} src={transferImage(liveDetail.detailTypeImg || bgImg)} mode='widthFix' className="bg_img"></Image>
            {this.renderBottom()}
          </View>
          : <Blank tips="当前直播活动已取消或下架" />
        }
        {/* 分享按钮 */}
        <ActSheet show={showShareMenu}>
          <ShareButtons
            circleBtn={showCircleBtn}
            onSharingCircleOfFriends={() => this.togglePosterStatus(true)}
          />
        </ActSheet>

      </Block>
    )
  }
}

