<template>
    <Modal v-model="opened"
        scrollable
        :width="800">
        <div slot="header">
            <span class="title">字段选择</span>
            <span class="description">Column Select</span>
        </div>
        <div class="ivu-ml-8 ivu-mr-8">
            <Tree :data="data"
                @on-select-change="select"></Tree>
        </div>
        <div slot="footer">
            <Button type="default"
                custom-icon="fa fa-times"
                @click="close">
                关闭
            </Button>
        </div>
    </Modal>
</template>
<script>
    import mixinPage from '../../mixins/page';
    import dataViewApi from '../../api/dataView';

    // 转换为tree列表对象
    var convertList = nodes => {
        if (!nodes) {
            return null;
        }

        return nodes.map(item => {
            return {
                column: {
                    code: item.code,
                    name: item.name,
                    dataType: item.dataType,
                    columns: item.columns
                },
                title: item.name + ' (' + item.code + ')',
                children: convertList(item.columns)
            };
        });
    };

    // 获取对象字段
    var getObjColumn = (code, data) => {
        for (let i = 0; i < data.length; i++) {
            if (data[i].column.code + 'id' === code) {
                return data[i].column;
            }

            if (data[i].children) {
                let result = getObjColumn(code, data[i].children);
                if (result) {
                    return result;
                }
            }
        }

        return null;
    };

    export default {
        mixins: [mixinPage],
        components: {},
        data() {
            return {
                data: [],
                opened: false,
                callback: null
            };
        },
        props: {},
        computed: {},
        methods: {
            open(dataView, callback, columns) {
                dataViewApi.queryColumnByModel(dataView.model).then(data => {
                    if (columns && columns.length > 0) {
                        data = data.filter(p => !columns.includes(p.code));
                    }
                    this.data = convertList(data);
                    this.opened = true;
                });

                this.callback = callback;
            },
            select(selected, checked) {
                if (checked.children) {
                    return;
                }

                let column = checked.column;
                // 外键字段
                if (column.dataType === 'BigInteger') {
                    column.objColumn = getObjColumn(column.code, this.data);
                }

                this.callback(column);
                this.opened = false;
            },
            close() {
                this.opened = false;
            }
        }
    };
</script>
