<script>
export default {
  name: 'MInput',
}
</script>
<script setup>
import { ref } from 'vue'

const props = defineProps({
  placeholder: {
    type: String,
    default: ''
  },
  type: {
    type: String,
    default: 'text'
  },
  name: {
    type: String,
    default: ''
  },
  disabled: {
    type: Boolean,
    default: false
  },
  modelValue: {
    type: String,
    default: ''
  },
  clearable: {
    type: Boolean,
    default: false
  },
  showPassword: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits([
  'update:modelValue',
  'clear'
])

function handleInput (e) {
  emit('update:modelValue', e.target.value)
}

function clear () {
  emit('clear')
}

const passwordVisible = ref(false)
function handlePassword () {
  passwordVisible.value = !passwordVisible.value
}
</script>

<template>
  <div
    class="m-input"
    :class="{'m-input--suffix': clearable || showPassword}"
  >
    <input
      :value="modelValue"
      class="m-input__inner"
      :class="{'is-disabled': disabled}"
      :placeholder="placeholder"
      :type="showPassword ? (passwordVisible ? 'text' : 'password') : type"
      :name="name"
      :disabled="disabled"
      @input="handleInput"
    />

    <span class="m-input__suffix">
      <i v-if="clearable && modelValue" class="m-icon-cancel" @click="clear"></i>
      <i v-if="showPassword && type === 'password'" class="m-icon-visible" @click="handlePassword"></i>
    </span>
  </div>
</template>

<style lang="scss" scoped>
.m-input {
  width: 100%;
  position: relative;
  font-size: 14px;
  display: inline-block;
}

.m-input__inner {
  -webkit-appearance: none;
  background-color: #fff;
  background-image: none;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  box-sizing: border-box;
  color: #606266;
  display: inline-block;
  font-size: inherit;
  height: 40px;
  line-height: 40px;
  outline: none;
  padding: 0 15px;
  transition: border-color .2s cubic-bezier(.645,045,.355,1);
  width: 100%;

  &:focus {
    outline: none;
    border-color: #409eff;
  }
  // input禁用样式
  &.is-disabled {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #c0c4cc;
    cursor:not-allowed;
  }
}

// 后面加suffix的意思是后面如果有后缀的话，触发该样式
.m-input--suffix {

  .m-input__inner {
    padding-right: 30px;
  }

  .m-input__suffix {
    position: absolute;
    right: 10px;
    height: 100%;
    top: 0;
    line-height: 40px;
    text-align: center;
    color: #c0c4cc;
    transition: all .3s;
    z-index: 900;

    i {
      color: #c0c4cc;
      font-size: 14px;
      cursor: pointer;
      transition: color .2s cubic-bezier(.645,.045,.355,1);
    }
  }
}
</style>
