package service

import (
	"fmt"
	"strings"
	"time"

	"XT_New/models"
	"XT_New/utils"

	"github.com/jinzhu/gorm"
)

func GetOrgPatientScheduleTemplateMode(orgID int64) (*models.PatientScheduleTemplateMode, error) {
	var mode models.PatientScheduleTemplateMode
	err := readDb.Model(&models.PatientScheduleTemplateMode{}).Where("org_id = ? AND status = 1", orgID).First(&mode).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &mode, nil
}

// 获取至多两个模板ID
func GetOrgPatientScheduleTemplateIDs(orgID int64) ([]*models.PatientScheduleTemplateId, error) {
	var ids []*models.PatientScheduleTemplateId
	err := readDb.Model(&models.PatientScheduleTemplateId{}).Where("org_id = ? AND status = 1", orgID).Limit(2).Find(&ids).Error
	if err != nil {
		return nil, err
	}
	return ids, nil
}

func GetOrgPatientScheduleTemplateIDByTemplateID(orgID int64, templateID int64) (*models.PatientScheduleTemplateId, error) {
	var id models.PatientScheduleTemplateId
	err := readDb.Model(&models.PatientScheduleTemplateId{}).Where("org_id = ? AND id = ? AND status = 1", orgID, templateID).First(&id).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &id, nil
}

type PatientScheduleTemplateItemViewModel struct {
	models.PatientScheduleTemplateItem

	Patient *models.Patients `gorm:"ForeignKey:PatientID" json:"patient"`
}

type PatientScheduleTemplateViewModel struct {
	// ID    int64 `gorm:"column:id" json:"id" form:"id"`
	// OrgID int64 `gorm:"column:org_id" json:"-" form:"org_id"`
	models.PatientScheduleTemplateId

	Items []*PatientScheduleTemplateItemViewModel `gorm:"ForeignKey:TemplateID" json:"items"`
}

func (PatientScheduleTemplateViewModel) TableName() string {
	return "xt_patient_schedule_template_id"
}

// 获取至多两个模板ID及其对应的模板排班列表
func GetOrgPatientScheduleTemplateItems(orgID int64) ([]*PatientScheduleTemplateViewModel, error) {
	var vms []*PatientScheduleTemplateViewModel
	err := readDb.
		Model(&PatientScheduleTemplateViewModel{}).
		Preload("Items", "org_id = ? AND status = 1", orgID).
		Preload("Items.Patient", "user_org_id = ? AND status = 1", orgID).
		Where("org_id = ? AND status = 1", orgID).
		Limit(2).
		Find(&vms).
		Error
	if err != nil {
		return nil, err
	}
	return vms, nil
}

// 获取指定模板ID的模板排班列表
func GetOrgPatientScheduleTemplateItemsByTemplateID(orgID int64, templateID int64) ([]*PatientScheduleTemplateItemViewModel, error) {
	var vms []*PatientScheduleTemplateItemViewModel
	err := readDb.
		Model(&PatientScheduleTemplateItemViewModel{}).
		Preload("Patient", "user_org_id = ? AND status = 1", orgID).
		Where("org_id = ? AND template_id = ? AND status = 1", orgID, templateID).
		Find(&vms).
		Error
	if err != nil {
		return nil, err
	}
	return vms, nil
}

func GetOrgPatientScheduleTemplateItemsWithoutPatientByTemplateID(orgID int64, templateID int64) ([]*models.PatientScheduleTemplateItem, error) {
	var items []*models.PatientScheduleTemplateItem
	err := readDb.Raw("select item.id,item.org_id,item.template_id,item.device_number_id,item.patient_id,item.treat_mode,item.weekday,item.time_type,item.status,item.status,item.ctime,item.mtime from xt_patient_schedule_template_item as item left join xt_patients as patient on item.patient_id = patient.id where item.org_id = ? AND item.template_id = ? AND item.status = 1 and patient.lapseto = 1 and patient.status = 1", orgID, templateID).Scan(&items).Error
	// err := readDb.
	// 	Model(&models.PatientScheduleTemplateItem{}).
	// 	Where("org_id = ? AND template_id = ? AND status = 1", orgID, templateID).
	// 	Find(&items).
	// 	Error
	if err != nil {
		return nil, err
	}
	return items, nil
}

type ScheduleDeviceNumberViewModel struct {
	models.DeviceNumber

	Zone *models.DeviceZone `gorm:"ForeignKey:ZoneID" json:"zone"`
}

func GetScheduleValidDeviceNumbers(orgID int64) ([]*ScheduleDeviceNumberViewModel, error) {
	var vms []*ScheduleDeviceNumberViewModel
	err := readDb.Model(&ScheduleDeviceNumberViewModel{}).Preload("Zone", "status = 1").Where("org_id = ? AND status = 1", orgID).Order("zone_id asc").Order("id asc").Find(&vms).Error
	if err != nil {
		return nil, err
	}
	return vms, nil
}

// 创建两个默认模板
func CreateTwoPatientScheduleTemplates(orgID int64) (*PatientScheduleTemplateViewModel, *PatientScheduleTemplateViewModel, error) {
	now := time.Now().Unix()
	firstTemp := models.PatientScheduleTemplateId{}
	firstTemp.OrgID = orgID
	firstTemp.Status = 1
	firstTemp.CreateTime = now
	firstTemp.ModifyTime = now

	secondTemp := models.PatientScheduleTemplateId{}
	secondTemp.OrgID = orgID
	secondTemp.Status = 1
	secondTemp.CreateTime = now
	secondTemp.ModifyTime = now

	tx := writeDb.Begin()
	if err := tx.Model(&models.PatientScheduleTemplateId{}).Create(&firstTemp).Error; err != nil {
		tx.Rollback()
		return nil, nil, err
	}
	if err := tx.Model(&models.PatientScheduleTemplateId{}).Create(&secondTemp).Error; err != nil {
		tx.Rollback()
		return nil, nil, err
	}

	vm1 := PatientScheduleTemplateViewModel{}
	vm1.ID = firstTemp.ID
	vm1.Items = make([]*PatientScheduleTemplateItemViewModel, 0, 0)

	vm2 := PatientScheduleTemplateViewModel{}
	vm2.ID = secondTemp.ID
	vm2.Items = make([]*PatientScheduleTemplateItemViewModel, 0, 0)
	tx.Commit()
	return &vm1, &vm2, nil
}

func CreatePatientScheduleTemplate(orgID int64) (*PatientScheduleTemplateViewModel, error) {
	now := time.Now().Unix()
	temp := models.PatientScheduleTemplateId{}
	temp.OrgID = orgID
	temp.Status = 1
	temp.CreateTime = now
	temp.ModifyTime = now
	tx := writeDb.Begin()
	if err := tx.Model(&models.PatientScheduleTemplateId{}).Create(&temp).Error; err != nil {
		tx.Rollback()
		return nil, err
	}
	vm := PatientScheduleTemplateViewModel{}
	vm.ID = temp.ID
	vm.Items = make([]*PatientScheduleTemplateItemViewModel, 0, 0)
	tx.Commit()
	return &vm, nil
}

type PatientScheduleTemplatePatientVM struct {
	ID   int64  `gorm:"column:id" json:"id" form:"id"`
	Name string `gorm:"column:name" json:"name" form:"name"`

	Contagions []*PatientScheduleContagion `gorm:"ForeignKey:PatientID" json:"contagions"`
}

func (PatientScheduleTemplatePatientVM) TableName() string {
	return "xt_patients"
}

type PatientScheduleContagion struct {
	ID        int64 `gorm:"column:id" json:"id" form:"id"`
	PatientID int64 `gorm:"column:patient_id" json:"-"`
	DiseaseID int64 `gorm:"column:disease_id" json:"disease_id" form:"disease_id"`
}

func (PatientScheduleContagion) TableName() string {
	return "xt_patients_infectious_diseases"
}

func PatientScheduleTemplateGetAllValidPatient(orgID int64) ([]*PatientScheduleTemplatePatientVM, error) {
	var vms []*PatientScheduleTemplatePatientVM
	err := readDb.
		Model(&PatientScheduleTemplatePatientVM{}).
		Preload("Contagions", "status = 1").
		Where("user_org_id = ? and lapseto=1 AND status = 1", orgID).
		Find(&vms).
		Error
	if err != nil {
		return nil, err
	}
	return vms, nil
}

func UpdateScheduleTemplate(orgID int64, templateID int64,
	addTemplateItems []*models.PatientScheduleTemplateItem,
	delTemplateItems []*models.PatientScheduleTemplateItem,
	changeTemplateItems []*models.PatientScheduleTemplateItem,
	shouldUpdateNextWeekSchedules bool,
	shouldUpdateNextSecondWeekSchedules bool) error {

	now := time.Now()
	tx := writeDb.Begin()

	// 批量插入 add template item
	if len(addTemplateItems) > 0 {
		// utils.TraceLog("addTemplateItems len: %v", len(addTemplateItems))
		valueStrs := make([]string, 0, len(addTemplateItems))
		values := make([]interface{}, 0, len(addTemplateItems)*10)
		for _, item := range addTemplateItems {
			valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
			values = append(values, orgID)
			values = append(values, templateID)
			values = append(values, item.DeviceNumberID)
			values = append(values, item.PatientID)
			values = append(values, item.TreatMode)
			values = append(values, item.Weekday)
			values = append(values, item.TimeType)
			values = append(values, 1)
			values = append(values, now.Unix())
			values = append(values, now.Unix())
		}

		sql := fmt.Sprintf("INSERT INTO xt_patient_schedule_template_item (org_id, template_id, device_number_id, patient_id, treat_mode, weekday, time_type, status, ctime, mtime) VALUES %v;", strings.Join(valueStrs, ", "))
		if insertErr := tx.Exec(sql, values...).Error; insertErr != nil {
			tx.Rollback()
			return insertErr
		}
	}

	// 批量假删除 del template item
	if len(delTemplateItems) > 0 {
		// utils.TraceLog("delTemplateItems len: %v", len(delTemplateItems))
		ins := make([]string, 0, len(delTemplateItems))
		for _, item := range delTemplateItems {
			ins = append(ins, fmt.Sprintf("(%v, %v, %v, %v, %v)", orgID, templateID, item.DeviceNumberID, item.Weekday, item.TimeType))
		}

		sql := fmt.Sprintf("UPDATE xt_patient_schedule_template_item SET status = 0, mtime = %v WHERE status = 1 AND (org_id, template_id, device_number_id, weekday, time_type) IN (%v);", now.Unix(), strings.Join(ins, ","))
		if delErr := tx.Exec(sql).Error; delErr != nil {
			tx.Rollback()
			return delErr
		}
	}

	// 批量更新 change template item
	if len(changeTemplateItems) > 0 {
		// utils.TraceLog("changeTemplateItems len: %v", len(changeTemplateItems))
		for _, item := range changeTemplateItems {
			if updateErr := tx.Exec("UPDATE xt_patient_schedule_template_item SET patient_id = ?, treat_mode = ?, mtime = ? WHERE status = 1 AND org_id = ? AND template_id = ? AND device_number_id = ? AND weekday = ? AND time_type = ?;", item.PatientID, item.TreatMode, now.Unix(), orgID, templateID, item.DeviceNumberID, item.Weekday, item.TimeType).Error; updateErr != nil {
				tx.Rollback()
				return updateErr
			}
		}
	}

	// 更改下两周的排班
	deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(orgID)
	if getDeviceNumbersErr != nil {
		tx.Rollback()
		return getDeviceNumbersErr
	}
	devicesMap := make(map[int64]*DeviceNumberViewModel, 0)
	for _, deviceNumber := range deviceNumbers {
		devicesMap[deviceNumber.ID] = deviceNumber
	}
	if shouldUpdateNextWeekSchedules {
		nextWeek := now.AddDate(0, 0, 7)
		if updateErr := _updateWeekSchedules(tx, orgID, nextWeek, addTemplateItems, delTemplateItems, changeTemplateItems, devicesMap); updateErr != nil {
			tx.Rollback()
			return updateErr
		}
	}
	if shouldUpdateNextSecondWeekSchedules {
		nextWeek := now.AddDate(0, 0, 14)
		if updateErr := _updateWeekSchedules(tx, orgID, nextWeek, addTemplateItems, delTemplateItems, changeTemplateItems, devicesMap); updateErr != nil {
			tx.Rollback()
			return updateErr
		}
	}

	tx.Commit()
	return nil
}

func _updateWeekSchedules(tx *gorm.DB, orgID int64, week time.Time, addTemplateItems []*models.PatientScheduleTemplateItem, delTemplateItems []*models.PatientScheduleTemplateItem, changeTemplateItems []*models.PatientScheduleTemplateItem, deviceNumberMap map[int64]*DeviceNumberViewModel) error {
	if deviceNumberMap == nil {
		deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(orgID)
		if getDeviceNumbersErr != nil {
			return getDeviceNumbersErr
		}
		deviceNumberMap = make(map[int64]*DeviceNumberViewModel, 0)
		for _, deviceNumber := range deviceNumbers {
			deviceNumberMap[deviceNumber.ID] = deviceNumber
		}
	}

	now := time.Now()
	monday, _ := utils.GetMondayAndSundayOfWeekDate(&week)

	// 先取消要取消的排班和新排班可能存在的重复排班
	delIns := make([]string, 0, len(addTemplateItems)+len(delTemplateItems))
	addValueStrs := make([]string, 0, len(addTemplateItems))
	addValues := make([]interface{}, 0, len(addTemplateItems)*11)

	for _, item := range addTemplateItems {
		scheduleDate := monday.AddDate(0, 0, int(item.Weekday-1))
		delIns = append(delIns, fmt.Sprintf("(%v, %v, %v)", item.DeviceNumberID, scheduleDate.Unix(), item.TimeType))

		// 构建新排班的条件
		deviceNumber := deviceNumberMap[item.DeviceNumberID]
		if deviceNumber != nil {
			addValueStrs = append(addValueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
			addValues = append(addValues, orgID)
			addValues = append(addValues, deviceNumber.ZoneID)
			addValues = append(addValues, item.DeviceNumberID)
			addValues = append(addValues, item.PatientID)
			addValues = append(addValues, scheduleDate.Unix())
			addValues = append(addValues, item.Weekday)
			addValues = append(addValues, item.TimeType)
			addValues = append(addValues, item.TreatMode)
			addValues = append(addValues, 1)
			addValues = append(addValues, now.Unix())
			addValues = append(addValues, now.Unix())
		}
	}
	for _, item := range delTemplateItems {
		delIns = append(delIns, fmt.Sprintf("(%v, %v, %v)", item.DeviceNumberID, monday.AddDate(0, 0, int(item.Weekday-1)).Unix(), item.TimeType))
	}
	if len(delIns) > 0 {
		sql := fmt.Sprintf("UPDATE xt_schedule SET status = 0, updated_time = %v WHERE user_org_id = %v AND status = 1 AND (bed_id, schedule_date, schedule_type) IN (%v);", now.Unix(), orgID, strings.Join(delIns, ","))
		if delErr := tx.Exec(sql).Error; delErr != nil {
			tx.Rollback()
			return delErr
		}
	}

	// 批量插入排班
	if len(addValueStrs) > 0 {
		sql := fmt.Sprintf("INSERT INTO xt_schedule (user_org_id, partition_id, bed_id, patient_id, schedule_date, schedule_week, schedule_type, mode_id, status, created_time, updated_time) VALUES %v;", strings.Join(addValueStrs, ", "))
		if insertErr := tx.Exec(sql, addValues...).Error; insertErr != nil {
			return insertErr
		}
	}

	// 更新已有排班
	if len(changeTemplateItems) > 0 {
		for _, item := range changeTemplateItems {
			if updateErr := tx.Exec("UPDATE xt_schedule SET patient_id = ?, mode_id = ?, updated_time = ? WHERE status = 1 AND user_org_id = ? AND bed_id = ? AND schedule_date = ? AND schedule_type = ?;", item.PatientID, item.TreatMode, now.Unix(), orgID, item.DeviceNumberID, monday.AddDate(0, 0, int(item.Weekday-1)).Unix(), item.TimeType).Error; updateErr != nil {
				tx.Rollback()
				return updateErr
			}
		}
	}

	return nil
}

func SavePatientScheduleTemplateMode(templateMode *models.PatientScheduleTemplateMode) error {
	tx := writeDb.Begin()
	saveErr := tx.Save(templateMode).Error
	if saveErr != nil {
		tx.Rollback()
		return saveErr
	}
	tx.Commit()
	return nil
}

// 1 -> 0 或 2 -> 0 则不处理排班，但清除所有模板item
func SavePatientScheduleTemplateModeAndClearAllTemplateItems(templateMode *models.PatientScheduleTemplateMode) error {
	tx := writeDb.Begin()
	saveErr := tx.Save(templateMode).Error
	if saveErr != nil {
		tx.Rollback()
		return saveErr
	}
	disableErr := tx.Model(&models.PatientScheduleTemplateItem{}).Where("org_id = ? AND status = 1", templateMode.OrgID).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	if disableErr != nil {
		tx.Rollback()
		return disableErr
	}
	tx.Commit()
	return nil
}

// 0 -> 1 或 0 -> 2 则直接清除下两周的排班
func SavePatientScheduleTemplateModeAndClearNextTwoWeekSchedules(templateMode *models.PatientScheduleTemplateMode) error {
	tx := writeDb.Begin()
	saveErr := tx.Save(templateMode).Error
	if saveErr != nil {
		tx.Rollback()
		return saveErr
	}

	now := time.Now()
	nextWeek := now.AddDate(0, 0, 7)
	nextMonday, _ := utils.GetMondayAndSundayOfWeekDate(&nextWeek)
	nextSecWeek := now.AddDate(0, 0, 14)
	_, nextSecSunday := utils.GetMondayAndSundayOfWeekDate(&nextSecWeek)
	disableErr := tx.Model(&models.Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date >= ? AND schedule_date <= ?", templateMode.OrgID, nextMonday.Unix(), nextSecSunday.Unix()).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
	if disableErr != nil {
		tx.Rollback()
		return disableErr
	}

	tx.Commit()
	return nil
}

// 1 -> 2 清除第二周排班
func SavePatientScheduleTemplateModeAndClearNextSecondWeekSchedules(templateMode *models.PatientScheduleTemplateMode) error {
	tx := writeDb.Begin()
	saveErr := tx.Save(templateMode).Error
	if saveErr != nil {
		tx.Rollback()
		return saveErr
	}

	now := time.Now()
	nextSecWeek := now.AddDate(0, 0, 14)
	nextSecMonday, nextSecSunday := utils.GetMondayAndSundayOfWeekDate(&nextSecWeek)
	disableErr := tx.Model(&models.Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date >= ? AND schedule_date <= ?", templateMode.OrgID, nextSecMonday.Unix(), nextSecSunday.Unix()).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
	if disableErr != nil {
		tx.Rollback()
		return disableErr
	}

	tx.Commit()
	return nil
}

// 2 -> 1 清除第二周模板item，清除第二周排班，将第一周的排班重复到第二周
func SavePatientScheduleTemplateMode2To1(templateMode *models.PatientScheduleTemplateMode, secondWeekTemplateID int64, firstWeekTemplateItems []*models.PatientScheduleTemplateItem) error {
	tx := writeDb.Begin()
	saveErr := tx.Save(templateMode).Error
	if saveErr != nil {
		tx.Rollback()
		return saveErr
	}

	now := time.Now()

	disableItemsErr := tx.Model(&models.PatientScheduleTemplateItem{}).Where("template_id = ? AND status = 1", secondWeekTemplateID).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
	if disableItemsErr != nil {
		tx.Rollback()
		return disableItemsErr
	}

	nextSecWeek := now.AddDate(0, 0, 14)
	nextSecMonday, nextSecSunday := utils.GetMondayAndSundayOfWeekDate(&nextSecWeek)
	disableSchsErr := tx.Model(&models.Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date >= ? AND schedule_date <= ?", templateMode.OrgID, nextSecMonday.Unix(), nextSecSunday.Unix()).Updates(map[string]interface{}{"status": 0, "mtime": now.Unix()}).Error
	if disableSchsErr != nil {
		tx.Rollback()
		return disableSchsErr
	}

	if len(firstWeekTemplateItems) > 0 {
		deviceNumbers, getDeviceNumbersErr := GetAllValidDeviceNumbers(templateMode.OrgID)
		if getDeviceNumbersErr != nil {
			tx.Rollback()
			return getDeviceNumbersErr
		}
		deviceNumberMap := make(map[int64]*DeviceNumberViewModel, 0)
		for _, deviceNumber := range deviceNumbers {
			deviceNumberMap[deviceNumber.ID] = deviceNumber
		}

		valueStrs := make([]string, 0, len(firstWeekTemplateItems))
		values := make([]interface{}, 0, len(firstWeekTemplateItems)*11)
		for _, item := range firstWeekTemplateItems {
			deviceNumber := deviceNumberMap[item.DeviceNumberID]
			if deviceNumber == nil {
				continue
			}

			valueStrs = append(valueStrs, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
			values = append(values, templateMode.OrgID)
			values = append(values, deviceNumber.ZoneID)
			values = append(values, item.DeviceNumberID)
			values = append(values, item.PatientID)
			values = append(values, nextSecMonday.AddDate(0, 0, int(item.Weekday-1)).Unix())
			values = append(values, item.Weekday)
			values = append(values, item.TimeType)
			values = append(values, item.TreatMode)
			values = append(values, 1)
			values = append(values, now.Unix())
			values = append(values, now.Unix())
		}

		sql := fmt.Sprintf("INSERT INTO xt_schedule (user_org_id, partition_id, bed_id, patient_id, schedule_date, schedule_week, schedule_type, mode_id, status, created_time, updated_time) VALUES %v;", strings.Join(valueStrs, ", "))
		if insertErr := tx.Exec(sql, values...).Error; insertErr != nil {
			return insertErr
		}
	}

	tx.Commit()
	return nil
}
