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 { report as reportCustomer } from '@/utils/customer'
import { getCardDetail } from '@/services/card'
import { ROLE_CODE } from '@/constants/user'
import Consultant from '@/components/consultant'
import AchievePhone from '@/components/achievePhone'
import AchieveAvatar from '@/components/achieveAvatar'
import { dispatchProjectDetail } from '@/actions/project'
import * as actions from '@/actions/card'
import ProjectItem from '../../project/item'
// import AuthorizationComponent from '@/components/authorizationComponent'
// import { reportClient } from '@/services/report'
import {
  addNewsUv,
  favorNews,
  // addNewsShareNum,
  queryNewsDetail,
  cancelFavorNews
} from '@/services/news'
import { connect } from '@tarojs/redux'
import { share as shareSavePoint } from '@/utils/shareSavePoint'

// @connect(state => state.user)
@connect(
  ({ user, card, project }) => ({ ...user, ...card, ...project }),
  { dispatchProjectDetail, ...actions }
)
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,  // 置业顾问悬浮框显示隐藏
    reportedCustomer: false,
    qrcodeParams: '',
    grantPhoneVisible: false, // 授权电话
    grantAvatarVisible: false, // 授权头像
    webViewVisible: false,
    queryInfo: {}
  }

  componentWillMount(options) {
    console.info('=====news ========>', this)
    ready.queue(() => {
      console.info('news-2:', this.$router)
      // 必须授权电话
      if (this.toggleGrantPhone()) {
        this.toggleGrantAvatar()
      }
      const newsId = this.$router.params.id

      if (this.$router.params.scene) {
        getQrCodeParams(this.$router.params.scene).then(res => {
          console.log(res, "扫码参数")
          this.setState({
            newsId: res.id,
            qrcodeParams: res,
            queryInfo: {
              channelId: res.channelId || '',
              qrCodeId: res.qrCodeId || '',
              scene: this.$router.params.scene,
            }
          }, () => {
            this.loadDetail()
            addNewsUv(res.id)
          })
        }).catch(err => {
          Taro.showToast({
            title: '没有找到资讯',
            icon: 'none'
          })
        })
      } else {
        console.log('有id,不请求扫码参数接口')
        this.setState({ newsId }, () => {
          this.loadDetail()
          addNewsUv(this.state.newsId)
        })
      }
    })
  }

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

    return true
  }

  // 调起授权头像
  toggleGrantAvatar = () => {
    const { userInfo: { person: { avatarurl } } } = this.props

    if (!avatarurl || avatarurl.indexOf('wx.qlogo.cn') === -1) {
      this.setState({ grantAvatarVisible: true })
      return false
    }

    console.log(avatarurl, "avatarurl")
    console.log(this.props.userInfo, "this.props")
    this.setState({
      webViewVisible: true
    })
    return true
  }

  // componentWillReceiveProps(nextProps) {
  //   this.reportClientFn()
  // }

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

  }

  // 报备客户
  // 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 })
  //     })
  //   }
  // }

  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: 'news',
      propertyName: '资讯详情收藏',
      data: '{}'
    }).then(res => {
      console.info('资讯详情收藏')
    })
  }
  toHome() {
    Taro.switchTab({
      url: `/pages/project/index`
    })
  }

  currentPageAndParams() {
    const { detail: { newsId }, qrcodeParams } = this.state
    const { userInfo: { person: { personId, personType, userId } } } = this.props
    const consultant1 = this.$router.params.consultant || qrcodeParams.consultant || Taro.getStorageSync('consultantId') || ''
    const consultantId1 = this.$router.params.consultantId || qrcodeParams.consultantId || ""
    const consultant = personType == ROLE_CODE['CONSULTANT'] ? personId : consultant1
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : consultantId1

    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, buildingId }, qrcodeParams } = this.state
    const { userInfo: { person: { personId, personType, userId } } } = this.props
    const consultantId1 = this.$router.params.consultantId || qrcodeParams.consultantId || ""
    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : consultantId1
    const consultant = personType == ROLE_CODE['CONSULTANT'] ? personId : ""
    const shareData = shareContents && shareContents.length ? shareContents[0] : { shareContentTitle: newsName, shareContentImg: newsImg };

    // 分享埋点
    shareSavePoint({
      event: 'share',
      eventType: 'news',
      propertyName: '资讯详情分享',
      consultantId: consultantId,
      sharePersonId: personId,
      targetId: newsId,
      buildingId: buildingId || '',
      data: '{}',
    }, 'news')

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

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

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

  loadDetail() {
    const { newsId, qrcodeParams, queryInfo } = this.state
    // const consultant = Taro.getStorageSync('consultantId') || ''
    const consultant = this.$router.params.consultant || qrcodeParams.consultant || Taro.getStorageSync('consultantId') || ''
    const consultantId = this.$router.params.consultantId || qrcodeParams.consultantId || ""
    const recommender = this.$router.params.recommender || qrcodeParams.recommender || Taro.getStorageSync('recommender') || ''
    const { dispatchProjectDetail, userInfo = {} } = this.props
    Taro.showLoading()
    console.log(newsId, "newsIdnewsIdnewsIdnewsIdnewsId")
    queryNewsDetail(newsId, queryInfo, { ['x-consultant']: consultant, ['x-recommender']: recommender }).then(res => {
      Taro.hideLoading()
      // 埋点
      savePoint({
        event: 'detail',
        eventType: 'news',
        propertyName: '资讯详情',
        buildingId: res.buildingId || '',
        targetId: res.newsId,
        consultantId: consultantId,
        sharePersonId: recommender,
        data: '{}',
        ...queryInfo
      }).then(res2 => {
        this.setState({
          recordId: res2.recordId
        })
        console.info('资讯详情')
      })
      if (res.buildingId) {
        dispatchProjectDetail(res.buildingId, undefined, { showToast: false, })
      }

      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)
    })
    const notSelf = userInfo.person.personId != consultant
    if (notSelf && consultant) {
      getCardDetail(consultant).then(res => {
        this.setState({
          consultData: res,
          consultShow: true
        })
      })
    }

    // this.reportClientFn()
  }
  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
      })
    }
    const { newsId, detail: { buildingId } } = this.state
    shareSavePoint({
      event: 'poster',
      eventType: 'news',
      propertyName: '生成资讯详情海报',
      targetId: newsId,
      buildingId: buildingId || '',
      data: '{}',
    }, 'news')
  }
  toProjectDetail = () => {
    const { projectDetail: { buildingId } } = this.props
    Taro.navigateTo({ url: `/pages/project/detail/index?id=${buildingId}` })
  }
  render() {
    const { webViewVisible, grantPhoneVisible, grantAvatarVisible, detail, queryInfo, loaded, isSaved, posterVisible, posterData, posterShow, consultData, consultShow } = this.state
    const { userInfo = { person: {} }, cardInfo, projectDetail = {} } = this.props

    const achieveParams = {
      buildingId: detail.buildingId || '',
      targetName: detail.newsName || '',
      targetType: 'news',
      targetId: detail.newsId || '',
      ...queryInfo

    }
    console.log(achieveParams, "achieveParamsachieveParamsachieveParamsachieveParams")
    return (
      <Block>
        {/* 生成海报 */}
        {posterVisible && (<Poster data={posterData} onCancel={() => this.setState({ posterVisible: false })} toggle={this.handleTogglePoster}></Poster>)}

        {
          grantPhoneVisible &&
          <AchievePhone user={userInfo.person} onSuccess={this.toggleGrantAvatar} achieveParams={achieveParams} buildingId={detail.buildingId}></AchievePhone>
        }
        {
          grantAvatarVisible &&
          <AchieveAvatar user={userInfo.person} onSuccess={() => { this.setState({ grantAvatarVisible: false, webViewVisible: true }) }} ></AchieveAvatar>
        }
        {
          loaded && (
            detail.newsDetailType == 0 ? webViewVisible && < WebView src={detail.newsDetail} /> :
              <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">
                    {/* <richText nodes={detail.newsDetail} ></richText> */}
                    <import src='../../../components/wxParse/wxParse.wxml' />
                    <template is='wxParse' data='{{wxParseData:article.nodes}}' />
                  </View>
                  {projectDetail.buildingId && <View className="pro__info"><ProjectItem data={projectDetail} onClick={this.toProjectDetail.bind(this)} /></View>}
                </ScrollView>
                <Notice></Notice>
                <BackHomeBtn style={consultShow ? "bottom:310rpx" : ''}></BackHomeBtn>
                {
                  consultShow && <Consultant style="bottom:150rpx" smallStyle="bottom:178rpx" personId={userInfo.person.personId} name={userInfo.person.name || userInfo.person.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>
    )
  }
}