<template>
  <view class="cv-code-area">
    <view class="cv-code-input-area">
      <input
        class="cv-code-input-item"
        placeholder-class="cv-code-input-item-placeholder"
        v-model="localVal"
        type="number"
        :maxlength="maxlength"
        :placeholder="diyPlaceholder"
        @input="funcOnInput"
      />
    </view>
    <view class="cv-code-button-area">
      <button
        size="mini"
        class="cv-code-button-item"
        :class="[btnType, btnDisabled ? 'cv-code-button-wait' : '']"
        :disabled="btnDisabled"
        @tap="getSmsCode"
      >
        {{ btnText }}
      </button>
    </view>
  </view>
</template>
<script>
import mpMixin from '../../libs/mixin/mpMixin.js';
import mixin from '../../libs/mixin/mixin.js';
export default {
  mixins: [mpMixin, mixin],
  name: 'cvCodeSms',
  emits: ['input', 'update:modelValue'],
  props: {
    value: {
      type: [Number, String],
      default: ''
    },
    modelValue: {
      type: [Number, String],
      default: ''
    },
    maxlength: {
      type: [Number, String],
      default: -1
    },
    mobile: {
      type: [Number, String],
      default: ''
    },
    mobileParam: {
      type: String,
      default: 'mobile'
    },
    codeSign: {
      type: Boolean,
      default: false
    },
    apiFunc: {
      type: Function,
      default: null
    },
    apiParam: {
      type: Object,
      default: {}
    },
    // 短信发送间隔
    waitTime: {
      type: [Number, String],
      default: 60
    },
    btnType: {
      type: [String],
      default: 'default'
    },
    onSendBefore: {
      type: Function,
      default: null
    }
  },
  watch: {
    mobile(newVal) {
      this.localMobile = newVal;
    },
    value(newVal) {
      this.localVal = newVal;
    },
    modelValue(newVal) {
      this.localVal = newVal;
    }
  },
  data() {
    return {
      // 验证码
      localVal: '',
      localMobile: '',
      nextTime: 0,
      diyPlaceholder: '短信验证码',
      // 按钮禁用
      btnDisabled: false,
      // 按钮文本
      btnText: '获取验证码',
      // 按钮定时器对象
      btnIntervalObj: null
    };
  },
  created() {
    this.localVal = this.doValueGet();
    this.localMobile = this.mobile;
    console.log(this.apiFunc);
  },
  methods: {
    doValueGet() {
      if (this.value === '') return this.modelValue;
      if (this.modelValue === '') return this.value;
      return this.value;
    },
    showDiyMsg(msg) {
      uni.showToast({
        title: msg,
        duration: 1200,
        icon: 'none'
      });
    },
    /******获取短信验证码************************************* */
    getSmsCode() {
      if (this.onSendBefore && typeof this.onSendBefore == 'function') {
        if (!this.onSendBefore()) {
          return false;
        }
      }
      if (!this.localMobile) {
        this.showDiyMsg('手机号不正确');
        return;
      }
      let mobileReg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!mobileReg.test(this.localMobile)) {
        this.showDiyMsg('手机号格式不正确');
        return;
      }

      if (!this.apiFunc) {
        this.showDiyMsg('短信接口方法不能为空');
        return;
      }

      // 禁用按钮
      this.btnDisabled = true;
      /* 请求接口 */
      if (this.btnIntervalObj) {
        // console.log('请勿重复提交验证码发送请求');
        return;
      }

      if (this.btnDisabled) {
        this.btnText = '请稍后...';
        if (this.apiFunc) {
          this.apiFunc({
            cto_sms_type: 'alterMobile',
            sendCode: '发送验证码',
            [this.mobileParam]: this.localMobile,
            ...this.apiParam
          })
            .then((successRes) => {
              let apiData = successRes;
              if (apiData.status == 200) {
                this.showDiyMsg('发送成功！');
                setTimeout(() => {
                  if (this.codeSign) {
                    let sign = (apiData.data && apiData.data.sign) || '';
                    this.diyPlaceholder = '识别码：' + sign;
                  }
                  this.smsCodeWaitTime();
                }, 500);
              } else {
                this.showDiyMsg('短信获取失败，请检查网络');
                this.btnDisabled = false;
                this.btnText = '获取验证码';
              }
            })
            .catch((errorRes) => {
              this.btnDisabled = false;
              this.btnText = '获取验证码';
            });
        } else {
          console.warn('url请求未完善，请使用：apiFunc');
          this.btnDisabled = false;
          this.btnText = '重新获取验证码';
        }
      }
    },
    smsCodeWaitTime() {
      this.nextTime = Date.parse(new Date()) / 1000 + parseInt(this.waitTime);
      this.btnIntervalObj = setInterval(() => {
        let currTime = this.nextTime - Date.parse(new Date()) / 1000;
        if (currTime <= 0) {
          clearInterval(this.btnIntervalObj);
          this.btnText = '重新获取验证码';
          this.btnIntervalObj = 0;
          this.btnDisabled = false;
        } else {
          this.btnDisabled = true;
          this.btnText = currTime.toString() + 's'; // '秒后重试';
        }
      }, 100);
    },
    funcOnInput(e) {
      this.$emit('input', this.localVal);
      this.$emit('update:modelValue', this.localVal);
    }
  }
};
</script>
<style>
.cv-code-area {
  min-height: 35px;
  line-height: 35px;
  font-size: 14px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
  padding-right: 10px;
}
.cv-code-input-area {
  width: calc(100% - 120px - 10px);
  display: flex;
  align-items: center;
}
.cv-code-input-item {
  height: 100%;
}
.cv-code-input-item-placeholder {
  font-size: 14px;
}
.cv-code-button-area {
  display: flex;
  align-items: center;
}
.cv-code-button-item.default {
  background-color: #f8f8f8;
  color: #333;
}
.cv-code-button-item.primary {
  background-color: #007aff;
  color: #ffffff;
}
</style>
