package service

import (
	"XT_New/models"
	"errors"
	"strings"
	"time"
)

func GetInspectionReference(orgId int64) (reference []*models.InspectionReference, err error) {
	var count int
	err = readDb.Model(&models.InspectionReference{}).Where("org_id=? and status=1", orgId).Count(&count).Error
	if count > 0 {
		err = readDb.Model(&models.InspectionReference{}).Where("org_id=? and status=1", orgId).Order("project_id").Find(&reference).Error
	} else {
		err = readDb.Model(&models.InspectionReference{}).Where("org_id=0 and status=1").Order("project_id").Find(&reference).Error
	}
	return
}

func GetPatientInspectionProjectCount(orgId, patientId int64) (projectCounts []*models.UserInspectionProjectCount, err error) {
	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and status=1", patientId, orgId).Select("count(distinct inspect_date) as count, project_id, patient_id").Group("project_id").Scan(&projectCounts).Error
	return
}

func GetPatientInspectionByDate(orgId, patientId, date, projectId int64) (inspections []*models.Inspection, err error) {
	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id =? and inspect_date =? and status=1", patientId, orgId, projectId, date).Find(&inspections).Error
	return
}

func GetAdvices(orgid int64, patientid int64, recorddate int64) (advcie []*models.DoctorAdvice, err error) {

	err = XTReadDB().Model(&models.DoctorAdvice{}).Where("patient_id = ? and user_org_id = ? and record_date = ? and status =1", patientid, orgid, recorddate).Find(&advcie).Error
	return
}

func CreatePatientInspection(inspectins []models.Inspection) (err error) {
	if len(inspectins) == 0 {
		err = errors.New("Inspections Cant be nil.")
		return
	}

	thisSQL := "INSERT INTO xt_inspection (patient_id, org_id, project_id, item_id, item_name, project_name, inspect_type, inspect_value, inspect_date, status, created_time, updated_time) VALUES "
	insertParams := make([]string, 0)
	insertData := make([]interface{}, 0)
	for _, inspectin := range inspectins {
		insertParams = append(insertParams, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
		insertData = append(insertData, inspectin.PatientId)
		insertData = append(insertData, inspectin.OrgId)
		insertData = append(insertData, inspectin.ProjectId)
		insertData = append(insertData, inspectin.ItemId)
		insertData = append(insertData, inspectin.ItemName)
		insertData = append(insertData, inspectin.ProjectName)
		insertData = append(insertData, inspectin.InspectType)
		insertData = append(insertData, inspectin.InspectValue)
		insertData = append(insertData, inspectin.InspectDate)
		insertData = append(insertData, 1)
		insertData = append(insertData, inspectin.CreatedTime)
		insertData = append(insertData, inspectin.UpdatedTime)
	}
	thisSQL += strings.Join(insertParams, ", ")
	err = writeDb.Exec(thisSQL, insertData...).Error
	return
}

func EditPatientInspection(add []models.Inspection, edit []models.Inspection, noDeleteIDs []int64, patientId, orgId, projectId, date int64) (err error) {
	if len(add) == 0 && len(edit) == 0 && len(noDeleteIDs) == 0 {
		err = errors.New(" Cant be nil.")
		return
	}

	tx := writeDb.Begin()

	if len(noDeleteIDs) > 0 {
		err = tx.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id =? and inspect_date =? and id NOT IN (?) and status=1", patientId, orgId, projectId, date, noDeleteIDs).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
		if err != nil {
			tx.Rollback()
			return
		}
	}

	if len(edit) > 0 {
		for _, item := range edit {
			err = tx.Save(&item).Error
			if err != nil {
				tx.Rollback()
				return
			}
		}
	}
	if len(add) > 0 {
		thisSQL := "INSERT INTO xt_inspection (patient_id, org_id, project_id, item_id, item_name, project_name, inspect_type, inspect_value, inspect_date, status, created_time, updated_time) VALUES "
		insertParams := make([]string, 0)
		insertData := make([]interface{}, 0)
		for _, inspectin := range add {
			insertParams = append(insertParams, "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
			insertData = append(insertData, inspectin.PatientId)
			insertData = append(insertData, inspectin.OrgId)
			insertData = append(insertData, inspectin.ProjectId)
			insertData = append(insertData, inspectin.ItemId)
			insertData = append(insertData, inspectin.ItemName)
			insertData = append(insertData, inspectin.ProjectName)
			insertData = append(insertData, inspectin.InspectType)
			insertData = append(insertData, inspectin.InspectValue)
			insertData = append(insertData, inspectin.InspectDate)
			insertData = append(insertData, 1)
			insertData = append(insertData, inspectin.CreatedTime)
			insertData = append(insertData, inspectin.UpdatedTime)
		}
		thisSQL += strings.Join(insertParams, ", ")
		err = tx.Exec(thisSQL, insertData...).Error
		if err != nil {
			tx.Rollback()
			return
		}
	}
	tx.Commit()

	return
}

func DeletePatientInspection(orgId, patientId, projectId, date int64) (err error) {
	err = writeDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id =? and inspect_date =? and status=1", patientId, orgId, projectId, date).Update(map[string]interface{}{"Status": 0, "UpdatedTime": time.Now().Unix()}).Error
	return
}

func GetPatientInspections(orgId, patientId, projectId, page int64) (inspections []*models.Inspection, total int64, date int64, err error) {

	var projectCount models.UserInspectionProjectCount
	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id=? and status=1", patientId, orgId, projectId).Select("count(distinct inspect_date) as count, project_id, patient_id").Scan(&projectCount).Error

	if err != nil {
		return
	}

	total = projectCount.Count
	if total == 0 || page > total {
		return
	}

	var Id models.InspectionDate
	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id=? and status=1", patientId, orgId, projectId).Select("inspect_date").Group("inspect_date").Order("inspect_date desc").Offset(page - 1).Limit(1).Scan(&Id).Error
	if err != nil {
		return
	}
	if Id.InspectDate == 0 {
		return
	}

	date = Id.InspectDate

	inspections, err = GetPatientInspectionByDate(orgId, patientId, Id.InspectDate, projectId)
	if err != nil {
		return
	}

	return

}

type DateViewModel struct {
	inspect_date int64 `gorm:"column:inspect_date" json:"inspect_date"`
	project_id   int64 `gorm:"column:project_id" json:"project_id"`
}

func FindLastRecordDate(orgId int64, patientId int64, project_id int64) (inspections models.Inspection, err error) {
	err = readDb.Raw("SELECT max(inspect_date) as inspect_date,project_id   FROM `xt_inspection`  WHERE (status = 1 AND org_id = ? AND project_id = ?  AND patient_id = ?) ORDER BY `xt_inspection`.`id` ASC LIMIT 1", orgId, project_id, patientId).Scan(&inspections).Error
	return
}

func UpDateInfectiousRecordTime(orgId int64, patientId int64, time int64, remind_cycle int64) (err error) {
	err = writeDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND id = ?", orgId, patientId).Updates(map[string]interface{}{"infectious_next_record_time": time, "remind_cycle": remind_cycle}).Error
	return
}

func GetAllPatientInspection(orgId, patientId, page int64, projectId int64, start_time int64, end_time int64) (inspections []*models.Inspection, date int64, err error) {

	//var projectCount models.UserInspectionProjectCount
	//err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id in (?)  and status=1", patientId, orgId,projectId).Select("count(distinct inspect_date) as count, project_id, patient_id").Scan(&projectCount).Error
	//
	//if err != nil {
	//	return
	//}
	//
	//total = projectCount.Count
	//if total == 0 || page > total {
	//	return
	//}

	var Id models.InspectionDate
	err = readDb.Model(&models.Inspection{}).Where("patient_id=? and org_id=? and project_id=? and status=1 and inspect_date >= ? and inspect_date <= ?", patientId, orgId, projectId, start_time, end_time).Select("inspect_date").Group("inspect_date").Order("inspect_date desc").Offset(page - 1).Limit(1).Scan(&Id).Error
	if err != nil {
		return
	}
	if Id.InspectDate == 0 {
		return
	}

	date = Id.InspectDate

	inspections, err = GetPatientInspectionByDate(orgId, patientId, Id.InspectDate, projectId)
	if err != nil {
		return
	}

	return

}

func GetAllInspectionReference(orgId int64) (inspectionReference []*models.InspectionReference, err error) {
	err = readDb.Model(&models.InspectionReference{}).Where("org_id = ? AND status = 1", orgId).Find(&inspectionReference).Error
	return
}