<template>
  <div :class="prefixCls" class="relative">
    <InputPassword
      v-if="showInput"
      v-bind="$attrs"
      allowClear
      v-model:value="innerValueRef"
      @change="handleChange"
      :disabled="disabled"
    >
      <template #[item]="data" v-for="item in Object.keys($slots)">
        <slot :name="item" v-bind="data || {}"></slot>
      </template>
    </InputPassword>
    <div class="input-state" v-if="innerValueRef">
      <a-progress :percent="pwdPercent" :steps="3" :stroke-color="pwdColor" :showInfo="false" />
      <span>{{ pwdText }}</span>
    </div>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, watchEffect } from 'vue';
  import { Input } from 'ant-design-vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { propTypes } from '/@/utils/propTypes';
  import { testPwdState } from '/@/utils/event/design';

  export default defineComponent({
    name: 'StrengthMeter',
    components: { InputPassword: Input.Password },
    props: {
      value: propTypes.string,
      showInput: propTypes.bool.def(true),
      disabled: propTypes.bool,
    },
    emits: ['score-change', 'change'],
    setup(props, { emit }) {
      const innerValueRef = ref('');
      const { prefixCls } = useDesign('strength-meter');
      const pwdPercent = ref(0);
      const pwdColor = ref('#e74242');
      const pwdText = ref('弱');

      function handleChange(e: ChangeEvent) {
        const pwdScore = testPwdState(e.target.value);
        if (pwdScore < 50) {
          pwdPercent.value = 30;
          pwdColor.value = '#e74242';
          pwdText.value = '弱';
        } else if (pwdScore < 75) {
          pwdPercent.value = 60;
          pwdColor.value = '#efbd47';
          pwdText.value = '中';
        } else {
          pwdPercent.value = 100;
          pwdColor.value = '#55d187';
          pwdText.value = '强';
        }
        emit('change', e.target.value, pwdPercent.value);
      }

      watchEffect(() => {
        innerValueRef.value = props.value || '';
      });

      return {
        handleChange,
        prefixCls,
        innerValueRef,
        pwdPercent,
        pwdColor,
        pwdText,
      };
    },
  });
</script>
<style lang="less" scoped>
  .input-state {
    display: flex;
    align-items: center;
    color: #b1b1b1;
    margin-left: 5px;

    span {
      margin: 0 10px;
    }
  }

  :deep(.ant-progress-steps-item) {
    height: 5px !important;
    width: 33% !important;
    margin-right: 5px;
  }
</style>
