import Taro, { Component } from '@tarojs/taro'
import * as actions from '@actions/user'
import getUserPhone from '@utils/getUserPhone'
import './index.scss'
import { getHFiveDetail } from '@services/user'
import ready from '@utils/ready'
import { reportClient } from '@services/report'
import { connect } from '@tarojs/redux'
import { ROLE_CODE } from '@constants/user'
import { getQrCodeParams } from '@utils/qrcode'
import { getMiniQrcode, savePoint, updatePoint } from '@services/common'
import { isEmpty } from '@utils/tools'

const bgImg = "https://estateagents.oss-cn-shanghai.aliyuncs.com/miniapp/images/helpgroup/bg.png"

@connect(state => state.user, { ...actions })
export default class Index extends Component {

  state = {
    recordId: undefined, // 埋点ID
    avatarVisible: false,
    phoneVisible: false,
    webViewVisible: false,
    // pageHide: true,
    pageInfo: {},
    codeParams: '', // 解析二维码参数
    h5Id: undefined,
  }

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

  // componentDidHide() {
  //   this.setState({ pageHide: true });
  // }

  // componentDidShow() {
  //   this.setState({ pageHide: false });
  // }

  // 埋点
  success() {
    const router = Taro.getStorageSync('router') || { query: {} }
    const firstShare = this.$router.params.firstShare || router.query.firstShare || ""
    const consultant = this.$router.params.consultant || router.query.consultant || ""
    const sharePersonId = this.$router.params.sharePersonId || router.query.sharePersonId || ""
    const h5Id = this.state.h5Id || this.$router.params.id || router.query.id

    savePoint({
      event: 'detail',
      eventType: 'h5',
      propertyName: 'h5活动',
      consultantId: consultant,
      sharePersonId: sharePersonId,
      targetId: h5Id,
      data: '{"firstShare":"' + firstShare + '"}'
    }).then(res => {
      this.setState({
        recordId: res.recordId
      })
      console.log('访问记录')
    })
  }

  // 分享好友
  onShareAppMessage = () => {
    const { pageInfo } = this.state
    const currentPage = `/${this.currentPageAndParams().join('?')}`


    const { userInfo: { person: { personId, personType, userId } } } = this.props

    const consultantId = personType == ROLE_CODE['CONSULTANT'] ? userId : ""
    const { h5Id } = this.state
    console.log(currentPage)
    savePoint({
      event: 'share',
      eventType: 'h5',
      propertyName: 'h5详情分享',
      consultantId: consultantId,
      sharePersonId: personId,
      targetId: h5Id,
      data: '{}'
    }).then(res => {
      console.info('h5详情分享')
    })
    return {
      title: pageInfo.shareTitle,
      path: currentPage,
      imageUrl: pageInfo.shareImg
    }
  }
  // // 生成二维码
  // getQRCode() {
  //   const [page, scene] = this.currentPageAndParams()
  //   const payload = { page, scene }
  //   return new Promise((resolve) => {
  //     getMiniQrcode(payload).then(qrCode => {
  //       this.setState({ qrCode }, resolve)
  //     })
  //   })
  // }

  currentPageAndParams() {
    const { userInfo: { person } } = this.props
    const { h5Id } = this.state
    const router = Taro.getStorageSync('router') || { query: {} }

    // const consultant = person.personType == ROLE_CODE['CONSULTANT'] ? person.personId : ""
    const consultantId = person.personType == ROLE_CODE['CONSULTANT'] ? person.userId : ""
    const firstShare = this.$router.params.firstShare || router.query.firstShare || person.personId

    let queryParams = [
      `sharePersonId=${person.personId}`,
      `consultant=${consultantId}`,
      `from='h5_share'`,
      // `consultantId=${consultantId}`,
      `firstShare=${firstShare}`,
      `id=${h5Id}`
    ]

    const res = [
      'pages/project/h5Page',
      queryParams.join('&'),
    ]

    return res
  }

  componentWillMount() {
    ready.queue(() => {

      Taro.showLoading()
      if (this.$router.params.scene) {

        getQrCodeParams(this.$router.params.scene).then((res) => {
          this.setState({
            codeParams: res['__raw'] || ''
          })

          if (isEmpty(res.id)) {
            Taro.showModal({
              title: '提示',
              content: '活动不存在',
              success: (res) => {
                if (res.confirm) {
                  this.gotoIndex()
                }
              },
            })
            return;
          }

          if (!this.state.h5Id) {
            this.loadH5Profile(res.id)
          }
          // console.log(codeParams, "解析二维码返回值")
        })
      }

      const router = Taro.getStorageSync('router') || { query: {} }
      const hFiveId = this.$router.params.id || router.query.id

      if (!isEmpty(hFiveId)) {
        this.loadH5Profile(hFiveId)
      }

      // 没有 H5ID, 也没有分享
      if (isEmpty(hFiveId) && !this.$router.params.scene) {
        Taro.showModal({
          title: '提示',
          content: '活动不存在',
          success: (res) => {
            if (res.confirm) {
              this.gotoIndex()
            }
          },
        })
        return;
      }

      const { userInfo: { person: { avatarurl, phone } } } = this.props

      if (avatarurl && avatarurl.indexOf('wx.qlogo.cn') != -1) {
        console.log(avatarurl, "有头像哦~")
        this.setState({
          avatarVisible: false,
        })
        Taro.hideLoading()
        console.log(phone, "phone#########")
        // 头像手机号都有
        if (phone) {
          this.reportClient()
          this.success()
          this.setState({
            phoneVisible: false,
            webViewVisible: true,
          })
        } else {
          this.setState({
            phoneVisible: true,
          })
        }
      } else {
        Taro.hideLoading()
        this.setState({
          avatarVisible: true,
        })
        if (phone) {
          this.setState({
            phoneVisible: false,
          })
        }
      }
    })
  }

  gotoIndex = () => {
    Taro.switchTab({
      url: '/pages/project/index'
    })
  }

  loadH5Profile = (id) => {
    // h5id 、第一个分享人ID、置业顾问ID、分享人ID
    getHFiveDetail(id).then(res => {
      Taro.hideLoading()
      if (res.status == 1) {
        this.setState({
          pageInfo: res,
          h5Id: id,
        })
      } else {
        Taro.showModal({
          title: '提示',
          content: '活动已下架',
          showCancel: false,
        }).then(() => {
          this.gotoIndex()
        })
      }
    })
  }

  // 授权头像成功
  onAvatarSuccess() {
    this.setState({
      avatarVisible: false,

    })
    const { userInfo: { person: { phone } } } = this.props
    if (phone) {
      this.setState({
        phoneVisible: false,
        webViewVisible: true,
      })
      this.success()
    } else {
      this.setState({
        phoneVisible: true,
      })
    }
    console.log("授权头像成功！")
  }

  // 授权用户信息
  getUserInfo() {
    const { dispatchUpdateUserInfo } = this.props
    const sessionKey = Taro.getStorageSync('sessionKey')

    Taro.showLoading()
    Taro.getUserInfo({
      lang: 'zh_CN',
      success: res => {
        const payload = Object.assign(res, { sessionKey })
        console.log(res, "获取用户信息返回值")
        // 用户信息保存至服务器
        dispatchUpdateUserInfo(payload).then(res => {
          this.onAvatarSuccess();
          console.log('获取用户信息成功')
          Taro.hideLoading()
        })
      },
      fail: (err) => {
        Taro.hideLoading()
        console.error(err)

        Taro.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
        return
      }
    })
  }

  // 授权手机号
  getPhoneNumber(e) {
    getUserPhone(e, (phoneNumber) => {
      if (!phoneNumber) {
        Taro.showToast({
          title: '获取手机号失败',
          icon: 'none'
        })
      } else {
        console.log('授权手机成功')
        this.success()
        this.reportClient()
        this.setState({
          phoneVisible: false,
          webViewVisible: true,
        })
      }
    })
  }

  // 报备客户
  reportClient() {
    const router = Taro.getStorageSync('router') || { query: {} }
    const consultant = this.$router.params.consultant || router.query.consultant || ""
    const { userInfo: { person: { phone, tel, personId, userId, personType } } } = this.props
    const isConsultant = personType == ROLE_CODE['CONSULTANT']

    if (isConsultant && consultant != userId) {
      const realPhone = phone || tel
      const payload = {
        realtyConsultant: consultant, //报备人 置业顾问
        phone: realPhone,
        showToast: false
      }

      reportClient(payload).then(res => {
        console.log('恭喜您绑定成功')
      }).catch(err => {
        console.error(err)
      })
    }
  }

  renderMaskBanner() {
    const { avatarVisible, phoneVisible, pageInfo, h5Id } = this.state
    return (
      <View>
        <Image src={pageInfo.middleImg || bgImg} mode='widthFix' className='bg_img'></Image>
        <View className="middle-page">
          {avatarVisible && h5Id &&
            <View className="content">
              <View className="title">授权头像，围观活动</View>
              <View className="touxiang"><open-data type="userAvatarUrl"></open-data></View>
              <View className="name"><open-data type="userNickName"></open-data></View>
              <Button className="btn" open-type="getUserInfo" lang="zh_CN" onGetUserInfo={this.getUserInfo}>好</Button>
            </View>
          }
          {phoneVisible && h5Id &&
            <Button className="phone-btn" open-type="getPhoneNumber" lang="zh_CN" onGetphonenumber={this.getPhoneNumber}>点击授权查看详情</Button>
          }
        </View>
      </View>
    )
  }
  render() {
    const router = Taro.getStorageSync('router') || { query: {} }
    const { pageInfo, webViewVisible, codeParams, pageHide, h5Id } = this.state
    const { userInfo: { person } } = this.props
    const consultant = person.personType == ROLE_CODE['CONSULTANT'] ? person.userId : ""
    const firstShare = this.$router.params.firstShare || router.query.firstShare || person.personId
    const webUrlParams = [
      `personId=${person.personId}`,
      `h5id=${h5Id}`,
      `consultant=${consultant}`,
      `firstShare=${firstShare}`,
      `codeParams=${encodeURIComponent(codeParams)}`,
    ].join('&')

    const showH5 = !isEmpty(h5Id) && pageInfo.h5Address && pageInfo.h5Address !== 'about' && pageInfo.h5Address !== 'http://about' && pageInfo.h5Address !== 'https://about'

    // console.log('----web-h5------>', showH5, `${pageInfo.h5Address}?${webUrlParams}`)

    return (
      <Block>
        {this.renderMaskBanner()}
        {webViewVisible && showH5 && <WebView src={`${pageInfo.h5Address}?${webUrlParams}`} />}
      </Block>
    )
  }
}
