<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">{{$t('entities.ibizbook.usr_gantt.nodata')}}</div>
</div>
</template>


<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 IBIZBOOKService from '@/service/ibizbook/ibizbook-service';
import UsrService from './usr-gantt-service';
import IBIZBOOKUIService from '@/uiservice/ibizbook/ibizbook-ui-service';
import GanttElastic from "ibiz-gantt-elastic/src/GanttElastic.vue";


@Component({
    components: {
      GanttElastic,

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

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

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

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

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

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

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



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

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

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


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

    /**
     *  计数器刷新
     *
     * @memberof UsrBase
     */
    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();
                }
            })
        }
    }



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

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

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

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

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

    /**
     * 配置参数
     *
     * @public
     * @type {any[]}
     * @memberof UsrBase
     */
    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: 'lendouttime',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'lendouttime')
                    },
                    width: 200,
                },
                {
                    label: '归还日期',
                    value: 'returntime',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'returntime')
                    },
                    width: 200,
                },
                {
                    label: '图书名称',
                    value: 'ibizbookname',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'ibizbookname')
                    },
                    width: 200,
                },
                {
                    label: '出版社',
                    value: 'press',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'press')
                    },
                    width: 200,
                },
                {
                    label: '作者',
                    value: 'author',
                    render: (task: any) => {
                        return this.getColumnValue(task, 'author')
                    },
                    width: 200,
                },
            ]
        }
    };

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

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

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

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

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

    /**
     * 获取代码项
     *
     * @public
     * @memberof UsrBase
     */
    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 UsrBase
     */
    public getOptions() {
        if(Object.is(this.locale, 'zh-CN')) {
            return { locale: this.localeZH, ...this.options };
        }
        return this.options;
    }

    /**
     * 搜索获取日程事件
     *
     * @param {*} $event 日期信息
     * @memberof UsrBase
     */
    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 UsrBase
     */
    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 UsrBase
     */
    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 UsrBase
     */
    public refresh(args?: any) {
        this.load();
    }



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

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

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

    /**
     * 执行created后的逻辑
     *
     * @memberof UsrBase
     */
    public afterCreated() {
        this.locale = this.$i18n.locale;
        if(AppCenterService && AppCenterService.getMessageCenter()){
            this.appStateEvent = AppCenterService.getMessageCenter().subscribe(({ name, action, data }) =>{
                if(!Object.is(name,"IBIZBOOK")){
                    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 UsrBase
     */
    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 UsrBase
     */
    public destroyed() {
        this.afterDestroy();
    }

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

}
</script>

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