<template>
  <div class="n-changer" :class="picker ? classes : 'n-changer-btn'" :name="name">
    <template v-if="picker">
      <span class="n-filter-placed" :class="size">{{placed}}</span>
      <template v-for="(option, index) in options">
        <span :key="index" class="n-changer-option" :class="{active: nValue === option.value}"
              @click="onClick(option)">{{option.label}}</span>
      </template>
      <n-icon v-if="hasRemoveIcon" size="16" type="circle-delete" scene="light"
              :disabled="disabled" @click="onRemove"></n-icon>
    </template>
    <template v-else>
      <template v-for="(option, index) in options">
        <n-button :key="index" type="default" outline :active="nValue === option.value" :disabled="disabled" size="small"
                  @click="onClick(option)">{{option.label}}</n-button>
      </template>
    </template>
  </div>
</template>

<script>
import vModel from '_common/vModel'
import NButton from '@uif/next/lib/components/button'
import {propsArray} from '@uif/next/lib/utils/tools'

export default {
  name: 'n-changer',
  mixins: [vModel],
  components: {
    NButton
  },
  props: {
    picker: {
      type: Boolean,
      default: false
    },
    placed: {
      type: String,
      default: ''
    },
    border: propsArray(['none', 'line', 'rect'], 'rect'),
    size: propsArray(['small', 'middle', 'large'], 'middle'),
    value: {
      default: undefined
    },
    name: {
      type: String,
      default: ''
    },
    options: {
      type: Array,
      default: () => [
        {label: '是', value: true},
        {label: '否', value: false}
      ]
    },
    disabled: {
      type: Boolean,
      default: false
    },
    // true时可取消所有选择
    clearable: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      nValue: this.value
    }
  },
  computed: {
    classes ({disabled, border}) {
      return [
        'n-changer-picker',
        'n-form-border',
        'n-form-border-' + border,
        'n-form-border-' + (disabled ? 'disabled' : 'available')
      ]
    },
    hasRemoveIcon ({clearable, disabled, nValue}) {
      return nValue !== undefined && clearable && !disabled
    }
  },
  methods: {
    onClick (option) {
      const isSelected = this.nValue === option.value
      const value = isSelected ? undefined : option.value
      if (!this.disabled && value !== this.nValue && (!isSelected || this.clearable)) {
        this.nValue = value
        this.$emit('u-update', this.nValue)
        this.$emit('u-change', this.nValue)
      }
    },
    onRemove () {
      this.nValue = undefined
      this.$emit('u-update', this.nValue)
      this.$emit('u-change', this.nValue)
    }
  }
}
</script>
