import Taro, { Component } from '@tarojs/taro'
import { View, Block } from '@tarojs/components'
import './index.scss'
import ready from '@/utils/ready'
import { connect, getStore } from '@tarojs/redux'
import * as houseActions from '@/actions/house'
import * as noticeType from '@/constants/common.js'
import BackHomeBtn from '@/components/BackHomeBtn'
import { queryRaiseDetail, contractCheck } from '@/services/project'
import { transferImage } from '@/utils/tools'

@connect(({ user, house }) => ({ ...user, house }), { ...houseActions })
export default class signResult extends Component {
  config = {
    navigationBarTitleText: '签署结果'
  }
  state = {
    result: {},
    raiseDetail: {},
  }


  componentWillMount() {
    Taro.showToast({
      title: '加载中...',
      icon: 'loading'
    })
    ready.queue(() => {
      const storageId = Taro.getStorageSync('raiseRecordId')
      const { id: raiseRecordId, } = this.$router.params
      contractCheck(({ raiseRecordId: storageId || raiseRecordId, showToast: false })).then(res => {
        Taro.hideToast()
        this.setState({
          result: res || {}
        })
      })
      queryRaiseDetail(storageId || raiseRecordId).then(res => {
        this.setState({
          raiseDetail: res.taRaiseRecord || {},

        })
      })
    })
  }

  toRaiseProfile(id) {
    const { userInfo: { miniApp: { tpls } } } = this.props
    const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_HOUSE && x.isSubscribe == true)[0] || {}).tplId

    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {
      },
      fail(res) {

      },
      complete() {
        Taro.navigateTo({
          url: `/onlineSelling/pages/raiseProfile/index?id=${id}`
        })
      }
    })
  }

  handleChatClick() {
    const { raiseDetail: { consultantInfo = {} } } = this.state
    const { 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)}`
        })
      }
    })
  }
  toBuilding(buildingId) {
    Taro.navigateTo({
      url: `/pages/project/detail/index?id=${buildingId}`
    })
  }
  toHouseList(id) {
    Taro.navigateTo({
      url: `/onlineSelling/pages/houseList/index?id=${id}`
    })
  }

  toSeeContract = (url) => {
    const { userInfo: { miniApp: { fddServerHost } } } = this.props

    // 替换 location.origin 部分
    const redirect = fddServerHost ? url.replace(/^http[^/]+\/\/[^/]+\//, fddServerHost) : url

    Taro.navigateTo({
      url: `/pages/project/panorama/index?url=${encodeURIComponent(redirect)}`
    })
  }

  toDownloadContract(url) {
    Taro.downloadFile({
      url,
      success: function (param) {
        if (param.statusCode === 200) {
          Taro.showToast({
            title: '下载合同成功',
            icon: 'none'
          })
        }
      },
      fail: function (res) {
        console.log('下载合同失败');
      }
    })

  }
  renderBtn() {
    const storageId = Taro.getStorageSync('raiseRecordId')
    const { result = {}, raiseDetail = {} } = this.state
    const status = this.$router.params.result_code == 3000 ? '1' : '2'
    const { id: raiseRecordId } = this.$router.params
    const viewUrl = this.$router.params.viewpdf_url ? decodeURIComponent(decodeURIComponent(this.$router.params.viewpdf_url)) : ''

    return (
      <View className="bottombar">
        <View className="bt-nav__left">
          <Button class='bt-nav__item' onClick={() => this.toBuilding(raiseDetail.buildingId || result.buildingId)}>
            <Image src={transferImage(require('@/assets/news/property.png'))} style="width:42rpx;height:42rpx"></Image>
            <Text className="text">查看项目</Text>
          </Button>
          <Button className='bt-nav__item' onClick={() => this.toHouseList(raiseDetail.salesBatchId)}>
            <Image src={transferImage(require('../../assets/list.png'))} style="width:40rpx;height:40rpx" ></Image>
            <Text className="text">房源列表</Text>
          </Button>
          {status != 1 && <Button className='bt-nav__item' onClick={() => this.handleChatClick()}>
            <Image src={transferImage(require('../../assets/consult.png'))} style="width:36rpx;height:40rpx"></Image>
            <Text className="text">置业顾问</Text>
          </Button>}
          {status == 1 && viewUrl && <Button className='bt-nav__item' onClick={() => this.toSeeContract(viewUrl)} >
            <Image src={transferImage(require('../../assets/see.png'))} style="width:42rpx;height:40rpx"></Image>
            <Text className="text" style="color:#E4A938" >查看合同</Text>
          </Button>}
          {/* {status == 1 && <Button className='bt-nav__item' onClick={() => this.toDownloadContract(result.contractDownloadUrl)} >
            <Image src={transferImage(require('../../assets/download.png'))} style="width:42rpx;height:40rpx"></Image>
            <Text className="text" style="color:#E4A938" >下载合同</Text>
          </Button>} */}

        </View>
        <Button className="btn" onClick={() => this.toRaiseProfile(storageId || result.invoiceTargetId || raiseRecordId)}>
          认筹单
        </Button>
      </View>
    )
  }

  render() {
    // const { result = {} } = this.state
    const status = this.$router.params.result_code == 3000 ? '1' : '2'
    const failInfo = { title: '合同签署失败', desc: '签署失败描述' }
    const showIcon = status == 1 ? require('../../assets/success2.png') : status == 2 ? require('../../assets/fail2.png') : ''
    const showTitle = status == 1 ? '恭喜已成功签署合同' : status == 2 ? failInfo.title : ''
    const reason = this.$router.params.result_desc ? decodeURIComponent(decodeURIComponent(this.$router.params.result_desc)) : ''
    console.log(reason, "reasonreasonreasonreasonreason")

    return (
      <View className="result">
        <Image className="result-img" src={showIcon}></Image>

        <View className="status" style={status != 1 ? 'color:#F4333B' : 'color:#118EE9'}>{showTitle}</View>
        {
          status == 2 && (
            <Block>
              <View className="tip" style="margin-top:10rpx">{reason || ''}</View>
              <View className="tip" style="margin-top:10rpx">请到认筹单中尝试重新签署合同</View>
              <View className="tip" style="margin-top:10rpx">或联系您的专属置业顾问</View>
            </Block>
          )
        }
        {this.renderBtn()}
        <BackHomeBtn style={{ right: '3%', bottom: '190rpx' }}></BackHomeBtn>
      </View>

    )
  }

}
