import Taro, { Component } from '@tarojs/taro';
import './index.scss'
import ready from '@utils/ready'
import dayjs from 'dayjs'
import Poster from './poster'
import WxParse from '@components/wxParse/wxParse'
import BackHomeBtn from '@components/BackHomeBtn'
import Notice from '@components/Notice'
import { getMiniQrcode, savePoint, updatePoint } from '@services/common'
import { getDownloadURL, transferImage } from '@utils/tools'
import { getQrCodeParams } from '@utils/qrcode'
import { getCardDetail } from '@services/card'
import { ROLE_CODE } from '@constants/user'
import Consultant from '@components/consultant'
import authorizationComponent from '@components/authorizationComponent'
import { reportClient } from '@services/report'
import {
  addNewsUv,
  favorNews,
  addNewsShareNum,
  queryNewsDetail,
  cancelFavorNews
} from '@services/news'
import { connect } from '@tarojs/redux'

@connect(state => state.user)
export default class NewsDetail extends Component {
  config = {
    navigationBarTitleText: '资讯详情'
  }

  state = {
    newsId: null,
    detail: {},
    recordId: null,
    isSaved: false,
    loaded: false,
    posterShow: 'none',
    posterData: {},
    posterVisible: false,
    consultData: {}, // 分享的置业顾问信息
    consultShow: false  // 置业顾问悬浮框显示隐藏
  }

  componentWillMount(options) {
    console.log('================options========================', options)
    console.log('===========wx.getLaunchOptionsSync()===========', wx.getLaunchOptionsSync())
    console.log('================this.$router===================', this.$router)

    console.info('ready status3', ready)
    ready.queue(() => {
      const router = Taro.getStorageSync('router')
      console.info('news-1:', router)
      console.info('news-2:', this.$router)

      const newsId = this.$router.params.id || router.query.id

      if (!newsId) {
        getQrCodeParams(this.$router.params.scene).then(res => {
          this.setState({ newsId: res.id }, () => {
            this.loadDetail()
            addNewsUv(res.id)
          })
        }).catch(err => {
          Taro.showToast({
            title: '没有找到资讯',
            icon: 'none'
          })
        })
      } else {
        this.setState({ newsId }, () => {
          this.loadDetail()
          addNewsUv(newsId)
        })
      }
    })
  }

  componentWillUnmount() {
    const { recordId } = this.state
    recordId && updatePoint(recordId)

    Taro.setStorageSync('router', { query: {} })
  }
  // 报备客户
  reportClientFn() {

    const router = Taro.getStorageSync('router') || { query: {} }
    const consultant = this.$router.params.consultant || router.query.consultant || ""
    const consultantId = this.$router.params.consultantId || router.query.consultantId || ""
    const { userInfo: { person: { phone, tel, personId } } } = this.props

    if (consultant && consultant != personId) {
      const realPhone = phone || tel
      const payload = {
        realtyConsultant: consultant, //报备人 置业顾问
        phone: realPhone,
        showToast: false
      }
      reportClient(payload).then(res => {
        console.log('恭喜您绑定成功')
      }).catch(err => {
        console.error(err)
      })
    }
  }

  handleFavor() {
    const { newsId, isSaved } = this.state
    if (isSaved) {
      cancelFavorNews(newsId).then(res => {
        Taro.showToast({
          title: '已取消收藏'
        })
        this.setState({
          isSaved: false
        })
      })
    } else {
      favorNews(newsId).then(res => {
        Taro.showToast({
          title: '收藏成功'
        })
        this.setState({
          isSaved: true
        })
      })
    }
    savePoint({
      event: 'save',
      eventType: 'activity',
      propertyName: '资讯详情收藏',
      data: '{}'
    }).then(res => {
      console.info('资讯详情收藏')
    })
  }
  toHome() {
    Taro.switchTab({
      url: `/pages/project/index`
    })
  }

  currentPageAndParams() {
    const { detail: { newsId } } = this.state
    const { userInfo: { person: { personId, personType, userId } } } = this.props
    const consultant = personType == ROLE_CODE['CONSULTANT'] ? personId : ""
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""

    let queryParams = [
      `id=${newsId}`,
      `from=news_share`,
      `recommender=${personId}`,
      `consultant=${consultant}`,
      `consultantId=${consultantId}`,
    ]

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

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

  onShareAppMessage = () => {
    const { detail: { shareContents, newsName, newsId, newsImg } } = this.state
    const { userInfo: { person: { personId, personType, userId } } } = this.props
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""
    const consultant = personType == ROLE_CODE['CONSULTANT'] ? personId : ""

    savePoint({
      event: 'share',
      eventType: 'news',
      propertyName: '资讯详情分享',
      consultantId: consultantId,
      sharePersonId: personId,
      targetId: newsId,
      data: '{}'
    }).then(res => {
      console.info('资讯详情分享')
    })

    const shareData = shareContents && shareContents.length ? shareContents[0] : { shareContentTitle: newsName, shareContentImg: newsImg };

    // 分享埋点
    addNewsShareNum(newsId)

    const [path, params] = this.currentPageAndParams();

    console.log('----share-url---->', `/${path}?${params}`)

    return {
      title: shareData.shareContentTitle,
      path: `/${path}?${params}`,//分享地址
      imageUrl: shareData.shareContentImg
    }
  }

  loadDetail() {
    const { newsId } = this.state
    const router = Taro.getStorageSync('router')
    const consultant = this.$router.params.consultant || router.query.consultant
    const consultantId = this.$router.params.consultantId || router.query.consultantId || ""
    const recommender = this.$router.params.recommender || router.query.recommender || ""
    Taro.showLoading()
    queryNewsDetail(newsId).then(res => {
      Taro.hideLoading()
      // 埋点
      savePoint({
        event: 'detail',
        eventType: 'news',
        propertyName: '资讯详情',
        buildingId: res.buildingId,
        targetId: res.newsId,
        consultantId: consultantId,
        sharePersonId: recommender,
        data: '{}'
      }).then(res2 => {
        this.setState({
          recordId: res2.recordId
        })
        console.info('资讯详情')
      })
    
      this.setState({
        detail: res,
        loaded: true,
        isSaved: res.isSave
      }, () => {
        const { detail } = this.state
        if (detail.posters && detail.posters.length && detail.posters[0].posterImg) {
          this.setState({
            posterShow: 'flex'
          })
        }
      })

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

    })

    if (consultant) {
      this.reportClientFn()
      getCardDetail(consultant).then(res => {
        this.setState({
          consultData: res,
          consultShow: true
        })
      })
    }
  }
  getPosterData = () => {
    return new Promise(resolve => {
      const { posterData } = this.state
      if (posterData.qrcode) {
        resolve(posterData)
        return
      }
      const { userInfo: { person, miniApp } } = this.props
      const { avatarurl, nickname, personId, personType, phone, tel, userId } = person
      const { newsId, detail: { posters, newsName, createDate, newsImg = '' } } = this.state
      // const consultant = personType == ROLE_CODE['CONSULTANT'] ? personId : ""
      // const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""
      // const phoneNum = phone || tel

      const [page, scene] = this.currentPageAndParams();

      const payload = { page, scene }
      const _avatarurl = getDownloadURL(avatarurl, 'avatar');

      const posterDt = posters && posters.length ? posters[0] : { posterTitle: newsName, posterDescription: '', posterImg: newsImg }

      getMiniQrcode(payload).then(qrcode => {
        let data = {
          qrcode,//小程序二维码
          nickname,//访问者名字
          avatarurl: _avatarurl,//访问者头像
          title: posterDt.posterTitle,//资讯海报标题
          posterDescription: posterDt.posterDescription,//资讯海报描述
          createDate: createDate,//资讯时间
          poster: posterDt.posterImg,
          miniAppName: miniApp.name,
        }
        resolve(data)
      })
    })
  }
  // 开始生成海报
  handleTogglePoster = (flag) => {
    if (flag) {
      this.getPosterData().then(posterData => {
        this.setState({
          posterVisible: !!flag,
          posterData
        })
      })
      // App.zhuge.track('生成资讯详情海报')
    } else {
      this.setState({
        posterVisible: !!flag
      })
    }
    savePoint({
      event: 'poster',
      eventType: 'news',
      propertyName: '生成资讯详情海报',
      data: '{}'
    }).then(res => {
      console.info('生成资讯详情海报')
    })
  }
  renderNews() {
    const { detail, loaded, isSaved, posterVisible, posterData, posterShow, consultData, consultShow } = this.state
    const { userInfo: { person: { personId, nickname, name } } } = this.props
    return (
      <Block>
        {/* 生成海报 */}
        {posterVisible && (<Poster data={posterData} toggle={this.handleTogglePoster}></Poster>)}
        {
          loaded && (
            <Block>
              <ScrollView className="detail" scrollY>
                <View class="detail-title">{detail.newsName}</View>
                <View className="detail-stat">
                  <View className='left-icon'>
                    <View className='eye-num'><Text className="iconfont icon-eye"></Text>{detail.pvNum || 0}</View>
                    {/* <View><Text className="iconfont icon-fenxiang1"></Text>{detail.shareNum || 0}</View> */}
                    <View className='fenx'><Image src={require('@assets/person/fenxiang.png')} className='fenxiang1-img'></Image>{detail.shareNum || 0}</View>
                  </View>
                  <View>{dayjs(detail.createDate).format('YYYY-MM-DD')}</View>
                </View>
                {/* <Image mode="widthFix" style={{ width: '100%', marginTop: '20px' }} src={transferImage(detail.newsImg)}></Image> */}
                <View className="detail-con">
                  <import src='../../../components/wxParse/wxParse.wxml' />
                  <template is='wxParse' data='{{wxParseData:article.nodes}}' />
                </View>
              </ScrollView>
              <Notice></Notice>
              <BackHomeBtn style={consultShow ? "bottom:310rpx" : ''}></BackHomeBtn>
              {
                consultShow && <Consultant style="bottom:150rpx" smallStyle="bottom:178rpx" personId={personId} name={name || nickname} data={consultData}></Consultant>
              }
              <View className="bot-nav flex">
                <View className='btn poster-btn' style={{ display: posterShow }} onClick={() => { this.handleTogglePoster(true) }}>
                  {/* <Text className="iconfont icon-xiazai"></Text> */}
                  <Image src={require('@assets/news/tupian.png')} className='poster-img'></Image>
                  <Text className="txt">海报</Text>
                </View>
                <Button className="btn share-btn" open-type="share">
                  {/* <Text className="icon-fenxiang iconfont"></Text> */}
                  <Image src={require('@assets/news/fasong.png')} className='fenxiang-img'></Image>
                  <Text className="txt">分享</Text>
                </Button>
                <View className="btn collection-btn" onClick={this.handleFavor}>
                  {
                    isSaved ? (
                      <Text className="iconfont icon-shoucang saved"></Text>
                    ) : (
                        <Text className="iconfont icon-shoucang1"></Text>
                      )
                  }
                  <Text className="txt">收藏</Text>
                </View>

              </View>
            </Block>
          )
        }
      </Block>
    );
  }
  
  render(){
  	return (
  		<authorizationComponent>
  			{this.renderNews()}
  		</authorizationComponent>
  	)
  }
}