<template>
    <div class='view-container orgpickup-tree-view'>
        <card class='view-card view-no-caption' :dis-hover="true" :bordered="false">
            <div class='content-container'>
                <div class="tree-contant">
                <view_tree 
                    :viewState="viewState"  
                    :viewparams="viewparams" 
                    :context="context" 
                    :showBusyIndicator="true"
                    name="tree"  
                    ref='tree' 
                    @selectionchange="tree_selectionchange($event)"  
                    @load="tree_load($event)"  
                    @closeview="closeView($event)">
                </view_tree>
                </div>
                <card v-if="ifShowButtons" :dis-hover="true" :bordered="false" class="footer">
                    <row :style="{ textAlign: 'right' }">
                        <i-button type="primary" :disabled="this.viewSelections.length > 0 ? false : true"  @click="onClickOk">确定</i-button>
                            &nbsp;&nbsp;
                        <i-button @click="onClickCancel">取消</i-button>
                    </row>
                </card>
            </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 ORGService from '@/service/org/org-service';

import PickupTreeViewEngine from '@engine/view/pickup-tree-view-engine';



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

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

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

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

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

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

	/**
	 * 视图标识
	 *
	 * @type {string}
	 * @memberof ORGPickupTreeViewBase
	 */
	protected viewtag: string = 'fb64841789cb49b6e8df3c74de787c50';

    /**
     * 视图模型数据
     *
     * @type {*}
     * @memberof ORGPickupTreeViewBase
     */
    protected model: any = {
        srfTitle: '机构选择树视图',
        srfCaption: 'org.views.pickuptreeview.caption',
        srfSubCaption: '',
        dataInfo: ''
    }

    /**
     * 视图参数变化
     *
     * @param {*} newVal
     * @param {*} oldVal
     * @memberof ORGPickupTreeViewBase
     */
    @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 ORGPickupTreeViewBase
     */
    @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 ORGPickupTreeViewBase
     */
    protected containerModel: any = {
        view_tree: { name: 'tree', type: 'TREEVIEW' },
    };

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


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

    /**
     * 引擎初始化
     *
     * @private
     * @memberof ORGPickupTreeViewBase
     */
    private engineInit(): void {
        this.engine.init({
            view: this,
            tree: this.$refs.tree,
            keyPSDEField: 'org',
            majorPSDEField: 'orgname',
            isLoadDefault: true,
        });
    }

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

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

    /**
     * 解析视图参数
     *
     * @private
     * @memberof ORGPickupTreeViewBase
     */
    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 ORGPickupTreeViewBase
     */
    protected created() {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     * @memberof ORGPickupTreeViewBase
     */    
    protected afterCreated(){
        const secondtag = this.$util.createUUID();
        this.$store.commit('viewaction/createdView', { viewtag: this.viewtag, secondtag: secondtag });
        this.viewtag = secondtag;
        this.parseViewParam();
        
    }

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

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

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


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


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




    /**
     * 关闭视图
     *
     * @param {any[]} args
     * @memberof ORGPickupTreeViewBase
     */
    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);
        }
    }

    /**
     * 销毁视图回调
     *
     * @memberof ORGPickupTreeViewBase
     */
    protected destroyed(){
        this.afterDestroyed();
    }

    /**
     * 执行destroyed后的逻辑
     * 
     * @memberof ORGPickupTreeViewBase
     */
    protected afterDestroyed(){
        if(this.viewDefaultUsage){
            let localStoreLength = Object.keys(localStorage);
            if(localStoreLength.length > 0){
                localStoreLength.forEach((item:string) =>{
                if(item.startsWith(this.context.srfsessionid)){
                    localStorage.removeItem(item);
                }
                })
            }
        }
    }

    /**
     * 是否显示按钮
     *
     * @type {boolean}
     * @memberof ORGPickupTreeView
     */
    @Prop({default: true}) public ifShowButtons!: boolean;

    /**
     * 节点过滤值
     *
     * @type {string}
     * @memberof ORGPickupTreeView
     */
    public srfnodefilter: string = '';

    /**
     * 快速搜索
     *
     * @returns {void}
     * @memberof ORGPickupTreeView
     */
    public onSearch(): void {
        if (!this.viewState) {
            return;
        }
        this.viewState.next({ tag: 'tree', action: 'filter', data: { srfnodefilter: this.srfnodefilter } });
    }

     /**
     * 视图选中数据
     *
     * @type {any[]}
     * @memberof ENTITYTEST1PickupView
     */
    public viewSelections:any[] = [];

     /**
     * 确定
     *
     * @memberof ENTITYTEST1PickupView
     */
    public onClickOk(): void {
        this.$emit('viewdataschange', this.viewSelections);
        this.$emit('close', null);
    }

    /**
     * 取消
     *
     * @memberof ENTITYTEST1PickupView
     */
    public onClickCancel(): void {
        this.$emit('close', null);
    }

}
</script>

<style lang='less'>
@import './orgpickup-tree-view.less';
</style>