import Taro, { Component } from '@tarojs/taro'
import { View, Block } from '@tarojs/components'
import './index.scss'
import ready from '@/utils/ready'
import { connect } from '@tarojs/redux'
import * as noticeType from '@/constants/common.js'
import { contractUser, contractGet, contractAuto, contractManual, queryRaiseDetail } from '@/services/project'
import ContactConsultant from '../../components/ContactConsultant'

@connect(({ user, house }) => ({ user, house }))

export default class Certification extends Component {
  config = {
    navigationBarTitleText: '正在实名认证'
  }
  state = {
    signDetail: null,
    autoErr: null,
    manualErr: null,
    userErr: null,
    raiseDetail: {}
  }
  
  componentDidShow() {
    // componentWillMount() {
    ready.queue(() => {
      const { id: raiseRecordId, raiseId } = this.$router.params
      const storageId = Taro.getStorageSync('raiseRecordId')
      queryRaiseDetail(storageId || raiseRecordId).then(res => {
        this.setState({
          raiseDetail: res.taRaiseRecord || {},
        })
      })
      contractUser({ raiseRecordId: storageId || raiseRecordId }).then(res => {
        this.setState({
          signDetail: res || {}
        }, () => {
          const { signDetail } = this.state
          if (signDetail.status == 2 && signDetail.authStatus == 'autoSign') {
            // 自动签署
            contractAuto({ raiseRecordId: storageId || raiseRecordId, showToast: false }).then(res => {
              // if (res.status == 0) {
              // 自动签署成功后调手动签署
              contractManual({ ...res, showToast: false }).then(res => {
                if (res) {
                  Taro.navigateTo({
                    url: `/pages/project/panorama/index?url=${encodeURIComponent(res)}&from=contractManual&raiseId=${raiseId}&id=${storageId || raiseRecordId}`
                  })
                } else {
                  Taro.showToast({
                    title: '无可跳转的认证地址',
                    icon: 'none'
                  })
                }
              }).catch(err => {
                this.setState({
                  manualErr: err.message || ''
                })
              })
              // } else {
              //   Taro.navigateTo({
              //     url: `/onlineSelling/pages/raiseMoney/signResult?id=${raiseRecordId}`
              //   })
              // }
            }).catch(err => {
              this.setState({
                autoErr: err.message || ''
              })
            })
          }
        })
      }).catch(error => {
        this.setState({
          userErr: error.message || ''
        })
      })

    })
  }

  handleChatClick() {
    const { raiseDetail: { consultantInfo = {} } } = this.state
    const { user: { userInfo: { miniApp: { tpls }, person: { personId, nickname, name } } } } = this.props
    const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_NOTICE && x.isSubscribe == true)[0] || {}).tplId
    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {
      },
      fail(res) {

      },
      complete() {
        Taro.navigateTo({
          url: `/pages/im/index?sendId=${personId}&sendName=${encodeURIComponent(name || nickname)}&receiverId=${consultantInfo.consultantPersonId}&receiverName=${encodeURIComponent(consultantInfo.nickname || consultantInfo.userName)}`
        })
      }
    })
  }
  handleBtnClick() {
    contractGet().then(res => {
      this.setState({
        signDetail: res || {}
      }, () => {
        const { id: raiseRecordId, raiseId } = this.$router.params
        const storageId = Taro.getStorageSync('raiseRecordId')
        contractUser({ raiseRecordId: storageId || raiseRecordId }).then(res => {
          this.setState({
            signDetail: res || {}
          }, () => {
            const { signDetail } = this.state
            if (signDetail.status == 2 && signDetail.authStatus == 'autoSign') {
              // 自动签署
              contractAuto({ raiseRecordId: storageId || raiseRecordId, showToast: false }).then(res => {
                // if (res.status == 0) {
                // 自动签署成功后调手动签署
                contractManual({ ...res, showToast: false }).then(res => {
                  if (res) {
                    Taro.navigateTo({
                      url: `/pages/project/panorama/index?url=${encodeURIComponent(res)}&from=contractManual&raiseId=${raiseId}&id=${storageId || raiseRecordId}`
                    })
                  } else {
                    Taro.showToast({
                      title: '无可跳转的认证地址',
                      icon: 'none'
                    })
                  }
                }).catch(err => {
                  this.setState({
                    manualErr: err.message || ''
                  })
                })
                // } else {
                //   Taro.navigateTo({
                //     url: `/onlineSelling/pages/raiseMoney/signResult?id=${raiseRecordId}`
                //   })
                // }
              }).catch(err => {
                this.setState({
                  autoErr: err.message || ''
                })
              })
            }
          })
        }).catch(error => {
          this.setState({
            userErr: error.message || ''
          })
        })
      })
    })
  }
  renderLoading() {
    return (
      <Block>
        <Image style=" width:60px;height:60px;margin-bottom:10px" src={require('../../assets/loading.gif')}></Image>
        <View className="status" >请稍等，正在准备实名认证</View>
      </Block>
    )
  }


  render() {
    const { signDetail, autoErr, userErr, manualErr } = this.state
    const status = signDetail ? signDetail.status : ''
    const showIcon = status == 2 ? require('../../assets/success2.png') : (status == 0 || status == 1 || status == 4) ? require('../../assets/fail2.png') : require('../../assets/going.png')

    const showTitle = (status == 0 || status == 1) ? '未激活/未认证' : status == 2 ? '审核通过' : status == 3 ? '待审核' : status == 4 ? '未通过' : '注册/获取失败'
    return (
      <View className="result" style="height:100vh">

        {!signDetail && !userErr && this.renderLoading()}
        {
          signDetail &&
          <Block>
            <Image className="result-img" src={showIcon}></Image>
            <View className="status" >实名认证<Text style={status == 3 ? 'color:#2CD7AA' : status == 2 ? 'color:#118EE9' : 'color:#F4333B'}>{showTitle}</Text></View>

            {status == 4 && <View className="tip" style="margin-top:14rpx">不通过原因：{signDetail.reason || ''}</View>}

            {status == 2 && <Block>
              {!autoErr && !manualErr && < View className="tip" style="margin-top:14rpx">正在准备合同，请不要退出···</View>}
              {autoErr && <Block>
                <View className="tip" style="margin-top:14rpx;color:#F4333B">自动签署失败</View>
                <View className="tip" style="margin-top:14rpx;color:#333">原因：{autoErr}</View>
              </Block>}
              {manualErr && <Block>
                <View className="tip" style="margin-top:14rpx;color:#F4333B">手动签署失败</View>
                <View className="tip" style="margin-top:14rpx;color:#333">原因：{manualErr}</View>
              </Block>}
            </Block>
            }
            {userErr && <View className="tip" style="margin-top:14rpx;color:#333">原因：{userErr}</View>}
            {(autoErr || userErr) && <Block>
              <View className="tip" style="margin-top:24rpx">请联系专属置业顾问解决</View>
              <ContactConsultant contactClick={() => this.handleChatClick()} text="请联系专属置业顾问" style=" position: absolute;bottom: 9vh;" />
            </Block>
            }

            {(status == 0 || status == 1 || status == 4) && <View className="tip" style="margin-top:14rpx">请返回重新发起认证</View>}

            {status == 3 && <View className="tip" style="margin-top:14rpx; display: flex;align-items: center;justify-content: center;" onClick={() => this.handleBtnClick()}>实名信息需要法大大审核，请刷新状态
            <Image style="width:18px;height:18px;margin-left:8rpx" src={require('../../assets/refresh.png')} />
            </View>}

            {status == 4 && <View class="certification-btn" onClick={() => this.handleBtnClick()}>查询不通过原因</View>}

            {status == 3 && <View class="certification-btn" onClick={() => this.handleBtnClick()}>更新我的实名认证信息</View>}
          </Block>
        }
      </View>
    )
  }
}
