package system

import (
	"go.uber.org/zap"
	"miniapp/global"
	"miniapp/model/common"
	"miniapp/model/common/request"
)

type HospitalService struct {
}

// GetHospitalList 获取医院列表
func (h HospitalService) GetHospitalList(p request.PageInfo) (list []common.Hospital, total int64, err error) {
	err = global.GVA_DB.Scopes(Page(p.Page, p.PageSize)).Preload("Notes").Preload("Todos").Find(&list).Offset(-1).Limit(-1).Count(&total).Error
	return
}

// CreateHospital 创建医院
func (h HospitalService) CreateHospital(hospital *common.Hospital) (err error) {
	return global.GVA_DB.Create(&hospital).Error
}

// UpdateHospital 更新医院
func (h HospitalService) UpdateHospital(hospital *common.Hospital) (err error) {
	for i := range hospital.Notes {
		if hospital.Notes[i].NotesTime == "手术前" {
			hospital.Notes[i].NotestimeNum = 1
		} else if hospital.Notes[i].NotesTime == "手术中" {
			hospital.Notes[i].NotestimeNum = 2
		} else {
			hospital.Notes[i].NotestimeNum = 3
		}
	}
	err = global.GVA_DB.Model(&common.Notes{}).Save(&hospital.Notes).Error
	if err != nil {
		global.GVA_LOG.Error("更新医院注意事项失败", zap.Error(err))
		return
	}
	err = global.GVA_DB.Model(&hospital).Association("Notes").Replace(&hospital.Notes)
	if err != nil {
		global.GVA_LOG.Error("更新医院注意事项失败", zap.Error(err))
		return
	}

	err = global.GVA_DB.Model(&common.Todos{}).Save(&hospital.Todos).Error
	if err != nil {
		global.GVA_LOG.Error("更新医院Todo失败", zap.Error(err))
		return
	}
	err = global.GVA_DB.Model(&hospital).Association("Todos").Replace(&hospital.Todos)
	if err != nil {
		global.GVA_LOG.Error("更新医院Todo关联失败", zap.Error(err))
		return
	}

	return global.GVA_DB.Save(&hospital).Error
}

// DeleteHospital 删除医院
func (h HospitalService) DeleteHospital(hospital *common.Hospital) (err error) {
	err = global.GVA_DB.Model(&hospital).Association("Notes").Clear()
	err = global.GVA_DB.Model(&hospital).Association("Todos").Clear()
	if err != nil {
		return err
	}
	return global.GVA_DB.Delete(&hospital).Error
}

// GetHospitalById 根据id获取医院
func (h HospitalService) GetHospitalById(id uint) (hospital *common.Hospital, err error) {
	err = global.GVA_DB.Where("id = ?", id).Preload("Notes").Preload("Todos").First(&hospital).Error
	return
}

func (h HospitalService) GetHospitalNotes(p request.GetHospitalNotes) (list []common.Notes, err error) {
	var ids []string
	err = global.GVA_DB.Table("hospital_notes").Where("hospital_id = ?", p.HospitalId).Pluck("notes_id", &ids).Error
	if err != nil {
		global.GVA_LOG.Error("获取医院注意事项失败", zap.Error(err))
		return
	}

	err = global.GVA_DB.Where("id in ? and notestime_num = ?", ids, p.TimeNum).Find(&list).Error
	return

}
