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, getThumbnail } from '@utils/tools'
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,
  }

  componentWillMount() {
    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 || '16'

      this.setState({ newsId }, () => {
        this.loadDetail()
        addNewsUv(newsId)
      })
    })
  }

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

  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`
    })
  }
  onShareAppMessage = () => {
    const { detail: { shareContents,newsName, newsId, newsImg } } = this.state
    const { userInfo: { person: { personId } } } = this.props
    savePoint({
      event: 'share',
      eventType: 'activity',
      propertyName: '资讯详情分享',
      data: '{}'
    }).then(res => {
      console.info('资讯详情分享')
    })

    // 分享埋点
    addNewsShareNum(newsId)

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

  loadDetail() {
    const { newsId } = this.state
    Taro.showLoading()
    queryNewsDetail(newsId).then(res => {
      Taro.hideLoading()
      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)
      // 埋点
      savePoint({
        event: 'detail',
        eventType: 'news',
        propertyName: '资讯详情',
        buildingId: res.buildingId,
        targetId: res.newsId,
        data: '{}'
      }).then(res => {
        this.setState({
          recordId: res.recordId
        })
        console.info('资讯详情')
      })
    })
  }
  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 { newsId, detail: { posters, newsName, createDate } } = this.state
      const payload = {
        "scene": `id=${newsId}&from=news_share&recommender=${personId}`,
        "page": 'pages/news/detail/index',
      }
      const _avatarurl = getDownloadURL(avatarurl, 'avatar');

      getMiniQrcode(payload).then(qrcode => {
        let data = {
          qrcode,//小程序二维码
          nickname,//访问者名字
          avatarurl: _avatarurl,//访问者头像
          title: posters[0].posterTitle,//资讯海报标题
          posterDescription: posters[0].posterDescription,//资讯海报描述
          createDate: createDate,//资讯时间
          poster: posters[0].posterImg
        }
        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('生成资讯详情海报')
    })
  }
  render() {
    const { detail, loaded, isSaved, posterVisible, posterData, posterShow } = this.state
    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={getThumbnail(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></BackHomeBtn>

              <View className="bot-nav flex">
                <View className='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" 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>
    );
  }
}