<template>
    <div class="data-tree">
        <ActionPane v-if="showActionPane && this.gridGuid && this.actions.length > 0"
            :actions="actions"
            :func-map="funcMap"
            class="action"></ActionPane>
        <FilterPane v-if="showFilterPane && this.gridGuid"
            v-show="isLoaded"
            :filters="filters"
            :columns="columns"
            @on-filter="filterData"
            class="filter"></FilterPane>
        <Tree class="data"
            :data="data"
            empty-text=""
            @on-select-change="changeNode"></Tree>
        <div v-if="this.gridGuid"
            class="pager">
            <div class="toolbar">
                <span class="info-func"
                    v-if="infoFunc"
                    v-html="infoFuncHtml">
                </span>
                <Button icon="ios-download-outline"
                    shape="circle"
                    type="success"
                    title="导出Excel"
                    @click.native="exportXlsx"></Button>
            </div>
        </div>
        <div v-if="!this.gridGuid"
            class="grid">警告! 没有配置对应网格!!!</div>
    </div>
</template>
<script>
import DataApi from '../../data/grid-sql'
import FilterPane from '../../components/filter-pane'
import ActionPane from '../grid/action-pane'
import GridInfoFuncs from '../../extern/grid-info-funcs'

export default {
    name: 'DataTree',
    data() {
        return {
            data: undefined,
            columns: undefined,
            actions: [],
            filters: [],
            whereItems: [],
            isLoading: false,
            isLoaded: false,
            selectItem: undefined,
            // 是否初始化完成
            isInitialized: false,
            // 显示额外信息
            infoFunc: false,
            infoFuncHtml: ''
        }
    },
    props: {
        /*是否自动初始化,在某些情况下，不希望自动初始化*/
        autoInit: {
            type: Boolean,
            default: true
        },
        /*是否显示Action面板*/
        showActionPane: {
            type: Boolean,
            default: true
        },

        /* 是否显示FilterPane */
        showFilterPane: {
            type: Boolean,
            default: true
        },
        /*GridGuid*/
        gridGuid: {
            type: String
        },
        /* guid field */
        guidField: {
            type: String,
            default: 'guid'
        },
        /**/
        funcMap: {
            type: Object
        },

        /* 请求的不同的service */
        queryUrl: {
            type: String,
            default: '/data-service'
        }
    },
    watch: {},
    components: {
        FilterPane,
        ActionPane
    },
    computed: {},
    methods: {
        /*确认是单选*/
        ensureSingleSelect() {
            if (!this.selectItem) {
                this.$Modal.warning({
                    title: '警告信息',
                    content: '请先选择一条信息'
                })

                return false;
            }

            return true;
        },

        /*提供给外部使用的函数*/
        /*获取所有数据*/
        getData() {
            return this.data;
        },

        /**
         * 获取选中项对应字段的值
         * @param field 对应字段名 默认guid
         */
        getSelect(field = 'guid') {
            return new Promise((resolve, reject) => {
                if (!this.ensureSingleSelect()) {
                    return
                }

                // 树形必须要guid
                resolve(this.selectItem['guid'])
            })
        },
        changeNode(arr, item) {
            this.selectItem = item
        },
        /**
         * 获取过滤数据数组
         */
        getFilterArray() {
            return this.whereItems
        },

        //获取指定过滤值
        getFilterValue(name) {
            return new Promise((resolve, reject) => {
                let f = this.whereItems.find((item) => {
                    return item.code === name
                })

                if (f) {
                    resolve(f.value)
                } else {
                    this.$Notice.error({ title: `${name}值为空` })

                    reject()
                }
            })
        },

        /*刷新数据*/
        refresh(item) {
            let selectGuid = null;
            if (item && item.type != 'delete') {
                selectGuid = item.guid;
            }
            let model = this.getQueryModel()
            this.isLoading = true
            DataApi.queryData(this.queryUrl, model).then((res) => {
                this.data = this.convertToTreeData(res.data, selectGuid)
                this.isLoading = false
            });

            if (!selectGuid) {
                //去掉过滤中的选中项
                this.selectItem = undefined
            }
        },

        /*点击过滤*/
        filterData(fa) {
            this.whereItems = this.wrapperWhereItems(fa)

            this.refresh()
        },

        wrapperWhereItems(fa) {
            let where = [].concat(fa)

            return where
        },

        convertToTreeData(data, selectGuid) {
            if (selectGuid) {
                return this.convertToTreeData2(data, selectGuid)
            } else {
                return this.convertToTreeData1(data)
            }
        },

        convertToTreeData1(data) {
            let tree = [];
            let temp = {};

            data.forEach((d) => {
                let item = Object.assign({}, d);
                if (item.parent) {
                    let parent = temp[item.parent];
                    if (parent) {
                        if (!parent["children"]) {
                            parent["children"] = [];
                        }

                        parent["children"].push(item);
                    } else {
                        tree.push(item);
                    }
                } else {
                    tree.push(item);
                }

                temp[item.guid] = item;
            });

            // 默认展开第一个节点
            if (tree.length > 0) {
                tree[0].expand = true
            }
            return tree;
        },

        convertToTreeData2(data, selectGuid) {
            console.log(selectGuid)
            let tree = [];
            let temp = {};

            data.forEach((d) => {
                let item = Object.assign({}, d);
                if (item.parent) {
                    let parent = temp[item.parent];
                    if (parent) {
                        if (!parent["children"]) {
                            parent["children"] = [];
                        }

                        parent["children"].push(item);
                    } else {
                        tree.push(item);
                    }
                } else {
                    tree.push(item);
                }

                if (item.guid == selectGuid) {
                    item.selected = true

                    if (item.parent) {
                        let parent = temp[item.parent];

                        parent.expand = true
                    }
                }

                temp[item.guid] = item;
            });

            // 默认展开第一个节点
            if (tree.length > 0) {
                tree[0].expand = true
            }
            return tree;
        },

        setupActions(conf) {
            let actions = []
            for (let a of conf.actions) {
                let act = {
                    caption: a.caption,
                    action: a.func_guid
                }

                actions.push(act);
            }

            this.actions = actions;
        },
        setupFilters(conf) {
            let filters = [];

            for (let f of conf.filters) {
                let filter = {
                    editor: f.editor,
                    type: f.type,
                    label: f.caption,
                    code: f.field,
                    op: f.operator,
                    width: f.width,
                    ds: f.ds,
                    defValue: f.def_value
                }
                filters.push(filter);
            }

            this.filters = filters;
        },


        /**
         * 构造查询模型
         * @param withTotal 是否获取总页数
         */
        getQueryModel() {
            return {
                "guid": this.gridGuid,
                "with_total": false,
                "page_index": 1,
                "page_size": 99999,
                "_where": this._getWhere()
            }
        },

        _getWhere() {
            return JSON.stringify(this.whereItems);
        },

        setInfoFunc(infoFunc) {
            if (!infoFunc) {
                return
            }

            this.infoFunc = infoFunc

            if (GridInfoFuncs[this.infoFunc]) {
                this.infoFuncHtml = GridInfoFuncs[this.infoFunc]()
            } else {
                console.log(`unimpleted function: ${infoFunc}`)
            }
        },

        init() {
            if (!this.gridGuid) {
                return;
            }

            if (this.isInitialized) {
                return
            }

            this.isInitialized = true;
            this.isLoading = true;
            DataApi.queryConfig(this.queryUrl, this.gridGuid).then((config) => {
                this.isLoaded = true;
                this.setupActions(config);
                // this.setupColumns(config);
                this.setupFilters(config);
                this.setInfoFunc(config.info_func)

                if (!this.showFilterPane) {
                    // 没有显示filterPane，不能直接查询数据
                    this.isLoading = false
                }
            });
        },

        exportXlsx() {
            let where = encodeURIComponent(this._getWhere())
            let xlsxUrl = `/data-service/sql-grid/xlsx?grid_guid=${this.gridGuid}&_where=${where}&token=${this.$token}`
            // fra-public 在应用中统一定义
            document.getElementById('fra-public').setAttribute('src', xlsxUrl)
        }
    },
    created() {},
    mounted() {
        // this.imageViewer = new ImageViewer(() => {
        //     return this.$el.querySelectorAll(".nx-grid-image-c")
        // })

        if (this.autoInit) {
            this.init();
        }
    }
};

</script>
<style lang="less">
.data-tree {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .action {
        padding: 8px 8px 8px 20px;
    }

    .filter {
        padding: 8px 8px 8px 20px;
    }

    .data {
        flex: 1;
        background-color: #fff;
        border: 1px solid rgba(0, 0, 0, 0.14);
        padding: 8px 8px 8px 20px;
        overflow: auto;
    }

    .pager {
        padding: 8px 8px 8px 20px;
        display: flex;

        .toolbar {
            flex: 1;

            .info-func {
                margin-right: 20px;
            }
        }
    }
}

</style>
