<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.userName">
          </div>
          <div class="value-gender">
            <p v-for="str in ['男', '女']" :key="str" @click="postData.userSex = str">
              <img src="./image/btn_xingbie_sel@2x.png" alt="" v-show="postData.userSex === str">
              <img src="./image/btn_xingbie_nor@2x.png" alt="" v-show="postData.userSex !== 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.userPhone"
            @input="postData.userPhone = postData.userPhone.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.provinceName">{{
              postData.provinceName + postData.cityName +
              postData.districtName
            }}</p>
          <p class="value-city init" v-show="!postData.provinceName">请选择所在城市</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.addressName"
            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.applyPrice * 1 > 0}"
            type="tel" placeholder="请输入需求金额"
            v-myBlur
            v-model.trim="amount"
            @input="amount = amount.replace(/[^\d]/, '').replace(/^0/, '')">
          <p v-show="postData.applyPrice * 1 > 0">{{ postData.applyPrice * 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.isHouse = str">
              <img src="./image/btn_xingbie_sel@2x.png" alt="" v-show="postData.isHouse === str">
              <img src="./image/btn_xingbie_nor@2x.png" alt="" v-show="postData.isHouse !== 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'
import { isMobile, isSmscode } from '../../../utils/validate'
import { getQueryString } from '../../../utils/getQueryString'

export default {
  name: 'actApply',
  components: {
    'van-popup': Popup,
    'van-picker': Picker
  },
  data () {
    return {
      postData: {
        userName: '', // 用户名称
        userSex: '男', // 性别(0男1女)
        userPhone: '', // 手机号码
        code: '', // 验证码
        applyPrice: '', // 申请金额
        provinceName: '', // 省份
        cityName: '', // 城市
        districtName: '', // 区域
        addressName: '', // 详细地址
        isHouse: '' // 是否有房(0无1有)
      },
      numCount: 60,
      arrErrorList: [],
      showPicker: false,
      columns: [],
      timer: null,
      channel: ''
    }
  },
  computed: {
    amount: {
      get () {
        return this.postData.applyPrice * 1 ? this.postData.applyPrice : ''
      },
      set (value) {
        this.postData.applyPrice = value
      }
    }
  },
  async mounted () {
    this.channel = getQueryString('channel') || ''
    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 === '浙江').map(item => {
            return {
              ...item,
              children: item.children.filter(city => city.text === '杭州' || city.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, 'provinceName', value[0])
      this.$set(this.postData, 'cityName', value[1])
      this.$set(this.postData, 'districtName', 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 { userPhone } = this.postData
      if (numCount < 60 && numCount > 0) {
        return
      }
      this.numCount = 60
      if (!isMobile(userPhone)) {
        Toast('请输入手机号码')
        return
      }

      this.funCutDown()
      sendSMS(userPhone, 0, '').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 {
        userName,
        userSex,
        userPhone,
        code,
        provinceName,
        cityName,
        districtName,
        addressName,
        applyPrice,
        isHouse
      } = this.postData
      this.arrErrorList = []
      if (!userName) {
        this.arrErrorList.push('请输入姓名')
      }
      if (!userSex) {
        this.arrErrorList.push('请选择性别')
      }
      if (!isMobile(userPhone)) {
        this.arrErrorList.push('请输入手机号码')
      }
      if (!isSmscode(code)) {
        this.arrErrorList.push('请输入验证码')
      }
      if (!provinceName || !cityName || !districtName) {
        this.arrErrorList.push('请选择所在城市')
      }
      if (!addressName) {
        this.arrErrorList.push('请输入小区名称')
      }
      if (applyPrice * 1 <= 0) {
        this.arrErrorList.push('请输入需求金额')
      }
      if (!isHouse) {
        this.arrErrorList.push('请选择是否有房')
      }
      return this.arrErrorList.length <= 0
    },
    funSubmit () {
      const postData = {
        ...this.postData,
        userSex: this.postData.userSex === '男' ? 0 : 1,
        isHouse: this.postData.isHouse === '有' ? 1 : 0,
        applyPrice: this.postData.applyPrice * 10000, // 后端要求金额为元
        channel: this.channel
      }
      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: '提交成功',
            duration: 5000,
            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%;
  padding-bottom: calc(constant(safe-area-inset-bottom));
  padding-bottom: calc(env(safe-area-inset-bottom));
  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: 665px;
  margin-top: 28px;
  background: url("./image/explain@2x.png") center top/100% 100% no-repeat;
}
</style>
