<template>
  <div class="kole-pwd">
    <div class="kole-pwd-field" :class="{ 'is-focus': focused }">
      <input
        ref="input"
        class="kole-pwd-input"
        :type="visible ? 'text' : 'password'"
        :value="value"
        :placeholder="placeholder"
        @input="onInput"
        @focus="focused = true"
        @blur="focused = false"
      />
      <button class="kole-pwd-toggle" type="button" @click="visible = !visible">
        {{ visible ? '隐藏' : '显示' }}
      </button>
    </div>
    <div v-if="showStrength" class="kole-pwd-strength">
      <span
        v-for="(b, i) in 3"
        :key="i"
        class="kole-pwd-bar"
        :class="barClass(i)"
      ></span>
    </div>
    <div class="kole-pwd-tip">{{ tip }}</div>
  </div>
</template>

<script>
export default {
  name: 'KolePasswordInput',
  props: {
    value: { type: String, default: '' },
    placeholder: { type: String, default: '请输入密码' },
    showStrength: { type: Boolean, default: true }
  },
  data() {
    return { visible: false, focused: false };
  },
  computed: {
    level() {
      const v = this.value;
      if (!v) return '';
      let s = 0;
      if (v.length >= 8) s++;
      if (/[a-z]/.test(v) && /[A-Z]/.test(v)) s++;
      if (/\d/.test(v)) s++;
      if (/[^A-Za-z0-9]/.test(v)) s++;
      if (v.length >= 12) s++;
      if (s <= 2) return 'weak';
      if (s <= 3) return 'mid';
      return 'strong';
    },
    tip() {
      if (this.level === 'weak') return '弱：建议使用字母、数字与符号组合';
      if (this.level === 'mid') return '中：再增加长度或符号更安全';
      if (this.level === 'strong') return '强：密码强度良好';
      return '';
    }
  },
  methods: {
    onInput(e) {
      this.$emit('input', e.target.value);
      this.$emit('change', e.target.value);
    },
    barClass(i) {
      if (!this.showStrength || !this.level) return '';
      const on =
        (this.level === 'weak' && i < 1) ||
        (this.level === 'mid' && i < 2) ||
        (this.level === 'strong' && i < 3);
      return on ? 'on ' + this.level : '';
    }
  }
};
</script>

<style src="./PasswordInput.css"></style>
