<template>
<#if ctrl.render??>
${ctrl.render.code}
<#else>
    <div class="app-searchbar<#if ctrl.getPSSysCss?? && ctrl.getPSSysCss()??> ${ctrl.getPSSysCss().getCssName()}</#if>">
        <div v-if="filterFields.length > 0" class="filter-group">
            <filter-tree :datas="filterItems" :fields="filterFields">
                <template slot-scope="{ data }">
                    <#if ctrl.getPSSearchBarFilters()??>
                    <#list ctrl.getPSSearchBarFilters() as filter>
                    <template v-if="Object.is(data.editor, '${filter.getName()}')">
                        ${P.getEditorCode(filter, "EDITOR.vue").code}
                    </template>
                    </#list>
                    </#if>
                </template>
            </filter-tree>
        </div>
        <div class="search-bar-footer">
            <#--  <#if !view.isEnableQuickSearch() && ctrl.getQuickSearchMode() gt 0>
            <i-input v-model="query" placeholder="<#if ctrl.getPSSearchBarQuickSearchs()??><#list ctrl.getPSSearchBarQuickSearchs() as search><#if search_index gt 0>,</#if><#if search.getPSDEField()??>${search.getPSDEField().getLogicName()}</#if></#list></#if>" style="<#if ctrl.getQuickSearchWidth() gt 0>width: ${ctrl.getQuickSearchWidth()?c}px;</#if>"></i-input>
            </#if>  -->
            <div class="search-bar-action">
                <el-select size="small" v-if="historyItems.length > 0" v-model="selectItem" @change="onFilterChange">
                    <el-option v-for="item in historyItems" :key="item.value" :label="item.name" :value="item.value"></el-option>
                </el-select>
                <i-button type="primary" @click="onSearch">{{ $t('app.searchButton.search') }}</i-button>
                <i-button @click="onReset">{{ $t('app.searchButton.reset') }}</i-button>
                <Poptip ref="propip" trigger="hover" placement="top-end" :title="$t('app.searchForm.custom')" :width="250" @on-popper-show="openPoper">
                    <i-button><i class="fa fa-floppy-o" aria-hidden="true"></i></i-button>
                    <template slot="content">
                        <div>
                            <i-input v-model="saveItemName" :placeholder="$t('app.searchForm.title')"></i-input>
                            <div class="save-action">
                                <i-button @click="onCancel">{{ $t('app.commonWords.cancel') }}</i-button>
                                <i-button type="primary" @click="onOk">{{ $t('app.commonWords.save') }}</i-button>
                            </div>
                        </div>
                    </template>
                </Poptip>
            </div>
        </div>
    </div>
</#if>
</template>
<#assign import_block>
import FilterTree from '@components/filter-tree/filter-tree.vue';
import moment from 'moment';
</#assign>

<#assign component_block>
FilterTree,
</#assign>

<#ibizinclude>
../@MACRO/CONTROL/CONTROL_HEADER-BASE.vue.ftl
</#ibizinclude>

    <#--  /**
     * 快速搜索值
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public query: string = '';  -->

    /**
     * 过滤属性集合
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    get filterFields() {
        return Object.values(this.detailsModel);
    }

    /**
     * 过滤属性模型集合
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public detailsModel: any = {
        <#if ctrl.getPSSearchBarFilters()??>
        <#list ctrl.getPSSearchBarFilters() as filter>
        '${filter.getName()}': {
            label: '<#if filter.getPSDEField()??>${filter.getPSDEField().getLogicName()}</#if>',
            name: '${filter.getName()}',
            prop: '<#if filter.getPSDEField()??>${filter.getPSDEField().getCodeName()?lower_case}<#else>${filter.getName()}</#if>',
            <#if filter.getPSDEFSearchMode()??>
            mode: '${filter.getPSDEFSearchMode().getValueOP()}',
            </#if>
            disabled: false
        },
        </#list>
        </#if>
    };

    /**
     * 过滤项集合
     *
     * @type {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public filterItems: any[] = [];

    /**
     * 应用实体名称
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public appdeName: string = '<#if ctrl.getPSDataEntity()??>${ctrl.getPSDataEntity().getCodeName()}</#if>';

    /**
     * modleId
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public modelId: string = "searchbar_<#if ctrl.getPSAppDataEntity()??>${ctrl.getPSAppDataEntity().getCodeName()?lower_case}<#else>app</#if>_${ctrl.getCodeName()?lower_case}";

    /**
     * 功能服务名称
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public utilServiceName: string = "<#if app.getPSAppFilterStorageUtil?? && app.getPSAppFilterStorageUtil()??>${app.getPSAppFilterStorageUtil().getCodeName()?lower_case}</#if>";

    /**
     * 历史记录
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    protected historyItems: any[] = [];

    /**
     * 选中记录
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    protected selectItem: any = null;

    /**
     * 存储项名称
     *
     * @type {string}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    protected saveItemName: string = '';

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public getDatas(): any[] {
        return [];
    }

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public getData(): any {
        let data: any = {};
        <#--  if(!Object.is(this.query, '')) {
            Object.assign(data, { query: this.query })
        }  -->
        if(this.filterFields.length > 0) {
            let filter: any = this.getFilter();
            Object.assign(data, { filter: filter ? JSON.stringify(filter) : null })
        }
        return data;
    }

    /**
     * 获取filter
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public getFilter(): any {
        if(this.filterItems.length === 0) {
            return null;
        }
        let ands: any[] = this.transformAnd(this.filterItems);
        this.transformResult(ands, '$and');
        if(ands.length === 0) {
            return null;
        }
        return { '$and': ands };
    }

    /**
     * 处理结果集
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public transformResult(datas: any[], pName: string) {
        let items: any[] = [];
        for(let i = datas.length - 1; i >= 0; i--) {
            let data: any = datas[i];
            let field: string = Object.is(pName, '$and') ? '$or' : '$and';
            if(data.hasOwnProperty(field)) {
                items.push(data);
                datas.splice(i, 1);
                this.transformResult(data[field], field);
            }

        }
        if(items.length > 0) {
            let item: any = {};
            item[pName] = items;
            datas.push(item);
        }
    }

    /**
     * 处理并且逻辑
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public transformAnd(datas: any[]): any {
        let result: any[] = [];
        datas.forEach((data: any) => {
            let item: any = {};
            if(data.field && data.mode) {
                item[data.field] = {};
                let valField: string = data.editor ? data.editor : data.field;
                item[data.field][data.mode] = (data[valField] == null  ? '' : data[valField]);
                result.push(item)
            } else if(Object.is(data.label, '$and')) {
                let items: any[] = this.transformAnd(data.children);
                result = [...result, ...items];
            } else if(Object.is(data.label, '$or')) {
                item[data.label] = this.transformOr(data.children);
                result.push(item)
            }
        })
        return result;
    }

    /**
     * 处理或逻辑
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public transformOr(datas: any[]) {
        let result: any[] = [];
        datas.forEach((data: any) => {
            let item: any = {};
            if(data.field && data.mode) {
                item[data.field] = {};
                let valField: string = data.editor ? data.editor : data.field;
                item[data.field][data.mode] = (data[valField] == null ? '' : data[valField]);
                result.push(item);
            } else if(Object.is(data.label, '$and')) {
                item[data.label] = this.transformAnd(data.children);
                result.push(item)
            } else if(Object.is(data.label, '$or')) {
                item[data.label] = this.transformOr(data.children);
                result.push(item);
            }
        })
        return result;
    }

    /**
     * Vue声明周期(处理组件的输入属性)
     *
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public created(): void {
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (Object.is('load', action)) {
                    this.load(data);
                }
            });
        }
    }

    /**
     * 删除过滤项
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public onRemove(index: number) {
        this.filterItems.splice(index, 1);
    } 

    /**
     * 搜索
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public onSearch() {
        this.$emit('search', this.getData());
    }

    /**
     * 保存
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public onSave(name?: string) {
        let time = moment();
        this.historyItems.push({
            name: (name ? name : time.format('YYYY-MM-DD HH:mm:ss')),
            value: time.unix().toString(),
            data: JSON.parse(JSON.stringify(this.filterItems))
        })
        this.selectItem = time.unix().toString();

        let param: any = {};
		Object.assign(param, {
            model: JSON.parse(JSON.stringify(this.historyItems)),
            appdeName: this.appdeName,
            modelid: this.modelId,
            utilServiceName: this.utilServiceName,
			...this.viewparams
		});
		let post = this.service.saveModel(this.utilServiceName, this.context, param);
		post.then((response: any) => {
			this.$emit("save", response.data);
		}).catch((response: any) => {
			console.log(response);
		});
    }

    /**
     * 重置
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public onReset() {
        <#--  this.query = '';  -->
        this.filterItems = [];
    }

    /**
     * 加载
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public load(data: any) {
        let param: any = {};
        Object.assign(param, {
            appdeName: this.appdeName,
            modelid: this.modelId,
            utilServiceName: this.utilServiceName,
            ...this.viewparams
        });
        let post = this.service.loadModel(this.utilServiceName, this.context, param);
		post.then((response: any) => {
			if(response.status == 200) {
                this.historyItems = response.data;
			}
		}).catch((response: any) => {
			console.log(response);
		});
    }

    /**
     * 改变过滤条件
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public onFilterChange(evt: any) {
        let item: any = this.historyItems.find((item: any) => Object.is(evt, item.value));
        if(item) {
            this.filterItems = JSON.parse(JSON.stringify(item.data));
        }
    }

    /**
     * 打开弹框
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public openPoper() {
        this.saveItemName = '';
    }

    /**
     * 确定
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public onOk() {
        let propip: any = this.$refs.propip;
        propip.handleMouseleave();
        this.onSave(this.saveItemName);
    }

    /**
     * 取消设置
     *
     * @return {*}
     * @memberof ${srfclassname('${ctrl.codeName}')}Base
     */
    public onCancel() {
        let propip: any = this.$refs.propip;
        propip.handleMouseleave();
        this.onSave();
    }
<#ibizinclude>
../@MACRO/CONTROL/CONTROL_BOTTOM-BASE.vue.ftl
</#ibizinclude>

<#ibizinclude>
../@MACRO/CONTROL/CONTROL-BASE.style.ftl
</#ibizinclude>