package service

import (
	"XT_New/models"
	"time"

	"github.com/jinzhu/gorm"
)

func GetPatientByID(orgID int64, patientID int64) (*models.Patients, error) {
	var patient models.Patients
	err := readDb.Model(&models.Patients{}).Where("id = ? and user_org_id=? and status=1", patientID, orgID).First(&patient).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &patient, nil
}

func GetPatientCourseOfDisease(orgID int64, patientID int64, startTime int64, endTime int64) ([]*models.PatientDiseaseCourse, error) {
	var records []*models.PatientDiseaseCourse
	err := readDb.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and patient_id = ? and record_time >= ? and record_time <= ? and status = 1", orgID, patientID, startTime, endTime).Order("record_time desc").Find(&records).Error
	if err != nil {
		return nil, err
	}
	return records, nil
}

func CreatePatientCourseOfDisease(record *models.PatientDiseaseCourse) error {
	err := writeDb.Model(&models.PatientDiseaseCourse{}).Create(record).Error
	return err
}

func GetPatientRescueRecords(orgID int64, patientID int64, startTime int64, endTime int64) ([]*models.PatientRescueRecord, error) {
	var records []*models.PatientRescueRecord
	err := readDb.Model(&models.PatientRescueRecord{}).Where("org_id = ? and patient_id = ? and record_time >= ? and record_time <= ? and status = 1", orgID, patientID, startTime, endTime).Order("record_time desc").Find(&records).Error
	if err != nil {
		return nil, err
	}
	return records, nil
}

func CreatePatientRescueRecord(record *models.PatientRescueRecord) error {
	err := writeDb.Model(&models.PatientRescueRecord{}).Create(record).Error
	return err
}

func ModifyPatientCourses(record *models.PatientDiseaseCourse) error {
	err := writeDb.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and patient_id = ? and status = 1 and id = ?", record.OrgID, record.PatientID, record.ID).Updates(map[string]interface{}{"content": record.Content, "record_time": record.RecordTime, "mtime": time.Now().Unix(), "title": record.Title}).Error
	return err
}

func DeletePatientCoursesInBatch(orgID int64, patientID int64, recordIDs []int64) error {
	err := writeDb.Model(&models.PatientDiseaseCourse{}).Where("org_id = ? and patient_id = ? and id in (?) and status = 1", orgID, patientID, recordIDs).Updates(map[string]interface{}{"status": 2, "mtime": time.Now().Unix()}).Error
	return err
}

func DeletePatientResuceRecordsInBatch(orgID int64, patientID int64, recordIDs []int64) error {
	err := writeDb.Model(&models.PatientRescueRecord{}).Where("org_id = ? and patient_id = ? and id in (?) and status = 1", orgID, patientID, recordIDs).Updates(map[string]interface{}{"status": 2, "mtime": time.Now().Unix()}).Error
	return err
}
