<template>
  <div class="wrapper">
    <h2 class="title">加入我们</h2>
    <p class="subtitle">欢迎加入我们，成为推手</p>
    <ul class="form-wrap">
      <li>
        <label class="required">
          <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>
        <label class="required">
          <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="funLimitLength">
        </div>
      </li>
      <li v-if="false">
        <label class="required">
          <span v-for="(str, index) in '图形验证：'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <input type="text" placeholder="图片验证码" v-myBlur v-model.trim="postData.capture">
        </div>
        <img class="capture-img" :src="strCapture" alt="" @click="funUpdateCapture">
      </li>
      <li>
        <label class="required">
          <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="funLimitLength">
        </div>
        <button class="get-code" @click="funGetCode">{{ [0, 60].includes(numCount) ? '获取' : numCount + '秒' }}</button>
      </li>
      <li>
        <label class="required">
          <span class="label-city" 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>
        <label class="required">
          <span class="label-profession" v-for="(str, index) in '职业：职业'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <input type="text" placeholder="请输入职业" v-myBlur v-model.trim="postData.orderUserProfess">
        </div>
      </li>
      <li v-if="false">
        <label class="required">
          <span class="label-age" v-for="(str, index) in '年龄：年龄'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap age-wrap">
          <input :class="{'opacity-0': postData.orderUserAge * 1 > 0}" type="tel" placeholder="请输入年龄" v-myBlur
                 v-model.trim="age">
          <p v-show="postData.orderUserAge * 1 > 0">{{ postData.orderUserAge * 1 }}</p>
        </div>
      </li>
      <li>
        <label>
          <span class="label-invite-code" v-for="(str, index) in '邀请码：码'" :key="index">{{ str }}</span>
        </label>
        <div class="value-wrap">
          <input type="text" placeholder="请输入邀请码" :disabled="isDisabled" v-myBlur v-model.trim="postData.inviteCode">
        </div>
      </li>
    </ul>
    <button class="submit" @click="funSubmit">提交</button>
    <p class="explain">
      <span>申请代表您同意</span>
      <router-link :to="{path: '/partner/agreement', query: {YYMMDD: YYMMDD, compactAddress: compactAddress}}">《服务协议》
      </router-link>
    </p>
    <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 { sendSMS } from '../../../api/common'
import { getMyPartnerOrder } from '../explain/api'
import { getChinaArea, createOrder } from './api'

const STRCAPTURE = process.env.API_DOMAIN + '/api/captcha'
export default {
  name: 'join',
  props: {
    inviteCode: {
      type: String,
      default: ''
    }
  },
  components: {
    'van-popup': Popup,
    'van-picker': Picker
  },
  data () {
    return {
      postData: {
        orderUserName: '', // 用户名称
        orderUserSex: '男',
        orderUserPhone: '', // 手机号码
        code: '', // 验证码
        capture: '',
        orderProvince: '', // 省份
        orderCity: '', // 城市
        orderDistrict: '', // 区域
        orderUserProfess: '', // 职业
        orderUserAge: 0,
        inviteCode: ''
      },
      numCount: 60,
      arrErrorList: [],
      strCapture: STRCAPTURE,
      showPicker: false,
      columns: [],
      timer: null,
      isDisabled: false
    }
  },
  computed: {
    age: {
      get () {
        return this.postData.orderUserAge ? this.postData.orderUserAge : ''
      },
      set (value) {
        this.postData.orderUserAge = /^[1-9]+$/.test(value) ? value * 1 : 0
      }
    },
    YYMMDD () {
      const date = new Date()
      const YY = date.getFullYear()
      const MM = date.getMonth() + 1
      const DD = date.getDate()
      return YY + '年' + MM + '月' + DD + '日'
    },
    compactAddress () {
      return this.orderProvince ? this.orderProvince + this.orderCity + this.orderDistrict : ''
    }
  },
  async mounted () {
    this.funGetChinaArea()
  },
  activated () {
    if (!this.$route.meta.isUseCache) {
      this.postData = {
        orderUserName: '',
        orderUserSex: '男',
        orderUserPhone: '',
        code: '',
        capture: '',
        orderProvince: '',
        orderCity: '',
        orderDistrict: '',
        orderUserProfess: '',
        orderUserAge: 0,
        inviteCode: ''
      }
      this.numCount = 60
      this.arrErrorList = []
      this.timer = null
      this.isDisabled = false
    } else {
      clearInterval(this.timer)
    }
    if (this.inviteCode) {
      this.isDisabled = true
      this.$set(this.postData, 'inviteCode', this.inviteCode)
    }
    this.$nextTick(() => {
      this.$refreshTitle('成为推手')
    })
    this.$route.meta.isUseCache = false
  },
  methods: {
    funInit () {
      getMyPartnerOrder().then(res => {
        if (res.status) {
          const { id } = res.data
          if (id) {
            Toast({
              message: res.msg,
              onClose: () => {
                this.$router.replace({ path: `/partner/detail/${id}` })
              }
            })
          }
        }
      }).catch(err => {
        Toast(err)
      })
    },
    funGetChinaArea () {
      getChinaArea().then(res => {
        if (res.status) {
          this.columns = res.data.filter(province => province.text === '浙江')
        } else {
          Toast(res.msg)
        }
      }).catch(err => {
        Toast(err)
      })
    },
    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])
    },
    funLimitLength () {
      const { orderUserPhone, code } = this.postData
      this.postData.orderUserPhone = orderUserPhone.length > 11 ? orderUserPhone.slice(0, 11) : orderUserPhone
      this.postData.code = code.length > 4 ? code.slice(0, 4) : code
    },
    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
      }

      // if (!capture) {
      //   Toast('请输入图片验证码')
      //   return
      // }
      this.funCutDown()
      sendSMS(orderUserPhone, 2, capture).then(res => {
        if (res.status) {
          Toast('发送成功')
        } else {
          Toast(res.msg)
          this.funUpdateCapture()
          clearInterval(this.timer)
          this.numCount = 60
        }
      }).catch(err => {
        Toast(err.msg)
        this.funUpdateCapture()
        clearInterval(this.timer)
        this.numCount = 60
      })
    },
    verifyData () {
      const { orderUserName, orderUserSex, orderUserPhone, code, orderProvince, orderCity, orderDistrict, orderUserProfess } = 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 (!orderUserProfess) {
        this.arrErrorList.push('请输入职业')
      }
      return this.arrErrorList.length <= 0
    },
    funUpdateCapture () {
      this.strCapture = STRCAPTURE + '?' + new Date().getTime()
    },
    funSubmit () {
      const postData = {
        ...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) {
          const { id } = res.data
          Toast({
            type: 'success',
            message: '提交成功',
            forbidClick: true,
            onClose: () => {
              this.$router.replace({ path: '/partner/detail/' + id })
            }
          })
          return
        }
        Toast(res.msg)
      }).catch(err => {
        myToast.clear()
        Toast(err)
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.funInit()
    })
  },
  beforeRouteLeave (to, from, next) {
    if (['partnerPrivacy', 'partnerAgreement'].includes(to.name)) {
      from.meta.isUseCache = true
    }
    next()
  }
}
</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;
  padding: 25px 0 200px;
  background: #fff;
}

h2.title {
  width: 327px;
  line-height: 33px;
  font-size: 24px;
  font-weight: 500;
  color: #333;
}

p.subtitle {
  width: 327px;
  margin-top: 4px;
  line-height: 22px;
  font-size: 16px;
  color: #333;
}

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

    &:nth-of-type(1) {
      margin-top: 40px;
    }
  }

  label {
    display: flex;

    &.required {
      position: relative;
      left: 0;
      top: 0;

      &:before {
        position: absolute;
        left: -12px;
        top: -4px;
        z-index: 1;
        content: '*';
        line-height: 33px;
        font-size: 24px;
        font-weight: 500;
        color: #FF3B30;
      }
    }

    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),
      &.label-city:nth-of-type(4),
      &.label-city:nth-of-type(5),
      &.label-profession:nth-of-type(4),
      &.label-profession:nth-of-type(5),
      &.label-age:nth-of-type(4),
      &.label-age:nth-of-type(5),
      &.label-invite-code:nth-of-type(5) {
        visibility: hidden;
      }
    }
  }

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

  .age-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;
    }
  }

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

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

    &.init {
      color: #999;
    }
  }

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

  .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: #C9A585;
  }
}

.submit {
  width: 327px;
  height: 45px;
  margin-top: 41px;
  border-radius: 4px;
  line-height: 20px;
  font-size: 14px;
  font-weight: 500;
  color: #fff;
  background: linear-gradient(90deg, #E5C7A5 0%, #CFAA7F 100%);
  box-shadow: 0 14px 9px -10px rgba(219, 208, 194, 1);
}

.explain {
  display: flex;
  margin-top: 12px;

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