<template>
  <section>
    <el-tree :current-node-key="currentNodeKey" @node-click="handleNodeClick" :props="defaultProps" :load="loadNode" node-key="code" accordion lazy highlight-current
      :expand-on-click-node="false" ref="tree" />
  </section>
</template>

<script>
// todo 大区组件
import { areaSelect, getProvinceByArea, getProvinceByParent } from "@/api/hardware/area";
const areaList = [];
export default {
  name: 'Region',
  props: {
    'currentNodeKey': {
      type: String,
      default: ''
    },
  },
  watch: {
    currentNodeKey(id) {
    // Tree 内部使用了 Node 类型的对象来包装用户传入的数据，用来保存目前节点的状态。可以用 $refs 获取 Tree 实例
      if (id.toString()) {
        this.$refs["tree"].setCurrentKey(id);
      } else {
        this.$refs["tree"].setCurrentKey(null);
      }
    }
  },
  data () {
    return {
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      },
    }
  },
  created () {
  },
  methods: {
    handleNodeClick (node) {
      if (!node.isArea) {
        this.$emit('selectdRegionCode',node)
      }
    },
    async loadNode (node, resolve) {
      if (node.level === 0) {
        if (areaList.length) return resolve(areaList)
        let { code, msg, select } = await areaSelect();
        if (200 == code) {
          select.map(v => {
            v.name = v.areaName;
            v.code = v.id;
            v.isArea = true;
            return v;
          })
          areaList.push(...select)
          return resolve(select)
        } else {
          return resolve([])
        }
        return resolve([])
      }

      if (node.level == 1) {
        let { code, data, msg } = await getProvinceByArea(node.key);
        if (200 == code) {
          data.map(v => {
            v.name = v.cityName;
            v.leaf = false;
            return v;
          })
          return resolve(data)
        } else {
          return resolve([])
        }
      }
      if (node.level > 1) {
        let { code, data, msg } = await getProvinceByParent(node.key);
        console.log(node.level > 1, node.level)
        if (200 == code) {
          data.map(v => {
            v.name = v.cityName;
            v.leaf = node.level > 1;
            return v;
          })
          return resolve(data)
        } else {
          return resolve([])
        }
      };
    }
  }
}
</script>

<style>
</style>