<template>
    <div class="">
        <app-searchbar :items="filterItems" :fields="filterFields">
            <template slot-scope="{ data }">
                <template v-if="Object.is(data.editor, 'filter')">
                    <input-box 
    v-model="data.filter"  
    @enter="onEnter($event)"  
      
    :disabled="detailsModel.filter.disabled" 
    type='text' 
    style="">
</input-box>

                </template>
                <template v-if="Object.is(data.editor, 'filter2')">
                    <input-box 
    v-model="data.filter2"  
    @enter="onEnter($event)"  
      
    :disabled="detailsModel.filter2.disabled" 
    type='text' 
    style="">
</input-box>

                </template>
                <template v-if="Object.is(data.editor, 'filter3')">
                    <date-picker type="datetime" :transfer="true" format="yyyy-MM-dd HH:mm:ss"  :value="data.filter3" :disabled="detailsModel.filter3.disabled" style="min-width: 150px; width:160px;" @on-change="(val1, val2) => { data.filter3 = val1 }"></date-picker>

                </template>
            </template>
        </app-searchbar>
    </div>
</template>
// 基于 @CONTROL/搜索栏/CONTROL-BASE.vue.ftl 生成

<script lang='tsx'>
import { Vue, Component, Prop, Provide, Emit, Watch, Model,Inject } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import { Subject, Subscription } from 'rxjs';
import { ControlInterface } from '@/interface/control';
import { UIActionTool,Util,ViewTool } from '@/utils';
import NavDataService from '@/service/app/navdata-service';
import AppCenterService from "@service/app/app-center-service";
import IBIZOrderEntityService from '@/service/ibizorder/ibizorder-service';
import SearchbarService from './searchbar-searchbar-service';
import IBIZOrderUIService from '@/uiservice/ibizorder/ibizorder-ui-service';
import moment from 'moment';


@Component({
    components: {
      
    }
})
export default class SearchbarBase extends Vue implements ControlInterface {

    /**
     * 名称
     *
     * @type {string}
     * @memberof SearchbarBase
     */
    @Prop() public name?: string;

    /**
     * 视图通讯对象
     *
     * @type {Subject<ViewState>}
     * @memberof SearchbarBase
     */
    @Prop() public viewState!: Subject<ViewState>;

    /**
     * 应用上下文
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    @Prop() public context!: any;

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    @Prop() public viewparams!: any;

    /**
     * 视图操作参数(父级)
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    @Prop() public pViewCtx!: any;

    /**
     * 视图操作参数
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    public viewCtx: any = {};

    /**
     * 监听视图操作参数变化
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    @Watch('pViewCtx', { immediate: true })
    public onViewCtxChange(newVal: any, oldVal: any) {
        Object.assign(this.viewCtx, newVal, { xData: this, ctrl: this });
    }

    /**
     * 视图状态事件
     *
     * @public
     * @type {(Subscription | undefined)}
     * @memberof SearchbarBase
     */
    public viewStateEvent: Subscription | undefined;

    /**
     * 获取部件类型
     *
     * @returns {string}
     * @memberof SearchbarBase
     */
    public getControlType(): string {
        return 'SEARCHBAR'
    }



    /**
     * 计数器服务对象集合
     *
     * @type {Array<*>}
     * @memberof SearchbarBase
     */    
    public counterServiceArray:Array<any> = [];

    /**
     * 建构部件服务对象
     *
     * @type {SearchbarService}
     * @memberof SearchbarBase
     */
    public service: SearchbarService = new SearchbarService({ $store: this.$store });

    /**
     * 实体服务对象
     *
     * @type {IBIZOrderService}
     * @memberof SearchbarBase
     */
    public appEntityService: IBIZOrderEntityService = new IBIZOrderEntityService({ $store: this.$store });
    


    /**
     * 转化数据
     *
     * @param {any} args
     * @memberof  SearchbarBase
     */
    public transformData(args: any) {
        let _this: any = this;
        if(_this.service && _this.service.handleRequestData instanceof Function && _this.service.handleRequestData('transform',_this.context,args)){
            return _this.service.handleRequestData('transform',_this.context,args)['data'];
        }
    }

    /**
     * 关闭视图
     *
     * @param {any} args
     * @memberof SearchbarBase
     */
    public closeView(args: any): void {
        let _this: any = this;
        _this.$emit('closeview', [args]);
    }

    /**
     *  计数器刷新
     *
     * @memberof SearchbarBase
     */
    public counterRefresh(){
        const _this:any =this;
        if(_this.counterServiceArray && _this.counterServiceArray.length >0){
            _this.counterServiceArray.forEach((item:any) =>{
                if(item.refreshData && item.refreshData instanceof Function){
                    item.refreshData();
                }
            })
        }
    }
    /**
     *  处理部件事件
     *
     * @memberof SearchbarBase
     */
    public async handleCtrlEvents(eventName: string, args: any = {}): Promise<boolean> {
        const actionData = {
            data: this.getData() || {},
            context: Util.deepCopy(this.context),
            viewparams: Util.deepCopy(this.viewparams),
            xData: this
        }
        let result: boolean = true;
        Object.assign(actionData, args);
        if (!result) {
            return false;
        }
        this.$emit(eventName, actionData);
        return true;
    }





    /**
     * 过滤属性集合
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    get filterFields() {
        return Object.values(this.detailsModel);
    }

    /**
     * 过滤属性模型集合
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    public detailsModel: any = {
        'filter': {
            label: '订单编号',
            name: 'filter',
            prop: 'orderuid',
            disabled: false
        },
        'filter2': {
            label: '订单名称',
            name: 'filter2',
            prop: 'ibizordername',
            disabled: false
        },
        'filter3': {
            label: '订单时间',
            name: 'filter3',
            prop: 'ordertime',
            disabled: false
        },
    };

    /**
     * 过滤项集合
     *
     * @type {*}
     * @memberof SearchbarBase
     */
    public filterItems: any[] = [];

    /**
     * 应用实体名称
     *
     * @type {string}
     * @memberof SearchbarBase
     */
    public appdeName: string = 'IBIZOrder';

    /**
     * modleId
     *
     * @type {string}
     * @memberof SearchbarBase
     */
    public modelId: string = "searchbar_ibizorder_searchbar";

    /**
     * 功能服务名称
     *
     * @type {string}
     * @memberof SearchbarBase
     */
    public utilServiceName: string = "";

    /**
     * 历史记录
     *
     * @type {string}
     * @memberof SearchbarBase
     */
    protected historyItems: any[] = [];

    /**
     * 选中记录
     *
     * @type {string}
     * @memberof SearchbarBase
     */
    protected selectItem: any = null;

    /**
     * 存储项名称
     *
     * @type {string}
     * @memberof SearchbarBase
     */
    protected saveItemName: string = '';

    /**
     * 获取多项数据
     *
     * @returns {any[]}
     * @memberof SearchbarBase
     */
    public getDatas(): any[] {
        return [];
    }

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof SearchbarBase
     */
    public getData(): any {
        if(this.filterFields.length > 0) {
            let filter: any = this.getFilter();
            return filter;
        }
    }

    /**
     * 获取filter
     *
     * @return {*}
     * @memberof SearchbarBase
     */
    public getFilter(): any {
        if(this.filterItems.length === 0) {
            return null;
        }
        let params: any = this.transformAnd(this.filterItems);
        if(Object.keys(params).length === 0) {
            return null;
        }
        return params;
    }

    /**
     * 处理并且逻辑
     *
     * @return {*}
     * @memberof SearchbarBase
     */
    public transformAnd(datas: any[]): any {
        let result: any = {};
        datas.forEach((data: any) => {
            if(data.field && data.mode) {
                let valField: string = data.editor ? data.editor : data.field;
                Object.assign(result, {[`n_${data.field}_${data.mode}`]: data[valField]});
            } 
        })
        return result;
    }

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

    /**
     * 删除过滤项
     *
     * @return {*}
     * @memberof SearchbarBase
     */
    public onRemove(index: number) {
        this.filterItems.splice(index, 1);
    } 

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

    /**
     * 保存
     *
     * @return {*}
     * @memberof SearchbarBase
     */
    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 SearchbarBase
     */
    public onReset() {
        this.filterItems = [];
    }

    /**
     * 加载
     *
     * @return {*}
     * @memberof SearchbarBase
     */
    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 SearchbarBase
     */
    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 SearchbarBase
     */
    public openPoper() {
        this.saveItemName = '';
    }

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

    /**
     * 取消设置
     *
     * @return {*}
     * @memberof SearchbarBase
     */
    public onCancel() {
        let propip: any = this.$refs.propip;
        propip.handleMouseleave();
        this.onSave();
    }
}
</script>