package service

import (
	"Xcx_New/models"
	"fmt"
	"github.com/jinzhu/gorm"
	"github.com/robfig/cron"
	"time"
)

//// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html
//var createWeekDisinfectionCronJob *cron.Cron
//
//func init() {
//  createWeekDisinfectionCronJob = cron.New()
//  //spec := "0 0 23 * * ?" // 每天23点执行一次
//  spec := "0 55 23 * * ?" // 每天23点55执行一次
//  //spec := "0 0 5 * * ?" // 每天23点55执行一次
//  //spec := "0 */1 * * * ?" // 每1分钟执行一次
//  createWeekDisinfectionCronJob.AddFunc(spec, func() {
//
//    AutoCreateWeekDisinfectionJob()
//  })
//}
//
//func BeginAutoCreateWeekDisinfectionJob() {
//
//  createWeekDisinfectionCronJob.Start()
//}

//// cron表达式 https://www.cnblogs.com/zuxingyu/p/6023919.html

var createStaffScheduleCronJob *cron.Cron

func init() {

	createStaffScheduleCronJob = cron.New()
	//spec := "0 */1 * * * ?" // 每1分钟执行一次
	//spec := "0 55 23 * * ?" // 每天23点55执行一次
	spec := "0 0 0 ? * Sun"
	createStaffScheduleCronJob.AddFunc(spec, func() {
		AutoCreateStaffScheduleJob()
	})
}

func BeginAutoCreateStaffScheduleJob() {

	createStaffScheduleCronJob.Start()
}

func AutoCreateStaffScheduleJob() {

	now := time.Now()

	offset := int(time.Monday - now.Weekday())
	if offset > 0 {
		offset = -6
	}
	weekStart := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
	fmt.Println("weekStart", weekStart.Unix())
	start_time := weekStart.Unix()
	fmt.Println("start_time", start_time)
	weekEnd := time.Date(now.Year(), now.Month(), now.Day()+6, 0, 0, 0, 0, time.Local).AddDate(0, 0, offset)
	fmt.Println("weekEnd", weekEnd.Unix())
	end_time := weekEnd.Unix()
	fmt.Println("end_time", end_time)

	//查询该机构的连续排班是否开启
	// 获取所有机构信息
	orgs, _ := GetAllOrgs()
	for _, item := range orgs {
		fmt.Println(item)
		//查询该机构是否开启连续排班功能
		schdule, _ := GetAutoContinueSchdule(item.ID)
		//如果状态值未开启不生成连续排班
		if schdule.IsStatus == 0 {
			fmt.Println("连续排班未开启")
		}
		//连续排班开启
		if schdule.IsStatus == 1 {
			//查询该机构本周的排班数据
			schedules, _ := GeThisWeekScheduleData(item.ID, start_time, end_time)
			for _, it := range schedules {
				staffSchedule := models.StaffSchedule{
					DoctorId:     it.DoctorId,
					DoctorType:   it.DoctorType,
					ScheduleType: it.ScheduleType,
					ScheduleWeek: it.ScheduleWeek,
					UserOrgId:    it.UserOrgId,
					StartTime:    it.StartTime + 604800,
					EndTime:      it.EndTime + 604800,
					Status:       1,
					Ctime:        time.Now().Unix(),
					ScheduleDate: it.ScheduleDate + 604800,
				}
				//产询该机构下周是否填加了数据
				_, errcode := GetNextWeekData(it.UserOrgId, it.DoctorId, it.ScheduleDate+604800)
				if errcode == gorm.ErrRecordNotFound {
					AddSchedules(&staffSchedule)
				} else {
					fmt.Println("下周数据已生成")
				}
				//if len(schedules) != len(schedule) {
				//    AddSchedules(&staffSchedule)
				//}else{
				//   fmt.Println("下周数据已生成")
				//   //createStaffScheduleCronJob.Stop()
				//}
			}
		}
	}
}

func GetAllOrgs() (orgs []*models.SgjUserOrg, err error) {

	err = UserReadDB().Model(&orgs).Where("status = 1").Find(&orgs).Error
	return orgs, err
}

func GetAutoContinueSchdule(orgid int64) (models.ContinueSchedule, error) {

	schedule := models.ContinueSchedule{}
	err := XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1", orgid).Find(&schedule).Error
	return schedule, err
}

func GeThisWeekScheduleData(orgid int64, startime int64, endtime int64) (staffschedule []*models.StaffSchedule, err error) {

	err = XTReadDB().Model(&staffschedule).Where("user_org_id = ? and status = 1 and start_time>=? and end_time<=?", orgid, startime, endtime).Find(&staffschedule).Error
	return staffschedule, err
}

func AddSchedules(schedule *models.StaffSchedule) error {

	err := XTWriteDB().Model(&schedule).Create(&schedule).Error
	return err
}

func GetNextWeekData(orgid int64, docid int64, scheduledate int64) (*models.StaffSchedule, error) {
	schedule := models.StaffSchedule{}
	err := XTReadDB().Model(&schedule).Where("user_org_id = ? and status = 1 and doctor_id =? and schedule_date =?", orgid, docid, scheduledate).Find(&schedule).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &schedule, nil
}
