<template>
<div class="app-gantt">
  <gantt-elastic v-if="tasks.length >0" :class="ganttClass" :tasks="tasks" :options="getOptions(this.locale)" :dynamic-style="dynamicStyle" @taskList-item-dblclick="taskClick" @task-item-expand="taskItemExpand">
  </gantt-elastic>
  <div v-else class="app-data-empty">{{'暂无数据'}}</div>
</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 GanttTreeService from './gantt-tree-gantt-service';
import IBIZOrderUIService from '@/uiservice/ibizorder/ibizorder-ui-service';
import GanttElastic from "ibiz-gantt-elastic/src/GanttElastic.vue";


@Component({
    components: {
      GanttElastic,

    }
})
export default class GanttTreeBase extends Vue implements ControlInterface {

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

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

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

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

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

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

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

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

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



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

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

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


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

    /**
     *  计数器刷新
     *
     * @memberof GanttTreeBase
     */
    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 GanttTreeBase
     */
    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 {boolean}
     * @memberof GanttTreeBase
     */
    @Prop({ default: true }) public showBusyIndicator?: boolean;

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

    /**
     * 部件样式名
     *
     * @public
     * @type {any[]}
     * @memberof GanttTreeBase
     */
    public ganttClass: string = "gantt";

     /**
     * 语言
     *
     * @public
     * @type {string}
     * @memberof GanttTreeBase
     */  
    public locale: string = 'zh-CN';

     /**
     * 语言资源
     *
     * @public
     * @type {any[]}
     * @memberof GanttTreeBase
     */   
    public localeZH: any =  {
        weekdays: ['星期一','星期二','星期三','星期四','星期五','星期六','星期日'],
        months: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
        Now: "现在",
        "X-Scale": "时间颗粒度",
        "Display task list": "显示列表",
        "Before/After": "数据范围"
    }

    /**
     * 配置参数
     *
     * @public
     * @type {any[]}
     * @memberof GanttTreeBase
     */
    public options: any = {
        isflex: true,
        maxRows: 1000,
        dataType: 'treegrid',
        title: {
            label: ""
        },
        header: {
            yScole: false,
            taskListWidth: false,
        },
        calendar: {
            hour: {
                display: false
            }
        },
        chart: {
            progress: {
                bar: false
            },
            expander: {
                display: true
            },
        },
        taskList: {
            expander: {
                straight: false
            },
            labelField: 'text',
            columns: [
                {
                    label: '名称',
                    value: 'name',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'name')
                    },
                    width: 280,
                },
                {
                    label: '标识',
                    value: 'datakey',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'datakey')
                    },
                    width: 280,
                },
                {
                    label: '更新日期',
                    value: 'end',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'end')
                    },
                    width: 280,
                },
                {
                    label: '新建时间',
                    value: 'start',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'start')
                    },
                    width: 280,
                },
            ]
        }
    };

    /**
     * 样式
     *
     * @public
     * @type {any[]}
     * @memberof GanttTreeBase
     */
    public dynamicStyle: any = {};

    /**
     * 日程事件集合
     *
     * @public
     * @type {any[]}
     * @memberof GanttTreeBase
     */
    public tasks: any[] = [];

    /**
     * 应用状态事件
     *
     * @public
     * @type {(Subscription | undefined)}
     * @memberof GanttTreeBase
     */
    public appStateEvent: Subscription | undefined;

    /**
     * 监听语言变化
     *
     * @public
     * @memberof GanttTreeBase
     */
    @Watch('$i18n.locale')
    public onLocaleChange(newval: any, val: any) {
        this.locale = newval;
    }

    /**
     * 获取列属性值
     *
     * @public
     * @memberof GanttTreeBase
     */
    public getColumnValue(task: any, field: string) {
        if(Object.is(task.id.split(';')[0], 'orderData')) {
            return task[field];
        }
        if(Object.is(task.id.split(';')[0], 'ROOT')) {
            return task[field];
        }
        if(Object.is(task.id.split(';')[0], 'orderDetailData')) {
            return task[field];
        }
    }

    /**
     * 获取代码项
     *
     * @public
     * @memberof GanttTreeBase
     */
    public getCodeListItem(codelist: any, val: any) {
        for(let i = 0; i < codelist.items.length; i++) {
            if(Object.is(codelist.items[i].value, val)) {
                return codelist.items[i].text;
            }
        }
        return codelist.emptytext;
    }

    /**
     * 获取部件参数
     *
     * @returns {any}
     * @memberof GanttTreeBase
     */
    public getOptions() {
        if(Object.is(this.locale, 'zh-CN')) {
            return { locale: this.localeZH, ...this.options };
        }
        return this.options;
    }

    /**
     * 搜索获取日程事件
     *
     * @param {*} $event 日期信息
     * @memberof GanttTreeBase
     */
    public load(task: any = {}) {
        const params: any = {
            srfnodeid: task && task.id ? task.id : "#",
            srfnodefilter: ''
        };
        let tempViewParams:any = JSON.parse(JSON.stringify(this.viewparams));
        let curNode:any = {}; 
        Util.deepObjectMerge(curNode, task);
        let tempContext:any = this.computecurNodeContext(curNode);
        if(curNode && curNode.srfparentdename) {
            Object.assign(tempContext,{ srfparentdename: curNode.srfparentdename });
            Object.assign(tempViewParams,{ srfparentdename: curNode.srfparentdename });
        }
        if(curNode && curNode.srfparentkey) {
            Object.assign(tempContext,{ srfparentkey: curNode.srfparentkey });
            Object.assign(tempViewParams,{ srfparentkey: curNode.srfparentkey });
        }
        Object.assign(params,{viewparams:tempViewParams});
        this.service.getNodes(tempContext,params).then((response: any) => {
            if (!response || response.status !== 200) {
                this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: response.info });
                return;
            }
            this.tasks = [...this.tasks, ...response.data];
            response.data.forEach((item: any) => {
                if(!item.collapsed) {
                    this.load(item);
                }
            })
            this.$emit("load", this.tasks);
        }).catch((response: any) => {
            if (response && response.status === 401) {
                return;
            }
            this.$Notice.error({ title: (this.$t('app.commonWords.wrong') as string), desc: response.info });
        });
    }

    /**
     * 计算当前节点的上下文
     *
     * @param {*} curNode 当前节点
     * @memberof GanttTreeBase
     */
    public computecurNodeContext(curNode:any){
        let tempContext:any = {};
        if(curNode && curNode.data && curNode.data.srfappctx){
            tempContext = JSON.parse(JSON.stringify(curNode.data.srfappctx));
        }else{
            tempContext = JSON.parse(JSON.stringify(this.context));
        }
        return tempContext;
    }

    /**
     * 节点展开
     *
     * @param {*} task 当前节点
     * @memberof GanttTreeBase
     */
    public taskItemExpand(task: any) {
        if(!task.collapsed) {
            let index: number = this.tasks.findIndex((item: any) => Object.is(task.id, item.parentId));
            if(index < 0) {
                this.load(task);
            }
        }
    }

    /**
     * 刷新
     *
     * @memberof GanttTreeBase
     */
    public refresh(args?: any) {
        this.load();
    }



    /**
     * 选中的数据
     *
     * @returns {any[]}
     * @memberof GanttTreeBase
     */
    public selections: any[] = [];

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

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof GanttTreeBase
     */
    public getData(): any {
        return null;
    }
             
    /**
     * vue 生命周期
     *
     * @returns
     * @memberof GanttTreeBase
     */
    public created() {
        this.afterCreated();
    }

    /**
     * 执行created后的逻辑
     *
     * @memberof GanttTreeBase
     */
    public afterCreated() {
        this.locale = this.$i18n.locale;
        if(AppCenterService && AppCenterService.getMessageCenter()){
            this.appStateEvent = AppCenterService.getMessageCenter().subscribe(({ name, action, data }) =>{
                if(!Object.is(name,"IBIZOrder")){
                    return;
                }
                if(Object.is(action,'appRefresh')){
                    this.refresh();
                }
            })
        }
        this.viewStateEvent = this.viewState.subscribe(({ tag, action, data }) => {
            if (!Object.is(tag, this.name)) {
                return;
            }
            if (Object.is('load', action)) {
                this.load(data);
            }
        });
    } 

    /**
     * 点击事件
     *
     * @returns
     * @memberof GanttTreeBase
     */
    public taskClick({event, data}: {event: any, data: any}) {
        const _this: any = this;
        let key: string = data.id.split(';')[0];
        if(_this[key + '_opendata'] instanceof Function) {
            _this[key + '_opendata']([data]);
        }
    }

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

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

}
</script>

<style lang='scss'>
@import './gantt-tree-gantt.scss';
</style>