<template>
    <div class='view-container jqxtbydgrid-view9'>
    <card class='view-card view-no-caption'  :dis-hover="true" :bordered="false">
        <div class='content-container'>
            <div class='view-top-messages'>
            </div>
            <view_grid 
                :viewState="viewState"  
                :viewparams="viewparams" 
                :context="context" 
                :isSingleSelect="isSingleSelect" 
                :showBusyIndicator="true"
                :isOpenEdit="true"
                @save="onSave"
                updateAction="UpdateTemp"
                removeAction="RemoveTemp"
                loaddraftAction="GetDraftTemp"
                loadAction="GetTemp"
                createAction="CreateTemp"
                fetchAction="FetchTempDefault"
                name="grid"  
                ref='grid' 
                @selectionchange="grid_selectionchange($event)"  
                @beforeload="grid_beforeload($event)"  
                @rowdblclick="grid_rowdblclick($event)"  
                @remove="grid_remove($event)"  
                @load="grid_load($event)"  
                @closeview="closeView($event)">
            </view_grid>
            <row style='margin-bottom: 6px;'>
                <div class='pull-right'>
                    <div class='toolbar-container'>
                        <tooltip :transfer="true" :max-width="600">
                            <i-button v-show="toolBarModels.tbitem1.visabled" :disabled="toolBarModels.tbitem1.disabled" class='' @click="toolbar_click({ tag: 'tbitem1' }, $event)">
                                <i class='fa fa-plus'></i>
                                <span class='caption'>{{$t('jqxtbyd.gridview9toolbar_toolbar.tbitem1.caption')}}</span>
                            </i-button>
                            <div slot='content'>{{$t('jqxtbyd.gridview9toolbar_toolbar.tbitem1.tip')}}</div>
                        </tooltip>
                    </div>
                </div>
            </row>
            <div class='view-bottom-messages'>
            </div>
        </div>
    </card>
</div>
</template>

<script lang='ts'>
import { Vue, Component, Prop, Provide, Emit, Watch } from 'vue-property-decorator';
import { UIActionTool } from '@/utils';
import { Subject } from 'rxjs';
import JQXTBYDService from '@/service/jqxtbyd/jqxtbyd-service';

import GridView9Engine from '@engine/view/grid-view9-engine';



@Component({
    components: {
    },
})
export default class JQXTBYDGridView9Base extends Vue {

    /**
     * 实体服务对象
     *
     * @type {JQXTBYDService}
     * @memberof JQXTBYDGridView9Base
     */
    protected appEntityService: JQXTBYDService = new JQXTBYDService;

    /**
     * 数据变化
     *
     * @param {*} val
     * @returns {*}
     * @memberof JQXTBYDGridView9Base
     */
    @Emit() 
    protected viewDatasChange(val: any):any {
        return val;
    }

    /**
     * 传入视图上下文
     *
     * @type {string}
     * @memberof JQXTBYDGridView9Base
     */
    @Prop() protected viewdata!: string;

    /**
     * 传入视图参数
     *
     * @type {string}
     * @memberof JQXTBYDGridView9Base
     */
    @Prop() protected viewparam!: string;

    /**
     * 视图默认使用
     *
     * @type {boolean}
     * @memberof JQXTBYDGridView9Base
     */
    @Prop({ default: true }) protected viewDefaultUsage!: boolean;

	/**
	 * 视图标识
	 *
	 * @type {string}
	 * @memberof JQXTBYDGridView9Base
	 */
	protected viewtag: string = '1b13efd6f691356abb6586fdf64524a4';

    /**
     * 视图模型数据
     *
     * @type {*}
     * @memberof JQXTBYDGridView9Base
     */
    protected model: any = {
        srfTitle: '交强险特别约定表格视图',
        srfCaption: 'jqxtbyd.views.gridview9.caption',
        srfSubCaption: '',
        dataInfo: ''
    }

    /**
     * 视图参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof JQXTBYDGridView9Base
     */
    @Watch('viewparam',{immediate: true, deep: true})
    onParamData(newVal: any, oldVal: any) {
        if(newVal){
            Object.assign(this.viewparams, JSON.parse(this.viewparam));
        } 
    }

    /**
     * 处理应用上下文变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof JQXTBYDGridView9Base
     */
    @Watch('viewdata')
    onViewData(newVal: any, oldVal: any) {
        const _this: any = this;
        if (!Object.is(newVal, oldVal) && _this.engine) {
            _this.parseViewParam();
            _this.engine.load();
        }
        
    }

    /**
     * 容器模型
     *
     * @type {*}
     * @memberof JQXTBYDGridView9Base
     */
    protected containerModel: any = {
        view_toolbar: { name: 'toolbar', type: 'TOOLBAR' },
        view_grid: { name: 'grid', type: 'GRID' },
    };

    /**
     * 视图状态订阅对象
     *
     * @private
     * @type {Subject<{action: string, data: any}>}
     * @memberof JQXTBYDGridView9Base
     */
    protected viewState: Subject<ViewState> = new Subject();

    /**
     * 工具栏模型
     *
     * @type {*}
     * @memberof JQXTBYDGridView9
     */
    public toolBarModels: any = {
        tbitem1: { name: 'tbitem1', caption: '新建', disabled: false, type: 'DEUIACTION', visabled: true, dataaccaction: '', uiaction: { tag: 'NewRow', target: '' } },

    };




    /**
     * 视图引擎
     *
     * @private
     * @type {Engine}
     * @memberof JQXTBYDGridView9Base
     */
    private engine: GridView9Engine = new GridView9Engine();

    /**
     * 引擎初始化
     *
     * @private
     * @memberof JQXTBYDGridView9Base
     */
    private engineInit(): void {
        this.engine.init({
            view: this,
            opendata: (args: any[], params?: any, $event?: any, xData?: any) => {
                this.opendata(args, params, $event, xData);
            },
            newdata: (args: any[], params?: any, $event?: any, xData?: any) => {
                this.newdata(args, params, $event, xData);
            },
            grid: this.$refs.grid,
            keyPSDEField: 'jqxtbyd',
            majorPSDEField: 'jqxtbydname',
            isLoadDefault: true,
        });
    }

    /**
     * 应用上下文
     *
     * @type {*}
     * @memberof JQXTBYDGridView9Base
     */
    protected context:any = {};

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof JQXTBYDGridView9Base
     */
    protected viewparams:any = {};

    /**
     * 解析视图参数
     *
     * @private
     * @memberof JQXTBYDGridView9Base
     */
    private parseViewParam(): void {
        if (!this.viewDefaultUsage && this.viewdata && !Object.is(this.viewdata, '')) {
            Object.assign(this.context, JSON.parse(this.viewdata));
            return;
        }
        const path = (this.$route.matched[this.$route.matched.length - 1]).path;
        const keys: Array<any> = [];
        const curReg = this.$pathToRegExp.pathToRegexp(path, keys);
        const matchArray = curReg.exec(this.$route.path);
        let tempValue: Object = {};
        keys.forEach((item: any, index: number) => {
            Object.defineProperty(tempValue, item.name, {
                enumerable: true,
                value: matchArray[index + 1]
            });
        });
        this.$viewTool.formatRouteParams(tempValue,this.context,this.viewparams);
        //初始化视图唯一标识
        Object.assign(this.context,{srfsessionid:this.$util.createUUID()});
    }

    /**
     * Vue声明周期
     *
     * @memberof JQXTBYDGridView9Base
     */
    protected created() {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     * @memberof JQXTBYDGridView9Base
     */    
    protected afterCreated(){
        const secondtag = this.$util.createUUID();
        this.$store.commit('viewaction/createdView', { viewtag: this.viewtag, secondtag: secondtag });
        this.viewtag = secondtag;
        this.parseViewParam();
        if(this.formDruipart){
            this.formDruipart.subscribe((res:any) =>{
                if(Object.is(res.action,'save')){
                    let opt ={data:res.data};
                    Object.assign(opt,this.context);
                    this.viewState.next({ tag:'grid', action: 'save', data: opt });
                }
                if(Object.is(res.action,'load')){
                    let opt ={data:res.data};
                    Object.assign(opt,this.context);
                    this.viewState.next({ tag:'grid', action: 'load', data: opt });
                }
            });
        }

    }

    /**
     * 销毁之前
     *
     * @memberof JQXTBYDGridView9Base
     */
    protected beforeDestroy() {
        this.$store.commit('viewaction/removeView', this.viewtag);
    }

    /**
     * Vue声明周期(组件初始化完毕)
     *
     * @memberof JQXTBYDGridView9Base
     */
    protected mounted() {
        this.afterMounted();
    }

    /**
     * 执行mounted后的逻辑
     * 
     * @memberof JQXTBYDGridView9Base
     */
    protected afterMounted(){
        const _this: any = this;
        _this.engineInit();
        if (_this.loadModel && _this.loadModel instanceof Function) {
            _this.loadModel();
        }
        
    }


    /**
     * toolbar 部件 click 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof JQXTBYDGridView9Base
     */
    protected toolbar_click($event: any, $event2?: any) {
        if (Object.is($event.tag, 'tbitem1')) {
            this.toolbar_tbitem1_click($event, '', $event2);
        }
    }


    /**
     * grid 部件 selectionchange 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof JQXTBYDGridView9Base
     */
    protected grid_selectionchange($event: any, $event2?: any) {
        this.engine.onCtrlEvent('grid', 'selectionchange', $event);
    }


    /**
     * grid 部件 beforeload 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof JQXTBYDGridView9Base
     */
    protected grid_beforeload($event: any, $event2?: any) {
        this.engine.onCtrlEvent('grid', 'beforeload', $event);
    }


    /**
     * grid 部件 rowdblclick 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof JQXTBYDGridView9Base
     */
    protected grid_rowdblclick($event: any, $event2?: any) {
        this.engine.onCtrlEvent('grid', 'rowdblclick', $event);
    }


    /**
     * grid 部件 remove 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof JQXTBYDGridView9Base
     */
    protected grid_remove($event: any, $event2?: any) {
        this.engine.onCtrlEvent('grid', 'remove', $event);
    }


    /**
     * grid 部件 load 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof JQXTBYDGridView9Base
     */
    protected grid_load($event: any, $event2?: any) {
        this.engine.onCtrlEvent('grid', 'load', $event);
    }



    /**
     * 逻辑事件
     *
     * @param {*} [params={}]
     * @param {*} [tag]
     * @param {*} [$event]
     * @memberof 
     */
    protected toolbar_tbitem1_click(params: any = {}, tag?: any, $event?: any) {
        // 参数

        // 取数
        let datas: any[] = [];
        let xData: any = null;
        // _this 指向容器对象
        const _this: any = this;
        let paramJO:any = {};
        
        let contextJO:any = {};
        xData = this.$refs.grid;
        if (xData.getDatas && xData.getDatas instanceof Function) {
            datas = [...xData.getDatas()];
        }
        // 界面行为
        this.NewRow(datas, paramJO,  $event, xData);
    }

    
    /**
     * 打开新建数据视图
     *
     * @param {any[]} args
     * @param {*} [params]
     * @param {*} [$event]
     * @param {*} [xData]
     * @memberof JQXTBYDGridView9
     */
    protected newdata(args: any[], params?: any, $event?: any, xData?: any) {
        const data: any = {};
        let curViewParam = JSON.parse(JSON.stringify(this.context));
        if(args.length >0){
            Object.assign(curViewParam,args[0]);
        }
        let deResParameters: any[] = [];
        deResParameters = [
            { pathName: 'cids', parameterName: 'cid' },
        ];
        const parameters: any[] = [
            { pathName: 'jqxtbyds', parameterName: 'jqxtbyd' },
        ];
        const _this: any = this;
        const openPopupModal = (view: any, data: any) => {
            let container: Subject<any> = this.$appmodal.openModal(view, curViewParam, data);
            container.subscribe((result: any) => {
                if (!result || !Object.is(result.ret, 'OK')) {
                    return;
                }
                if (!xData || !(xData.refresh instanceof Function)) {
                    return;
                }
                xData.refresh(result.datas);
            });
        }
        const view: any = {
            viewname: 'jqxtbydedit-view', 
            height: 0, 
            width: 0,  
            title: '交强险特别约定编辑视图', 
        };
        openPopupModal(view, data);
    }


    /**
     * 打开编辑数据视图
     *
     * @param {any[]} args
     * @param {*} [params]
     * @param {*} [$event]
     * @param {*} [xData]
     * @memberof JQXTBYDGridView9
     */
    protected opendata(args: any[], params?: any, $event?: any, xData?: any) {
        const data: any = {};
        let curViewParam = JSON.parse(JSON.stringify(this.context));
        if(args.length >0){
            Object.assign(curViewParam,args[0]);
        }
        let deResParameters: any[] = [];
        deResParameters = [
            { pathName: 'cids', parameterName: 'cid' },
        ];
        const parameters: any[] = [
            { pathName: 'jqxtbyds', parameterName: 'jqxtbyd' },
        ];
        const _this: any = this;
        const openPopupModal = (view: any, data: any) => {
            let container: Subject<any> = this.$appmodal.openModal(view, curViewParam, data);
            container.subscribe((result: any) => {
                if (!result || !Object.is(result.ret, 'OK')) {
                    return;
                }
                if (!xData || !(xData.refresh instanceof Function)) {
                    return;
                }
                xData.refresh(result.datas);
            });
        }
        const view: any = {
            viewname: 'jqxtbydedit-view', 
            height: 0, 
            width: 0,  
            title: '交强险特别约定编辑视图', 
        };
        openPopupModal(view, data);
    }


    /**
     * 新建行
     *
     * @param {any[]} args
     * @param {*} [params]
     * @param {*} [$event]
     * @param {*} [xData]
     * @memberof JQXTBYDGridView9Base
     */
    protected NewRow(args: any[], params?: any, $event?: any, xData?: any) {
        const _this: any = this;
        const data: any = {};
        if (_this.newRow && _this.newRow instanceof Function) {
            _this.newRow([{ ...data }], params, $event, xData);
        } else if(xData.newRow && xData.newRow instanceof Function) {
            xData.newRow([{ ...data }], params, $event, xData);
        }else{
            _this.$Notice.error({ title: '错误', desc: 'newdata 视图处理逻辑不存在，请添加!' });
        }
    }

    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof JQXTBYDGridView9Base
     */
    protected closeView(args: any[]): void {
        let _view: any = this;
        if (_view.viewdata) {
            _view.$emit('viewdataschange', [args]);
            _view.$emit('close', [args]);
        } else if (_view.$tabPageExp) {
            _view.$tabPageExp.onClose(_view.$route.fullPath);
        }
    }


    /**
     * 是否单选
     *
     * @type {boolean}
     * @memberof JQXTBYDGridView9Base
     */
    public isSingleSelect: boolean = false;

    /**
    * 界面关系通讯对象
    *
    * @type {Subject<ViewState>}
    * @memberof JQXTBYDGridView9Base
    */
    @Prop() public formDruipart?: Subject<ViewState>;

    /**
     * 搜索值
     *
     * @type {string}
     * @memberof JQXTBYDGridView9Base
     */
    public query: string = '';

    /**
     * 是否展开搜索表单
     *
     * @type {boolean}
     * @memberof JQXTBYDGridView9Base
     */
    public isExpandSearchForm: boolean = false;

    /**
     * 表格行数据默认激活模式
     * 0 不激活
     * 1 单击激活
     * 2 双击激活
     *
     * @type {(number | 0 | 1 | 2)}
     * @memberof JQXTBYDGridView9Base
     */
    public gridRowActiveMode: number | 0 | 1 | 2 = 2;

    /**
     * 快速搜索
     *
     * @param {*} $event
     * @memberof JQXTBYDGridView9Base
     */
    public onSearch($event: any): void {
        const grid: any = this.$refs.grid;
        if (grid) {
            grid.load(this.context);
        }
    }

    /**
     * grid 部件 save 事件
     *
     * @param {*} [args={}]
     * @param {*} $event
     * @memberof ENTITYTEST1Usr2GridViewBase
     */
    public onSave($event: any) {
        this.$emit('drdatasaved', $event);
    }

    /**
     * 刷新数据
     *
     * @readonly
     * @type {(number | null)}
     * @memberof JQXTBYDGridView9Base
     */
    get refreshdata(): number | null {
        return this.$store.getters['viewaction/getRefreshData'](this.viewtag);
    }

    /**
     * 监控数据变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @returns
     * @memberof JQXTBYDGridView9Base
     */
    @Watch('refreshdata')
    onRefreshData(newVal: any, oldVal: any) {
        if (newVal === null || newVal === undefined) {
            return;
        }
        if (newVal === 0) {
            return;
        }
        const grid: any = this.$refs.grid;
        if (grid) {
            grid.load({});
        }
    }

}
</script>

<style lang='less'>
@import './jqxtbydgrid-view9.less';
</style>