import {Component, ViewChild} from '@angular/core';
import {NavController, IonicPage, Slides} from 'ionic-angular';
import {ActivityListPage} from '../../activity/activityList/activityList';
import {Http, Response} from '@angular/http';
import {ActivityStatisticService} from '../../../service/activityStatisticService';
import {MyActivityListPage} from '../../mine/myActivityList/myActivityList';
import {AppService, AppGlobal} from '../../../service/appHttpService';
import {Calendar} from '@ionic-native/calendar';
import {ActivityApplyPage} from '../../activity/activityApply/activityApply'
import {ActivityConfirmPage} from '../../activity/activityConfirm/activityConfirm';
import {OutGoingReportPage} from '../../report/outGoingReport/outGoingReport';
import {OperationListPage} from '../../operation-list/operation-list';
import {AnnouncementPage} from '../../announcement/announcement';
import {Storage} from '@ionic/storage';
import {OutGoingReportEditPage} from '../../report/outGoingReportEdit/outGoingReportEdit';
import {AnnouncementViewPage} from '../../announcementView/announcementView';
import {MoreAppPage} from "../../home/more-app/more-app";
import {ReportTrackPage} from "../../report/reportTrack/reportTrack";
import {CalendarComponentOptions, DayConfig} from "ion2-calendar";
import {NoticePage} from "../notice/notice";
import {monthCh, weekDay} from "../../../app/main";
import {Badge} from '@ionic-native/badge';
import {ActivityDetailPage} from "../../activity/activityDetail/activityDetail";

declare var Swiper;

@IonicPage()
@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})

export class HomePage {
    @ViewChild(Slides) slides: Slides;

    hasNewActivity: number = 0;
    hasNewNotice: number = 0;
    hasNewPremanager: number = 0;
    hasNewMessage: number = 0;

    //日历
    date: string;
    type: 'string';

    optionsMulti: CalendarComponentOptions;
    newArr: DayConfig[] = [];

    //待出行
    waitgoCount = '0';
    //待确认
    waitsureCount = '0';
    //未读通知
    NoticeNotreadCount = '0';
    //尚未报备
    PremanagerNotdoCount = '0';
    //是否显示正在开发中
    isWait: boolean = false;

    slidersItems = [];
    noticeList = [];

    picture: string = AppGlobal.picture;

    operations: Array<string>;

    //当前年份
    year;
    //当前月份
    month;
    //当前第几周
    weekNo;

    noticeTips;
    role;

    constructor(public navCtrl: NavController, public activityStatisticService: ActivityStatisticService,
                public appService: AppService, public http: Http, private calendar: Calendar, public storage: Storage,
                public badge: Badge) {

    }


    goActivity() {
        this.navCtrl.push('ActivityListPage', {});
    }

    goAnnouncement() {
        this.navCtrl.push("AnnouncementPage");
    }

    ngOnInit(): void {
        this.appService.ObserverHttpGet("/wisdomgroup/modules/message/findAllActivityForAppWithXQ", null).subscribe((res: Response) => {
            this.noticeList = res.json().slice(0, 2);
        }, error => {
            this.appService.alert('系统错误！');
        });
    }

    ionViewDidEnter() {

        //获取权限
        this.getRole();
        //获取消息数量
        this.getNewCount();
        //获取日历
        this.getCalendar();
    }

    ionViewWillEnter() {


        this.slidersItems = [];
        //初始化日期
        this.getHasNewActivity();
        this.getHasNewNotice();
        this.getHasNewMessage();
        this.getHasNewPremanager();
        //统计待进行和待确认活动数目
        this.activityStatisticService.myActivityOrderCount((data) => {
            this.waitgoCount = data.waitgoOrder;
            this.waitsureCount = data.waitSureOrder;
        });

        this.appService.ObserverHttpGet("/wisdomgroup/modules/common/file/getBanner", {}).subscribe((res: Response) => {
            this.slidersItems = res.json();
        }, error => {
        })

        //初始化统计未读通知
        this.activityStatisticService.myNoticeNotreadCount((data) => {
            this.NoticeNotreadCount = data;
        });
        //初始化统计尚未报备
        this.activityStatisticService.myNotdoPremanagerCount((data) => {
            this.PremanagerNotdoCount = data;
        });

        //初始化操作记录
    }

    ionViewDidLeave() {
        this.newArr = [];
        this.slides.stopAutoplay();
    }


    //获取权限
    getRole() {
        this.appService.ObserverHttpGet("/wisdomgroup/app/getRoles", null).subscribe((res: Response) => {
            this.role = res.json();
        }, error => {
            this.appService.alert('系统错误！');
        });
    }

    goMyActivity() {
        this.navCtrl.push("MyActivityListPage");
    }

    goMyNotice() {
        this.navCtrl.push("AnnouncementPage");
    }

    //问卷调查
    goToSurveyManage() {
        this.navCtrl.push('ListPage');
    }

    //活动跟踪
    goActivityTrack() {
        this.navCtrl.push("ActivityTrackPage");
    }

    //报备跟踪
    goReportTrack() {
        this.navCtrl.push("ReportTrackPage");
    }

    wait() {
        this.isWait = true;
    }

    cancleWait() {
        this.isWait = false;
    }


    go(item) {
        if (item.type == 1) {
            this.getActivity(item.id);
        } else if (item.type == 2) {
            this.getPremanager(item.id);
        } else if (item.type == 3) {
            this.navCtrl.push("AnnouncementViewPage", {
                id: item.id
            });
        }
    }

    //获取活动ById
    getActivity(id) {
        this.appService.ObserverHttpPost("/wisdomgroup/modules/activity/appFindById", {id: id})
            .toPromise()
            .then(res => {
                let activity = res.json();
                this.navCtrl.push('ActivityDetailPage', {id: activity.id});
            })
            .catch(error => {
            });
    }


    //获取报备
    getPremanager(id) {
        this.appService.ObserverHttpPost("/wisdomgroup/modules/premanager/findById", {id: id}).
        subscribe((res) => {
            let premanager = res.json();
            this.storage.set("premanager", premanager);
            this.navCtrl.push("OutGoingReportEditPage");
        })
    }


    findMyOrderByOrderId(orderid, callback?) {
        let order = this.appService.ObserverHttpPost("/wisdomgroup/modules/order/findMyOrderByOrderId", {"orderid": orderid})
            .subscribe((res: Response) => {
                    let data = res.json();
                    callback(data == null ? "[]" : data);
                }, error => {
                }
            );
    }

    isExitOrderWithActivity(activity, callback?): any {
        this.appService.ObserverHttpPost("/wisdomgroup/modules/order/isExitOrderWithActivity", activity)
            .toPromise()
            .then(res => {
                var data = res.json();
                callback(data == null ? "[]" : data);
            })
            .catch(error => {
            });
    }


    //消息通知
    gotoNotice() {
        this.navCtrl.setRoot(NoticePage);
        this.navCtrl.parent.select(2);
    }

    goOperationListPage() {
        this.navCtrl.push("OperationListPage");
    }

    //外出报备跳转
    goOutGoingReportAboutAll() {
        this.navCtrl.push("OutGoingReportPage", {
            type: 1
        });
    }

    //问卷调查
    goToMySurvey() {
        this.navCtrl.push('SurveryPage');
    }

    goDuty() {
        this.navCtrl.push("DutyPage");
    }

    //更多应用
    gotoMore() {
        this.navCtrl.push('MoreAppPage')
    }

    //尚未报备跳转
    goOutGoingReportAboutNot() {
        this.navCtrl.push("OutGoingReportPage", {
            type: 2
        });
    }

    //获取是否有新的活动
    getHasNewActivity() {
        this.appService.ObserverHttpGet("/wisdomgroup/modules/activity/hasNewActivity", null)
            .subscribe((res: Response) => {
                    let data = res.json();
                    this.hasNewActivity = data;
                }, error => {
                }
            );
    }

    //获取是否有新的公告
    getHasNewNotice() {
        this.appService.ObserverHttpGet("/wisdomgroup/modules/notice/hasNewNotice", null)
            .subscribe((res: Response) => {
                    let data = res.json();
                    this.hasNewNotice = data;
                }, error => {
                }
            );
    }

    //获取是否有新消息
    getHasNewMessage() {
        this.appService.ObserverHttpGet("/wisdomgroup/modules/message/hasNewMessage", null)
            .subscribe((res: Response) => {
                    let data = res.json();
                    this.hasNewMessage = data;
                }, error => {
                }
            );
    }

    //获取是否有新的报备
    getHasNewPremanager() {
        this.appService.ObserverHttpGet("/wisdomgroup/modules/premanager/hasNewPremanager", null)
            .subscribe((res: Response) => {
                    let data = res.json();
                    this.hasNewPremanager = data;
                }, error => {
                }
            );
    }

    getNewCount() {
        this.appService.ObserverHttpGetData('/wisdomgroup/modules/activity/hasNewCount', null)
            .subscribe((res) => {
                let data = Number(res.json());
                this.noticeTips = data;
                if (data > 0) {
                    this.badge.set(data);
                } else {
                    this.badge.clear();
                }
            })
    }

    //日历

    getCalendar() {
        this.newArr = [];
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;

        //2.参加活动日期
        this.appService.ObserverHttpGetOption("/wisdomgroup/modules/order/appOrderCal", null)
            .subscribe((res: Response) => {
                let response = res.json();
                response.forEach(event => {
                    this.newArr.push({
                        date: new Date(event.batch.batchGoDate),
                        disable: true,
                        cssClass: 'dayOff2'
                    })
                });

                //3.离沪日期
                this.appService.ObserverHttpGetOption("/wisdomgroup/modules/userpre/appPreCal", null)
                    .subscribe((res: Response) => {
                        let response = res.json();
                        response.forEach(event => {
                            this.newArr.push({
                                date: new Date(event.formshTime),
                                disable: true,
                                cssClass: 'dayOff4'
                            })
                        });
                    }, error => {
                    });
                this.loadEvent(year, month);
            }, error => {
            });


    }

    loadEvent(year, month) {
        //5.获取每月值班信息
        const data = {
            date: year + '/' + month + '/01'
        };
        this.appService.ObserverHttpGetOption("/wisdomgroup/schedule/app/getMyScheduleOnMonth", data)
            .subscribe((res: Response) => {
                    let response = res.json();
                    for (let i = 0; i < response.length; i++) {
                        const data = {
                            date: new Date(response[i].dutyDate),
                            disable: true,
                            cssClass: 'dayOff3'
                        };
                        this.newArr.push(data);
                    }

                    //1.获取节假日
                    this.appService.ObserverHttpGetOption("/wisdomgroup/workCalendar/getFestivalAboutMonth", data)
                        .subscribe((res) => {
                            let data = res.json();
                            data.forEach(event => {
                                const data = {
                                    date: new Date(event.date),
                                    disable: true,
                                    cssClass: 'dayOff1'
                                };
                                this.newArr.push(data);
                            });
                            this.setCalendar(year,month);
                        });
                }, error => {
                }
            );

    }

    setCalendar(year,month){
        let date = new Date();
        //4.每月的周末
        let d = new Date(year, month, 0).getDate();
        for (let i = 1; i < d + 1; i++) {
            date.setFullYear(year, month - 1, i);
            let day = date.getDay();
            if (day == 6 || day == 0) {
                const data = {
                    date: new Date(year, month - 1, i),
                    disable: true,
                    cssClass: 'dayOff1'
                };
                this.newArr.push(data);
            }
        }

        this.optionsMulti = {
            pickMode: 'multi',
            monthFormat: 'YYYY 年 MM 月 ',
            weekdays: weekDay,
            monthPickerFormat: monthCh,
            weekStart: 0,
            disableWeeks: [0, 1, 2, 3, 4, 5, 6],
            daysConfig: this.newArr
        };
    }

    onChange(e) {
    }

    //月份改变
    monChange(e) {
        this.loadEvent(e.newMonth.years, e.newMonth.months);
    }

}

//定义星期实体
export class Week {
    id: number;
    title: string;
    date: number;
    isToday: boolean = false;
}
