package service

import (
	"XT_New/models"
	"fmt"
	"strconv"
	"strings"
	"time"

	"github.com/jinzhu/gorm"
)

//GetSchedulePartitionPanel 取出排班面板，分区-机号
func GetSchedulePartitionPanel(orgID int64) (partitions []*models.Partition, err error) {

	err = readDb.Model(&models.DeviceZone{}).Preload("Jihaos", "org_id=? and status=1", orgID).Where("org_id=? and status=1", orgID).Find(&partitions).Error

	return
}

func GetPatientWithScheduleAndSolution(orgID int64, keywords string, weekStart, weekEnd, schedule, contagion int64) (patients []*models.Patients, err error) {
	db := readDb.Table("xt_patients as p").
		Preload("DialysisSolutions", "user_org_id=? and initiate_mode=1 and affirm_state=1 and parent_id=0 and status=1", orgID).
		Preload("Schedules", "user_org_id=? and schedule_date>=? and schedule_date<= ? and status=1", orgID, weekStart, weekEnd).
		Preload("Contagions", "status=1").
		Where("p.user_org_id=? and p.lapseto=1 and p.status=1", orgID)
	if len(keywords) > 0 {
		likeKey := "%" + keywords + "%"
		db = db.Where("p.name LIKE ?", likeKey)
	}

	if schedule == 1 {
		db = db.Where("EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.schedule_date>=? and iss.schedule_date<= ? and iss.status=1", weekStart, weekEnd).QueryExpr())
	} else if schedule == 2 {
		db = db.Where("NOT EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.schedule_date>=? and iss.schedule_date<= ? and iss.status=1", weekStart, weekEnd).QueryExpr())
	}
	if contagion > 0 {
		db = db.Where("EXISTS (?)", readDb.Table("xt_patients_infectious_diseases as pid").Where("pid.patient_id=p.id and pid.disease_id=? and pid.status=1", contagion).QueryExpr())
	}

	err = db.Find(&patients).Error
	return
}

func GetWeekSchedule(orgID int64, start, end int64) (schedules []*models.Schedule, err error) {

	err = readDb.
		Table("xt_schedule as s").
		Preload("PatientInfectiousDiseases", "status = 1 ").
		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
		Where("s.user_org_id=? and s.schedule_date>=? and s.schedule_date<=? and s.status=1", orgID, start, end).
		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id, s.status, s.created_time, s.updated_time, p.name as patient").
		Order("updated_time asc").
		Find(&schedules).Error
	return
}

func GetDaySchedule(orgID, start, end, patientID int64) (schedule models.Schedule, err error) {
	err = readDb.Model(&models.Schedule{}).Where("user_org_id=? and patient_id=? and schedule_date>=? and schedule_date<=? and status=1", orgID, patientID, start, end).First(&schedule).Error
	return
}

func GetDayScheduleTwo(orgID, start, patientID int64) (schedule models.Schedule, err error) {
	err = readDb.Model(&models.Schedule{}).Where("user_org_id=? and patient_id=? and schedule_date = ? and status=1", orgID, patientID, start).Preload("DialysisOrder", "status = 1").First(&schedule).Error
	return
}

func GetDayScheduleByBedid(orgID, start, bed_id int64, schedule_type int64) (schedule models.Schedule, err error) {
	err = readDb.Model(&models.Schedule{}).Where("user_org_id=?  and schedule_date=? and bed_id=? and status=1 AND schedule_type = ?", orgID, start, bed_id, schedule_type).Preload("DialysisOrder", "status = 1").First(&schedule).Error
	return
}

func GetPatientScheduleFormDay(orgID, start, end, patientID int64) (schedules []*models.PatientSchedule, err error) {

	err = readDb.Table("xt_schedule as s").
		Preload("DeviceZone", "org_id=? and status=1", orgID).
		Preload("DeviceNumber", "org_id=? and status=1", orgID).
		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=? and s.schedule_date < ? and s.status=1", patientID, orgID, start, end).
		Find(&schedules).Error

	return
}

func GetNextSchedule(orgID, end, patientID int64) (schedules []*models.PatientSchedule, err error) {
	err = readDb.Table("xt_schedule as s").
		Preload("DeviceZone", "org_id=? and status=1", orgID).
		Preload("DeviceNumber", "org_id=? and status=1", orgID).
		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=?  and s.status=1", patientID, orgID, end).
		Find(&schedules).Error

	return
}

func GetPointSchedule(orgID, scheduleDate, scheduleWeek, scheduleType, bedId int64) (schedule models.Schedule, err error) {
	err = readDb.Model(&models.Schedule{}).Where("user_org_id=? and schedule_date=? and bed_id=? and schedule_week=? AND schedule_type=? and status=1", orgID, scheduleDate, bedId, scheduleWeek, scheduleType).First(&schedule).Error

	if err == gorm.ErrRecordNotFound {
		err = nil
		return
	}
	return
}

func CreateSchedule(m *models.Schedule) error {
	return writeDb.Model(&models.Schedule{}).Create(&m).Error
}

func GetSchedule(orgID, id int64) (*models.Schedule, error) {
	var schedule models.Schedule
	var err error
	err = readDb.Model(&models.Schedule{}).Where("id = ? and user_org_id=? and status=1", id, orgID).First(&schedule).Error
	if err != nil {
		return nil, err
	}
	return &schedule, nil
}

func UpdateSchedule(m *models.Schedule) error {
	return writeDb.Model(&models.Schedule{}).Save(&m).Error
}

func GetPatientScheduleFormToday(orgId, id, start int64) (schedules []*models.PatientSchedule, err error) {

	err = readDb.Table("xt_schedule as s").
		Preload("DeviceZone", "org_id=? and status=1", orgId).
		Preload("DeviceNumber", "org_id=? and status=1", orgId).
		Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=? and s.status=1", id, orgId, start).
		Find(&schedules).Error

	return
}

type WeekSchedulePrintVM struct {
	ID             int64 `gorm:"column:id" json:"id"`
	ZoneID         int64 `gorm:"column:partition_id" json:"zone_id"`
	DeviceNumberID int64 `gorm:"column:bed_id" json:"device_number_id"`
	PatientID      int64 `gorm:"column:patient_id" json:"patient_id"`
	ScheduleDate   int64 `gorm:"column:schedule_date" json:"schedule_date"`
	ScheduleType   int64 `gorm:"column:schedule_type" json:"schedule_type"`
	ScheduleWeek   int64 `gorm:"column:schedule_week" json:"schedule_week"`
	ModeID         int64 `gorm:"column:mode_id" json:"mode_id"`

	Patient      *models.Patients      `gorm:"ForeignKey:PatientID" json:"patient"`
	DeviceNumber *models.DeviceNumber  `gorm:"ForeignKey:DeviceNumberID" json:"device_number"`
	Zone         *models.DeviceZone    `gorm:"ForeignKey:ZoneID" json:"zone"`
	Mode         *models.TreatmentMode `gorm:"ForeignKey:ModeID" json:"mode"`
}

func GetPrinitWeekSchedules(orgID int64, start, end int64) ([]*WeekSchedulePrintVM, error) {
	var schedules []*WeekSchedulePrintVM
	err := readDb.Table("xt_schedule as s").
		Preload("Patient", "status = 1 and user_org_id = ?", orgID).
		Preload("DeviceNumber", "status = 1 and org_id = ?", orgID).
		Preload("Zone", "status = 1 and org_id = ?", orgID).
		Preload("Mode", "status = 1").
		// Joins("JOIN xt_patients as p ON p.id = s.patient_id").
		Where("s.user_org_id = ? and s.schedule_date >= ? and s.schedule_date <= ? and s.status = 1", orgID, start, end).
		// Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id").
		Find(&schedules).Error
	return schedules, err
}

// func ExchangeScheduleTimeWithWeekSchedules(orgID int64, nextWeekSchs []*models.Schedule, nextTwoWeekSchs []*models.Schedule) error {
// 	templateMode, getTemplateModeErr := GetOrgPatientScheduleTemplateMode(orgID)
// 	if getTemplateModeErr != nil {
// 		return getTemplateModeErr
// 	}
// 	if templateMode == nil {
// 		return errors.New("模板模式不存在")
// 	}

// 	tx := writeDb.Begin()

// 	updateTime := time.Now().Unix()

// 	for _, sch := range nextWeekSchs {
// 		sch.PatientInfectiousDiseases = nil

// 		date := time.Unix(sch.ScheduleDate, 0)
// 		sch.ScheduleDate = date.AddDate(0, 0, 7).Unix()
// 		sch.UpdatedTime = updateTime

// 		updateSchErr := tx.Save(sch).Error
// 		if updateSchErr != nil {
// 			tx.Rollback()
// 			return updateSchErr
// 		}
// 	}

// 	for _, sch := range nextTwoWeekSchs {
// 		sch.PatientInfectiousDiseases = nil

// 		date := time.Unix(sch.ScheduleDate, 0)
// 		sch.ScheduleDate = date.AddDate(0, 0, -7).Unix()
// 		sch.UpdatedTime = updateTime

// 		updateSchErr := tx.Save(sch).Error
// 		if updateSchErr != nil {
// 			tx.Rollback()
// 			return updateSchErr
// 		}
// 	}

// 	templateMode.ModifyTime = updateTime
// 	templateMode.ExecuteTimes += 1
// 	updateModeErr := tx.Save(templateMode).Error
// 	if updateModeErr != nil {
// 		tx.Rollback()
// 		return updateModeErr
// 	}

// 	tx.Commit()
// 	return nil
// }

func GetSchedualPatientsByKeywords(keywords string, org_id int64) (schedule []*models.Schedule, err error) {
	likeKey := "%" + keywords + "%"

	err = readDb.
		Table("xt_schedule as s").
		Preload("PatientInfectiousDiseases", "status = 1 ").
		Preload("DeviceZone", "status = 1 ").
		Preload("DeviceNumber", "status = 1 ").
		Preload("TreatmentMode", "status = 1 ").
		Joins("JOIN xt_patients as p ON p.id = s.patient_id AND (p.name LIKE ? OR p.dialysis_no LIKE ?)", likeKey, likeKey).
		Where("s.user_org_id=? and s.schedule_date >= UNIX_TIMESTAMP(DATE_FORMAT(NOW(),'%Y-%m-%d 00:00:00')) and s.schedule_date <= UNIX_TIMESTAMP(DATE_FORMAT( SUBDATE(CURDATE(),DATE_FORMAT(CURDATE(),'%w')-7), '%Y-%m-%d 23:59:59')) and s.status=1", org_id).
		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id, s.status, s.created_time, s.updated_time, p.name as patient").
		Order("schedule_date asc").
		Find(&schedule).Error
	return

}

func GetWeekDaySchedule(orgID int64, scheduleDate int64, scheduleDates *time.Time) (schedules []*models.WeekSchedule, err error) {

	err = readDb.
		Table("xt_schedule as s").
		Preload("DeviceZone", "status = 1 ").
		Preload("DeviceNumber", "status = 1 ").
		Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1").Order("id desc")
		}).
		Joins("JOIN xt_patients as p ON p.id = s.patient_id").
		Where("s.user_org_id=? and s.schedule_date = ? and s.status=1", orgID, scheduleDate).
		Select("s.id, s.user_org_id, s.partition_id, s.bed_id, s.patient_id, s.schedule_date, s.schedule_type, s.schedule_week, s.mode_id, s.status, s.created_time, s.updated_time, p.name as patient").
		Order("schedule_type").
		Find(&schedules).Error

	for _, item := range schedules {
		_, config := FindDoctorAdviceRecordByOrgId(item.UserOrgId)
		if config.IsOpenRemind > 0 {
			//开启推送提醒逻辑    提交长期处方的时候，弹起长期医嘱推送
			var advice_three []*models.DoctorAdvice
			advices, _ := GetLastLongAdviceByGroupNoOther(item.UserOrgId, item.PatientId)
			advices_two, _ := GetLastLongAdviceByGroupNoThreeOther(item.UserOrgId, item.PatientId)
			for _, advice := range advices {
				advice.IsCheck = 1
				if advice.FrequencyType == 3 {
					week := int(scheduleDates.Weekday())
					fmt.Println(advice.WeekDay)
					switch week {
					case 1:
						if strings.Index(advice.WeekDay, "周一") > -1 {
							advice_three = append(advice_three, advice)
						}
						break
					case 2:
						if strings.Index(advice.WeekDay, "周二") > -1 {
							advice_three = append(advice_three, advice)
						}
						break
					case 3:
						if strings.Index(advice.WeekDay, "周三") > -1 {
							advice_three = append(advice_three, advice)
						}
						break
					case 4:
						if strings.Index(advice.WeekDay, "周四") > -1 {
							advice_three = append(advice_three, advice)
						}
						break
					case 5:
						if strings.Index(advice.WeekDay, "周五") > -1 {
							advice_three = append(advice_three, advice)
						}
						break
					case 6:
						if strings.Index(advice.WeekDay, "周六") > -1 {
							advice_three = append(advice_three, advice)
						}
						break
					case 0:
						if strings.Index(advice.WeekDay, "周日") > -1 {
							advice_three = append(advice_three, advice)
						}
						break
					}
				} else if advice.FrequencyType == 1 {
					advice_three = append(advice_three, advice)
				}
			}

			for _, advice := range advices_two {
				now := scheduleDates.Unix()
				dayStr := strconv.FormatInt(advice.DayCount, 10)
				dayStr2 := "-" + dayStr
				count, _ := strconv.ParseInt(dayStr2, 10, 64)
				oldTime := scheduleDates.AddDate(0, 0, int(count)).Unix()
				advices, _ := FindAllDoctorAdviceByTimeOther(now, oldTime, item.PatientId, item.UserOrgId, advice.TemplateId)
				if len(advices) == 0 {
					advice_three = append(advice_three, advice)
				}
			}

			item.DoctorAdvice = append(item.DoctorAdvice, advice_three...)
		}
	}
	return
}

func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
	newArr = make([]*models.DoctorAdvice, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i].ID == arr[j].ID {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}

func GetLastLongAdviceByGroupNoOther(orgId int64, patient_id int64) (advice []*models.DoctorAdvice, err error) {
	err = readDb.Model(&models.DoctorAdvice{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND advice_type = 1  AND stop_state = 2 AND parent_id = 0", orgId, patient_id).Preload("ChildDoctorAdvice", "status = 1").Find(&advice).Error
	return
}

func GetLastLongAdviceByGroupNoThreeOther(orgId int64, patient_id int64) (advice []*models.DoctorAdvice, err error) {
	err = readDb.Model(&models.DoctorAdvice{}).Where("status = 1 AND user_org_id = ? AND patient_id = ?  AND  advice_type = 1 AND frequency_type = 2 AND stop_state = 2 AND parent_id = 0 ", orgId, patient_id).Preload("ChildDoctorAdvice", "status = 1").Find(&advice).Error
	return
}

func FindAllDoctorAdviceByTimeOther(now int64, end int64, patient_id int64, orgId int64, temp_id string) (advice []*models.DoctorAdvice, err error) {
	err = readDb.Model(&models.DoctorAdvice{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND advice_type = 2   AND frequency_type = 2 AND advice_date > ? AND advice_date < ? AND template_id = ?  ", orgId, patient_id, end, now, temp_id).Preload("ChildDoctorAdvice", "status = 1").Find(&advice).Error
	return
}
