<template>
  <div class="wrapper">
    <img class="goods-cover" src="./image/banner@2x.png" alt="">
    <ul class="form-wrap">
      <li class="form-item">
        <label>
          <span class="label-name" v-for="(str, index) in '姓名：姓名'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <div class="value-name">
            <input type="text" placeholder="请输入姓名" v-myBlur v-model.trim="postData.orderUserName">
          </div>
          <div class="value-gender">
            <p v-for="str in ['男', '女']" :key="str" @click="postData.orderUserSex = str">
              <img src="./image/btn_xingbie_sel@2x.png" alt="" v-show="postData.orderUserSex === str">
              <img src="./image/btn_xingbie_nor@2x.png" alt="" v-show="postData.orderUserSex !== str">
              <span>{{ str }}</span>
            </p>
          </div>
        </div>
      </li>
      <li class="form-item">
        <label>
          <span v-for="(str, index) in '手机号码：'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <input
            type="tel"
            placeholder="请输入手机号码"
            v-myBlur
            v-model.trim="postData.orderUserPhone"
            @input="postData.orderUserPhone = postData.orderUserPhone.replace(/[^\d]/, '').replace(/^0/, '').replace(/(\d{11})(.*)/, '$1')">
        </div>
      </li>
      <li class="form-item">
        <label>
          <span class="label-code" v-for="(str, index) in '验证码：码'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <input
            type="tel"
            placeholder="请输入验证码"
            v-myBlur v-model.trim="postData.code"
            @input="postData.code = postData.code.replace(/[^\d]/, '').replace(/(\d{4})(.*)/, '$1')">
        </div>
        <button class="get-code" @click="funGetCode">{{ [0, 60].includes(numCount) ? '获取' : numCount + '秒' }}</button>
      </li>
      <li class="form-item">
        <label>
          <span v-for="(str, index) in '所在城市：'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap" @click="showPicker = true">
          <p class="value-city" v-show="postData.orderProvince">{{
              postData.orderProvince + postData.orderCity +
              postData.orderDistrict
            }}</p>
          <p class="value-city init" v-show="!postData.orderProvince">请选择所在城市</p>
          <img src="./image/btn_next@2x.png" alt="">
        </div>
      </li>
      <li class="form-item">
        <label>
          <span v-for="(str, index) in '小区名称：'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <textarea
            name=""
            rows="1"
            placeholder="请输入小区名称"
            v-model.trim="postData.orderAddress"
            v-myBlur
            ref="myTextarea"></textarea>
        </div>
      </li>
      <li class="form-item">
        <label>
          <span v-for="(str, index) in '需求金额（万元）：'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap amount-wrap">
          <input
            :class="{'opacity-0': postData.orderPrice * 1 > 0}"
            type="tel" placeholder="请输入需求金额"
            v-myBlur
            v-model.trim="amount"
            @input="amount = amount.replace(/[^\d]/, '').replace(/^0/, '')">
          <p v-show="postData.orderPrice * 1 > 0">{{ postData.orderPrice * 1 | toThousands }}</p>
        </div>
      </li>
      <li class="form-item">
        <label>
          <span v-for="(str, index) in '是否有房'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <div class="value-name"></div>
          <div class="value-gender">
            <p v-for="str in ['有', '无']" :key="str" @click="postData.orderUserSex = str">
              <img src="./image/btn_xingbie_sel@2x.png" alt="" v-show="postData.orderUserSex === str">
              <img src="./image/btn_xingbie_nor@2x.png" alt="" v-show="postData.orderUserSex !== str">
              <span>{{ str }}</span>
            </p>
          </div>
        </div>
      </li>
      <li>
        <button class="submit" @click="funSubmit">提交</button>
      </li>
      <li>
        <p class="explain">
          <span>申请代表您同意</span>
          <router-link :to="{path: '/loan/privacy'}">《用户隐私协议》</router-link>
          <span>和</span>
          <router-link :to="{path: '/loan/agreement'}">《服务协议》</router-link>
        </p>
      </li>
    </ul>
    <div class="about"></div>
    <van-popup v-model="showPicker" round position="bottom">
      <van-picker
        show-toolbar
        title="所在城市"
        :columns="columns"
        @cancel="showPicker = false"
        @confirm="onConfirm"/>
    </van-popup>
  </div>
</template>

<script>
import { Popup, Picker, Toast } from 'vant'
import { createOrder } from './api'
import { getChinaArea, sendSMS } from '../../../api/common'

export default {
  name: 'onlineAct',
  components: {
    'van-popup': Popup,
    'van-picker': Picker
  },
  props: {
    partnerId: {
      type: String,
      default: ''
    },
    RId: {
      type: [String, Number],
      default: ''
    }
  },
  data () {
    return {
      postData: {
        orderUserName: '', // 用户名称
        orderUserSex: '男',
        orderUserPhone: '', // 手机号码
        code: '', // 验证码
        capture: '',
        orderPrice: '', // 申请金额
        orderProvince: '', // 省份
        orderCity: '', // 城市
        orderDistrict: '', // 区域
        orderAddress: '' // 详细地址
      },
      numCount: 60,
      arrErrorList: [],
      showPicker: false,
      columns: [],
      timer: null
    }
  },
  computed: {
    amount: {
      get () {
        return this.postData.orderPrice * 1 ? this.postData.orderPrice : ''
      },
      set (value) {
        this.postData.orderPrice = value
      }
    }
  },
  async mounted () {
    this.funGetChinaArea()
    await this.$nextTick()
    const textarea = this.$refs.myTextarea
    if (textarea) {
      this.handleTextarea(textarea)
      textarea.addEventListener('input', this.handleTextarea(textarea, 1), false)
      this.$once('hook:beforeDestroy', () => {
        textarea.addEventListener('input', this.handleTextarea(textarea, 1), false)
      })
    }
    this.$refreshTitle('在线申请')
  },
  methods: {
    funGetChinaArea () {
      getChinaArea().then(res => {
        if (res.status) {
          this.columns = res.data.filter(province => province.text === '浙江')
        } else {
          Toast(res.msg)
        }
      }).catch(err => {
        Toast(err)
      })
    },
    handleTextarea (el, auto) {
      return () => {
        if (auto) {
          el.style.height = 'auto'
        }
        el.style.height = el.scrollHeight + 'px'
      }
    },
    onConfirm (value) {
      this.showPicker = false
      this.$set(this.postData, 'orderProvince', value[0])
      this.$set(this.postData, 'orderCity', value[1])
      this.$set(this.postData, 'orderDistrict', value[2])
    },
    funCutDown () {
      clearInterval(this.timer)
      this.timer = setInterval(() => {
        if (this.numCount === 0) {
          clearInterval(this.timer)
          this.numCount = 0
          return
        }
        this.numCount--
      }, 1000)
    },
    // 获取验证码
    funGetCode () {
      const numCount = this.numCount
      const { orderUserPhone, capture } = this.postData
      if (numCount < 60 && numCount > 0) {
        return
      }
      this.numCount = 60
      if (!(/^1[2|3|4|5|6|7|8|9]\d{9}$/.test(orderUserPhone))) {
        Toast('请输入手机号码')
        return
      }

      this.funCutDown()
      sendSMS(orderUserPhone, 0, capture).then(res => {
        if (res.status) {
          Toast('发送成功')
        } else {
          Toast(res.msg)
          clearInterval(this.timer)
          this.numCount = 60
        }
      }).catch(err => {
        Toast(err.msg)
        clearInterval(this.timer)
        this.numCount = 60
      })
    },
    verifyData () {
      const {
        orderUserName,
        orderUserSex,
        orderUserPhone,
        code,
        orderProvince,
        orderCity,
        orderDistrict,
        orderAddress,
        orderPrice
      } = this.postData
      this.arrErrorList = []
      if (!orderUserName) {
        this.arrErrorList.push('请输入姓名')
      }
      if (!orderUserSex) {
        this.arrErrorList.push('请选择性别')
      }
      if (!/^1[2|3|4|5|6|7|8|9]\d{9}$/.test(orderUserPhone)) {
        this.arrErrorList.push('请输入手机号码')
      }
      if (!(/^\d{4}$/.test(code))) {
        this.arrErrorList.push('请输入验证码')
      }
      if (!orderProvince || !orderCity || !orderDistrict) {
        this.arrErrorList.push('请选择所在城市')
      }
      if (!orderAddress) {
        this.arrErrorList.push('请输入小区名称')
      }
      if (orderPrice * 1 <= 0) {
        this.arrErrorList.push('请输入需求金额')
      }
      return this.arrErrorList.length <= 0
    },
    funSubmit () {
      const postData = {
        partnerId: this.partnerId,
        userNewId: this.RId,
        ...this.postData
      }
      delete postData.capture
      if (!this.verifyData()) {
        Toast({
          message: this.arrErrorList[0],
          forbidClick: true
        })
        return
      }
      const myToast = Toast.loading({
        message: '提交中...',
        duration: 1000 * 100,
        forbidClick: true
      })
      createOrder(postData).then(res => {
        myToast.clear()
        if (res.status) {
          Toast({
            type: 'success',
            message: '提交成功',
            forbidClick: true,
            onClose: () => {
            }
          })
          return
        }
        Toast(res.msg)
      }).catch(err => {
        myToast.clear()
        Toast(err)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  position: relative;
  left: 0;
  top: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  min-height: 100vh;
  background: #3D82D9;
}

.goods-cover {
  display: block;
  width: 100%;
  min-height: 170px;
  margin-bottom: 10px;
}

.form-wrap {
  width: 356px;
  padding-top: 8px;
  padding-bottom: 26px;
  border-radius: 9px;
  background: #FFFFFF;

  .form-item {
    position: relative;
    left: 0;
    top: 0;
    display: flex;
    align-items: flex-start;
    width: 327px;
    padding: 13px 14px;
    margin: 8px auto 0;
    border: 1px solid #E8E8E8;
    border-radius: 4px;
  }

  label {
    display: flex;

    span {
      line-height: 22px;
      font-size: 16px;
      font-weight: 500;
      color: #333;

      &.label-name:nth-of-type(4),
      &.label-name:nth-of-type(5),
      &.label-code:nth-of-type(5), {
        visibility: hidden;
      }
    }
  }

  .value-wrap {
    flex: 1;
    display: flex;
    margin-left: 9px;
  }

  .amount-wrap {
    position: relative;
    left: 0;
    top: 0;

    input {
      position: absolute;
      left: 0;
      top: 0;
      z-index: 1;

      &.opacity-0 {
        opacity: 0;
      }
    }

    p {
      width: 100%;
      padding-top: 2px;
      line-height: 20px;
      font-size: 15px;
      color: #333;
    }
  }

  input,
  textarea {
    width: 100%;
    min-height: 20px;
    padding-top: 2px;
    line-height: 20px;
    font-size: 15px;
    color: #333;
    word-break: break-all;
    resize: none;
    outline: 0 none;
    overflow: hidden;
    background: transparent;
    -webkit-text-fill-color: #333;
    opacity: 1;

    &::-webkit-input-placeholder {
      color: #999;
      -webkit-text-fill-color: #999;
      opacity: 1;
    }
  }

  .value-name {
    display: flex;
    width: 100%;
  }

  .value-gender {
    display: flex;

    p {
      display: flex;

      &:nth-of-type(2) {
        margin-left: 15px;
      }
    }

    span {
      margin-left: 4px;
      line-height: 22px;
      font-size: 16px;
      color: #333;
    }
  }

  .value-city {
    flex: 1;
    line-height: 22px;
    font-size: 15px;
    color: #333;

    &.init {
      color: #999;
    }
  }

  img {
    width: 22px;
    height: 22px;
  }

  .capture-img {
    @include vertical-center;
    right: 14px;
    z-index: 1;
    display: block;
    width: 125px;
    height: 31px;
    border-radius: 4px;
    overflow: hidden;
  }

  .get-code {
    @include vertical-center;
    right: 0;
    z-index: 1;
    display: block;
    min-width: 87px;
    padding: 6px;
    line-height: 22px;
    font-size: 16px;
    font-weight: 500;
    color: #3D82D9;
  }
}

.submit {
  display: block;
  width: 327px;
  height: 45px;
  margin: 18px auto 0;
  border-radius: 4px;
  line-height: 45px;
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  background: #3D82D9;
}

.explain {
  display: flex;
  width: 327px;
  padding-left: 10px;
  margin: 12px auto 0;

  span,
  a {
    line-height: 17px;
    font-size: 12px;
    color: #666;
  }
}

.about {
  width: 100%;
  height: 647px;
  margin-top: 28px;
  background: url("./image/explain@2x.png") center top/100% 100% no-repeat;
}
</style>
