package service

import (
	"Xcx_New/models"
	"fmt"
	"github.com/jinzhu/gorm"
)

func GetDialysisParametersByKeyword(orgID int64, keyword string, schedulType int64, partitionType int64, page int64, limit int64, schedulDate int64) ([]*models.DialysisParameter, error, int64) {
	fmt.Println("scheduletye ======================", schedulType)
	var patients []*models.Patients
	getPatientErr := readDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND (name like ? OR dialysis_no like ?)", orgID, "%"+keyword+"%", "%"+keyword+"%").Find(&patients).Error
	if getPatientErr != nil {
		return nil, getPatientErr, 0
	}
	patientIDs := make([]int64, len(patients))
	for index, patient := range patients {
		patientIDs[index] = patient.ID
	}

	db := readDb.
		Model(&models.DialysisSchedule{}).
		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
		Preload("TreatmentMode", "status = 1").
		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
	db = db.Where("xt_schedule.status = 1 AND patient_id in (?)", patientIDs)
	if schedulType > 0 {
		db = db.Where("schedule_type = ?", schedulType)
	}
	if partitionType > 0 {
		db = db.Joins("inner join xt_device_number as d_n on d_n.id = xt_schedule.bed_id and d_n.zone_id = ? and d_n.status = 1", partitionType)
	}
	if schedulDate > 0 {
		db = db.Where("schedule_date = ?", schedulDate)
	}
	var schedules []*models.DialysisParameter
	total := int64(0)
	err := db.Count(&total).Offset(limit * (page - 1)).Limit(limit).Order("schedule_date desc").Find(&schedules).Error
	return schedules, err, total
}

func GetDialysisParameter(orgID int64, schedulDate int64, schedulType int64, partitionType int64, page int64, limit int64) (schedule []*models.DialysisParameter, err error, total int64) {
	db := readDb.
		Model(&models.MonitorDialysisSchedule{}).
		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
		Preload("TreatmentMode", "status = 1").
		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("MonitoringRecord", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", orgID).Order("operate_time asc")
		}).
		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
	db = db.Where("xt_schedule.status = 1 AND user_org_id = ?", orgID)
	if schedulDate > 0 {
		db = db.Where("schedule_date = ?", schedulDate)
	}
	if schedulType > 0 {
		db = db.Where("schedule_type = ?", schedulType)
	}
	if partitionType > 0 {
		db = db.Joins("inner join xt_device_number on xt_device_number.id = xt_schedule.bed_id and xt_device_number.zone_id = ? and xt_device_number.status = 1", partitionType)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Offset(offset).Limit(limit).Order("bed_id desc").Find(&schedule).Error
	return schedule, err, total
}

func GetDialysisBatchParameters(schIDs []string, orgID int64) (schedule []*models.DialysisParameter, err error) {

	db := readDb.
		Model(&models.DialysisSchedule{}).
		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
		Preload("TreatmentMode", "status = 1").
		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
	db = db.Where("xt_schedule.status = 1 AND id in (?)", schIDs)
	var schedules []*models.DialysisParameter
	err = db.Order("schedule_date desc").Find(&schedules).Error
	return schedules, err
}

func GetWareHouseOutList(startime int64, endtime int64, orgid int64) (warehouse []*models.XtWarehouseOutInfo, err error) {

	db := XTReadDB().Table("xt_warehouse_out_info as x").Where("x.status = 1")
	if startime > 0 {
		db = db.Where("x.sys_record_time >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.sys_record_time<=?", endtime)
	}
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	err = db.Select("x.id,x.warehouse_out_id,x.good_id,x.good_type_id,x.count,x.warehouse_out_order_number,x.sys_record_time,s.specification_name,t.type_name").Joins("left join xt_good_information as s on s.id = x.good_id").Where("s.status = 1 and s.org_id = ?", orgid).Joins("left join xt_goods_type as t on t.id = x.good_type_id").Order("x.id desc").Scan(&warehouse).Error
	return warehouse, err
}

func GetAllMaterial(startime int64, endtime int64, orgid int64) (reducedetail []*models.XtAutomaticReduceDetail, err error) {

	db := XTReadDB().Table("xt_automatic_reduce_detail as x").Where("x.status = 1")
	if startime > 0 {
		db = db.Where("x.record_time>=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.record_time<=?", endtime)
	}
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	err = db.Select("x.patient_id,x.record_time,x.good_id,t.type_name").Joins("left join xt_goods_type as t on t.id = x.good_type_id").Group("x.good_type_id").Scan(&reducedetail).Error
	return reducedetail, err
}

func GetCollectList(limit int64, page int64, partitionType int64, schedulType int64, schedulDate int64, orgID int64, keyword string) ([]*models.DialysisParameter, error, int64) {

	var patients []*models.Patients
	getPatientErr := readDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND (name like ? OR dialysis_no like ?)", orgID, "%"+keyword+"%", "%"+keyword+"%").Find(&patients).Error
	if getPatientErr != nil {
		return nil, getPatientErr, 0
	}
	patientIDs := make([]int64, len(patients))
	for index, patient := range patients {
		patientIDs[index] = patient.ID
	}

	db := readDb.
		Model(&models.DialysisSchedule{}).
		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
		Preload("TreatmentMode", "status = 1").
		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
	db = db.Where("xt_schedule.status = 1 AND patient_id in (?)", patientIDs)
	if schedulType > 0 {
		db = db.Where("schedule_type = ?", schedulType)
	}
	if partitionType > 0 {
		db = db.Joins("inner join xt_device_number as d_n on d_n.id = xt_schedule.bed_id and d_n.zone_id = ? and d_n.status = 1", partitionType)
		// db = db.Where("partition_id = ?", partitionType)
	}
	if schedulDate > 0 {
		db = db.Where("schedule_date = ?", schedulDate)
	}
	var schedules []*models.DialysisParameter
	total := int64(0)
	err := db.Count(&total).Offset(limit * (page - 1)).Limit(limit).Order("schedule_date desc").Find(&schedules).Error
	return schedules, err, total
}

func GetDialysisConsumables(startime int64, endtime int64, orgid int64) (reducedetail []*models.XtAutomaticReduceDetail, err error) {

	db := XTReadDB().Table("xt_automatic_reduce_detail as x").Where("x.status = 1")
	table := XTReadDB().Table("xt_warehouse_out_info as f").Where("f.status = 1 and f.org_id = ?", orgid)
	fmt.Println(table)
	if startime > 0 {
		db = db.Where("x.record_time >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.record_time <=?", endtime)
	}
	if orgid > 0 {
		db = db.Where("x.org_id =?", orgid)
	}
	err = db.Select("x.patient_id,x.count,x.good_id,x.good_type_id,t.specification_name,s.type_name").Joins("left join xt_good_information as t on t.id = x.good_id").Where("t.org_id = ? and t.status = 1", orgid).Joins("left join xt_goods_type as s on s.id = x.good_type_id").Joins("left join xt_warehouse_out_info as f on f.id = x.warehouse_out_id").Scan(&reducedetail).Error
	return reducedetail, err
}

func GetBatchCollection(orgID int64, schIDs []string) (schedules []*models.DialysisParameter, err error) {

	db := readDb.
		Model(&models.DialysisSchedule{}).
		Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
		// Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
		Preload("TreatmentMode", "status = 1").
		Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
		Preload("AssessmentBeforeDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("AssessmentAfterDislysis", "status = 1 AND  user_org_id = ?", orgID).
		Preload("MonitoringRecord", "status = 1 AND  user_org_id = ?", orgID).
		Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
		Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID)
	db = db.Where("xt_schedule.status = 1 AND id in (?)", schIDs)
	err = db.Order("schedule_date desc").Find(&schedules).Error
	return schedules, err
}

func GetAnticoagulantCount(startime int64, endtime int64, orgid int64) (prescriptionCount []*models.DialysisPrescriptionCount, err error) {

	db := XTReadDB().Table("xt_dialysis_prescription as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ? and x.anticoagulant <> 0", orgid)
	}
	if startime > 0 {
		db = db.Where("x.record_date >= ?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.record_date<=?", endtime)
	}

	err = db.Select("x.patient_id,x.anticoagulant,x.record_date,count(id) as count").Group("x.anticoagulant").Scan(&prescriptionCount).Error
	return prescriptionCount, err
}

func GetDialysisTodaySchedulePatient(orgid int64, startime int64, page int64, limit int64) (schedule []*models.XtSchedule, err error) {
	offset := (page - 1) * limit
	err = XTReadDB().Model(&schedule).Where("user_org_id = ? and schedule_date = ? and status = 1", orgid, startime).Offset(offset).Limit(limit).Find(&schedule).Error
	return schedule, err
}

func GetToDayDialysisPrescription(patientid int64, orgid int64, startime int64) (*models.XtDialysisPrescription, error) {
	prescription := models.XtDialysisPrescription{}
	err := XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and record_date = ? and status = 1", patientid, orgid, startime).Find(&prescription).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &prescription, nil

}

func GetLastDialysisPrescription(patientid int64, orgid int64) (models.XtDialysisPrescription, error) {

	prescription := models.XtDialysisPrescription{}
	err = XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and status = 1", patientid, orgid).Last(&prescription).Error
	return prescription, err
}

func GetLastAssessmentBeforDialysis(patientid int64, orgid int64) (models.PredialysisEvaluation, error) {

	evaluation := models.PredialysisEvaluation{}
	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and status = 1", patientid, orgid).Last(&evaluation).Error
	return evaluation, err
}

func GetDialysisPrescriptionList(patientid int64, orgid int64, startime int64) (models.XtDialysisPrescription, error) {
	prescription := models.XtDialysisPrescription{}
	err := XTReadDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and status = 1 and record_date = ?", patientid, orgid, startime).Find(&prescription).Error
	return prescription, err
}

func GetTodayAssessmentBeforDialysis(patientid int64, orgid int64, startime int64) (*models.PredialysisEvaluation, error) {

	evaluation := models.PredialysisEvaluation{}
	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and assessment_date = ? and status = 1", patientid, orgid, startime).Find(&evaluation).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &evaluation, nil
}

func GetAssessmentBeforDialysisByStartime(patientid int64, orgid int64, startime int64) (models.PredialysisEvaluation, error) {
	evaluation := models.PredialysisEvaluation{}
	err := XTReadDB().Model(&evaluation).Where("patient_id = ? and user_org_id = ? and assessment_date = ? and status = 1", patientid, orgid, startime).Find(&evaluation).Error
	return evaluation, err
}

func GetAotoMaticReduceByPatientId(patientid int64, orgid int64, startime int64, endtime int64) (*models.BloodAutomaticReduceDetail, error) {

	detail := models.BloodAutomaticReduceDetail{}
	err := XTReadDB().Model(&detail).Where("patient_id = ? and org_id =? and record_time >=? and record_time <=? and status = 1", patientid, orgid, startime, endtime).Find(&detail).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &detail, nil
}

func GetMaticReduece(patientid int64, orgid int64) (models.BloodAutomaticReduceDetail, error) {

	detail := models.BloodAutomaticReduceDetail{}
	err := XTReadDB().Model(&detail).Where("patient_id = ? and org_id= ?  and status = 1", patientid, orgid).Last(&detail).Error

	return detail, err
}

func GetMaticeReduceByPatientId(patientid int64, orgid int64, startime int64, endtime int64) (models.BloodAutomaticReduceDetail, error) {

	detail := models.BloodAutomaticReduceDetail{}
	err := XTReadDB().Model(&detail).Where("patient_id = ? and org_id = ? and record_time >=? and record_time<=? and status =1", patientid, orgid, startime, endtime).Find(&detail).Error
	return detail, err
}
