<template>
  <div :ref="uuid"
       class="ipub-input-wrap">
    <template v-if="!tag">
      <div :class="`ipub-input ` + ipubClass">
        <ipub-icon class="ipub-input__icon"
                   v-if="prefixIcon"
                   :type="prefixIcon" />
        <input class="ipub-input__input data-hj-allow"
               :value="val"
               @input="handleInput"
               :placeholder="placeholder"
               @focus="handleFocus"
               @blur="handleBlur"
               @click.stop
               :autocomplete="search?'off':autocomplete"
               :name="placeholder"
               :disabled="disabled"
               :type="number?'number':(password&&!showPwd)?'password':'text'">
        <template v-if="clearable && val">
          <ipub-icon class="ipub-input__icon ipub-cursor-pointer main-color"
                     @click.stop="handleClear"
                     style="font-size:10px"
                     type="iconClose" />
        </template>
        <ipub-icon class="ipub-input__icon"
                   v-else-if="password"
                   @click="()=>{showPwd = !showPwd}"
                   :type="showPwd?'iconNotView':'iconView1'" />
        <ipub-icon class="ipub-input__icon"
                   v-else-if="search"
                   @click="handleSearch"
                   type="iconSearch" />
        <ipub-icon :class="['ipub-input__icon', iconClick?'ipub-cursor-pointer':'']"
                   @click="iconClick"
                   v-else-if="suffixIcon"
                   :type="suffixIcon" />
      </div>
    </template>
    <template v-else>
      <div :class="`ipub-input flex ` + ipubClass"
           style="padding: 0 12px;flex-wrap: wrap;"
           @click="tagFocus">
        <ipub-label :style="{margin: '4px 8px 4px 0'}"
                    v-for="(item, index) in value"
                    :key="'specialIssue.keywords'+index"
                    size="common"
                    cover
                    :type="isFocus?'link':'default'"
                    circle>{{item}}
          <a @click="del(index)">
            <ipub-icon style="font-size: 10px;margin-left:10px"
                       type="iconClose" />
          </a>
        </ipub-label>
        <input v-model="tagInput"
               v-show="!disabled"
               @focus="handleFocus"
               @blur="handleBlur"
               @input="handleTagBlur"
               :placeholder="(value&&value.length)?'':placeholder"
               class="ipub-input__tag__input"
               ref="ipub-input__tag__input"
               type="text">
      </div>
    </template>
    <div v-show="showOptions"
         :style="style"
         @click.stop
         :class="['ipub-input__select ipub-shadow',showOptions?'ipub-input__select--open':'']">
      <ipub-select-option v-for="(item, index) in select"
                          class="ipub-input__select__item"
                          :key="'ipub-input__select__item'+(item[optionKey]||item)+index"
                          :value="item"
                          @select="handleSelect"
                          :optionTitle="optionTitle"
                          :optionKey="optionKey"></ipub-select-option>
    </div>
  </div>
</template>

<script>
import IpubSelectOption from '../../select/src/option.vue'
import IpubLabel from '../../label/src/main.vue'
import { guid } from '../../../src/utils/utils'
export default {
  name: 'IpubInput',
  components: { IpubSelectOption, IpubLabel },
  props: {
    value: {
      type: [String, Number, Array],
      default: ''
    },
    placeholder: {
      type: String,
      default: 'Please input'
    },
    suffixIcon: {
      type: String,
      default: ''
    },
    prefixIcon: {
      type: String,
      default: ''
    },
    fixed: {
      type: Number,
    },
    select: {
      type: Array,
      default () {
        return []
      },
    },
    optionTitle: {
      type: String,
      default: 'name'
    },
    optionKey: {
      type: String,
      default: 'id'
    },
    autocomplete: {
      type: String,
      default: 'off',
      validator (val) {
        return ['on', 'off'].indexOf(val) !== -1
      }
    },
    disabled: Boolean,
    clearable: Boolean,
    search: Boolean,
    password: Boolean,
    number: Boolean,
    tag: Boolean,
  },
  inject: {
    ipubFormItem: {
      default: false
    }
  },
  data () {
    return {
      uuid: '',
      style: {},
      isFocus: false,
      showPwd: false,
      showOptions: false,
      val: '',
      tagInput: ''
    }
  },
  watch: {
    tag () {
      this.initKeyup()
    },
    value: {
      handler (val) {
        this.val = val
      },
      immediate: true
    }
  },
  computed: {
    ipubClass () {
      let newClass = ''
      if (this.isFocus) {
        newClass += 'ipub-input--focus '
      }
      if (this.disabled) {
        newClass += 'ipub-input--disable '
      }
      if (this.clearable) {
        newClass += 'ipub-input--clearable '
      }
      if (this.password) {
        newClass += 'ipub-input--password '
        if (this.showPwd) {
          newClass += 'ipub-input--password--show '
        }
      }
      if (this.search) {
        newClass += 'ipub-input--search '
      }
      if (this.prefixIcon) {
        newClass += 'ipub-input--prefixIcon '
      }
      if (this.suffixIcon) {
        newClass += 'ipub-input--suffixIcon '
      }
      if (this.ipubFormItem && this.ipubFormItem.validateStatus) {
        newClass += 'ipub--validateStatus '
      }
      return newClass
    }
  },
  mounted () {
    this.uuid = guid()
    if (this.tag) {
      this.initKeyup()
    }
  },
  methods: {
    handleInput ($event) {
      // 通过input标签的原生事件input将值emit出去，以达到值得改变实现双向绑定
      if (this.number && $event.target.value || $event.target.value === 0) {
        this.val = parseFloat($event.target.value) || 0
      } else {
        this.val = $event.target.value
      }
      this.$emit('input', this.val)
      if (this.ipubFormItem) {
        this.ipubFormItem.validate('change')
      }
    },
    handleTagBlur ($event) {
      this.$emit('tagInput', $event.target.value)
      if (this.ipubFormItem) {
        this.ipubFormItem.validate('blur')
      }
    },
    handleSearch () {
      this.$emit('search', this.val)
    },
    handleClear () {
      this.val = ''
      this.$emit('input', this.val)
      this.$emit('clear')
    },
    handleFocus () {
      this.isFocus = true
      this.$emit('focus', this.val)
      if (this.select && this.select.length) {

        const el = this.$refs[this.uuid]
        const sty = el.getBoundingClientRect() || {}

        this.$set(this.style, 'left', sty.left + 'px')
        this.$set(this.style, 'top', sty.bottom + 'px')
        this.$set(this.style, 'width', sty.width + 'px')

        this.showOptions = !this.showOptions
        if (this.showOptions) {
          setTimeout(() => {
            document.addEventListener('click', this.fun)
            document.addEventListener('scroll', this.fun)
          }, 0);
        }
      }
    },
    handleBlur () {
      this.isFocus = false
      if (this.val && (this.fixed || this.fixed === 0)) {
        this.val = parseFloat(this.val.toFixed(this.fixed))
        this.$emit('input', this.val)
      }
      this.getValue()
      this.$emit('blur', this.val)
      if (this.ipubFormItem) {
        this.ipubFormItem.validate('blur')
      }
    },
    handleSelect (val, obj) {
      if (this.tag) {
        this.tagInput = val
        this.getValue()
      } else {
        this.val = val
        this.$emit('input', this.val)
        this.$emit('select', obj)
        if (this.ipubFormItem) {
          this.ipubFormItem.validate('change')
        }
      }
      this.showOptions = false
    },

    // 绑定输入框回车事件
    initKeyup () {
      this.$refs['ipub-input__tag__input'].onfocus = () => {
        document.onkeyup = e => {
          // 兼容FF和IE和Opera
          var event = e || window.event
          var key = event.which || event.keyCode || event.charCode
          if (key == 13) {
            this.getValue()
          } else if (key == 8) {
            if (this.tag && !this.tagInput) {
              this.del(this.value.length - 1)
            }
          }
        }
      }
      this.$refs['ipub-input__tag__input'].onblur = () => {
        this.getValue()
        this.isFocus = false
        document.onkeyup = null
      }
    },

    getValue () {
      if (!this.tagInput) {
        return
      }
      const value = JSON.parse(JSON.stringify(this.value || []))
      let arr = this.tagInput.split('; ')
      if (arr.length < 2) {
        arr = this.tagInput.split(';')
      }
      if (arr.length < 2) {
        arr = this.tagInput.split(', ')
      }
      if (arr.length < 2) {
        arr = this.tagInput.split(',')
      }
      value.push(...arr)
      this.$emit('input', value)
      this.tagInput = ''
    },

    del (index) {
      if (index < 0) {
        return
      }
      const value = JSON.parse(JSON.stringify(this.value || []))
      value.splice(index, 1)
      this.$emit('input', value)
    },
    iconClick (e) {
      this.$emit('iconClick', e)
    },

    tagFocus () {
      this.$nextTick(function () {
        //DOM 更新了
        this.$refs['ipub-input__tag__input'].focus()
      })
    },
    fun () {
      this.showOptions = false
    }
  }
}
</script>

<style lang="scss">
.ipub-input {
  display: inline-block;
  font-family: $p_family;
  background: #fff;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid $border_color;
  transition: 0.3s all;
  width: 100%;
  box-sizing: border-box;
  min-height: 40px;
  &__input,
  &__tag__input {
    width: 100%;
    display: inline-block;
    box-sizing: border-box;
    color: $main_color;
    border: none;
    outline: none;
    line-height: 20px;
    padding: 10px 16px;
    font-size: 14px;
    &::placeholder {
      color: $default_color;
    }
  }
  &__tag__input {
    width: auto;
    min-width: 500px;
    padding: 9px 8px;
  }
}
.ipub-input.ipub-input--focus {
  // box-shadow: 0 0 0px 1px $border_color;
  border: 1px solid $link_color;
}
.ipub-input.ipub-input--disable {
  background: $disable_color;
  .ipub-input__input {
    cursor: not-allowed;
  }
}

.ipub-input.ipub-input--clearable,
.ipub-input.ipub-input--search,
.ipub-input.ipub-input--password,
.ipub-input.ipub-input--prefixIcon,
.ipub-input.ipub-input--suffixIcon {
  display: inline-flex;
  align-items: center;
  .ipub-input__input {
    width: calc(100% - 30px);
  }
  .ipub-input__icon {
    display: inline-block;
    width: 20px;
    font-size: 16px;
    text-align: center;
    color: $main_color;
  }
  .main-color {
    color: $main_color;
  }
}
.ipub-input.ipub-input--password,
.ipub-input.ipub-input--search {
  cursor: pointer;
}
// .ipub-input.ipub-input--password--show {
//   .ipub-input__icon {
//     // color: $main_color;
//   }
// }
.ipub-input.ipub-input--prefixIcon {
  .ipub-input__icon {
    margin-left: 10px;
  }
  .ipub-input__input {
    padding-left: 10px;
  }
}
.ipub-input.ipub-input--suffixIcon.ipub-input--prefixIcon {
  .ipub-input__input {
    width: calc(100% - 70px);
  }
}

.ipub-input__select {
  position: fixed;
  width: max-content;
  max-height: 0;
  width: 100%;
  border-radius: 4px;
  transition: all 0.3s;
  overflow: hidden;
  box-sizing: border-box;
  z-index: 999;
  left: 0;
  margin-top: 5px;
  border: 1px solid $border_color;
  padding: 10px 0;
  overflow-y: auto;
  background: #fff;
  .ipub-input__select__item {
    border-radius: 4px;
    .ipub-select-option {
      font-weight: 400;
      transition: 0.3s all;
      position: relative;
      display: flex;
      align-items: center;
      padding: 5px 16px;
      cursor: pointer;
      &:hover {
        background: rgba($link_color, 0.2);
      }
    }
  }
  &--open {
    max-height: 300px;
  }
}
</style>
