<template>
    <div class="design-tree-container">
        <context-menu-container>
            <el-tree
            v-if="inited"
            ref="treeexpbar_tree"
            class="design-tree"
            node-key="id"
            lazy
            :default-expanded-keys="expandedKeys"
            :props="{
                label: 'text',
                isLeaf: 'leaf'
            }"
            :load="load"
            :highlight-current="true"
            :expand-on-click-node="false"
            @current-change="selectionChange"
            :filter-node-method="filterNode"
            >
                <div slot-scope="{ node, data }">
                <!-- <context-menu contextMenuStyle={{ width: '100%' }} data={node} renderContent={this.renderContextMenu}> -->
                    <tooltip transfer style="width: 100%;" max-width="2000" placement="right">
                        <div class="tree-node" @dblclick="doDefaultAction(node)">
                            <span class="icon">
                                <i v-if=" data.iconcls && !Object.is(data.iconcls, '')" :class="data.iconcls"></i>
                                <img v-else-if="data.icon && !Object.is(data.icon, '')" :src="data.icon" />
                                <icon v-else-if="isOutputIconDefault" type="ios-paper-outline"></icon>&nbsp;
                            </span>
                            <span class="text">
                                <span v-if="data.html" v-html="data.html"></span>
                                <span v-else>{{data.text}}</span>
                            </span>
                        </div>
                        <template slot="content">
                            <span v-if="data.html" v-html="data.html"></span>
                            <span v-else>{{ data.text }}</span>
                        </template>
                    </tooltip>
                <!-- </context-menu> -->
                </div>
            </el-tree>
        </context-menu-container>
    </div>
</template>
<script lang='ts'>
import { Vue, Component, Prop, Provide, Emit, Watch, Model } from 'vue-property-decorator';
import { CreateElement } from 'vue';
import { Subject, Subscription } from 'rxjs';
import { ControlInterface } from '@/interface/control';
import { UICounter,UIActionTool } from '@/utils';
import ORGService from '@/service/org/org-service';
import UsrService from './usr-treeview-service';



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

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

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

    /**
     * 应用上下文
     *
     * @type {*}
     * @memberof Usr
     */
    @Prop() protected context: any;

    /**
     * 视图参数
     *
     * @type {*}
     * @memberof Usr
     */
    @Prop() protected viewparams: any;

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

    /**
     * 获取部件类型
     *
     * @returns {string}
     * @memberof Usr
     */
    protected getControlType(): string {
        return 'TREEVIEW'
    }

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

    /**
     * 实体服务对象
     *
     * @type {ORGService}
     * @memberof Usr
     */
    protected appEntityService: ORGService = new ORGService({ $store: this.$store });
    


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


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

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

    /**
     * 显示处理提示
     *
     * @type {boolean}
     * @memberof Usr
     */
    @Prop({ default: true }) protected showBusyIndicator?: boolean;

    /**
     * 初始化完成
     *
     * @type {boolean}
     * @memberof Usr
     */
    protected inited: boolean = false;

    /**
     * 选中数据
     *
     * @type {*}
     * @memberof Usr
     */
    protected selectData: any = {};

    /**
     * 部件行为--update
     *
     * @type {string}
     * @memberof Usr
     */
    @Prop() protected updateAction!: string;

    /**
     * 部件行为--fetch
     *
     * @type {string}
     * @memberof Usr
     */
    @Prop() protected fetchAction!: string;

    /**
     * 部件行为--remove
     *
     * @type {string}
     * @memberof Usr
     */
    @Prop() protected removeAction!: string;

    /**
     * 部件行为--load
     *
     * @type {string}
     * @memberof Usr
     */
    @Prop() protected loadAction!: string;

    /**
     * 部件行为--create
     *
     * @type {string}
     * @memberof Usr
     */
    @Prop() protected createAction!: string;

    /**
     * 父数据
     *
     * @type {*}
     * @memberof Usr
     */
    protected parentData: any = {};

    /**
     * 过滤属性
     *
     * @type {string}
     * @memberof Usr
     */
    protected srfnodefilter: string = '';

    /**
     * 默认输出图标
     *
     * @type {boolean}
     * @memberof Usr
     */
    protected isOutputIconDefault: boolean = true;

    /**
     * 树数据
     *
     * @type {any[]}
     * @memberof Usr
     */
    @Provide()
    protected nodes: any[] = [];

    /**
     * 数据展开主键
     *
     * @type {string[]}
     * @memberof Usr
     */
    @Provide()
    protected expandedKeys: string[] = [];

    /**
     * 选中数据变更事件
     *
     * @private
     * @param {*} data
     * @memberof Usr
     */
    private selectionChange(data: any, node: any) {
        this.selectData = {};
        if (data.disableselect) {
            node.isCurrent = false;
            this.$emit('selectionchange', []);
            return;
        }
        Object.assign(this.selectData, data);
        this.$emit('selectionchange', [this.selectData]);
    }

    /**
     * Vue声明周期(处理组件的输入属性)
     *
     * @memberof Usr
     */
    protected created() {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     *  @memberof Usr
     */    
    protected afterCreated(){
        if (this.viewState) {
            this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
                if (!Object.is(tag, this.name)) {
                    return;
                }
                if (Object.is('load', action)) {
                    if (data) {
                        Object.assign(this.parentData, data);
                    }
                    this.inited = false;
                    this.$nextTick(() => {
                        this.inited = true;
                    });
                }
                if (Object.is('filter', action)) {
                    this.srfnodefilter  = data.srfnodefilter;
                    // this.inited = false;
                    // this.$nextTick(() => {
                    //     this.inited = true;
                    // });
                    (this.$refs.tree as any).filter(this.srfnodefilter);
                }
                if (Object.is('refresh_parent', action)) {
                    this.refresh_parent();
                }
            });
        }
    }

    /**
     * 对树节点进行筛选操作
     * @memberof OrderTree
     */
    protected filterNode(value:any, data:any) {
        if (!value) return true;
        return data.text.indexOf(value) !== -1;
    }


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

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

    /**
     * 刷新数据
     *
     * @memberof Usr
     */
    protected refresh_all(): void {
        this.inited = false;
        this.$nextTick(() => {
            this.inited = true;
        });
    }

    /**
     * 刷新父节点
     *
     * @memberof Usr
     */
    protected refresh_parent(): void {
        if (Object.keys(this.selectData).length === 0) {
            return;
        }
        const tree: any = this.$refs.treeexpbar_tree;
        const node: any = tree.getNode(this.selectData.id);
        if (!node || !node.parent) {
            return;
        }
        const { parent: _parent } = node;
        const id: string = _parent.key ? _parent.key : '#';
        const param: any = { srfnodeid: id };
        Object.assign(param, this.parentData);
        this.refresh_node(param, true);
    }

    /**
     * 数据加载
     *
     * @param {*} node
     * @memberof Usr
     */
    protected load(node: any = {}, resolve?: any) {
        if (node.data && node.data.children) {
            resolve(node.data.children);
            return;
        }
        const params: any = {
            srfnodeid: node.data && node.data.id ? node.data.id : "#",
            srfnodefilter: this.srfnodefilter
        };
        Object.assign(params, this.parentData);
        Object.assign(params,this.viewparams);
        this.service.getNodes(this.context,params).then((response: any) => {
            if (!response || response.status !== 200) {
                this.$Notice.error({ title: "错误", desc: response.info });
                resolve([]);
                return;
            }
            const _items = response.data.records;
            this.formatExpanded(_items);
            if (!node.level || node.level === 0) {
                this.nodes = [..._items];
            }
            this.nodes = response.data.records;
            resolve([..._items]);
            //this.setDefaultSelection(_items);
            this.$emit("load", _items);
        }).catch((response: any) => {
            resolve([]);
            if (response && response.status === 401) {
                return;
            }
            this.$Notice.error({ title: "错误", desc: response.info });
        });
    }

    /**
     * 刷新功能
     *
     * @param {any[]} args
     * @memberof Usr
     */
    protected refresh(args: any[]): void {
        if (Object.keys(this.selectData).length === 0) {
            return;
        }
        const id: string = this.selectData.id;
        const param: any = { srfnodeid: id };
        Object.assign(param, this.parentData);
        this.refresh_node(param, false);
    }

    /**
     * 刷新节点
     *
     * @private
     * @param {*} [arg={}]
     * @param {boolean} parentnode
     * @memberof Usr
     */
    private refresh_node(arg: any = {}, parentnode: boolean): void {
        const { srfnodeid: id } = arg;
        Object.assign(arg,this.viewparams);
        const get: Promise<any> = this.service.getNodes(this.context,arg);
        get.then((response: any) => {
            if (!response || response.status !== 200) {
                this.$Notice.error({ title: '错误', desc: response.info });
                return;
            }
            const _items = [...response.data];
            this.formatExpanded(_items);
            const tree: any = this.$refs.tree;
            tree.updateKeyChildren(id, _items);
            if (parentnode) {
                this.selectData = {};
            }
            //this.setDefaultSelection(_items);
        }).catch((response: any) => {
            if (response && response.status === 401) {
                return;
            }
            this.$Notice.error({ title: '错误', desc: response.info });
        });
    }

    /**
     * 格式化数据
     *
     * @private
     * @param {any[]} items
     * @returns {any[]}
     * @memberof Usr
     */
    private formatExpanded(items: any[]): any[] {
        const data: any[] = [];
        items.forEach((item) => {
            if (item.expanded || (item.children && item.children.length > 0)) {
                this.expandedKeys.push(item.id);
            }
        });
        return data;
    }

    /**
     * 设置默认选中
     *
     * @param {any[]} items
     * @memberof Usr
     */
    protected setDefaultSelection(items: any[]): void {
        const index = items.findIndex((item: any) => item.selected);
        if(index === -1) {
            return ;
        }
        const data = items[index];
        this.setTreeNodeHighLight(data);
        this.$emit('selectionchange', [this.selectData]);
    } 

    /**
     * 设置选中项
     *
     * @param {*} data
     * @memberof Usr
     */
    protected setTreeNodeHighLight(data: any): void {
        this.selectData = {};
        Object.assign(this.selectData, data);
        const tree: any = this.$refs.tree;
        tree.setCurrentKey(data.id);
    }

    /**
     * 绘制右击菜单
     *
     * @param {*} node
     * @returns
     * @memberof Usr
     */
    protected renderContextMenu(node: any) {
        let content;
        if (node && node.data) {
            const data: any = node.data;
            this.selectData = { ...data };
            const tags: string[] = data.id.split(';');
        }
        return content;
    }

    /**
     * 执行默认界面行为
     *
     * @param {*} node
     * @memberof AppView
     */
    protected doDefaultAction(node: any) {
        if (node && node.data) {
            const data: any = node.data;
            const tags: string[] = data.id.split(';');
        }
    }

}
</script>

<style lang='less'>
@import './usr-treeview.less';
</style>