<template>
<section class="dlr-input-content">
<div class="dlr-form-input">
  <input ref="input" :class="inputElSty"
    :type="type"
    :number="type === 'number'"
    :placeholder="placeholder"
    :maxlength="inputMax"
    :disabled="disabled"
    :readonly="readonly"
    :value="inputVal"
    @focus="focusHandler"
    @blur="blurHandler"
    @input="inputHandler"
    @change="changeHandler">
</div>
 <!-- 清除图标 -->
  <div v-show="ui.showClear" class="input-clear" @click="clearHandler">
    <i class="input-clear-i"></i>
  </div>
  <!-- 获取验证码 -->
  <div ref="btnSMS" v-show="inputRoleVal === 'sms' && !ui.showSeconds" @click.stop="msmClickHandler()">
    <a href="#" class="ver-bnt">获取验证码</a>
  </div>
  <!-- 倒计时 -->
  <div ref="seconds" v-show="ui.showSeconds">
    <a href="#" class="ver-bnt disabled">{{secondsVal+' s'}}</a>
  </div>
  <!-- 扩展插槽 -->
  <slot></slot>
</section>
</template>

<script>
const trim = (string) => {
  return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '')
}
export default {
  name: 'dlrFormInput',
  props: {
    type: {
      type: String,
      default () {
        return 'text'
      }
    },
    // normal:普通输入，sms：短信验证码模式，img:图片验证码模式
    'input-role': {
      type: [String],
      default () {
        return 'normal'
      }
    },
    // v-model
    value: {
      type: [String, Object],
      default () {
        return 'text'
      }
    },
    // 是否只读
    readonly: {
      type: [Boolean],
      default () {
        return false
      }
    },
    disabled: {
      type: [Boolean],
      default () {
        return false
      }
    },
    placeholder: {
      type: [String],
      default () {
        return ''
      }
    },
    'max-length': {
      type: [Number, String],
      default () {
        return 20
      }
    },
    // 倒计时秒数:
    seconds: {
      type: [Number, String],
      default () {
        return 60
      }
    },
    // 短信发送事件前，返回false 可终止
    'send-sms-before': {
      type: [Function],
      default () {
        return null
      }
    }
  },
  data () {
    return {
      ui: {
        showClear: false, // 显示清除按钮
        showSeconds: false // 显示倒计时
      },
      inputMax: this.$props.maxLength.toString(),
      inputVal: this.$props.value,
      inputRoleVal: this.$props.inputRole, // 普通输入、短信验证码、图片验证码
      secondsVal: this.$props.seconds, // 倒计时 秒
      secondsValOrg: this.$props.seconds,
      timeIntv: null
    }
  },
  watch: {
    value (val) {
      this.inputVal = trim(val)
    },
    inputVal (val) {
      val = trim(val)
      this.$emit('input', val)
    },
    attr: {
      immediate: true,
      handler (attrs) {
        this.$nextTick(() => {
          const target = [this.$refs.input]
          target.forEach(el => {
            if (!el || !attrs) return
            Object.keys(attrs).map(name => el.setAttribute(name, attrs[name]))
          })
        })
      }
    }
  },
  mounted () {
    this.$nextTick(() => {
      this.init()
    })
  },
  methods: {
    init () {
      if (trim(this.inputVal).length > 0) {
        this.ui.showClear = true
      }
    },
    inputHandler (evt) {
      this.inputVal = evt.target.value
      if (this.$props.type === 'number') {
        if (this.inputVal.length > this.inputMax) {
          this.inputVal = this.inputVal.slice(0, this.inputMax)
        }
      }
      if (this.inputVal === '' || this.inputVal.length === 0) {
        this.ui.showClear = false
      } else {
        this.ui.showClear = true
      }
    },
    changeHandler () {
      this.$emit('on-change', this.inputVal)
    },
    // 清除输入事件
    clearHandler () {
      if (this.$props.disabled || this.$props.readonly) return
      this.inputVal = ''
      this.ui.showClear = false
      this.$emit('on-clear')
      this.$emit('input', this.inputVal)
    },
    focusHandler () {
      if (this.inputVal.length > 0) {
        this.ui.showClear = true
      }
      this.$emit('on-focus')
    },
    blurHandler (evt) {
      setTimeout(() => {
        this.ui.showClear = false
      }, 1000)
      this.$emit('on-blur')
    },
    // 发短信事件
    msmClickHandler () {
      const _exec = (params) => {
        this.ui.showSeconds = true
        this.startSeconds()
        this.$emit('on-send-sms')
      }
      const onSendBefore = this.$props.sendSmsBefore
      const res = onSendBefore()
      if (res === true) {
        _exec()
      }
    },
    // 终止倒计时
    abordSeconds () {
      if (this.timeIntv) {
        clearTimeout(this.timeIntv)
        this.timeIntv = null
        this.secondsVal = this.secondsValOrg
        this.ui.showSeconds = false
      }
    },
    // 开始倒计时
    startSeconds () {
      if (this.timeIntv) {
        clearTimeout(this.timeIntv)
        this.timeIntv = null
      }
      this.timeIntv = setInterval(() => {
        if (this.secondsVal <= 0) {
          this.ui.showSeconds = false
          clearTimeout(this.timeIntv)
          this.timeIntv = null
          this.secondsVal = this.secondsValOrg
        } else {
          this.secondsVal--
        }
      }, 1000)
    },
    // 提供基础验证
    getValidate () {
      let res = true
      const result = { msg: '', res: true, code: 0 }
      if (!this.inputRoleVal) {
        return { msg: '未指定模式，无法提供验证模式', res: false, code: 100 }
      }
      if (this.inputRoleVal === 'sms') { // 短信验证码验证
        if (this.inputVal.length === 0) {
          result.msg = '请输入验证码'
          result.code = 101
          res = false
        }
        if (res) {
          res = /^[0-9]+?$/.test(this.inputVal)
          !res && (Object.assign(result, { msg: '验证码输入有误', code: 102 }))
        }
        if (this.inputVal.length > this.maxlength) {
          Object.assign(result, { msg: '验证码输入过长', code: 103 })
          res = false
        }
      }
      if (this.inputRoleVal === 'normal') { // 普通文本输入
        if (this.inputVal.length === 0) {
          Object.assign(result, { msg: '请输入信息', code: 104 })
          res = false
        }
        if (res) {
          const forbidden = '`~!@@#$%^*()<>,.;:\'"/?\\ ￥　&？[]、|｜（）+=-——_～。，《》÷…“”'
          for (let i = 0; i < forbidden.length; i++) {
            if (this.inputVal.indexOf(forbidden.charAt(i)) > -1) {
              res && (res = false)
              Object.assign(result, { msg: '请输入正确的内容', code: 105 })
            }
          }
        }
        if (res) {
          if (this.inputVal.length > this.maxlength) {
            Object.assign(result, { msg: '输入信息过长', code: 106 })
            res = false
          }
        }
      }
      if (this.inputRoleVal === 'phone') { // 手机号输入
        if (this.inputVal.length === 0) {
          Object.assign(result, { msg: '请输入手机号', code: 107 })
          res = false
        }
        if (res) {
          res = /^(1)\d{10}$/.test(this.inputVal)
          !res && (Object.assign(result, { msg: '请输入正确的手机号码', code: 108 }))
        }
      }
      result.res = res
      return result
    }
  },
  computed: {
    inputElSty () {
      if (this.inputRoleVal === 'normal') { // 普通输入模式
        return 'dlr-form-input-normal'
      }
      if (this.inputRoleVal === 'sms') { // 短信输入模式
        return 'dlr-form-input-sms'
      }
      return ''
    }
  }
}
</script>

<style lang="scss">
  @import '../sass/core/_setting.scss';
  @import '../sass/core/_mixin.scss';
//图片地址
  $imges: 'https://s.autoimg.cn/dealer/m/sj/live';

  .dlr-input-content {
    flex: 1;
    max-width: 100%;
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
    display: flex;
    -webkit-box-pack: justify;
    justify-content: space-between;
    -webkit-box-align: center;
    align-items: center;

    .dlr-form-input{
      flex: 1;
      &-normal { // 普通模式
          display: block;
          width: 100%;
          height: ptrd(68);
          color: #3d4145;
          font-size: ptrd(30);
          line-height: normal;
      }
      &-sms{ // 短信输入模式
        display: block;
        width: 100%;
        height: ptrd(68);
        color: #3d4145;
        font-size: ptrd(30);
        line-height: normal;
      }
    }
    .input-clear{ // 清除图标
      white-space: nowrap;
      flex-shrink: 0;
      margin-left: ptrd(10);
      display: flex;
      max-height: ptrd(60);
      .input-clear-i{ // x
        display: inline-block;
        width: ptrd(32);
        height: ptrd(32);
        background: url(#{$imges}/icon_list_close.png) no-repeat center center;
        background-size: ptrd(44);
      }
    }
    .ver-bnt{ // 验证码
      display: block;
          min-width: ptrd(110);
          font-size: ptrd(32);
          color: #FA5B20;
          padding-left: ptrd(20);

          &.disabled {
            color: #aaa;
          }
    }
  }

</style>
