<template>
    <div class="search-box circle" :id="ctlId" :class="alignClass">
        <div class="clearfix">
            <div
                :id="searchId"
                class="search-select pull-left"
                @mouseover="showSelItems(searchId)"
                @mouseleave="levelParentItemPanel(searchId)"
            >
                <div style="color: #666">--{{'查询条件'}}--</div>
            </div>
            <div class="pull-left" :id="searchId + '_icon'" @click.stop="showSelItems(searchId)">
                <a class="search-button">
                    <i class="ivu-icon ivu-icon-md-arrow-dropdown"></i>
                </a>
            </div>
            <div
                @mouseover.stop="levelParentItemPanel(searchId)"
                class="search-input pull-left"
                :id="searchInputId"
            ></div>
            <div @click="searchFun" class="pull-left">
                <a class="search-button">
                    <i class="ivu-icon ivu-icon-ios-search"></i>
                </a>
            </div>
        </div>

        <div  @mouseleave="levelSubItemPanel(searchId)"  @mouseover="showSubSelItems(searchId)" :id="itemsId"  v-show="openComboFlag" class="search-items">
            <div :key="index" @mouseover="showSubSelItems()"  class="search-item" fieldid="groupName" @click="selectItem(sonItem, searchId, $event)"  v-for="(sonItem, index) of searchFieldItems">
                <span v-if="showSonItem(sonItem)"> {{ sonItem.label }}</span>
            </div>
        </div>
    </div>
</template>

<script>
    import {GoingUtils, AssertUtils} from "goingutils";
    import {findComponentUpward} from '../../common/assist';
    import goSearchMixins from "./mixins/goSearchMixins";
    import EditorTypeUtils from "../../common/editorTypeUtils";

    var moveTimeout = null;
    var subMoveTimeout = null;
    export default {
        name: "go-search-box",
        mixins: [goSearchMixins],
        data: function () {
            return {
                ctlId: GoingUtils.getUUid(12),
                searchWidth:0,
                joinSub: false,
                queryCtl: {prefixCls: GoingUtils.getUUid(12).substring(0, 11)},
                searchId: GoingUtils.getUUid(12),
                curSelItem: null,
                openComboFlag: false,
                joinParent: false
            };
        },
        props: {
            //排除部分选项
            exclude: {
                type: Array,
                default: () => []
            },
            //对齐方式
            align: {
                type: String,
                default: "left"
            },
            //label的宽度
            labelWidth: {
                type: [Number, String],
                default: 110
            },
            //输入框的宽度
            inputWidth: {
                type: [Number, String],
                default: 130
            }
        },
        computed: {
            searchFieldItems() {
                return this.getSearchItems();
            },
            //获取居左 居右的样式
            alignClass() {
                if (this.align === "left") {
                    return "pull-left";
                } else if (this.align === "right") {
                    return "pull-right";
                }
                return "";
            },
            //查询输入框
            searchInputId() {
                return this.searchId + "_input";
            },
            //查询选项
            itemsId() {
                return this.searchId + "_items";
            }
        },
        methods: {
            showSonItem(sonItem) {
                return sonItem.query != false;
            },
            destroyPreCtl() {
                let queryCtl = this.queryCtl;
                if (this.curSelItem != null) {
                    let inputId = `${queryCtl.prefixCls}_${this.curSelItem["id"]}`;
                    if (
                        queryCtl[inputId] != null &&
                        AssertUtils.isObject(queryCtl[inputId])
                    ) {
                        queryCtl[inputId].unload();
                    }
                }
            },
            setItemSel(searchId, event, itemConfig) {
                //设置当前选中项
                $("#" + searchId + "_items .active-item").removeClass("active-item");
                if (event != null) {
                    $(event.target)
                        .closest(".search-item")
                        .addClass("active-item");
                }
                $(`#${searchId}`).html(itemConfig["label"]);

                this.openComboFlag = false;
            },
            /**
             * 根据类型获取其对应的输入框html内容 对部分特殊组件需要进行特殊处理
             * @param itemConfig
             * @param targetObj
             * @returns {*}
             */
            getHtmlByItem(itemConfig, targetObj) {
                //如果编辑类型为空 则去type作为编辑类型
                if (!AssertUtils.isNotEmpty(itemConfig["editorType"])) {
                    itemConfig["editorType"] = itemConfig["type"];
                }
                //如果是switch控件 需要转换下
                if (itemConfig["editorType"] === "switch") {
                    itemConfig["items"] = [
                        {id: "true", label: "启动"},
                        {id: "false", label: "停用"}
                    ];
                    itemConfig["editorType"] = "staticDrop";
                }

                //如果是radiobox
                if (itemConfig["editorType"] === "radioBox") {
                    itemConfig["editorType"] = "staticDrop";
                }
                return EditorTypeUtils.getItemHtmlByType(
                    itemConfig,
                    "singleQuery",
                    targetObj
                );
            },
            //点击某个查询字段
            selectItem(itemConfig, searchId, event) {
                const $parent = findComponentUpward(this, 'go-tool-bar');
                //销毁以前定义的相关控件
                this.destroyPreCtl();
                this.curSelItem = itemConfig;
                let queryCtl = this.queryCtl;
                queryCtl.labelWidth = this.labelWidth;
                queryCtl.inputWidth = this.inputWidth;
                //设置字段被选中
                this.setItemSel(searchId, event, itemConfig);


                if(itemConfig.id==='empty'){
                    $(`#${searchId}_input`).html("");
                    $parent&&$parent.changeRightArea&&$parent.changeRightArea(parseFloat($("#"+$parent["toolBarId"]).find(".search-box").width())-this.searchWidth,this.searchWidth);
                    return void(0);
                }

                //获取对应类型的字符串
                let htmls = this.getHtmlByItem(itemConfig, queryCtl);

                if(!AssertUtils.isNotEmpty(htmls)){
                    GoingUtils.showErrorMessage("获取的html为空，请确认！",this);
                    return;
                }

                $(`#${searchId}_input`).html(htmls);

                //初始化控件的事件
                EditorTypeUtils.initCtlByItemType(
                    itemConfig,
                    $(`#${searchId}_input`),
                    queryCtl.inputWidth,
                    queryCtl
                );
                //第一个输入框给与焦点
                $(`#${searchId}_input input:eq(0)`).focus();


                $parent&&$parent.changeRightArea&&$parent.changeRightArea(parseFloat($("#"+$parent["toolBarId"]).find(".search-box").width())-this.searchWidth,this.searchWidth);
            },
            showSelItems() {
                //显示下拉菜单内容
                this.openComboFlag = true;
                this.joinParent = true;
            },
            //如果是移开父节点
            levelParentItemPanel() {
                let vueObj = this;
                vueObj.joinParent = false;
                //如果定时器存在 则清除以前的定时器
                if (moveTimeout != null) {
                    clearTimeout(moveTimeout);
                }
                //重新定义定时器
                moveTimeout = setTimeout(function () {
                    if (!vueObj.joinSub) {
                        vueObj.openComboFlag = false;
                    }
                }, 100);
            },
            //如果是光标进入到子菜单区域
            showSubSelItems() {
                //显示下拉菜单内容
                this.openComboFlag = true;
                this.joinSub = true;
            },
            //如果是光标移出子菜单区域
            levelSubItemPanel() {
                let vueObj = this;
                vueObj.joinSub = false;
                //如果定时器存在 则清除以前的定时器
                if (subMoveTimeout != null) {
                    clearTimeout(subMoveTimeout);
                }
                //重新定义定时器
                subMoveTimeout = setTimeout(function () {
                    if (!vueObj.joinParent) {
                        vueObj.openComboFlag = false;
                    }
                }, 100);
            },
            //点击查询按钮 执行查询操作
            searchFun() {
                let queryCtl = this.queryCtl;
                if (AssertUtils.isNotNull(this.curSelItem)) {
                    let backJson = {};
                    EditorTypeUtils.getSubmitDataByItem(
                        this.curSelItem,
                        backJson,
                        "singleQuery",
                        queryCtl
                    );
                    this.$emit("searchFun", {datas: backJson});
                }
            }
        },
        mounted: function () {
            EditorTypeUtils.initGoForm();
            let vueObj = this;
            //如果查询条件只有1个的时候 默认选择上查询条件
            let items = vueObj.getSearchItems();
            if (items.length === 1) {
                this.selectItem(items[0], this.searchId);
            }
            this.searchWidth=parseFloat($("#"+this.ctlId).width());
            //如果点击不是该控件范围只内 则隐藏该控件下拉
            $(document).click(function (e) {
                let target = $(e.target);
                if (
                    !target.is("#" + vueObj.searchId) &&
                    !target.is("#" + vueObj.searchId + " *") &&
                    !target.is("#" + vueObj.searchId + "_icon") &&
                    !target.is("#" + vueObj.searchId + "_icon *")
                ) {
                    vueObj.openComboFlag = false;
                }
            });
        },
        components: {},
        //组件销毁
        beforeDestroy() {
        }
    };
</script>
