<template>
  <el-cascader
    v-model="selected"
    :props="cascaderProps"
    v-bind="$attrs"
    v-on="$listeners"
  />
</template>

<script>
import { getStockPageList } from '@/api/wms/base/stock'
import { getStockAreadropDownList } from '@/api/wms/base/stockArea'
import { getStockLocationPageList } from '@/api/wms/base/stockLocation'

export default {
  props: {
    // v-model
    value: {
      type: [String, Number, Array, Object],
      default: undefined
    },
    // 需要获取的value的key
    valueKey: {
      type: String,
      default: 'id'
    },
    // 层数，默认最大为3，最小为1
    level: {
      type: Number,
      default: 3,
      validator(value) {
        return value <= 3 && value >= 1
      }
    },
    // props的数据
    propsData: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      cascaderProps: {}
    }
  },
  computed: {
    selected: {
      get() {
        return this.value
      },
      set(v) {
        this.$emit('input', v)
      }
    }
  },
  created() {
    this.setProps()
  },
  methods: {
    isLeaf(level) {
      return this.level === level + 1
    },
    getResolveData(data = [], level) {
      return data.map(item => {
        const { name: label, id } = item
        return {
          value: item[this.valueKey],
          id,
          label,
          level: level + 1,
          leaf: this.isLeaf(level)
        }
      })
    },
    setProps() {
      this.cascaderProps = {
        ...this.propsData,
        lazy: true,
        lazyLoad: (node, reslove) => {
          const { level } = node
          if (level === 0) {
            // 获取仓库列表
            getStockPageList().then(res => {
              const { data = [] } = res || {}
              reslove(this.getResolveData(data, level))
            })
          } else if (level === 1) {
            const { data: nodeData } = node
            const { id } = nodeData
            getStockAreadropDownList({ wmsStockId: id }).then(res => {
              const { data = [] } = res || {}
              reslove(this.getResolveData(data, level))
            })
          } else if (level === 2) {
            const { data: nodeData } = node
            const { id } = nodeData
            getStockLocationPageList({ stockArea: id }).then(res => {
              const { data = [] } = res || {}
              reslove(this.getResolveData(data, level))
            })
          }
        }
      }
    }
  }
}
</script>
