import { subareaQueryAll } from '@/api/subarea'
const Subarea = {
  template: `
        <a-select
          :id="id"
          :placeholder="placeholder"
          allowClear
          :value="defaultVal"
          :mode="mode"
          :showSearch="true"
          @change="handleChange"
          :filter-option="filterOption">
          <a-select-option v-for="item in list" :key="item[defValKey]" :value="item[defValKey]">{{ item.subareaName }}</a-select-option>
        </a-select>
    `,
  props: {
    value: {
      type: [String,Array],
      defatut: ''
    },
    mode: {
      type: String,
      default:'default'
    },
    id: {
      type: String,
      default: ''
    },
    defValKey: {
      type: String,
      default: 'subareaSn'
    },
    placeholder: {
      type: String,
      default: '请选择分区'
    }
  },
  data() {
    return {
      defaultVal: this.value,
      list: []
    };
  },
  watch: {
    value(newValue, oldValue) {
      this.defaultVal = newValue
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleChange(value) {
      console.log(value)
      this.defaultVal = value;
      const item = this.list.filter(item =>{
        if(this.mode !== 'multiple'){
          return item[this.defValKey] == value
        }else{
          return value.includes(item[this.defValKey])
        }
      })
      this.$emit('change', value, item);
      this.$emit('input', value);
    },
    // 列表数据
    getList () {
      const _this = this
      subareaQueryAll().then(res => {
        if (res.status == 200) {
          _this.list = res.data.reverse() || []
        } else {
          _this.list = []
        }
      })
    },
    // 根据名称数组 返回对应的 sn 数组
    getValByName(data){
      let ret = []
      this.list.filter(item => data.includes(item.subareaName)).map(item => ret.push(item.subareaSn))
      return ret
    }
  },
};

export default Subarea