import { productTypeQuery } from '@/api/productType'
const ProductType = {
  template: `
      <a-cascader
        @change="handleChange"
        :change-on-select="changeOnSelect"
        :value="defaultVal"
        style="width:100%;"
        :expand-trigger="expandType"
        :options="productTypeList"
        :show-search="{ filter }"
        :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
        :id="id"
        :size="size"
        placeholder="请选择产品分类"
        :allowClear="true"/>
    `,
  props: {
    value: {
      type: Array,
      defatut: function () {
        return []
      }
    },
    expandType: {
      type: String,
      default: 'hover'
    },
    id: {
      type: String,
      default: ''
    },
    level: {
      type: [String, Number],
      default: ''
    },
    changeOnSelect: {
      type: Boolean,
      default: true
    },
    size:{
      type: String,
      default: 'default'
    }
  },
  data () {
    return {
      defaultVal: this.value,
      productTypeList: []
    }
  },
  watch: {
    value (newValue, oldValue) {
      this.defaultVal = newValue
    }
  },
  mounted () {
    this.getProductType()
  },
  methods: {
    filter (inputValue, path) {
      console.log(inputValue, path)
      return path.some(option => option.productTypeName.indexOf(inputValue) > -1)
    },
    setDefValue (defaultVal) {
      this.handleChange(defaultVal)
    },
    handleChange (value, row) {
      this.defaultVal = value
      this.$emit('change', this.defaultVal, this.id, row)
      this.$emit('input', this.defaultVal)
    },
    //  产品分类列表
    getProductType () {
      productTypeQuery({}).then(res => {
        if (res.status == 200) {
          if (this.level) {
            this.productTypeList = this.getBylevel(res.data)
          } else {
            this.productTypeList = res.data
          }
        } else {
          this.productTypeList = []
        }
      })
    },
    getBylevel (data) {
      const ret = []
      // 显示一级分类
      if (this.level == 1) {
        data.map(item => {
          if (item.children) {
            delete item.children
          }
        })
      }
      // 显示二级分类
      if (this.level == 2) {
        data.map(item => {
          if (item.children) {
            item.children.map(cd => {
              if (cd.children) {
                delete cd.children
              }
            })
          }
        })
      }
      return data
    }
  }
}

export default ProductType
