package service

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

func GetSignPatients(orgId int64, keywords string, dateTime, schedule_type int64) (patients []*models.SignPatients, err error) {
	db := readDb.
		Table("xt_patients as p").Where("p.user_org_id=?", orgId).
		Preload("SignWeight", "user_org_id = ? AND record_date=? AND status = 1", orgId, dateTime).
		Preload("DialysisOrder", "user_org_id = ? and dialysis_date = ? AND status = 1  ", orgId, dateTime).
		Preload("Schedule", "user_org_id = ? and schedule_date=? and status = 1", orgId, dateTime).
		Preload("PredialysisEvaluation", "user_org_id = ? and  assessment_date = ?", orgId, dateTime)
	if len(keywords) > 0 {
		likekey := "%" + keywords + "%"
		db = db.Where("p.name LIKE ? OR p.dialysis_no LIKE ? ", likekey, likekey)
	}
	db = db.Where("p.status=1")

	if schedule_type >= 1 && schedule_type <= 3 {
		db = db.Joins("JOIN xt_schedule AS s ON s.patient_id=p.id").Where("s.schedule_date = ? and s.schedule_type=? and s.status=1", dateTime, schedule_type)
	}
	err = db.Select("p.id, p.user_org_id, p.user_id, p.avatar, p.patient_type, p.dialysis_no, p.admission_number, p.source, p.lapseto, p.partition_id, p.bed_id, p.name, p.alias, p.gender, p.marital_status, p.id_card_no, p.birthday, p.reimbursement_way_id, p.health_care_type, p.health_care_no, p.health_care_due_date, p.height, p.blood_type, p.rh, p.health_care_due_alert_date, p.education_level, p.profession, p.phone, p.home_telephone, p.relative_phone, p.relative_relations, p.home_address, p.work_unit, p.unit_address, p.children, p.receiving_date, p.is_hospital_first_dialysis, p.first_dialysis_date, p.first_dialysis_hospital, p.predialysis_condition, p.pre_hospital_dialysis_frequency, p.pre_hospital_dialysis_times, p.hospital_first_dialysis_date, p.induction_period, p.initial_dialysis, p.total_dialysis, p.attending_doctor_id, p.head_nurse_id, p.evaluate, p.diagnose, p.remark, p.registrars_id, p.registrars, p.qr_code, p.binding_state, p.status, p.created_time, p.updated_time").Find(&patients).Error

	return
}

//GetSignPanels  签到称重班次休息
func GetSignPanels(orgid, dateTime int64) (map[int64]map[string]int64, error) {
	fmt.Println(dateTime)
	fmt.Println("世界的尽头")
	fmt.Println(orgid)
	panel := map[int64]map[string]int64{
		1: {"schedule": 0, "sign": 0, "before": 0, "after": 0},
		2: {"schedule": 0, "sign": 0, "before": 0, "after": 0},
		3: {"schedule": 0, "sign": 0, "before": 0, "after": 0},
	}
	var err error

	type schedule struct {
		ScheduleType int64
		ScheduleNums int64
	}

	var schedulePanels []schedule
	err = readDb.Model(&models.Schedule{}).Select("schedule_type, count(schedule_type) as schedule_nums").Where("schedule_date=? and user_org_id=? and status=?", dateTime, orgid, 1).Group("schedule_type").Scan(&schedulePanels).Error
	if err != nil {
		return panel, err
		fmt.Println("panel是什么", panel)
	}
	for _, schedulePanel := range schedulePanels {
		if _, exist := panel[schedulePanel.ScheduleType]; exist {
			panel[schedulePanel.ScheduleType]["schedule"] = schedulePanel.ScheduleNums
		}
	}

	type sign struct {
		ScheduleType int64
		SignNums     int64
	}

	var signPanels []sign
	err = readDb.Table("xt_assessment_before_dislysis as sw").Joins("JOIN xt_schedule as s ON s.patient_id = sw.patient_id").Select("count(sw.id) as sign_nums,s.schedule_type").Where("s.schedule_date = ? and sw.assessment_date = ? and s.user_org_id = ? and sw.status = 1 and s.status = 1", dateTime, dateTime, orgid).Group("s.schedule_type").Scan(&signPanels).Error

	if err != nil {
		return panel, err
	}
	fmt.Println("singpanels是什么东西", signPanels)
	for _, signPanel := range signPanels {
		if _, exist := panel[signPanel.ScheduleType]; exist {
			panel[signPanel.ScheduleType]["sign"] = signPanel.SignNums
		}
	}

	type befor struct {
		ScheduleType int64
		SignNums     int64
	}

	var befors []befor
	err = readDb.Table("xt_assessment_before_dislysis as sw").Joins("JOIN xt_schedule as s ON s.patient_id = sw.patient_id").Select("count(sw.id) as sign_nums,s.schedule_type").Where("s.schedule_date = ? and sw.assessment_date = ? and s.user_org_id = ? and sw.status = 1 and s.status = 1", dateTime, dateTime, orgid).Group("s.schedule_type").Scan(&befors).Error

	if err != nil {
		return panel, err
	}
	fmt.Println("singpanels是什么东西", befors)
	for _, signPanel := range befors {
		if _, exist := panel[signPanel.ScheduleType]; exist {
			panel[signPanel.ScheduleType]["before"] = signPanel.SignNums
		}
	}

	type after struct {
		ScheduleType int64
		AfterNums    int64
	}

	var afters []after
	err = readDb.Table("xt_assessment_after_dislysis as sw").Joins("JOIN xt_schedule as s ON s.patient_id = sw.patient_id").Select("count(sw.id) as after_nums,s.schedule_type").Where("s.schedule_date = ? and sw.assessment_date = ? and s.user_org_id = ? and sw.status = 1 and s.status = 1", dateTime, dateTime, orgid).Group("s.schedule_type").Scan(&afters).Error

	if err != nil {
		return panel, err
	}
	fmt.Println("after是什么东西", afters)
	for _, signPanel := range afters {
		if _, exist := panel[signPanel.ScheduleType]; exist {
			panel[signPanel.ScheduleType]["after"] = signPanel.AfterNums
		}
	}

	return panel, nil

}

func GetPatientDateSign(orgid, dateTime, patientId int64) (*models.SigninAndWeigh, error) {
	var sig models.SigninAndWeigh
	var err error
	err = readDb.Model(&models.SigninAndWeigh{}).Where("record_date = ? and patient_id=? and user_org_id=?", dateTime, patientId, orgid).First(&sig).Error
	fmt.Println("错误", err)
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}

	return &sig, nil
}

func EditPatientSign(m *models.SigninAndWeigh) error {
	var err error
	if m.ID > 0 {
		err = writeDb.Save(&m).Error
	} else {
		err = writeDb.Create(&m).Error
	}
	return err
}

func GetPatientInformationList(orgid, patientId int64, datetime int64) *models.PredialysisEvaluation {
	var pre models.PredialysisEvaluation
	err := readDb.Model(&models.PredialysisEvaluation{}).Where("patient_id=? and user_org_id=? and assessment_date =?", patientId, orgid, datetime).First(&pre).Error
	if err != nil {

	}
	return &pre
}

func GetInforByPatient(orgid, patientId int64, datetime int64) *models.AssessmentAfterDislysis {
	var ass models.AssessmentAfterDislysis
	err := readDb.Model(&models.AssessmentAfterDislysis{}).Where("patient_id=? and user_org_id=? and assessment_date=?", patientId, orgid, datetime).First(&ass).Error
	if err != nil {

	}

	return &ass
}

func SaveData(pre *models.PredialysisEvaluation, patientId int64, orgId int64) error {
	err := writeDb.Model(pre).Where("patient_id=? and user_org_id=?", patientId, orgId).Update(map[string]interface{}{"weight_before": pre.WeightBefore,
		"dry_weight": pre.DryWeight, "temperature": pre.Temperature, "pulse_frequency": pre.PulseFrequency, "breathing_rate": pre.BreathingRate, "systolic_blood_pressure": pre.SystolicBloodPressure, "diastolic_blood_pressure": pre.DiastolicBloodPressure}).Error
	return err
}

func Editdata(dis *models.AssessmentAfterDislysis, patientId int64, orgId int64) error {
	err := writeDb.Model(dis).Where("patient_id=? and user_org_id=?", patientId, orgId).Update(map[string]interface{}{"weight_after": dis.WeightAfter,
		"dry_weight": dis.DryWeight, "temperature": dis.Temperature, "pulse_frequency": dis.PulseFrequency, "breathing_rate": dis.BreathingRate, "systolic_blood_pressure": dis.SystolicBloodPressure, "diastolic_blood_pressure": dis.DiastolicBloodPressure}).Error

	return err
}

func Savesignweigh(sw *models.SignWeight) error {
	var err error
	err = writeDb.Create(&sw).Error
	return err
}
func Updatesignweigh(sw *models.SignWeight, patientId int64, orgId int64) error {
	writeDb.Model(sw).Where("patient_id=? and user_org_id=?", patientId, orgId).Update(map[string]interface{}{"sign_time": sw.SignTime,
		"record_date": sw.RecordDate, "weightbefore": sw.WeightBefore, "dry_weight_before": sw.DryWeightBefore, "temperature_before": sw.TemperatureBefore,
		"pulse_frequency_before": sw.PulseFrequencyBefore, "breathing_rate_before": sw.BreathingRateBefore, "systolic_blood_pressure_before": sw.SystolicBloodPressureBefore,
		"diastolic_blood_pressure_before": sw.DiastolicBloodPressureBefore, "weightafter": sw.WeightAfter, "temperature_after": sw.TemperatureAfter, "pulse_frequency_after": sw.PulseFrequencyAfter,
		"breathing_rate_after": sw.BreathingRateAfter, "systolic_blood_pressure_after": sw.SystolicBloodPressureAfter, "diastolic_blood_pressure_after": sw.DiastolicBloodPressureAfter,
		"status": sw.Status, "created_time": sw.CreatedTime, "weigh_before_time": sw.WeighBeforeTime, "weigh_time": sw.WeighTime})
	return err
}

func GetSign(orgid, dateTime, patientId int64) (*models.SignWeight, error) {
	var sigs models.SignWeight
	var err error
	err = readDb.Model(&models.SignWeight{}).Where("record_date = ? and patient_id=? and user_org_id = ?", dateTime, patientId, orgid).First(&sigs).Error
	fmt.Println("错误", err)
	if err == gorm.ErrRecordNotFound {

		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &sigs, nil
}

func GetSignweigh(orgid, patientId int64) *models.SignWeight {
	var sw models.SignWeight
	err := readDb.Model(&models.SignWeight{}).Where("patient_id=? and user_org_id =?", patientId, orgid).First(&sw).Error
	if err != nil {

	}
	return &sw
}

func GetDislysisBerfore(orgid, dateTime, patientId int64) (*models.PredialysisEvaluation, error) {
	var pre models.PredialysisEvaluation
	var err error
	err = readDb.Model(&models.PredialysisEvaluation{}).Where("assessment_date =? and patient_id =? and user_org_id = ?", dateTime, patientId, orgid).Find(&pre).Error
	fmt.Println("错误", err)
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &pre, nil

}

func SaveDislysisiBefore(pre *models.PredialysisEvaluation) error {
	var err error
	err = writeDb.Create(&pre).Error
	return err
}

func UpdataDislysisiBefore(pre *models.PredialysisEvaluation, patientId int64, orgId int64, datatime int64) error {
	writeDb.Model(pre).Where("patient_id=? and user_org_id=? and assessment_date =?", patientId, orgId, datatime).Update(map[string]interface{}{"weight_before": pre.WeightBefore,
		"dry_weight": pre.DryWeight, "temperature": pre.DryWeight, "pulse_frequency": pre.PulseFrequency, "systolic_blood_pressure": pre.SystolicBloodPressure, "diastolic_blood_pressure": pre.DiastolicBloodPressure, "status": 1})
	return err
}

func GetAssessmentaafterdislysis(orgid, dateTime, patientId int64) (*models.AssessmentAfterDislysis, error) {
	var ass models.AssessmentAfterDislysis
	var err error
	err = readDb.Model(&models.AssessmentAfterDislysis{}).Where("assessment_date =? and patient_id =? and user_org_id = ?", dateTime, patientId, orgid).Find(&ass).Error
	fmt.Println("错误", err)
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &ass, nil
}
func SaveAssessmentafter(ass *models.AssessmentAfterDislysis) error {
	var err error
	err = writeDb.Create(&ass).Error
	return err
}

func UpdataAssessment(ass *models.AssessmentAfterDislysis, patientId int64, orgId int64, datetime int64) error {
	writeDb.Model(ass).Where("patient_id=? and user_org_id=? and assessment_date=? ", patientId, orgId, datetime).Update(map[string]interface{}{"weight_after": ass.WeightAfter,
		"dry_weight": ass.DryWeight, "temperature": ass.Temperature, "pulse_frequency": ass.PulseFrequency, "systolic_blood_pressure": ass.SystolicBloodPressure, "diastolic_blood_pressure": ass.DiastolicBloodPressure, "status": 1})
	return err
}

func GetForenoonData(dataTime int64, orgid int64, scheduleType int64) (total int64, schedule []*models.Schedule, err error) {
	err = readDb.Count(total).Where("schedule_date = ? AND user_org_id = ? AND schedule_type = ?", dataTime, orgid, scheduleType).Find(&scheduleType).Error
	fmt.Println("heeeeeeeeeehhhhh", err)
	return total, schedule, err
}
