import { productBrandQuery } from '@/api/productBrand'
const ProductBrand = {
  template: `
      <a-select
        :placeholder="placeholder"
        :id="id"
        allowClear
        style="width:100%;"
        :size="size"
        :value="defaultVal"
        :showSearch="true"
        :disabled="disabled"
        @change="handleChange"
        option-filter-prop="children"
        :filter-option="filterOption">
        <a-select-option v-for="item in productBrandList" :key="item.brandSn" :value="item.brandSn">{{ item.brandName }}</a-select-option>
      </a-select>
    `,
  props: {
    value: {
      type: String,
      defatut: ''
    },
    id: {
      type: String,
      default: ''
    },
    placeholder:{
      type: String,
      default: '请选择产品品牌'
    },
    brandType: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    },
    size: {
      type: String,
      default: 'default'
      },
    // 是否显示全品牌
    showAllBrand:{
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      defaultVal: this.value,
      productBrandList: []
    };
  },
  mounted() {
    const a = this.$store.state.app.productBrandAllList
    // 有缓存
    if(a){
      this.setBrandData(a||[])
    }else{
      this.getProductBrand()
    }
  },
  watch: {
    value(newValue, oldValue) {
      this.defaultVal = newValue
    },
    brandType(newValue,oldValue){
      this.handleChange(undefined)
      const a = this.$store.state.app.productBrandAllList
      // 有缓存
      if(a){
        this.setBrandData(a||[])
      }else{
        this.getProductBrand()
      }
    }
  },
  methods: {
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    handleChange(value) {
      this.defaultVal = value;
      const row = this.productBrandList.find(item => item.brandSn == value)
      this.$emit('input', value);
      this.$emit('change', value, this.id, row);
    },
    setBrandData(data){
      // brandType: 1 自主品牌 2 代理品牌
      if(this.brandType!=''){
        this.productBrandList = data.filter(item => item.brandType == this.brandType)
      }else{
        this.productBrandList = data
      }
      // 是否显示全品牌
      const hasAll = this.productBrandList.find(item => item.brandSn == 'ALL')
      if(this.showAllBrand && !hasAll){
        this.productBrandList.unshift({brandSn:'ALL',brandName:'全品牌'})
      }
    },
    //  产品品牌列表,
    getProductBrand () {
      productBrandQuery({}).then(res => {
        let ret = []
        if (res.status == 200) {
          ret = res.data
        } else {
          ret = []
        }
        // 缓存数据
        this.$store.state.app.productBrandAllList = ret
        this.setBrandData(ret)
      })
    },
  },
};

export default ProductBrand