<template>
  <div class="ta-tag-select">
    <span>{{ title ? title + '：':'' }}</span>
    <template v-for="item in data">
      <div
        v-if="item[defaultProps.value] != undefined && item[defaultProps.label] != undefined"
        :key="item[defaultProps.value]"
        class="ant-btn ant-btn-default tag-select-btn"
        :class="{'ant-btn-sm': cSize =='small', 'tag-select-btn-sm': cSize =='small', 'ant-btn-lg': cSize =='large', 'tag-select-btn-lg': cSize =='large', 'checked': selectedTags.indexOf(item[defaultProps.value]) > -1}"
        @click="handleChange(item)"
      >{{item[defaultProps.label]}}<ta-icon type="check" v-if="selectedTags.indexOf(item[defaultProps.value]) > -1"/>
      </div>
    </template>
  </div>
</template>
<script>
let _defaultProps = {
  value: 'value', // 标签值
  label: 'label', // 标签名称
}
export default {
  name: 'TaTagSelect',
  props: {
    props: {
      type: Object,
      default: function () {
        return _defaultProps
      },
    },
    value: {
      type: Array,
      default: () => {
        return []
      },
    },
    data: {
      type: Array,
      default: () => {
        return []
      },
    },
    size: {
      type: String,
    },
    isMulti: {
      type: Boolean,
      default: false,
    },
    required: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
    },
  },
  data () {
    return {
      selectedTags: this.value,
    }
  },
  computed: {
    defaultProps () {
      return {
        value: this.props.value || _defaultProps.value,
        label: this.props.label || _defaultProps.label,
      }
    },
    cSize(){
      let { size } = this.$props
      size = size || ((this.$ELEMENT || {})['tag-select'] || {}).size || (this.$ELEMENT || {}).size || 'small'
      return size
    },
  },
  watch: {
    value (val) {
      this.selectedTags = val
    },
  },
  methods: {
    handleChange (tag) {
      const {selectedTags, required, defaultProps} = this
      let checked = selectedTags.some(t => t == tag[defaultProps.value])
      if (required && checked && selectedTags.length == 1) {
        return false
      }
      if (this.isMulti) {
        this.selectedTags = checked ? selectedTags.filter(t => t !== tag[defaultProps.value]) : [...selectedTags, tag[defaultProps.value]]
      } else {
        this.selectedTags = checked ? selectedTags.filter(t => t !== tag[defaultProps.value]) : [tag[defaultProps.value]]
      }
      this.$emit('input', [...this.selectedTags])
      this.$emit('change', [...this.selectedTags])
    },
  },
}
</script>
<style scoped lang="less" type="text/less">
  @import "../style/index.less";
</style>
