import Taro, { Component } from '@tarojs/taro'
import { View, Block, RichText } from '@tarojs/components'
import './index.scss'
import RaiseCard from '../../components/RaiseCard'
import Statement from '../../components/Statement'
import ConsultantItem from '../../components/ConsultantItem/index'
import ready from '@/utils/ready'
import dayjs from 'dayjs'
import { connect } from '@tarojs/redux'
import * as houseActions from '@/actions/house'
import NextStep from './NextStep'
import { fetch, apis } from '@/utils/request'
import Captcha from './Captcha'
import { raiseOrder, cancelOrder, queryPreselectionRecord } from '@/services/project'
import { getCodeMessage } from '@/services/getCode'
import { checkIDCard, isEmpty } from '@/utils/tools'
import ContactConsultant from '../../components/ContactConsultant'
import RadioList from './RadioList'

const getRaiseProfile = ({ salesBatchId, raiseRecordId, personId }) => {
  const queryString = [
    `${raiseRecordId ? 'raiseRecordId=' + raiseRecordId : ''}`,
    `${salesBatchId ? 'salesBatchId=' + salesBatchId : ''}`,
    `${personId ? 'personId=' + personId : ''}`,
  ].filter(Boolean).join('&')

  return fetch({ url: `${apis.API_RAISE_PROFILE}?${queryString}` })
}

const saveRaiseRecord = (record, raise) => {
  const payload = {
    ...record,
    raiseId: raise.raiseId,
    orgId: raise.orgId,
    salesBatchId: raise.salesBatchId,
    buildingId: raise.buildingId,
  }

  return fetch({ url: `${apis.API_SAVE_RAISE_RECORD}`, method: 'POST', payload })
}

@connect(({ user, house }) => ({ ...user, house }), { ...houseActions })
export default class raiseMoney extends Component {
  config = {
    navigationBarTitleText: '认筹确认'
  }
  state = {
    current: 0,
    inputName: '',
    raiseProfile: undefined,  // 认筹主记录
    record: {},               // 认筹单
    preselectList: [],        // 我的预选 - 当前批次
    protocolCountdown: 10,    // 单位 s
    captchaCountdown: 60,     // 单位 s
    payType: '',              // 缴费方式
    failInfo: undefined,      // 操作失败 - 对象 { title, desc }
    payTypeList: [
      { label: '线上缴费', value: 'onLine' },
      { label: '线下缴费', value: 'offLine' },
    ],
  }

  captchaLock = false

  // 此页面不支持分享，以及二维码
  componentWillMount() {
    ready.queue(() => {
      const {
        salesBatchId,    // 批次, 从房源详情进入的
        houseId,       // 房源号, 备用
        raiseRecordId,  // 认筹单ID, // 从认筹列表进入
      } = this.$router.params

      if (!salesBatchId && !raiseRecordId) {
        Taro.showToast({
          title: '错误, 请返回上一步',
          icon: 'none',
        })
        return;
      }

      this.loadInfo(salesBatchId, raiseRecordId)

      if (this.$router.params.type == 'pay') {
        this.setState({ current: 3 })
      }
    })
  }

  loadInfo(salesBatchId, raiseRecordId) {
    const { userInfo, house } = this.props
    const { personId } = userInfo.person
    const defaultRecord = this.initRecord()

    // 请求认筹信息
    getRaiseProfile({ salesBatchId, raiseRecordId, personId }).then(res => {
      let payType = ''
      const payTypeSettings = (res.payType || '').split(',')
      if (payTypeSettings.length === 1) {
        payType = payTypeSettings[0]
      }

      this.setState({ raiseProfile: res, payType, record: res.record || defaultRecord })

      // 销售批次已被取消发布
      if (res.status != 1) {
        this.setState({ current: 4, failInfo: { title: '认筹失败', desc: '销售批次已被取消发布' } })  
      }

      // 不在认筹时间内
      if (!dayjs().isBefore(res.raiseEndTime) || !dayjs().isAfter(res.raiseStartTime)) {
        this.setState({ current: 4, failInfo: { title: '认筹失败', desc: '不在认筹时间内' } })  
      }

      // 请求置业顾问列表
      if (!house.consultantList || !house.consultantList.length) {
        this.props.dispatchGetConsultants({
          buildingId: res.buildingId,
          pageSize: 999,
          pageNumber: 1,
        })
      }

      this.getMyPreselection({
        personId,
        pageNumber: 1,
        pageSize: 999,
        salesBatchId: res.salesBatchId,
      }).then((res2) => {
        // 如果认筹必须预选
        if (res.needPreselection && res2.length < 1) {
          this.setState({ current: 4, failInfo: { title: '认筹失败', desc: '需要先预选才能认筹' } })
        }
      })
    })
  }

  // 我的预选
  getMyPreselection = (params) => {
    return new Promise((resolve, reject) => {
      queryPreselectionRecord(params).then((res) => {
        this.setState({ preselectList: res.records })
        resolve(res.records)        
      }).catch(() => {
        resolve([])
        // reject()
      })
    })
  }

  initRecord = () => {
    const { userInfo } = this.props
    const { personId, nickname, idcard, tel, phone } = userInfo.person

    return { personId, name: nickname, idcard, tel: tel || phone }
  }

  handleCancel = (house) => {
    Taro.showModal({
      title: '提示',
      content: '确认取消选择该房源?',
      success: (res) => {
        if (res.confirm) {
          this.props.dispatchSubCart(house)
        }
      }
    })
  }

  gotoHouseSelect = (pageType) => {
    const { raiseProfile } = this.state
    const isMulti = raiseProfile.houseLockingType != 'auto'

    const url = pageType == 'all' ?
      `/onlineSelling/pages/houseCart/index?id=${raiseProfile.salesBatchId}&multi=${isMulti}` :
      `/onlineSelling/pages/addHouse/index?id=${raiseProfile.salesBatchId}`

    Taro.navigateTo({ url })
  }

  renderTop() {
    const tabList = [
      { title: '确认房源', value: 0 },
      { title: '阅读协议', value: 1 },
      { title: '填写资料', value: 2 },
      { title: '缴纳定金', value: 3 },
      { title: '认筹结果', value: 4 },
    ]
    const { current } = this.state

    return (
      <View className="top-con">
        {tabList.map((item, index) => (
          <View className="flex" key={index + 'top'} style={current == item.value ? 'color:#333;font-weight:700' : ''}>
            {item.title}
            {item.value != 4 &&
              <View className="flex" style="margin:0 12rpx 0 4rpx">
                <View className='right-icon'></View>
                <View className='right-icon icon2'></View>
                <View className='right-icon icon3'></View>
              </View>
            }

          </View>
        ))
        }
      </View>
    )
  }
  renderHouse() {
    const { house: { raiseCart } } = this.props
    const { raiseProfile = {} } = this.state
    const disabled = raiseProfile.houseLockingType === 'auto'

    return (
      <ScrollView scrollY className="container">
        {
          raiseCart.map(item => (
            <View key={item.houseId} >
              <RaiseCard type="raiseMoney" style="height:auto" summary={item} onCancel={this.handleCancel} disableCancel={disabled} />
            </View>
          ))
        }
        {
          !disabled &&
          (
            <Block>
              {
                !raiseProfile.needPreselection &&
                (<View className="addhouse">从 <Text style="color:#F3B82E" onClick={this.gotoHouseSelect.bind(this, 'all')}>房源列表</Text> 中添加其他房源</View>)
              }              
              <View className="addhouse">从 <Text style="color:#BB9C79" onClick={this.gotoHouseSelect.bind(this, 'select')}>预选记录</Text> 中添加其他房源</View>
            </Block>
          )
        }
        <Statement style="margin-top:80rpx" />
      </ScrollView>
    )
  }
  renderAgreement() {
    const { raiseProfile = {} } = this.state

    return (
      <ScrollView scrollY className="container3">
        <View className="agent-box">
          <View className="center-title">线上选房协议</View>
          <View className="rich-text">
            <RichText nodes={raiseProfile.payProtocol || ''} />
          </View>
        </View>
      </ScrollView >
    )
  }

  // 获取输入
  handleInput = (key, e) => {
    const { person } = this.props.userInfo

    this.setState({
      record: {
        ...(this.state.record || {}),
        personId: person.personId,
        [`${key}`]: e.detail.value,
      }
    })
  }

  //
  prepareGetCaptcha = () => {
    const { record } = this.state
    const disabled = !!record.raiseRecordId
    if (disabled) return false;

    if (this.captchaLock) {
      Taro.showToast({
        title: '发送中, 请稍后',
        icon: 'none'
      })
      return false;
    }

    const { tel } = this.state.record || {}

    if (isEmpty(tel) || tel.length < 11) {
      Taro.showToast({
        title: '请填写正确的手机号',
        icon: 'none'
      })
      return false;
    }

    return true
  }

  // 获取验证码
  handleCaptcha = e => {
    const { tel } = this.state.record || {}

    if (!tel) {
      Taro.showToast({
        title: '请填写手机号',
        icon: 'none'
      })
      return Promise.reject();
    }

    return new Promise((resolve, reject) => {
      this.captchaLock = true
      getCodeMessage(tel).then(() => {
        Taro.showToast({ title: '发送成功' })
        this.captchaLock = false
        resolve()
      }).catch(() => {
        this.captchaLock = false
        reject()
      })
    })
  }

  tochooseConsultant() {
    Taro.navigateTo({
      url: '/onlineSelling/pages/chooseConsultant/index'
    })
  }

  getConsultant = () => {
    const { house } = this.props
    return house.chooseConsultant || (house.consultantList || []).filter(x => x.mine)[0]
  }

  renderProfile() {
    const { record, captchaCountdown } = this.state
    const consultant = this.getConsultant()
    const disabled = !!record.raiseRecordId

    return (
      <ScrollView scrollY className="container2">
        <View className="profile-box">
          <View className="title">我的个人信息</View>
          <View style="font-size:24rpx;color:#999;line-height:60rpx">除手机号外其他信息修改后会保存到个人信息中</View>
          <View className="profile-item">
            <View className="name">
              <Text style="color:#FF3C3C;font-size:32rpx;margin-right:8rpx">*</Text>
              姓名
            </View>
            <Input className='input' placeholder-style="color:#999" disabled={disabled} value={record.name} onInput={this.handleInput.bind(this, 'name')} type='text' placeholder='请填写真实姓名' />
          </View>
          <View className="profile-item">
            <View className="name">
              <Text style="color:#FF3C3C;font-size:32rpx;margin-right:8rpx">*</Text>
              身份证号
            </View>
            <Input className='input' placeholder-style="color:#999" disabled={disabled} value={record.idcard} onInput={this.handleInput.bind(this, 'idcard')} type='text' placeholder='请填写身份证号' />
          </View>
          <View className="profile-item">
            <View className="name">
              <Text style="color:#FF3C3C;font-size:32rpx;margin-right:8rpx">*</Text>
              手机号
            </View>
            <Input className='input' placeholder-style="color:#999" disabled={disabled} value={record.tel} type='text' onInput={this.handleInput.bind(this, 'tel')} placeholder='请填写手机号' />
          </View>
          <View className="profile-item">
            <View className="name">
              <Text style="color:#FF3C3C;font-size:32rpx;margin-right:8rpx">*</Text>
              验证码
            </View>
            <Input className='inputCode' placeholder-style="color:#999" type='text' disabled={disabled} onInput={this.handleInput.bind(this, 'captcha')} placeholder='请填写验证码' />
            <Captcha countdown={captchaCountdown} require={this.prepareGetCaptcha.bind(this)} onClick={this.handleCaptcha} />
          </View>
          <View className="profile-flex" style="margin-top:20rpx">
            <View className="title">我的置业顾问信息</View>
            <View className="choose" onClick={this.tochooseConsultant}>选择置业顾问</View>
          </View>
          <ConsultantItem
            data={consultant}
            style="padding:30rpx 0;width:690rpx; border-bottom: 1px solid #dcdcdc;"
            type="raiseMoney"
            tips="show"
          />
        </View>
      </ScrollView >
    )
  }
  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
  }

  handleChangeType = (e) => {
    console.log('----------------->', e)
    this.setState({ payType: e.detail.value })
  }

  renderMoney() {
    const { raiseProfile = {}, payTypeList, payType } = this.state
    const payTypeSettings = (raiseProfile.payType || '').split(',')
    const showTypes = payTypeList.filter(x => (payTypeSettings.indexOf(x.value) > -1))
    const showProtocal = payType === 'onLine' ? raiseProfile.payDescriptionOnline : raiseProfile.payDescriptionOffline
    const payTip = payType === 'onLine' ? '线上缴费说明' : '线下缴费说明'

    return (
      <ScrollView scrollY className="container2" style="padding:0 30rpx">
        <View className="profile-flex">
          <View className="title">认筹金额</View>
          <View className="price">{this.regFenToYuan(raiseProfile.raisePrice)}元</View>
        </View>
        {
          (payTypeSettings.length > 1) &&
          (
            <View className="pay-type">
              <View className="head">请选择缴费方式：</View>
              <View className="body">
                <RadioList dataset={showTypes} value={payType} onChange={this.handleChangeType} />
              </View>
            </View>
          )
        }
        <View className="center-title">{payTip}</View>
        <RichText nodes={showProtocal || ''} />
      </ScrollView >
    )
  }

  checkRaise = () => {
    const { record, raiseProfile, preselectList } = this.state
    const { house } = this.props

    // 当前选中房源
    const houseList = house.raiseCart || []

    if (!houseList.length) {
      Taro.showToast({ title: '请选择房源', icon: 'none' })
      return Promise.reject()
    }

    // 如果要求预选, 预先房源跟当前列表必须一致
    if (raiseProfile.needPreselection) {
      for (let i in houseList) {
        const exists = preselectList.filter(x => x.houseId === houseList[i].houseId)[0]
        if (!exists) {
          Taro.showToast({ title: '需要先预选才能认筹', icon: 'none' })
          return Promise.reject()
        }
      }
    }

    if (record.raiseRecordId) {
      // 如果认筹单跟预选的房源不一致, 说明是新的认筹
      let found = true
      for (let inx in houseList) {
        const has = (record.taHousingResourcesList || []).filter(x => x.houseId == houseList[inx].houseId)[0]

        if (!has) {
          found = false;
          break;
        }
      }

      if (!found) {
        const defaultRecord = this.initRecord()
        this.setState({ record: defaultRecord })
      }
    }

    return Promise.resolve()
  }

  makeRaiseRecord = () => {
    const { record, raiseProfile } = this.state
    const { house } = this.props
    const houseList = house.raiseCart.map(x => x.houseId)
    const disabled = !!record.raiseRecordId
    if (disabled) return Promise.resolve();

    if (isEmpty(record.name)) {
      Taro.showToast({
        title: '姓名不能为空',
        icon: 'none',
      })

      return Promise.reject()
    }

    // 校验身份证号
    if (isEmpty(record.idcard) || !checkIDCard(record.idcard)) {
      Taro.showToast({
        title: '身份证号码不合法',
        icon: 'none',
      })

      return Promise.reject()
    }

    debugger

    // 校验手机号
    if (isEmpty(record.tel) || record.tel.length < 11) {
      Taro.showToast({
        title: '手机号格式不正确',
        icon: 'none',
      })

      return Promise.reject()
    }

    // 验证码
    if (isEmpty(record.captcha)) {
      Taro.showToast({
        title: '验证码不能为空',
        icon: 'none',
      })

      return Promise.reject()
    }

    // 校验置业
    const consultant = this.getConsultant()
    if (!consultant || !consultant.id) {
      Taro.showToast({
        title: '置业顾问不能为空',
        icon: 'none',
      })
      return Promise.reject()
    }

    return new Promise((resolve, reject) => {
      saveRaiseRecord({
        ...record,
        houseList,
        userId: consultant.userId,
        userName: consultant.name,
      }, raiseProfile).then((res) => {
        this.setState({ record: res })
        resolve(res)
      }).catch((err) => {
        this.setState({ current: 4, failInfo: { title: '认筹失败', desc: err.message || err } }) 
      })
    })
  }

  makePay = () => {
    const { payType, record = {} } = this.state
    if (!payType) {
      Taro.showToast({
        title: '请确定支付方式',
        icon: 'none'
      })
      return Promise.reject()
    }

    if (payType === 'offLine') {
      return Promise.resolve()
    }

    const params = {
      targetId: this.$router.params.raiseRecordId || record.raiseRecordId,
      targetType: 'house'
    }

    return new Promise((resolve, reject) => {
      raiseOrder(params).then(res => {

        Taro.requestPayment({
          timeStamp: String(res.timeStamp),
          nonceStr: res.nonceStr,
          package: res.package,
          signType: res.signType,
          paySign: res.sign,

          success(res) {
            // 最后
            resolve()
          },
          fail(err) {
            console.log(err, "errrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr")

            cancelOrder(params).then(res => { })

            // 然后
            reject()
          }
        })
      })
    })

  }
  toRaiseProfile(id) {
    Taro.navigateTo({
      url: `/onlineSelling/pages/raiseProfile/index?id=${id}`
    })
  }
  renderResult() {
    const { raiseProfile = {}, record = {}, failInfo } = this.state
    const isOk = !failInfo
    const showIcon = isOk ? require('../../assets/success2.png') : require('../../assets/fail2.png')
    const showTitle = isOk ? '提交成功' : failInfo.title

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

        <View className="status">{showTitle}</View>

        {
          isOk &&
          (
            <Block>
              <View className="tip" style="margin-bottom:10rpx">详情请查看认筹单</View>
              <View className="tip">支付结果请留意微信支付通知</View>
            </Block>
          )
        }

        {
          !isOk && (<View className="tip">{(failInfo || {}).desc}</View>)
        }

        <ContactConsultant buildingId={raiseProfile.buildingId} style=" position: absolute;bottom: 11vh;" />
        {
          record.raiseRecordId &&
          (<View className="look-btn" onClick={() => this.toRaiseProfile(record.raiseRecordId)}>查看认筹单</View>)
        }        
      </View>

    );
  }

  nextStep(current) {
    switch (current) {
      // 确认房源
      case 0:
        this.checkRaise().then(() => {
          this.setState({
            current: current + 1
          })
        })
        return;

      // 认筹确认
      case 2:
        this.makeRaiseRecord().then((res) => {
          console.log(res, "res")
          this.setState({
            current: current + 1
          })
        })
        return;

      // 缴费
      case 3:
        this.makePay().then(() => {
          this.setState({
            current: current + 1
          })
        })
        return;

      //
      default:
        this.setState({
          current: current + 1
        })

    }
  }

  upStep(current) {
    this.setState({
      current: current - 1
    })
  }

  renderBottomBtn() {
    const { current, protocolCountdown } = this.state
    return (
      <View className="bottom-btn">
        {current == 1 && <View style="font-size:24rpx;color:#999;line-height:70rpx">请仔细阅读选房协议直到结尾才能进入下一步</View>}
        {current != 4 &&
          <NextStep
            countdown={current == 1 ? protocolCountdown : 0}
            onClick={() => this.nextStep(current)}
            text={current == 3 ? '现在缴费' : '下一步'}
          />
        }
        {current != 0 && current != 4 && <View className="up-btn" onClick={() => this.upStep(current)}>上一步</View>}
      </View>
    )
  }

  render() {
    const { current } = this.state
    return (
      <View className="raiseMoney">
        {this.renderTop()}
        {current == 0 && this.renderHouse()}
        {current == 1 && this.renderAgreement()}
        {current == 2 && this.renderProfile()}
        {current == 3 && this.renderMoney()}
        {current == 4 && this.renderResult()}
        {this.renderBottomBtn()}
      </View>
    )
  }

}
