<template>
  <div :name="name" :class="getFilterBorderClass({disabled, isFocus, pointer: true})" @click="toFocus">
    <!-- label -->
    <span v-if="label" :class="getFilterValueClass({disabled, label: true})">{{label}}</span>
    <!-- 有值 -->
    <template v-if="hasValue">
      <!-- label -->
      <span :class="getFilterValueClass({disabled, multiple})">{{firstLabel}}</span>
      <!-- +6 -->
      <span v-if="values.length > 1" :class="getFilterValueClass({disabled, multiple})">+{{values.length - 1}}</span>
    </template>
    <!-- icon -->
    <n-icon v-if="iconProps" class="n-filter-icon" v-bind="iconProps" @click="onIconClick"></n-icon>
  </div>
</template>

<script>
import NIcon from '@uif/next/lib/components/icon'
import {isValueArray, prop} from '@uif/next/lib/utils/tools'
import {getFilterBorderClass, getFilterValueClass, getValuesFirstLabel} from '_common/formUtils'

export default {
  name: 'n-filter-refer',
  components: {
    NIcon
  },
  model: {
    prop: 'isFocus',
    event: 'setFocus'
  },
  props: {
    // 提示文本
    label: prop.string('请选择'),
    // 提示文本
    // placeholder: prop.string('请选择'),
    // 激活状态
    isFocus: prop.boolean(),
    // 表单名称
    name: prop.string(),
    // 选中的option列表
    values: prop.array(),
    // 搜索选项
    state: prop.object(),
    // 多选
    multiple: prop.boolean(),
    // 禁用
    disabled: prop.boolean(),
    // 可删除
    clearable: prop.boolean(),
    // 下拉图标
    dropIconType: prop.string('drop-down')
  },
  data () {
    return {
      getFilterBorderClass,
      getFilterValueClass
    }
  },
  computed: {
    // 有值
    hasValue ({values}) {
      return isValueArray(values)
    },
    firstLabel ({values}) {
      return getValuesFirstLabel(values)
    },
    // 右侧icon
    iconProps ({hasValue, clearable, disabled, dropIconType}) {
      if (hasValue && clearable && !disabled) {
        // 删除按钮
        return {type: 'circle-delete', scene: 'light', isRemove: true}
      } else if (dropIconType) {
        // 下拉按钮
        return {type: dropIconType}
      }
      return null
    }
  },
  methods: {
    // 获焦事件
    toFocus () {
      if (!this.disabled) {
        this.$emit('setFocus', true)
      }
    },
    // 删除全部
    onIconClick (event) {
      if (this.iconProps.isRemove) {
        event.stopPropagation()
        this.$emit('u-update', [])
      }
    }
  }
}
</script>
