// 统计后台的 service

package service

import (
	"Data_Upload_Api/models"
	"Data_Upload_Api/models/sz"

	"github.com/jinzhu/gorm"
	"strings"
)

func GetSyncTimeByOrgId(org_id int64, sync_type int64) (sync_info models.XTSyncInfo, err error) {
	err = readDb.Model(&models.XTSyncInfo{}).Where("org_id = ? and sync_type = ? ", org_id, sync_type).Last(&sync_info).Error
	return
}

func FindAllDataUploadConfigOrgInfo(province_id int64, city_id int64, config_type int64) (data []*sz.DataUploadConfig, err error) {
	err = readDb.Model(&sz.DataUploadConfig{}).Where("status = 1 AND province_id = ? AND city_id = ? AND config_type = ?", province_id, city_id, config_type).Find(&data).Error
	return
}

func FindDataUploadOrgInfo(org_id int64, module_type int64) (data sz.DataUpload, err error) {
	err = readDb.Model(&sz.DataUpload{}).Where(" org_id = ? AND module_type = ?", org_id, module_type).Last(&data).Error
	return
}

func FindOrgData(org_id int64, sync_time int64) (org models.UserOrg, err error) {
	err = readUserDb.Model(&models.UserOrg{}).Where("status = 1 AND id = ? AND ctime > ?", org_id, sync_time).Preload("DeviceNumber", func(db *gorm.DB) *gorm.DB {
		return readDb.Where("status = 1")
	}).Find(&org).Error
	return
}
func FindOrgRolesData(org_id int64, lastUploadTime int64, nowTime int64) (role []*models.UserAdminRole, err error) {
	db := readUserDb.Model(&models.UserAdminRole{}).Where("status = 1 AND org_id = ?  ", org_id)
	db.Where("ctime >= ? AND ctime <= ?", lastUploadTime, nowTime)
	err = db.Find(&role).Error
	return
}
func FindOrgPatientData(org_id int64, lastUploadTime int64, nowTime int64) (patient []*models.Patients, err error) {
	db := readDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ?", org_id)
	db = db.Where("created_time >= ? AND created_time <= ?", lastUploadTime, nowTime)
	err = db.Find(&patient).Error

	return
}

func FindOrgPatientOutData(org_id int64, lastUploadTime int64, nowTime int64) (patient []*models.Patients, err error) {
	db := readDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND lapseto = 2 ", org_id).Preload("PatientLapseto", "status = 1")
	db = db.Where("created_time >= ? AND created_time <= ?", lastUploadTime, nowTime)
	err = db.Find(&patient).Error
	return
}

func FindOrgScheduleData(org_id int64, lastUploadTime int64, nowTime int64) (sch []*models.Schedule, err error) {
	db := readDb.Model(&models.Schedule{}).Where("status = 1 AND user_org_id = ?", org_id).Preload("DeviceNumber", "status = 1")

	if lastUploadTime != 0 && nowTime != 0 {
		db = db.Where("created_time >= ? AND created_time <= ?", lastUploadTime, nowTime)
	}
	err = db.Find(&sch).Error
	return
}

func FindOrgDialysisPrescriptionData(org_id int64, lastUploadTime int64, nowTime int64) (ps []*models.DialysisPrescription, err error) {
	db := readDb.Model(&models.DialysisPrescription{}).Where("status = 1 AND user_org_id = ?", org_id).Preload("AssessmentBeforeDislysis", "status = 1").Preload("DialysisOrder", "status = 1")
	db = db.Where("created_time >= ? AND created_time <= ?", lastUploadTime, nowTime)
	err = db.Find(&ps).Error
	return
}

func FindOrgMonitorRecordData(org_id int64, lastUploadTime int64, nowTime int64) (monitor []*models.MonitoringRecord, err error) {
	db := readDb.Model(&models.MonitoringRecord{}).Where("status = 1 AND user_org_id = ?", org_id)

	db = db.Where("created_time >= ? AND created_time <= ?", lastUploadTime, nowTime)
	err = db.Find(&monitor).Error

	return
}

func CreateOrgRecord(hospital *sz.TempHdHospital) (err error) {
	err = writeDb.Model(&sz.TempHdHospital{}).Create(&hospital).Error
	return
}

func CreateUploadRecord(upload *sz.DataUpload) (err error) {
	err = writeDb.Model(&sz.DataUpload{}).Create(&upload).Error
	return
}

func FindOrgDialysisData(org_id int64, lastUploadTime int64, nowTime int64) (ps []*models.VMSchedule, err error) {
	db := readDb.Model(&models.VMSchedule{}).Where("status = 1 AND user_org_id = ? ", org_id).
		Preload("DeviceNumber", "status = 1").
		Preload("VMDialysisPrescription", "status = 1").
		Preload("AssessmentBeforeDislysis", "status = 1").
		Preload("AssessmentAfterDislysis", "status = 1").
		Preload("DialysisOrder", "status = 1").
		Preload("MonitoringRecord", "status = 1")

	if lastUploadTime != 0 && nowTime != 0 {
		db = db.Where("created_time >= ? AND created_time <= ?", lastUploadTime, nowTime)
	}
	err = db.Find(&ps).Error
	return
}
func FindOrgDeviceZoneRecordData(org_id int64, lastUploadTime int64, nowTime int64) (zone []*models.DeviceZone, err error) {
	db := readDb.Model(&models.DeviceZone{}).Where("status = 1 AND  org_id = ?", org_id)
	if lastUploadTime != 0 && nowTime != 0 {
		db = db.Where("ctime >= ? AND ctime <= ?", lastUploadTime, nowTime)
	}
	err = db.Find(&zone).Error

	return
}

func FindOrgWaterMachineData(org_id int64, lastUploadTime int64, nowTime int64) (waterMachine []*models.VMDeviceAddmacher, err error) {

	db := readDb.Model(&models.VMDeviceAddmacher{}).Where("status = 1 AND  user_org_id = ?", org_id)

	db = db.Where("ctime >= ? AND ctime <= ?", lastUploadTime, nowTime)

	err = db.Find(&waterMachine).Error

	return
}

func BatchCreateWMsRecord(wms []*sz.TempHdWm, rdb *gorm.DB) (err error) {
	if len(wms) > 0 {
		utx := rdb.Begin()
		if len(wms) > 0 {
			thisSQL := "INSERT INTO t_hd_wm (HOSPITAL_ID, EQUIPMENT_ID, EQUIPMENT_BRAND, EQUIPMENT_MODEL, ENABLE_TIME,DISCARDED_TIME,EQUIPMENT_TYPE,XGBZ,CREATE_TIME,UPDATE_TIME,SJSCSJ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, wm := range wms {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, wm.HospitalId)
				insertData = append(insertData, wm.EquipmentId)
				insertData = append(insertData, wm.EquipmentBrand)
				insertData = append(insertData, wm.EquipmentModel)
				insertData = append(insertData, wm.EnableTime)
				insertData = append(insertData, wm.DiscardedTime)
				insertData = append(insertData, wm.EquipmentType)
				insertData = append(insertData, wm.Xgbz)
				insertData = append(insertData, wm.CreateTime)
				insertData = append(insertData, wm.UpdateTime)
				insertData = append(insertData, wm.Sjscsj)

			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreateStaffRecord(staffs []*sz.TempHdStaff, rdb *gorm.DB) (err error) {
	if len(staffs) > 0 {
		utx := rdb.Begin()
		if len(staffs) > 0 {
			thisSQL := "INSERT INTO t_hd_staff (HOSPITAL_ID, STAFF_ID, STAFF_NAME, POSITION, PERMANENT_TYPE,CREATE_TIME,UPDATE_TIME,SJSCSJ,MJ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range staffs {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.HospitalId)
				insertData = append(insertData, info.StaffId)
				insertData = append(insertData, info.StaffName)
				insertData = append(insertData, info.Position)
				insertData = append(insertData, info.PermanentType)
				insertData = append(insertData, info.CreateTime)
				insertData = append(insertData, info.UpdateTime)
				insertData = append(insertData, info.Sjscsj)
				insertData = append(insertData, info.Xgbz)
			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreatePatinet(patients []*sz.TempHdPatient, rdb *gorm.DB) (err error) {
	if len(patients) > 0 {
		utx := rdb.Begin()
		if len(patients) > 0 {
			thisSQL := "INSERT INTO t_hd_patient (HOSPITAL_ID, PATIENT_NK, CARD_NO, CARD_TYPE, ID_NO,ID_TYPE,PATIENT_NAME,GENDER,BORN_DATE,DIAGNOSIS_SUMMARY,IS_CRF,CREATE_TIME,UPDATE_TIME,SJSCSJ,XGBZ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range patients {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.HospitalId)
				insertData = append(insertData, info.PatientNk)
				insertData = append(insertData, info.CardNo)
				insertData = append(insertData, info.CardType)
				insertData = append(insertData, info.IdNo)
				insertData = append(insertData, info.IdType)
				insertData = append(insertData, info.PatientName)
				insertData = append(insertData, info.Gender)
				insertData = append(insertData, info.BornDate)
				insertData = append(insertData, info.DiagnosisSummary)
				insertData = append(insertData, info.IsCrf)
				insertData = append(insertData, info.CreatedTime)
				insertData = append(insertData, info.UpdateTime)
				insertData = append(insertData, info.Sjscsj)
				insertData = append(insertData, info.Xgbz)

			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreateSchedual(patients []*sz.TempHdShift, rdb *gorm.DB) (err error) {
	if len(patients) > 0 {
		utx := rdb.Begin()
		if len(patients) > 0 {
			thisSQL := "INSERT INTO t_hd_shift (PS_ID, HOSPITAL_ID, PATIENT_NK, SCHEDULE_DATE, SHIFT_TYPE,SICKBED_NO,SCHEDULE_STATUS,CREATE_TIME,SJSCSJ,XGBZ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range patients {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.PsId)
				insertData = append(insertData, info.HospitalId)
				insertData = append(insertData, info.PatientNk)
				insertData = append(insertData, info.ScheduleDate)
				insertData = append(insertData, info.ShiftType)
				insertData = append(insertData, info.SickbedNo)
				insertData = append(insertData, info.ScheduleStatus)
				insertData = append(insertData, info.CreateTime)
				insertData = append(insertData, info.Sjscsj)
				insertData = append(insertData, info.Xgbz)

			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreatePs(patients []*sz.TempHdPs, rdb *gorm.DB) (err error) {
	if len(patients) > 0 {
		utx := rdb.Begin()
		if len(patients) > 0 {
			thisSQL := "INSERT INTO t_hd_shift (PRESCRIBE_ID, HOSPITAL_ID, PATIENT_NK, K, CA,NA,DIALYSIS_FREQUENCY,FREQUENCY_UNIT,DIALYSIS_DURATION,HDF,HP,HP_FREQUENCY,HP_FREQUENCY_UNIT,HP_DURATION,HDF_FREQUENCY_UNIT,HDF_FREQUENCY,HDF_DURATION,CREATE_TIME,SJSCSJ,XGBZ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range patients {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.PrescribeId)
				insertData = append(insertData, info.HospitalId)
				insertData = append(insertData, info.PatientNk)
				insertData = append(insertData, info.K)
				insertData = append(insertData, info.Ca)
				insertData = append(insertData, info.Na)
				insertData = append(insertData, info.DialysisFrequency)
				insertData = append(insertData, info.FrequencyUnit)
				insertData = append(insertData, info.DialysisDuration)
				insertData = append(insertData, info.Hdf)
				insertData = append(insertData, info.Hp)
				insertData = append(insertData, info.HpFrequency)
				insertData = append(insertData, info.HpFrequencyUnit)
				insertData = append(insertData, info.HpDuration)
				insertData = append(insertData, info.HdfFrequencyUnit)
				insertData = append(insertData, info.HdfFrequency)
				insertData = append(insertData, info.HdfDuration)
				insertData = append(insertData, info.CreateTime)
				insertData = append(insertData, info.Sjscsj)
				insertData = append(insertData, info.Xgbz)

			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreatePsm(psms []*sz.TempHdPsMedicine, rdb *gorm.DB) (err error) {
	if len(psms) > 0 {
		utx := rdb.Begin()
		if len(psms) > 0 {
			thisSQL := "INSERT INTO t_hd_shift (PRESCRIBE_ID, HOSPITAL_ID, MEDICINE_TYPE_ID,MEDICINE_ID,CREATE_TIME,SJSCSJ,XGBZ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, psm := range psms {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?)")
				insertData = append(insertData, psm.PrescribeId)
				insertData = append(insertData, psm.HospitalId)
				insertData = append(insertData, psm.MedicineTypeId)
				insertData = append(insertData, psm.MedicineId)
				insertData = append(insertData, psm.CreatedTime)
				insertData = append(insertData, psm.Sjscsj)
				insertData = append(insertData, psm.Xgbz)

			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreatePatientOut(patientOuts []*sz.TempHdPatientOut, rdb *gorm.DB) (err error) {
	if len(patientOuts) > 0 {
		utx := rdb.Begin()
		if len(patientOuts) > 0 {
			thisSQL := "INSERT INTO t_hd_patient_out (HOSPITAL_ID, PATIENT_NK,SEQUELAE_DATE,SEQUELAE_TYPE,CREATE_TIME,SJSCSJ,XGBZ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, out := range patientOuts {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?)")
				insertData = append(insertData, out.HospitalId)
				insertData = append(insertData, out.PatientNk)
				insertData = append(insertData, out.SequelaeDate)
				insertData = append(insertData, out.SequelaeType)
				insertData = append(insertData, out.CreateTime)
				insertData = append(insertData, out.Sjscsj)
				insertData = append(insertData, out.Xgbz)

			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreateDoctorsAdvice(advices []*sz.TempHdDoctorsAdvice, rdb *gorm.DB) (err error) {
	if len(advices) > 0 {
		utx := rdb.Begin()
		if len(advices) > 0 {
			thisSQL := "INSERT INTO t_hd_doctors_advice (MEDICAL_ORDER_ID, HOSPITAL_ID,DIALYSIS_ID,ORDER_TYPE,PATIENT_NK,DIALYSIS_DURATION,BLOOD_VOL,CREATE_TIME,SJSCSJ,XGBZ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, advice := range advices {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, advice.MedicalOrDerId)
				insertData = append(insertData, advice.HospitalId)
				insertData = append(insertData, advice.DialysisId)
				insertData = append(insertData, advice.OrderType)
				insertData = append(insertData, advice.PatientNk)
				insertData = append(insertData, advice.DialysisDuration)
				insertData = append(insertData, advice.BloodVol)
				insertData = append(insertData, advice.CreateTime)
				insertData = append(insertData, advice.Sjscsj)
				insertData = append(insertData, advice.Xgbz)

			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}

func BatchCreateMonitor(advices []*sz.TempHdMiddle, rdb *gorm.DB) (err error) {
	if len(advices) > 0 {
		utx := rdb.Begin()
		if len(advices) > 0 {
			thisSQL := "INSERT INTO t_hd_doctors_advice (HOSPITAL_ID, PATIENT_NK,DIALYSIS_ID,MONITOR_TIME,SBP,DBP,CREATE_TIME,SJSCSJ,XGBZ) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, advice := range advices {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, advice.HospitalId)
				insertData = append(insertData, advice.PatientNk)
				insertData = append(insertData, advice.DialysisId)
				insertData = append(insertData, advice.MonitorTime)
				insertData = append(insertData, advice.Sbp)
				insertData = append(insertData, advice.Dbp)
				insertData = append(insertData, advice.CreateTime)
				insertData = append(insertData, advice.Sjscsj)
				insertData = append(insertData, advice.Xgbz)
			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return
}
