import Taro, { Component } from '@tarojs/taro'
import { View, Block } from '@tarojs/components'
import dayjs from 'dayjs'
import CellBlock from './CellBlock'
import Statement from '../../components/Statement'
import ContactConsultant from '../../components/ContactConsultant'
import ConsultantItem from '../../components/ConsultantItem/index'
import RaiseCard from '../../components/RaiseCard'
import { queryRaiseDetail, contractUser } from '@/services/project'
import { connect } from '@tarojs/redux'
import * as noticeType from '@/constants/common.js'
import './index.scss'
import * as houseActions from '@/actions/house'

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

export default class Raise extends Component {
  config = {
    navigationBarTitleText: '认筹单',
  }

  state = {
    buildingId: '',
    raiseDeatil: {},
    houseList: [],
    raiseOrder: {},
    orderDetail: {},
    refundOrder: {},
    payDisable: true,
    signDetail: null,
    contractDetail: null,
  }
  componentDidShow() {
    // componentWillMount() {
    Taro.showToast({
      title: '加载中...',
      icon: 'loading'
    })
    const { id: raiseRecordId } = this.$router.params
    queryRaiseDetail(raiseRecordId).then(res => {
      this.setState({
        buildingId: res.taRaiseRecord.buildingId,
        raiseDeatil: res.taRaiseRecord || {},
        houseList: res.houseList || [],
        raiseOrder: res.taRaise || {},
        orderDetail: res.taOrder || {},
        refundOrder: res.refundOrder || {},
        contractDetail: res.taContract || null,
      }, () => {
        const { raiseDeatil: { showContract } } = this.state
        if (showContract == 1) {
          contractUser({ showToast: false, raiseRecordId, }).then(res => {
            this.setState({
              signDetail: res || null
            }, () => {
              Taro.hideToast()
            })
          }).catch(err => {
            Taro.hideToast()
          })
        } else {
          Taro.hideToast()
        }
      })
    })
  }

  // 复制数据
  copyData(data) {
    Taro.setClipboardData({
      data: `${data}`,
      onSuccess: (() => { }),
    })
  }

  // 查看所有认筹房源
  viewAllHouses = () => {
    const { id } = this.$router.params
    Taro.navigateTo({
      url: `/onlineSelling/pages/raiseProfile/houseResource?raiseRecordId=${id}`
    })
  }

  renderHead() {
    const { houseList } = this.state
    const showHouse = (houseList || []).filter(x => x.mineLocked == 'mine')[0] || houseList[0]
    return (
      <Block>
        <View className="head flexSpace">
          <View className="flexSpace-fixed">
            <View className="title">认筹房源</View>
          </View>
          <View className="flexSpace-fixed">
            {houseList.length > 1 && <View className="gray" onClick={this.viewAllHouses}>
              <Text>查看全部（{houseList.length}）</Text>
              <Text className='at-icon at-icon-chevron-right'></Text>
            </View>}
          </View>
        </View>
        <RaiseCard summary={showHouse} type="raiseProfile" style="height:auto" />
      </Block>
    )
  }

  // 取消认购原因
  renderCancelReason() {
    const { raiseDeatil } = this.state;
    return (
      <Block>
        <View className="cancelReason flexSpace">
          <View className="flexSpace-fixed">
            <Image src={require('../../assets/void.png')} style="width:120rpx;height:120rpx"></Image>
          </View>
          <View className="flexSpace-item" style="margin-left: 20px">
            <View>认筹单作废原因：</View>
            <View className="gray">{raiseDeatil.invalidReason}</View>
          </View>
        </View>
        <View className="hr"></View>
      </Block>
    )
  }
  // 跳转去交费
  toPay = () => {
    this.setState({
      payDisable: false,
    })
    const { raiseDeatil: { raiseRecordId } } = this.state
    const { user: { userInfo: { miniApp: { tpls } } } } = this.props
    const tplId = (tpls.filter(x => x.tplType == noticeType.TPL_HOUSE && x.isSubscribe == true)[0] || {}).tplId
    const that = this
    wx.requestSubscribeMessage({
      tmplIds: [tplId],
      success(res) {
      },
      fail(res) {

      },
      complete() {
        that.setState({
          payDisable: true
        })
        Taro.navigateTo({
          url: `/onlineSelling/pages/raiseMoney/index?type=pay&raiseRecordId=${raiseRecordId}`
        })
      }
    })

  }
  // 未交费提示
  renderUnpayNotice() {
    const { raiseOrder, payDisable } = this.state
    return (
      <Block>
        <View className="unpayNotice flexSpace" onClick={payDisable ? this.toPay : ''}>
          <View className="flexSpace-fixed">
            <Image src={require('../../assets/pay.png')} style="width:64rpx;height:64rpx"></Image>
            <View className="a-line txt">未缴费？点我缴费</View>
          </View>
          <View className="flexSpace-fixed">
            <Text className="a-line">认筹金额</Text>
            <Text className="a-line price">{this.regFenToYuan(raiseOrder.raisePrice)}元</Text>
          </View>
        </View>
        <View className="hr"></View>
      </Block>
    )
  }
  handleChatClick(item) {

    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=${item.consultantPersonId}&receiverName=${encodeURIComponent(item.name || item.nickname || item.userName)}`
        })
      }
    })
  }
  toDecimal2 = (x) => {
    var f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + 2) {
      s += '0';
    }
    return s;
  }
  regFenToYuan = (fen) => {
    var num = fen;
    num = fen * 0.01;
    num += '';
    var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
    num = num.replace(reg, '$1');
    num = this.toDecimal2(num)
    return num
  }
  toAgreement = () => {
    const { raiseOrder } = this.state;
    const { payProtocol, buildingId } = raiseOrder || {}

    this.props.dispatchSetOnlineProtocol(payProtocol)
    const { id: raiseRecordId } = this.$router.params

    Taro.navigateTo({
      url: `/onlineSelling/pages/protocol/index?buildingId=${buildingId}&id=${raiseRecordId}`
    })
  }
  toSign = () => {
    Taro.setStorageSync('raiseRecordId', this.$router.params.id)
    const { signDetail, raiseDeatil: { consultantInfo: { name, userName, personId, consultantPersonId } } } = this.state
    const { id: raiseRecordId } = this.$router.params
    const status = signDetail ? signDetail.status : ''
    const { user: { 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() {
        if (status == 2) {
          Taro.reLaunch({
            url: `/onlineSelling/pages/raiseMoney/Certification?id=${raiseRecordId}&consultantName=${encodeURIComponent(name || userName || '')}&consultantId=${consultantPersonId || personId || ''}`
          })
        } else {
          if (signDetail.certifiedAddress) {
            Taro.reLaunch({
              url: `/pages/project/panorama/index?url=${encodeURIComponent(signDetail.certifiedAddress)}&from=raiseProfile&consultantName=${encodeURIComponent(name || userName || '')}&consultantId=${consultantPersonId || personId || ''}&id=${raiseRecordId}`
            })
          } else {
            Taro.showToast({
              title: '无可跳转的认证地址',
              icon: 'none'
            })
          }

        }
      }
    })
  }
  toSeeContract(url) {
    Taro.navigateTo({
      url: `/pages/project/panorama/index?url=${encodeURIComponent(url)}`
    })
  }
  toDownloadContract(url) {
    Taro.downloadFile({
      url,
      success: function (param) {
        if (param.statusCode === 200) {
          Taro.showToast({
            title: '下载合同成功',
            icon: 'none'
          })
        }
      },
      fail: function (res) {
        console.log('下载合同失败');
      }
    })

  }

  render() {
    const { buildingId, raiseDeatil, orderDetail, refundOrder, raiseOrder, signDetail, contractDetail } = this.state;


    // 认筹信息
    const raiseInfo = [
      { head: '认筹人', body: raiseDeatil.name || '', },
      { head: '身份证号', body: raiseDeatil.idcard || '' },
      { head: '手机号', body: raiseDeatil.tel || '' },
    ]

    // 缴费信息
    const payInfo = [
      { head: '缴费方式', body: `${raiseDeatil.payType == 'onLine' ? '线上缴费' : '线下缴费'}` },
      { head: '实际支付费用', body: raiseDeatil.payType == 'onLine' ? this.regFenToYuan(orderDetail.totalFee) + '元' : this.regFenToYuan(raiseOrder.raisePrice) + '元' },
      { head: '缴费成功时间', body: dayjs(orderDetail.payTime).format('YYYY/MM/DD HH:mm:ss') },
    ]

    // 退费信息
    const refundInfo = [
      { head: '退费状态', body: refundOrder.payStatus == 'refunded' ? '退费完成' : '退费中' },
      { head: '退费结果', body: refundOrder.payStatus == 'refunded' ? '成功' : '失败' },
      { head: '退费发起时间', body: dayjs(refundOrder.createDate).format('YYYY/MM/DD HH:mm:ss') },
      { head: '实退费用', body: this.regFenToYuan(refundOrder.totalFee) + '元' },
      { head: '退费到账时间', body: dayjs(refundOrder.payTime).format('YYYY/MM/DD HH:mm:ss') },
      { head: '退费原因', desc: raiseDeatil.refundReason },
    ]

    // 其他信息
    const otherInfo = [
      { head: '其他信息', body: '供核对数据使用' },
      { head: '认筹单编号', body: raiseDeatil.raiseRecordId || '', action: true },
      { head: '微信缴费单', body: orderDetail.tradeNo || '', action: true, hide: !(raiseDeatil.payType == 'onLine' && (raiseDeatil.payStatus == 'refunded' || raiseDeatil.payStatus == 'paid')) },
      { head: '微信退费单', body: refundOrder.refundNo || '', action: true, hide: refundOrder.payStatus != 'refunded' },
    ]

    console.log('------------------>', raiseOrder.payType == 'onLine' && (raiseDeatil.payStatus == 'refunded' || raiseDeatil.payStatus == 'paid'))


    return (
      <View className="raiseProfilePage">
        <View className="main">
          {this.renderHead()}
          <View className="tip">{raiseOrder.raisePrecautions || ''}</View>
          {raiseDeatil.status == '0' && this.renderCancelReason()}
          {raiseDeatil.payStatus == 'unpaid' && raiseDeatil.status == 1 && this.renderUnpayNotice()}
          <View className="raise-flex">
            <View className="date">认筹提交时间  {dayjs(raiseDeatil.createDate).format('YYYY/MM/DD HH:mm:ss')}</View>
            <View className="agreement" onClick={this.toAgreement}>在线选房协议<Text className="right-icon"></Text></View>
          </View>
          {contractDetail &&
            <View className="raise-flex">
              <View className="date">合同签署时间  {dayjs(contractDetail.customerTime).format('YYYY/MM/DD HH:mm:ss')}
                {/* <Image className="download" onClick={() => this.toDownloadContract(contractDetail.contractDownloadUrl)} src={require('../../assets/download.png')} /> */}
              </View>
              <View className="agreement" onClick={() => this.toSeeContract(contractDetail.contractViewUrl)}>查看合同<Text className="right-icon"></Text></View>
            </View>}

          {
            raiseDeatil.showContract == 1 && signDetail &&
            <View className="sign" onClick={this.toSign}>
              为保障您的权益，请签署认筹合同<Text className="right-icon" style="opacity:0.3"></Text><Text className="right-icon" style="opacity:0.6"></Text><Text className="right-icon"></Text>
            </View>
          }
          <View>
            <CellBlock dataset={raiseInfo} />
            {raiseDeatil.consultantInfo && <ConsultantItem
              data={raiseDeatil.consultantInfo}
              type="raiseProfile"
              style="height:140rpx;margin-bottom:0rpx;width:690rpx;padding:1px 0"
              contactClick={() => this.handleChatClick(raiseDeatil.consultantInfo)}
            />}
            <View className="hr" />
            {(raiseDeatil.payStatus == 'paid' || raiseDeatil.payStatus == 'refunded') &&
              <Block>
                <CellBlock dataset={payInfo} />
                <View className="hr" />
              </Block>}

            {/* unpaid未缴费paid已缴费refunded已退费 */}
            {raiseDeatil.payStatus == 'refunded' &&
              <Block>
                <CellBlock dataset={refundInfo} />
                <View className="hr" />
              </Block>}
            <CellBlock dataset={otherInfo} disable onActionClick={dt => this.copyData(dt.body)} />
          </View>
          <View></View>
          <View></View>
        </View>
        <View className="contact">
          <ContactConsultant text="如有问题，请联系置业顾问" buildingId={buildingId} />
        </View>
        <Statement />
      </View>
    )
  }
}