import { productTypeQueryAll } from '@/api/productType'
const ProductType = {
  template: `
      <a-cascader
        @change="handleChange"
        change-on-select
        :value="defaultVal"
        expand-trigger="hover"
        :options="productTypeList"
        :disabled="disabled"
        :show-search="{ filter }"
        :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
        :id="id"
        :placeholder="placeholder"
        allowClear />
    `,
  props: {
    value: {
      type: Array,
      defatut: function () {
        return []
      }
    },
    placeholder:{
      type: String,
      default: '请选择产品分类'
    },
    id: {
      type: String,
      default: ''
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  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 () {
      productTypeQueryAll({}).then(res => {
        if (res.status == 200) {
          if (res.data && res.data.length > 0) {
            //  递归处理disabled禁用
            this.recursionFun(res.data, false)
            this.productTypeList = res.data
          } else {
            this.productTypeList = []
          }
        } else {
          this.productTypeList = []
        }
      })
    },
    //  递归函数
    recursionFun (data, state) {
      if (data) {
        data.map((item, index) => {
          // enabledFlag为0表示禁用，父级禁用则子级也为禁用
          if ((item.enabledFlag && item.enabledFlag == 0) || state) {
            item.disabled = true
          } else {
            item.disabled = false
          }
          if (item.children && item.children.length == 0) {
            delete item.children
          } else {
            this.recursionFun(item.children, item.disabled)
          }
        })
      }
    },
  }
}

export default ProductType
