<template>
    <div class='app-dr-bar' :style="{ width: `${width}px` }">
        <el-menu
            :mode="menuDir"
            :default-openeds="defaultOpeneds"
            :default-active="selection ? selection.id : ''"
            @select="onSelect"
            @open="onOpen"
            @close="onClose">
            <app-sider-menus :menus="items"></app-sider-menus>
        </el-menu>
    </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  DemoIBIZORDERCounterService  from '@/counter/demo-ibizorder/demo-ibizorder-counter';
import IBIZOrderEntityService from '@/service/ibizorder/ibizorder-service';
import DefaultService from './default-drbar-service';
import IBIZOrderUIService from '@/uiservice/ibizorder/ibizorder-ui-service';


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

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

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

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

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

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

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

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

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

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


    
    /**
     * DemoIBIZORDERCounterService计数器服务对象
     *
     * @type {DemoIBIZORDERCounterService}
     * @memberof DefaultBase
     */
    public demoibizordercounterservice: DemoIBIZORDERCounterService = new DemoIBIZORDERCounterService({context:this.context,viewparams:this.viewparams});

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

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

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


    /**
     * 转化数据
     *
     * @param {any} args
     * @memberof  DefaultBase
     */
    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 DefaultBase
     */
    public closeView(args: any): void {
        let _this: any = this;
        _this.$emit('closeview', [args]);
    }

    /**
     *  计数器刷新
     *
     * @memberof DefaultBase
     */
    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 DefaultBase
     */
    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 {('horizontal' | 'vertical')}
     * @memberof DefaultBase
     */
    @Prop({ default: 'vertical' }) public menuDir?: 'horizontal' | 'vertical';

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

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof DefaultBase
     */
    public getData(): any {
        return this.selection;
    }

    /**
     * 加载行为
     *
     * @type {string}
     * @memberof DefaultBase
     */
    @Prop() public loadAction?: string;

    /**
     *  表单数据
     *
     * @type {*}
     * @memberof DefaultBase
     */
    public formData: any = {};

    /**
     * 数据选中项
     *
     * @type {*}
     * @memberof DefaultBase
     */
    public selection: any = {};

    /**
     * 关系栏数据项
     *
     * @type {any[]}
     * @memberof DefaultBase
     */
    public items: any[] = [
        {
            text: '详细信息',
            id: 'a7c7923d37319b42645a41908d62bae9',
            name: 'a7c7923d37319b42645a41908d62bae9',
            codeName: 'a7c7923d37319b42645a41908d62bae9',
            hidden: false,
            items: [
                {
                    text: "订单明细",
                    disabled: false,
                    id: "dritem2",
                    groupCodeName: 'a7c7923d37319b42645a41908d62bae9',
                    navView: 'ibizorder-detail-sgrid-view',
                    localContext:{CONTEXTPARAM1:"%orderstate%"},
                    localViewParam:{param2:"%orderstate%"}
                },
            ]
        },
    ]

    /**
     * 默认打开项
     *
     * @type {string[]}
     * @memberof DefaultBase
     */
    public defaultOpeneds: string[] = [];

    /**
     * 父数据
     *
     * @public
     * @type {*}
     * @memberof DefaultBase
     */
    public parentData: any = {};

    /**
     * 宽度
     *
     * @type {number}
     * @memberof DefaultBase
     */
    public width: number = 240;

    /**
     * 生命周期
     *
     * @memberof DefaultBase
     */
    public created(): void {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     *  @memberof DefaultBase
     */    
    public afterCreated(){
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(tag, this.name)) {
                    return;
                }
                if (Object.is('state', action)) {
                    this.handleFormChange(data);
                }
                if (Object.is('change', action)) {
                    this.selection = data;
                }
            });
        }
    }

    /**
     * vue 生命周期
     *
     * @memberof DefaultBase
     */
    public destroyed() {
        this.afterDestroy();
    }

    /**
     * 执行destroyed后的逻辑
     *
     * @memberof DefaultBase
     */
    public afterDestroy() {
        if (this.viewStateEvent) {
            this.viewStateEvent.unsubscribe();
        }
    }

    /**
     * 处理数据
     *
     * @public
     * @param {any[]} items
     * @memberof DefaultBase
     */
    public dataProcess(items: any[]): void {
        items.forEach((_item: any) => {
            if (_item.expanded) {
                this.defaultOpeneds.push(_item.id);
            }

            _item.disabled = false;
            if (_item.items && Array.isArray(_item.items) && _item.items.length > 0) {
                this.dataProcess(_item.items);
            }
        });
    }

    /**
     * 获取子项
     *
     * @param {any[]} items
     * @param {string} id
     * @returns {*}
     * @memberof DefaultBase
     */
    public getItem(items: any[], id: string): any {
        const item: any = {};
        items.some((_item: any) => {
            if (Object.is(_item.id, id)) {
                Object.assign(item, _item);
                return true;
            }
            if (_item.items && _item.items.length > 0) {
                const subItem = this.getItem(_item.items, id);
                if (Object.keys(subItem).length > 0) {
                    Object.assign(item, subItem);
                    return true;
                }
            }
            return false;
        });
        return item;
    }

    /**
     * 节点选中
     *
     * @param {*} $event
     * @memberof DefaultBase
     */
    public onSelect(key: string): void {
        if (key === this.selection.id) {
            return;
        }
        const selectItem = this.getItem(this.items, key);
        if (!selectItem) {
            return;
        }
        const tempContext = Util.deepCopy(this.context);
        const tempViewParams = Util.deepCopy(this.viewparams);
        if (selectItem.localContext && Object.keys(selectItem.localContext).length > 0) {
            const _context: any = this.$util.computedNavData(this.formData, tempContext, tempViewParams, selectItem.localContext);
            Object.assign(tempContext, _context);
        }
        if (this.formData.srfparentkey) {
           Object.assign(tempContext, { srfparentkey: this.formData.srfparentkey });
           Object.assign(tempViewParams, { srfparentkey: this.formData.srfparentkey });
        }
        if (selectItem.localViewParam && Object.keys(selectItem.localViewParam).length > 0) {
            const _params: any = this.$util.computedNavData(this.formData, tempContext, tempViewParams, selectItem.localViewParam);
            Object.assign(tempViewParams, _params);
        }
        if (this.formData.srfparentdename) {
            Object.assign(tempContext, { srfparentdename: this.formData.srfparentdename });
            Object.assign(tempViewParams, { srfparentdename: this.formData.srfparentdename });
        }
        const drItem = {
            id: selectItem.id,
            navView: selectItem.navView,
            srfnavdata: {
                context: tempContext,
                viewparams: tempViewParams
            }
        }
        this.$emit('selectionchange', drItem);
    }

    /**
     * 处理表单变化
     *
     * @param {*} $event
     * @memberof DefaultBase
     */
    public handleFormChange(args: any) {
        if (args && Object.is(args.srfuf, '1')) {
            this.setDisabled(this.items, false);
        } else {
            this.setDisabled(this.items, true);
        }
        this.formData = args;
    }

    /**
     * 子节点打开
     *
     * @param {*} $event
     * @memberof DefaultBase
     */
    public onOpen($event: any): void {
        const item = this.getItem(this.items, $event);
        if (Object.is(item.id, this.selection.id)) {
            return;
        }
        this.selection = {};
        Object.assign(this.selection, item);
        if (Object.is(item.id, 'form') || (item.viewname && !Object.is(item.viewname, ''))) {
            this.$emit('selectionchange', [this.selection]);
        }
    }

    /**
     * 子节点关闭
     *
     * @param {*} $event
     * @memberof DefaultBase
     */
    public onClose($event: any): void {
        const item = this.getItem(this.items, $event);
        if (Object.is(item.id, this.selection.id)) {
            return;
        }
        this.selection = {};
        Object.assign(this.selection, item);
        if (Object.is(item.id, 'form') || (item.viewname && !Object.is(item.viewname, ''))) {
            this.$emit('selectionchange', [this.selection]);
        }
    }

    /**
     * 设置禁用状态
     *
     * @memberof DefaultBase
     */
    public setDisabled(items: any[], state: boolean) {
        items.forEach((item: any) => {
            item.disabled = state;
            if (item && item.items && item.items.length > 0) {
                this.setDisabled(item.items, state);
            }
        })
    }

}
</script>

<style lang='less'>
@import './default-drbar.less';
</style>