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 NamedIcon from '../../components/NamedIcon'
import RaiseCard from '../../components/RaiseCard'
import { queryRaiseDetail } from '@/services/project'
import { connect } from '@tarojs/redux'
import * as noticeType from '@/constants/common.js'
import './index.scss'

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

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

  state = {
    buildingId: '',
    raiseDeatil: {},
    houseList: [],
    raiseOrder: {},
    orderDetail: {},
    refundOrder: {},
  }

  componentWillMount() {
    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 || {},
      })
    })
  }

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

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

  renderHead() {
    const { houseList } = this.state
    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={houseList[0]} 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 = () => {
    console.log(this.props, "this.propsthis.propsthis.props")
    const { raiseDeatil: { raiseRecordId } } = this.state
    const { user: { userInfo: { miniApp: { tpls } } } } = 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: `/onlineSelling/pages/raiseMoney/index?type=pay&raiseRecordId=${raiseRecordId}`
        })
      }
    })

  }
  // 未交费提示
  renderUnpayNotice() {
    const { raiseOrder } = this.state
    return (
      <Block>
        <View className="unpayNotice flexSpace" onClick={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(agreement, buildingId) {
    Taro.navigateTo({
      url: `/onlineSelling/pages/protocol/index?agreement=${agreement}&buildingId=${buildingId}`
    })
  }

  render() {
    const { buildingId, raiseDeatil, orderDetail, refundOrder, raiseOrder } = 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: this.regFenToYuan(orderDetail.totalFee) + '元' },
      { 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.payStatus != 'paid' },
      { head: '退费单编号', body: refundOrder.refundNo || '', action: true, hide: raiseDeatil.payStatus != 'refunded' },
    ]


    return (
      <View className="raiseProfilePage">
        <View className="main">
          {this.renderHead()}
          <View className="tip">{raiseDeatil.payDescription || ''}</View>
          {raiseDeatil.status == '0' && this.renderCancelReason()}
          {raiseDeatil.payStatus == 'unpaid' && 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(raiseOrder.payProtocol, raiseOrder.buildingId)}>线上选房协议<Text className="right-icon"></Text></View>
          </View>
          <View>
            <CellBlock dataset={raiseInfo} />
            {raiseDeatil.consultantInfo && <ConsultantItem
              data={raiseDeatil.consultantInfo}
              type="raiseProfile"
              style="height:140rpx;margin-bottom:0rpx;width:690rpx"
              contactClick={() => this.handleChatClick(raiseDeatil.consultantInfo)}
            />}
            <View className="hr" />
            {raiseDeatil.payStatus == 'paid' &&
              <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>
    )
  }
}