package service

import (
	"Xcx_New/models"
	"time"
)

func GetHisPrescriptionTemplatesList(patient_id int64, org_id int64, page int64, limit int64) (templates []*models.HisPrescriptionTemplate, total int64, err error) {
	offset := (page - 1) * limit
	db := readDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND patient_id= ? AND status = 1", org_id, patient_id)
	err = db.Count(&total).Offset(offset).Limit(limit).Find(&templates).Error
	return
}

func GetHisPrescriptionTemplateByID(template_id int64) (prescription models.HisPrescriptionTemplate, err error) {
	err = readDb.Model(&models.HisPrescriptionTemplate{}).Where("id = ? AND status = 1 ", template_id).First(&prescription).Error
	return
}

func SaveHisPrescriptionTemplate(template *models.HisPrescriptionTemplate) (err error) {
	err = writeDb.Save(&template).Error
	return

}

func DelelteHisPrescriptionInfoTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func DelelteHisPrescriptionTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0}).Error
	err = writeDb.Model(&models.HisPrescriptionInfoTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func DelelteHisPrescriptionAdviceTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionAdviceTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func DelelteHisPrescriptionProjectTemplate(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error

	return
}
