import { Component, OnInit,EventEmitter,Input,Output,ViewContainerRef, ViewChild,OnDestroy} from '@angular/core';
import { Subject } from 'rxjs';
import { Http } from '@global/service/Http';
import { AppNotification } from '@global/service/Notification';
import { NavController, ModalController } from '@ionic/angular';
import { App } from '@global/service/App';
import * as moment from 'moment';
import { ComUtil } from '@global/util/ComUtil';
import { AppEnvironment } from 'src/environments/AppEnvironment';


@Component({
  selector: 'ctrl-zbxx-calendar',
  templateUrl: './zbxx-calendar.html',
  styleUrls: ['./zbxx-calendar.scss']
})
export class Calendar implements OnInit,OnDestroy {

    /**
     * 名称
     *
     * @type {string}
     * @memberof Calendar
     */
    @Input() public name: string;

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


    /**
     * 是否为内嵌视图
     *
     * @type {boolean}
     * @memberof Calendar
     */
    @Input() public isembeddedView: boolean;

    /**
     * 是否为模态模式
     *
     * @type {boolean}
     * @memberof Calendar
     */
    @Input() public isModalMode: boolean;

    /**
     * 当前部件激活数据
     *
     * @public
     * @type {void}
     * @memberof Calendar
     */
    public $activeData: Array<any> = [];

    constructor(private $http: Http, private $notification: AppNotification,private $navCtrl:NavController,private $app:App,private $modalCtrl: ModalController) {

    }


    /**
     * 返回
     *
     * @memberof Calendar
     */
    public backView() {
        if (this.isModalMode) {
            let res: any;
            if (this.$activeData && this.$activeData.length > 0) {
                res = { ret: 'OK', result: this.$activeData };
            } else {
                res = { ret: 'NO', result: [] };
            }
            this.$modalCtrl.dismiss(res, 'close');
        } else {
            this.$navCtrl.back();
        }
    }

    /**
     * 查询action
     *
     * @type {string}
     * @memberof Calendar
     */
    @Input() public searchAction: string;

    /**
     * 加载抛出事件
     *
     * @type {EventEmitter}
     * @memberof Calendar
     */
    @Output()  public loademit =new EventEmitter();

    /**
     * 传入数据
     *
     * @type {string}
     * @memberof Calendar
     */
    public $items:Array<any> =[];

    /**
     * 当前年份
     *
     * @type {string}
     * @memberof Calendar
     */
    public year:number;

    /**
     * 当前月份
     *
     * @type {string}
     * @memberof Calendar
     */
    public month:number;

    /**
     * 当前天
     *
     * @type {string}
     * @memberof Calendar
     */
    public day:number;

    /**
     * Api地址
     *
     * @type {string}
     * @memberof Calendar
     */
    public url: string = 'mob/demo/zb/zbxxcalendar/';

    /**
     * 日历数据项
     *
     * @type {string}
     * @memberof Calendar
     */
    public calendarDataConfig:any=[];
    public calendarDataConfig2: any = {};

    
    /**
     * 选中日期数据
     *
     * @type {any[]}
     * @memberof Calendar
     */
    public activeDateItems:Array<any> =[];

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

    /**
     * 获取单项树
     *
     * @returns {*}
     * @memberof Calendar
     */
    public getData(): any {
        return this.activeDateItems[0];
    }

    /**
     * 初始化当前时间
     *
     * @returns {*}
     * @memberof Calendar
     */
    public initcurrentTime(){
        let  tempTime=new Date();
        this.year =tempTime.getFullYear();
        this.month =tempTime.getMonth();
        this.day =tempTime.getDate();
    }

    /**
     * 初始化基础数据项
     *
     * @returns {*}
     * @memberof Calendar
     */
    public regDataConfig(): void {
        this.regDataItemConfig({name:'值班信息',type:'ZB',style:{'background-color':'','color':''}});
    }

    /**
     * 注册数据项配置
     *
     * @returns {*}
     * @memberof Calendar
     */
    public regDataItemConfig(config: any): void {
        this.calendarDataConfig.push(config);
        this.calendarDataConfig2[config.type] = config;
    }

    ngOnInit(): void {
      this.initcurrentTime();
      this.regDataConfig();
      if (this.viewState) {
        this.viewState.subscribe(({ tag, action, data }) => {
            if (!Object.is(this.name, tag)) {
                return;
            }
            if (Object.is(action,'load')) {
                let start = moment().startOf('month').format('YYYY-MM-DD HH:mm:ss');
                let end = moment().endOf('month').format('YYYY-MM-DD HH:mm:ss');
                if(!data){
                    data ={};
                }
                Object.assign(data,{"srfbegintime":start,"srfendtime":end});
                this.load(data);
            }
        });
    }
    }

    ngOnDestroy(): void {}

    /**
     * 日历部件数据加载
     *
     * @private
     * @param {*} [arg={}]
     * @memberof Calendar
     */
    private load(opt: any = {}): void {
        const arg: any = {...opt};

        const parentdata: any = {};
        Object.assign(arg, parentdata);

        const post: any = this.$http.post(this.url + 'search', arg);
        post.then((response: any) => {
            if (!response) {
                if (response.errorMessage) {
                    this.$notification.error('错误'+response.message);
                }
                return;
            }
            const data: any = response;
            let tempItems:any;
            if (Object.keys(data).length > 0) {
                tempItems = JSON.parse(JSON.stringify(data.records));
            }
            this.loademit.emit(tempItems);
            this.dataFormat(tempItems);
        }).catch((error: any) => {
            this.$notification.error('错误'+error.message);
        });
    }

    /**
     * 日历部件数据选择回调
     *
     * @private
     * @param {*} [arg={}]
     * @memberof Calendar
     */
    public activeDateChange(data: { year: number, month: number, day: number }) {
        if (data) {
            this.year = data.year;
            this.month = data.month;
            this.day = data.day;
            let curtime = new Date(this.year,this.month,this.day);
            let start =moment(curtime).startOf('day').format('YYYY-MM-DD HH:mm:ss');
            let end =moment(curtime).endOf('day').format('YYYY-MM-DD HH:mm:ss');
            this.load({"srfbegintime":start,"srfendtime":end});
        }
    }

    /**
     * 数据格式化
     *
     * @param {*} items
     * @memberof Calendar
     */
    public dataFormat(items: any[] = []): void {
        this.$items = items;
        this.activeDateItems = [];
        items.forEach((item: any) => {
            const date: Date = moment(item.begintime).toDate();
            if (this.year === date.getFullYear() && this.month === date.getMonth() && this.day === date.getDate()) {
                this.activeDateItems.push(item);
            }
        });
        this.dataGrounps();
    }

    /**
     * 数据分组
     *
     * @memberof Calendar
     */
    public dataGrounps(): void {
        if (this.activeDateItems.length > 0) {
            let dest = [];
            for (let i = 0; i < this.activeDateItems.length; i++) {
                let tempObj = this.activeDateItems[i];
                if (dest.length === 0) {
                    dest.push({ name: tempObj['type'], items: [tempObj] });
                } else {
                    let tempFlag = true;
                    dest.forEach((ele) => {
                        if (Object.is(ele.name, tempObj['type'])) {
                            ele.items.push(tempObj);
                            tempFlag = false;
                        }
                    });
                    if (tempFlag) {
                        dest.push({ name: tempObj['type'], items: [tempObj] });
                    }
                }
            }
            this.activeDateItems = JSON.parse(JSON.stringify(dest));
        }
    }




}