<template>
    <div class="customQueryBody">
        <query-tab
            :queryHandler="queryHandler"
            :dynamicSeniorQueryCondition='dynamicSeniorQueryCondition'
            :isShowTabCountZero='isShowTabCountZero'
            :contentIcon='contentIcon'
            ref='queryTabs'
            :extrCondition='extrCondition'
            :queryBus="queryBus"
            :defaultGroup='defaultGroup'
            :groups="groups"
            :content="content"
            @innerSceneQuery='innerSceneQuery'
            :groupCount="groupCount"
            :extraActionObject="extraActionObject"
        />
    </div>
</template>

<script>
import QueryUtil from "./queryUtil.js";
import QueryTab from "./query-filter-tabs.vue";
import helper from "./helper/index.js";
export default {
    name: "CustomQuery",
    data() {
        return {
            contentIcon: "", //查询内容图标
            isShowNoticeLine: false, //是否展示提示信息
            isOpenDrawer: false, //是否打开已标记资产卡片
            showMark: false, //配置是否展示已标记资产
            clicked: false, //点击配置时打开已标记资产卡片
            queryBus: helper.generateQueryBusObject(), //默认查询列表配置信息
            groups: [], //查询配置中页签数组配置集合
            isShowTabCountZero: true, //控制展示页签
            content: {}, //查询元数据配置内容
            groupCount: null, //自定义查询页签
            titleBar: { //查询标题工具栏
                title: "",
                description: "",
                fuzzySearch: [],
                actions: [],
                mark: {}
            },
            remind: [], //提醒信息数组
            text: "", //默认第一条提醒信息内容
            showUseListDrawer: false, //控制展示领用选择组件
            dataconfig: {}, //资产个性化代码，关于领用组件
            queryHandler: {}, //操作表格数据的方法对象
        };
    },
    watch: {
        groups(newVal, oldVal) {
            if (newVal) {
                this.getGroup(this.defaultGroup);
            }
        },
        //监听templateName改变时获取查询元数据配置
        templateName(val) {
            if (val) {
                this.initTemplate(val);
            }
        },
        //监听查询元数据配置变化时
        config(val) {
            if (val && !this.templateName) {
                this.initConfig(JSON.parse(val));
            }
        }
    },
    props: {
        templateName: {
            type: String,
            default: ""
        },
        config: {
            type: String,
            default: "",
            require: true
        },
        //默认页签，推测是资产在元数据自定义的默认页签，这里传的值为默认页签名称，但在实现中并没有特别处理，疑问？
        defaultGroup: {
            type: String,
            default: ""
        },
        extrCondition: {
            type: Array,
            default: function () {
                return new Array();
            }
        },
        dynamicSeniorQueryCondition: {
            type: Array,
            default: function () {
                return new Array();
            }
        },
        title: {
            type: String,
            default: "查询"
        },
        //查询增加额外属性，用来处理额外的动作触发传值
        extraActionObject: {
            type: [Object, Array]
        }
    },
    components: {
        QueryTab
    },
    created() {
    },
    mounted() {
        var that = this;
        // this.queryHandler.getTemplate = function () {
        //     return that.templateName;
        // };
        // this.queryHandler.getTitle = function () {
        //     return that.titleBar.title;
        // };
        if (this.templateName) {
            this.initTemplate(this.templateName);
        } else {
            this.initConfig(JSON.parse(this.config));
        }
    },
    methods: {
        //获取相关通知信息，确认是否展示通知区域
        getNotice() {
            let obj = {
                datasource: this.remind[0].datasource
            };
            //@king GMS中拿$http
            GMS.$http.post(
                QueryUtil.api.count,
                JSON.stringify(obj),
                {
                    contentType: "application/json"
                }
            ).then((response) => {
                let data = response.data;
                if (data > 0) {
                    this.isShowNoticeLine = true;
                } else {
                    this.isShowNoticeLine = false;
                }
            }).catch((error) => {
                this.isShowNoticeLine = false;
            });
        },
        //关闭通知区域
        closeLine() {
            this.isShowNoticeLine = false;
        },
        //选择内置查询方案时触发（个性化）
        innerSceneQuery(data) {
            let currentGroup = this.queryBus.currGroup;
            this.forItemAndGroup(data, currentGroup);
        },
        //通知信息点击处理时触发（个性化）
        clickHandle() {
            let handleGroup = this.remind[0].handle.group;
            let handleScene = this.remind[0].handle.scene;
            let group = this.getGroup(handleGroup);
            let item = this.getScene(group, handleScene);
            if (!item) {
                return;
            }
            this.forItemAndGroup(item, group);
        },
        //通过name值得到对应页签数组groups中的页签配置对象group
        getGroup(groupName) {
            if (!groupName) {
                return null;
            }
            let group = {};
            for (let i = 0; i < this.groups.length; i++) {
                let item = this.groups[i];
                if (groupName == item.name) {
                    this.$refs.queryTabs.tabOnClick(i);
                    this.$refs.queryTabs.labelStr = String(i);
                    group = item;
                    break;
                }
            }
            group.content = group.content ? group.content : this.content
            group.content.scenes = group.content.scenes ? group.content.scenes : this.content.scenes;
            group.content.arguments = group.content.arguments ? group.content.arguments : this.content.arguments;
            return group;
        },
        //通过name值得到对应页签内查询方案数组配置的查询方案
        getScene(group, sceneName) {
            if (!group || !group.content) {
                return
            }
            //得到group中content中scenes中items项
            let scenes = group.content.scenes;
            if (!scenes || !scenes.items || scenes.items.length == 0) {
                return null;
            }
            let items = scenes.items;
            for (let i = 0; i < items.length; i++) {
                let item = items[i];
                if (sceneName == item.name) {
                    return item;
                }
            }
            return null;
        },
        //针对当前查询页签配置group和查询方案item配置关联？
        forItemAndGroup(item, group) {
            let result = [];
            let obj = {};
            for (let i = 0; i < item.conditions.length; i++) {
                let iItem = item.conditions[i];
                obj = {};
                if (iItem.argsId) {
                    obj.name = iItem.name;
                    obj.value = iItem.values;
                    obj.dataType = iItem.dataType;
                    result.push(obj);
                } else {
                    let args = group.content.arguments;
                    if (!args || !args.items || args.items.length == 0) {
                        return;
                    }
                    for (let j = 0; j < args.items.length; j++) {
                        let jItem = args.items[j];
                        for (let k = 0; k < jItem.length; k++) {
                            let kItem = jItem[k];
                            if (iItem.argsId == kItem.id) {
                                obj = {
                                    id: iItem.argsId,
                                    title: kItem.title,
                                    name: iItem.name,
                                    value: iItem.values,
                                    dataType: kItem.dataType,
                                    text: iItem.text
                                };
                                if (kItem.type == "INPUT") {
                                    obj.text = iItem.values;
                                    if (kItem.dataType == "STRING") {
                                        obj.type = "strInput";
                                        obj.fuzzySearch = kItem.fuzzySearch == false ? false : true;
                                    }
                                    if (kItem.dataType == "NUMBER") {
                                        obj.type = "numInput";
                                    }
                                    result.push(obj);
                                    break;
                                } else if (kItem.type == "PERSON") {
                                    obj.type = "person";
                                    result.push(obj);
                                    break;
                                } else if (kItem.type == "DEPARTMENT") {
                                    obj.type = "department";
                                    result.push(obj);
                                    break;
                                } else if (kItem.type == "DEPOSITARY") {
                                    obj.type = "depositary";
                                    result.push(obj);
                                    break;
                                } else if (kItem.type == "DATE") {
                                    obj.text = this.toTimeStr(iItem.values);
                                    obj.type = "DATE";
                                    result.push(obj);
                                    break;
                                } else if (kItem.type == "SELECT") {
                                    if (kItem.config.isMulti) {
                                        obj.isMulti = true;
                                        obj._index = [];
                                        obj.text = [];
                                        for (let i = 0; i < kItem.config.values.length; i++) {
                                            obj._index.push(-1);
                                        }
                                        for (let i = 0; i < iItem.values.length; i++) {
                                            for (let j = 0; j < kItem.config.values.length; j++) {
                                                if (iItem.values[i] == kItem.config.values[j].value) {
                                                    this.$set(obj._index, j, j);
                                                    obj.text.push(kItem.config.values[j].title);
                                                    break;
                                                }
                                            }
                                        }
                                    } else {
                                        obj._index = "";
                                        obj.text = "";
                                        for (let i = 0; i < iItem.values.length; i++) {
                                            for (let j = 0; j < kItem.config.values.length; j++) {
                                                if (iItem.values[i] == kItem.config.values[j].value) {
                                                    obj._index = j;
                                                    obj.text = kItem.config.values[j].title;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    obj.type = "select";
                                    result.push(obj);
                                    break;
                                } else if (kItem.type == "RANGE") {
                                    if (kItem.dataType == "DATE") {
                                        obj.type = "dateRange";
                                        obj._index = -1;
                                        obj.text = this.toTimeStr(obj.value.min) + " - " + this.toTimeStr(obj.value.max);
                                        if (kItem.config.values && kItem.config.values.length != 0) {
                                            for (let i = 0; i < kItem.config.values.length; i++) {
                                                if (obj.value.min == kItem.config.values[i].min && obj.value.max == kItem.config.values[i].max) {
                                                    obj.isChoseEnum = true;
                                                    obj._index = i;
                                                    obj.text = kItem.config.values[i].title;
                                                    break;
                                                }
                                            }
                                        }
                                        result.push(obj);
                                        break;
                                    }
                                    if (kItem.dataType == "NUMBER") {
                                        obj.type = "numRange";
                                        obj._index = -1;
                                        obj.text = obj.value.min + "-" + obj.value.max;
                                        if (kItem.config.values && kItem.config.values.length != 0) {
                                            for (let i = 0; i < kItem.config.values.length; i++) {
                                                if (obj.value.min == kItem.config.values[i].min && obj.value.max == kItem.config.values[i].max) {
                                                    obj.text = kItem.config.values[i].title;
                                                    obj.isChoseEnum = true;
                                                    obj._index = i;
                                                    break;
                                                }
                                            }
                                        }
                                        result.push(obj);
                                        break;
                                    }
                                } else if (kItem.type == "DROPDOWN") {
                                    if (kItem.config.isMulti == true) {
                                        obj.text = [];
                                        for (let i = 0; i < iItem.values.length; i++) {
                                            for (let j = 0; j < kItem.config.values.length; j++) {
                                                if (iItem.values[i] == kItem.config.values[j].value) {
                                                    obj.text.push(
                                                        kItem.config.values[j].title
                                                    );
                                                    break;
                                                }
                                            }
                                        }
                                    } else {
                                        obj.text = "";
                                        for (let k = 0; k < kItem.config.values.length; k++) {
                                            if (iItem.values == kItem.config.values[k].value) {
                                                obj.text = kItem.config.values[k].title;
                                                break;
                                            }
                                        }
                                    }
                                    obj.type = "dropdown";
                                    result.push(obj);
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            let conditions = JSON.parse(JSON.stringify(result));
            GMS.vbus.$emit("getQueryPlanData", conditions);
        },
        //打开标记资产卡片
        openDrawer() {
            this.clicked = true;
            this.$nextTick(function () {
                if (this.titleBar.mark.type == "platform") {
                    this.showUseListDrawer = true;
                    this.dataconfig = {
                        types: 1
                    };
                } else {
                    this.isOpenDrawer = true;
                    this.$refs.markfund.refreshFirstEnterData();
                }
            });
        },
        //资产个性化，关闭资产领用组件触发
        closeUseListDrawer() {
            this.showUseListDrawer = false;
        },
        //关闭已标记资产
        closeDrawer() {
            this.isOpenDrawer = false;
        },
        //模糊搜索时触发
        fuzzySearch() {
            this.$refs.queryTabs.buttonRefreshData();
        },
        //日期格式转为年-月-日
        toTimeStr(timeStamp) {
            var timeDate = new Date(timeStamp);
            var year = timeDate.getFullYear(); //当前年份
            var month = timeDate.getMonth() + 1; //当前月份
            var date = timeDate.getDate(); //天
            var timeStr = year + "-" + month + "-" + date;
            return timeStr;
        },
        //对于页签数组进行初始化，使页签下功能进行完善，包括：表格(table)、场景(scenes)、动作(actions)、datasource和高级查询(arguments)等
        initMeta(groups, config) {
            for (let i = 0; i < groups.length; i++) {
                let item = groups[i];
                if (!item.content) {
                    item.content = JSON.parse(JSON.stringify(config.content));
                } else {
                    let content = item.content;
                    content.datasource = content.datasource ? content.datasource : config.content.datasource;
                    content.actions = content.actions ? content.actions : JSON.parse(JSON.stringify(config.content.actions));
                    content.table = content.table ? content.table : JSON.parse(JSON.stringify(config.content.table));
                    content.arguments = content.arguments ? content.arguments : JSON.parse(JSON.stringify(config.content.arguments));
                    if (!content.scenes && config.content.scenes) {
                        content.scenes = JSON.parse(JSON.stringify(config.content.scenes));
                    }
                    if (!content.page && config.content.page) {
                        content.page = JSON.parse(JSON.stringify(config.content.page));
                    }
                }
            }
            return config;
        },
        //初始化查询元数据主页签（外层）配置,此时config为整体的查询配置content
        initConfig(config) {
            this.contentIcon = config.contentIcon ? "#icon-_" + config.contentIcon : "";
            this.queryBus.config = this.initMeta(config.groups ? config.groups : [{}], config);
            this.titleBar = {
                title: config.title,
                description: config.description,
                name: config.name,
                fuzzySearch: config.fuzzySearch ? config.fuzzySearch : [],
                actions: config.actions ? config.actions : [],
                mark: config.mark ? config.mark : {}
            };
            this.isShowTabCountZero = config.isShowTabCountZero == false ? false : true;
            this.groups = config.groups ? config.groups : [{}];
            this.content = config.content;
            this.groupCount = config.groupCount;
            this.remind = config.remind ? config.remind : [];
            if (this.remind.length == 0) {
                this.isShowNoticeLine = false;
            } else {
                this.getNotice();
            }
            if (config.mark) {
                this.showMark = true;
            }
        },
        //通过查询templateName获取元数据配置
        initTemplate(templateName) {
            let url = `/bcp/query/advance/view/${templateName}`;
            GMS.$http.get(url).then(
                function(response) {
                    if (response.data) {
                        this.initConfig(response.data);
                    }
                }.bind(this)
            ).catch(
                function(error) {
                    console.log("获取配置文件错误");
                }.bind(this)
            )
        }
    }
};
</script>
<style lang='less' scoped>
.circle {
    font-weight: bold;
    padding: 10px 30px;
    color: #565555;

    b {
        height: 4px;
        width: 4px;
        margin: 4px 4px 3px 10px;
        display: inline-block;
        border-radius: 50%;
        background-color: #565555;
    }
}

.customQueryBody {
    padding: 10px 15px 15px 15px;
    // position: relative;
    // box-sizing: border-box;
    height: 100%;
}

.height15 {
    height: 15px;
}

.tips {
    position: absolute;
    left: 120px;
    top: 18px;
    width: 14px;
    height: 14px;
    text-align: center;
    line-height: 14px;
    background-color: #828fa0;
    border-radius: 50%;
    color: #fff;
}
</style>