<template>
    <a-tree-select
            v-model="value"
            tree-data-simple-mode
            allowClear
            :tree-data="treeData"
            placeholder="请选择"
            :load-data="onLoadData"
    />
</template>

<script>
    /**
     * 所有地区选择控件
     */
    export default {
        name: "allAreaTreeSelect",
        created() {},
        mounted() {
            this.getDataList(0);
        },
        data() {
            return {
                value: undefined,
                treeData: [],
            };
        },
        watch: {
            value(value) {
                this.$emit('input', value);
            },
        },
        methods: {
            getDataList(areaCode) {
                let treeData = [];
                this.$api.common.fetchAreaByCode(areaCode).then(({code, data}) => {
                    if (code === "SUCCESS") {
                        data.forEach(x => {
                            let item = {
                                id: x.areaCode,
                                pId: 0,
                                value: x.areaCode,
                                title: x.areaName,
                                isLeaf: x.areaLevel == 5 ? true : false
                            };
                            treeData.push(item);
                        });
                        this.treeData = treeData;
                    }
                });
            },
            onLoadData(treeNode) {
                let that = this;
                return new Promise(resolve => {
                    this.$api.common.fetchAreaByCode(treeNode.value).then(({code, data}) => {
                        let treeData = [];
                        if (code === "SUCCESS") {
                            if (this.$api.utils.isNoBlank(data)) {
                                data.forEach(x => {
                                    let item = {
                                        id: x.areaCode,
                                        pId: treeNode.value,
                                        value: x.areaCode,
                                        title: x.areaName,
                                        isLeaf: x.areaLevel == 5 ? true : false
                                    };
                                    treeData.push(item);
                                });
                                that.treeData = that.treeData.concat(treeData);
                            }
                            resolve();
                        }
                    });
                });
            },
        },
    }
</script>

<style scoped>

</style>
