<template>
  <el-cascader ref="address-cascader" v-model="data" :props="props" :options="dataOptions" :multiple="multiple" :placeholder="placeholder" :clearable="clearable" :style="{'min-width': (level +1) * 75 + 'px'}" @change="cascaderChange" />
</template>

<script>
import { getSysArea } from '@/api/basic'
export default {
  name: 'AddressCascader',
  props: {
    value: {
      type: Array,
      default: () => [],
    },
    level: {
      type: Number,
      default: 2,
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    clearable: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      data: [],
      props: {
        lazy: true,
        multiple: this.multiple,
        lazyLoad: new Function(),
        value: 'id',
        label: 'name',
        checkStrictly: true
      },
      dataOptions: []
    }
  },
  watch: {
    value: {
      deep: true,
      handler() {
        this.initValue()
      }
    }
  },
  created() {
    this.initValue()
    this.initLazyLoad()
  },
  methods: {
    initValue() {
      // console.log(this.level)
      this.data = this.value || []
      if (this.level && this.multiple) this.initDataOptions()
    },
    async initDataOptions() {
      const that = this
      const { data, props } = this
      // console.log(data)
      if (!data || !data.length) return
      if (props.multiple) {
        if (data.findIndex(add => add === undefined) !== -1) return
        const dataOptions = await this.getAddress(0)
        const pros = data.map((item) => {
          return item.reduce(async(prev, current, index) => {
            const prevData = await prev
            const addressItem = prevData.find((it) => current === it.id)
            let children = addressItem.children
            if (!children && index < that.level) {
              children = await this.getAddress(current)
              if (index >= that.level - 1) {
                children = children.map(ars => {
                  ars.leaf = true
                  return ars
                })
              }
              addressItem.children = children
            }
            return children
          }, dataOptions)
        })
        await Promise.all(pros)
        this.$set(this, 'dataOptions', dataOptions)
      } else {
        this.dataOptions = []
      }
    },
    initLazyLoad() {
      this.props.lazyLoad = (node, resolve) => {
        console.log(node)
        const { level, value, path } = node
        const { dataOptions } = this
        if (path) {
          let childrens = dataOptions
          path.forEach((p) => {
            if (childrens) {
              const childrenItem = childrens.find(c => c[this.props.value] === p)
              if (childrenItem) {
                childrens = childrenItem.children
              } else {
                childrens = childrenItem
              }
            }
          })
          if (childrens) {
            resolve([])
          } else {
            this.getNodes(level, resolve, value)
          }
        } else {
          this.getNodes(level, resolve, value)
        }
      }
    },
    getNodes(level, resolve, value = 0) {
      getSysArea({ pid: value, _t: Math.random() }).then((res) => {
        const { lists } = res.data
        // console.log(this.$refs['address-cascader'])
        const nodeArr = lists.map(item => ({
          id: item.id,
          name: item.name,
          leaf: level >= this.level,
        }))
        resolve(nodeArr)
      })
    },
    getAddress(pid) {
      return getSysArea({ pid, _t: Math.random() }).then(res => res.data.lists)
    },
    cascaderChange(e) {
      this.$emit('input', e)
    },
  },
}
</script>

<style scoped>
</style>
