package service

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

func GetIllnessListTwo() (ills []*models.Illness, err error) {
	err = readUserDb.Where("status=1").Find(&ills).Error
	return
}

func GetBloodDialysisPatient(orgid int64, page int64, limit int64) (patients []*models.Patients, total int64, err error) {
	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.created_time desc").Offset(offset).Limit(limit).
		Select("x.id,x.user_org_id,x.user_id,x.avatar,x.patient_type,x.dialysis_no,x.admission_number,x.source,x.lapseto,x.partition_id,x.bed_id,x.name,x.alias,x.gender,x.marital_status,x.id_card_no,x.birthday,x.reimbursement_way_id,x.health_care_type,x.health_care_no,x.health_care_due_date,x.height,x.blood_type,x.rh,x.health_care_due_alert_date,x.education_level,x.profession,x.phone,x.home_telephone,x.relative_phone,x.relative_relations,x.home_address,x.work_unit,x.unit_address,x.children,x.receiving_date,x.is_hospital_first_dialysis,x.first_dialysis_date,x.first_dialysis_hospital,x.predialysis_condition,x.pre_hospital_dialysis_frequency,x.pre_hospital_dialysis_times,x.hospital_first_dialysis_date,x.induction_period,x.initial_dialysis,x.total_dialysis,x.attending_doctor_id,x.head_nurse_id,x.evaluate,x.diagnose,x.remark,x.registrars_id,x.registrars,x.qr_code,x.binding_state,x.patient_complains,x.present_history,x.past_history,x.temperature,x.pulse,x.respiratory,x.sbp,x.dbp,x.status,x.created_time,x.updated_time,x.nation,x.native_place,x.age,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id").Find(&patients).Error
	fmt.Println("err是什么", err)
	return
}

func GetAllBloodDialysisPatient(orgid int64, page int64, limit int64) (patients []*models.XtPatientsNew, total int64, err error) {
	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ? and x.blood_patients = 1", orgid)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.created_time desc").Offset(offset).Limit(limit).
		Select("x.id,x.user_org_id,x.user_id,x.avatar,x.patient_type,x.dialysis_no,x.admission_number,x.source,x.lapseto,x.partition_id,x.bed_id,x.name,x.alias,x.gender,x.marital_status,x.id_card_no,x.birthday,x.reimbursement_way_id,x.health_care_type,x.health_care_no,x.health_care_due_date,x.height,x.blood_type,x.rh,x.health_care_due_alert_date,x.education_level,x.profession,x.phone,x.home_telephone,x.relative_phone,x.relative_relations,x.home_address,x.work_unit,x.unit_address,x.children,x.receiving_date,x.is_hospital_first_dialysis,x.first_dialysis_date,x.first_dialysis_hospital,x.predialysis_condition,x.pre_hospital_dialysis_frequency,x.pre_hospital_dialysis_times,x.hospital_first_dialysis_date,x.induction_period,x.initial_dialysis,x.total_dialysis,x.attending_doctor_id,x.head_nurse_id,x.evaluate,x.diagnose,x.remark,x.registrars_id,x.registrars,x.qr_code,x.binding_state,x.patient_complains,x.present_history,x.past_history,x.temperature,x.pulse,x.respiratory,x.sbp,x.dbp,x.status,x.created_time,x.updated_time,x.nation,x.native_place,x.age,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id").Find(&patients).Error
	fmt.Println("err是什么", err)
	return
}

func GetAllSlowPatient(orgid int64, page int64, limit int64) (patients []*models.XtPatientsNew, total int64, err error) {
	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ? and x.slow_patients = 1", orgid)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.created_time desc").Offset(offset).Limit(limit).
		Select("x.id,x.user_org_id,x.user_id,x.avatar,x.patient_type,x.dialysis_no,x.admission_number,x.source,x.lapseto,x.partition_id,x.bed_id,x.name,x.alias,x.gender,x.marital_status,x.id_card_no,x.birthday,x.reimbursement_way_id,x.health_care_type,x.health_care_no,x.health_care_due_date,x.height,x.blood_type,x.rh,x.health_care_due_alert_date,x.education_level,x.profession,x.phone,x.home_telephone,x.relative_phone,x.relative_relations,x.home_address,x.work_unit,x.unit_address,x.children,x.receiving_date,x.is_hospital_first_dialysis,x.first_dialysis_date,x.first_dialysis_hospital,x.predialysis_condition,x.pre_hospital_dialysis_frequency,x.pre_hospital_dialysis_times,x.hospital_first_dialysis_date,x.induction_period,x.initial_dialysis,x.total_dialysis,x.attending_doctor_id,x.head_nurse_id,x.evaluate,x.diagnose,x.remark,x.registrars_id,x.registrars,x.qr_code,x.binding_state,x.patient_complains,x.present_history,x.past_history,x.temperature,x.pulse,x.respiratory,x.sbp,x.dbp,x.status,x.created_time,x.updated_time,x.nation,x.native_place,x.age,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id").Find(&patients).Error
	fmt.Println("err是什么", err)
	return
}

func GetAllMemberPatient(orgid int64, page int64, limit int64) (patients []*models.XtPatientsNew, total int64, err error) {
	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ? and x.member_patients = 1", orgid)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.created_time desc").Offset(offset).Limit(limit).
		Select("x.id,x.user_org_id,x.user_id,x.avatar,x.patient_type,x.dialysis_no,x.admission_number,x.source,x.lapseto,x.partition_id,x.bed_id,x.name,x.alias,x.gender,x.marital_status,x.id_card_no,x.birthday,x.reimbursement_way_id,x.health_care_type,x.health_care_no,x.health_care_due_date,x.height,x.blood_type,x.rh,x.health_care_due_alert_date,x.education_level,x.profession,x.phone,x.home_telephone,x.relative_phone,x.relative_relations,x.home_address,x.work_unit,x.unit_address,x.children,x.receiving_date,x.is_hospital_first_dialysis,x.first_dialysis_date,x.first_dialysis_hospital,x.predialysis_condition,x.pre_hospital_dialysis_frequency,x.pre_hospital_dialysis_times,x.hospital_first_dialysis_date,x.induction_period,x.initial_dialysis,x.total_dialysis,x.attending_doctor_id,x.head_nurse_id,x.evaluate,x.diagnose,x.remark,x.registrars_id,x.registrars,x.qr_code,x.binding_state,x.patient_complains,x.present_history,x.past_history,x.temperature,x.pulse,x.respiratory,x.sbp,x.dbp,x.status,x.created_time,x.updated_time,x.nation,x.native_place,x.age,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id").Find(&patients).Error
	fmt.Println("err是什么", err)
	return
}

func GetAllPatient(orgid int64) (patients []*models.PatientsNew, err error) {
	db := XTReadDB().Table("xt_patients_new as x")

	err = db.Raw("select id,name from xt_patients_new where user_org_id = ? and status =1", orgid).Scan(&patients).Error
	return
}

func ChechLastDialysisNoTwo(orgID int64) (dialysisNo int64) {
	var patient models.Patients
	err := readDb.Model(&models.Patients{}).Where("user_org_id=? and status = 1", orgID).Order("dialysis_no desc").First(&patient).Error
	if err != nil {
		return
	}

	if patient.ID == 0 {
		return
	}
	dialysisNo, _ = strconv.ParseInt(patient.DialysisNo, 10, 64)
	return
}

func GetBloodPatientInfo(orgid int64, phone string) (*models.Patients, error) {
	patients := models.Patients{}
	var err error
	err = XTReadDB().Model(&patients).Where("user_org_id = ? and phone = ? and status = 1", orgid, phone).Find(&patients).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &patients, nil
}

func GetSlowPatientInfo(orgid int64, phone string) (*models.CdmPatients, error) {
	patients := models.CdmPatients{}
	var err error
	err = PatientReadDB().Model(&patients).Where("user_org_id = ? and phone = ? and status = 1", orgid, phone).Find(&patients).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &patients, nil
}

func GetMemberPatientInfo(orgid int64, phone string) (*models.SgjUserCustomer, error) {
	customer := models.SgjUserCustomer{}
	err := UserReadDB().Model(&customer).Where("user_org_id = ? and mobile = ? and status =1", orgid, phone).Find(&customer).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &customer, nil
}

func CreateOldPatient(patients *models.Patients) error {

	err := XTWriteDB().Create(&patients).Error
	return err
}

func GetLastOldPatient(orgid int64) (models.Patients, error) {
	patients := models.Patients{}
	err := XTReadDB().Model(&patients).Where("user_org_id = ? and status =1", orgid).Last(&patients).Error
	return patients, err
}

func AddContagions(patienid int64, createdtime int64, updatedtime int64, contagions []int64) (err error) {
	utx := writeDb.Begin()
	if len(contagions) > 0 {
		thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
		insertParams := make([]string, 0)
		insertData := make([]interface{}, 0)
		for _, contagion := range contagions {
			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
			insertData = append(insertData, patienid)
			insertData = append(insertData, contagion)
			insertData = append(insertData, 1)
			insertData = append(insertData, createdtime)
			insertData = append(insertData, updatedtime)
		}
		thisSQL += strings.Join(insertParams, ",")
		err = utx.Exec(thisSQL, insertData...).Error
		fmt.Println("这个错误err", err)
	}
	utx.Commit()
	return
}

func AddSlowContagions(patienid int64, createdtime int64, updatedtime int64, contagions []int64, orgid int64) (err error) {
	utx := PatientWriteDB().Begin()
	if len(contagions) > 0 {
		thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time,user_org_id) VALUES "
		insertParams := make([]string, 0)
		insertData := make([]interface{}, 0)
		for _, contagion := range contagions {
			insertParams = append(insertParams, "(?, ?, ?, ?, ?,?)")
			insertData = append(insertData, patienid)
			insertData = append(insertData, contagion)
			insertData = append(insertData, 1)
			insertData = append(insertData, createdtime)
			insertData = append(insertData, updatedtime)
			insertData = append(insertData, orgid)
		}
		thisSQL += strings.Join(insertParams, ", ")
		err = utx.Exec(thisSQL, insertData...).Error
		if err != nil {
			utx.Rollback()
			utx.Rollback()
			return
		}
	}
	utx.Commit()
	return
}

func AddSlowDiseases(patienid int64, createdtime int64, updatedtime int64, diseases []int64, orgid int64) (err error) {
	utx := PatientWriteDB().Begin()
	if len(diseases) > 0 {
		thisSQL := "INSERT INTO xt_patients_chronic_diseases (patient_id, disease_id, status, created_time, updated_time,user_org_id) VALUES "
		insertParams := make([]string, 0)
		insertData := make([]interface{}, 0)
		for _, disease := range diseases {
			insertParams = append(insertParams, "(?, ?, ?, ?, ?,?)")
			insertData = append(insertData, patienid)
			insertData = append(insertData, disease)
			insertData = append(insertData, 1)
			insertData = append(insertData, createdtime)
			insertData = append(insertData, updatedtime)
			insertData = append(insertData, orgid)
		}
		thisSQL += strings.Join(insertParams, ", ")
		err = utx.Exec(thisSQL, insertData...).Error
		if err != nil {
			utx.Rollback()
			return
		}
	}
	utx.Commit()
	return
}

func CreateNewPatient(patientsNew *models.XtPatientsNew) error {
	err := XTWriteDB().Create(&patientsNew).Error
	return err
}

func CreateCdmPatient(cdmpatient *models.CdmPatients) error {
	err := PatientWriteDB().Create(&cdmpatient).Error
	return err
}

func CreateMemberPatient(customer *models.SgjUserCustomer) error {

	err := UserWriteDB().Create(&customer).Error
	return err
}

func GetOldCdmPatient(orgid int64) (models.CdmPatients, error) {
	patients := models.CdmPatients{}
	err := PatientReadDB().Model(&patients).Where("user_org_id = ? and status =1", orgid).Last(&patients).Error
	return patients, err
}

func GetPatientDetailTwo(id int64) (models.XtPatientsNew, error) {
	patients := models.XtPatientsNew{}
	err := XTReadDB().Where("id=? and status = 1", id).Find(&patients).Error
	return patients, err
}

func GetPatientDiseasesTwo(id int64) []int64 {
	var dis []models.XtPatientsInfectiousDiseases
	ids := make([]int64, 0)
	err := XTReadDB().Model(&models.XtPatientsInfectiousDiseases{}).Where("patient_id = ? and status = 1", id).Find(&dis).Error
	if err != nil || len(dis) == 0 {
		return ids
	}
	for _, item := range dis {
		ids = append(ids, item.DiseaseId)
	}
	return ids
}

func GetSlowPatientDiseases(id int64) (infeciousdisease []*models.CdmPatientsInfectiousDiseases, err error) {
	//var dis  []models.CdmPatientsInfectiousDiseases
	//diseases := models.CdmPatientsChronicDiseases{}
	//ids := make([]int64, 0)
	//err := PatientReadDB().Model(&diseases).Where("patient_id = ? and status =1", id).Find(&ids).Error
	//if err != nil || len(dis) == 0 {
	//  return ids
	//}
	//for _, item := range dis {
	//  ids = append(ids, item.DiseaseId)
	//}
	//return ids
	err = PatientReadDB().Model(&infeciousdisease).Where("patient_id = ? and status =1", id).Find(&infeciousdisease).Error
	return infeciousdisease, err
}

func GetCronicDiseases(id int64) (chronic []*models.CdmPatientsChronicDiseases, err error) {
	//var dis  []models.CdmPatientsChronicDiseases
	//ids := make([]int64, 0)
	//err := PatientReadDB().Model(&models.CdmPatientsChronicDiseases{}).Where("patient_id = ? and status =1", id).Find(&ids).Error
	//if err != nil || len(dis) == 0 {
	//  return ids
	//}
	//for _, item := range dis {
	//  ids = append(ids, item.DiseaseId)
	//}
	//return ids
	err = PatientReadDB().Model(&chronic).Where("patient_id = ? and status =1", id).Find(&chronic).Error
	return chronic, err
}

func CreatePatientTwo(patient *models.Patients, contagions []int64, diseases []int64) (err error) {

	user, _ := GetSgjUserByMobild(patient.Phone)
	customer, _ := GetSgjCoustomerByMobile(patient.UserOrgId, patient.Phone)

	utx := writeDb.Begin()
	btx := writeUserDb.Begin()

	if user.ID == 0 {

		user.Mobile = patient.Phone
		user.Avatar = patient.Avatar
		user.AvatarThumb = patient.Avatar
		user.Birthday = patient.Birthday
		user.Username = patient.Name
		user.Gender = patient.Gender
		user.Sources = 11
		user.Introduce = patient.Remark
		user.Status = 1
		user.UpdatedTime = patient.UpdatedTime
		user.CreatedTime = patient.CreatedTime
		err = btx.Create(&user).Error
		if err != nil {
			utx.Rollback()
			btx.Rollback()
			return
		}
	}
	patient.UserId = user.ID

	if customer == nil {
		err = btx.Create(&models.SgjCustomer{
			UserOrgId:   patient.UserOrgId,
			UserId:      user.ID,
			Mobile:      patient.Phone,
			Name:        patient.Name,
			Gender:      patient.Gender,
			Birthday:    patient.Birthday,
			Sources:     11,
			Status:      1,
			CreatedTime: patient.CreatedTime,
			UpdatedTime: patient.UpdatedTime,
			Avatar:      patient.Avatar,
			Remark:      patient.Remark,
		}).Error
		if err != nil {
			utx.Rollback()
			btx.Rollback()
			return
		}
	}

	err = utx.Create(patient).Error
	if err != nil {
		utx.Rollback()
		btx.Rollback()
		return
	}

	var lapseto models.PatientLapseto
	lapseto.PatientId = patient.ID
	lapseto.LapsetoType = patient.Lapseto
	lapseto.CreatedTime = patient.CreatedTime
	lapseto.UpdatedTime = patient.CreatedTime
	lapseto.Status = 1
	lapseto.LapsetoTime = patient.CreatedTime

	err = utx.Create(&lapseto).Error
	if err != nil {
		utx.Rollback()
		btx.Rollback()
		return
	}

	if len(contagions) > 0 {
		thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
		insertParams := make([]string, 0)
		insertData := make([]interface{}, 0)
		for _, contagion := range contagions {
			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
			insertData = append(insertData, patient.ID)
			insertData = append(insertData, contagion)
			insertData = append(insertData, 1)
			insertData = append(insertData, patient.CreatedTime)
			insertData = append(insertData, patient.UpdatedTime)
		}
		thisSQL += strings.Join(insertParams, ", ")
		err = utx.Exec(thisSQL, insertData...).Error
		if err != nil {
			utx.Rollback()
			btx.Rollback()
			return
		}
	}
	if len(diseases) > 0 {
		thisSQL := "INSERT INTO xt_patients_chronic_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
		insertParams := make([]string, 0)
		insertData := make([]interface{}, 0)
		for _, disease := range diseases {
			insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
			insertData = append(insertData, patient.ID)
			insertData = append(insertData, disease)
			insertData = append(insertData, 1)
			insertData = append(insertData, patient.CreatedTime)
			insertData = append(insertData, patient.UpdatedTime)
		}
		thisSQL += strings.Join(insertParams, ", ")
		err = utx.Exec(thisSQL, insertData...).Error
		if err != nil {
			utx.Rollback()
			btx.Rollback()
			return
		}
	}
	utx.Commit()
	btx.Commit()

	return
}

func GetPatientData(phone string, orgid int64) (*models.XtPatientsNew, error) {
	var patientnew models.XtPatientsNew
	var err error
	err = XTReadDB().Model(&patientnew).Where("user_org_id = ? and phone = ? and status =? and blood_patients = ?", orgid, phone, 1, 1).Find(&patientnew).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &patientnew, nil
}

func GetSlowPatientData(phone string, orgid int64) (*models.CdmPatients, error) {
	var patientnew models.CdmPatients
	err = PatientReadDB().Model(&patientnew).Where("user_org_id = ? and phone = ? and status = ?", orgid, phone, 1).Find(&patientnew).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &patientnew, nil
}

func GetMemberNewPatient(phone string, orgid int64) (*models.XtPatientsNew, error) {
	var patientnew models.XtPatientsNew
	err = XTReadDB().Model(&patientnew).Where("user_org_id = ? and phone = ? and status = ? and member_patients = ?", orgid, phone, 1, 1).Find(&patientnew).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &patientnew, nil
}

func GetLastMemberPatient(orgid int64) (models.SgjUserCustomer, error) {
	customer := models.SgjUserCustomer{}
	err := UserReadDB().Model(&customer).Where("user_org_id = ? and status = 1", orgid).Last(&customer).Error
	return customer, err
}

func GetLastNewSlowPatient(phone string, orgid int64) (*models.XtPatientsNew, error) {
	var patientnew models.XtPatientsNew
	err = XTReadDB().Model(&patientnew).Where("user_org_id = ? and phone = ? and status = ? and slow_patients = ?", orgid, phone, 1, 1).Find(&patientnew).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &patientnew, nil
}

func GetNewDoctorAdvice(patientid int64, doctype int64, startime int64, endtime int64, limit int64, page int64, orgId int64) (doctoradvice []*models.DoctorAdvices, total int64, err error) {
	db := XTReadDB().Table("xt_doctor_advice as x").Where("x.status = 1")
	if orgId > 0 {
		db = db.Where("x.user_org_id = ?", orgId)
	}

	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if startime != 0 {
		db = db.Where("x.record_date>= ?", startime)
	}
	if endtime != 0 {
		db = db.Where("x.record_date<=?", endtime)
	}

	if doctype > 0 {
		db = db.Where("x.advice_type = ?", doctype)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.record_date desc").Offset(offset).Limit(limit).Group("x.id").Select("x.id, x.user_org_id, x.patient_id, x.advice_type, x.advice_date, x.record_date, x.start_time, x.advice_name,x.advice_desc, x.reminder_date, x.drug_spec, x.drug_spec_unit, x.single_dose, x.single_dose_unit, x.prescribing_number, x.prescribing_number_unit, x.delivery_way, x.execution_frequency, x.advice_doctor, x.created_time,x.updated_time, x.advice_affirm, x.remark, x.stop_time, x.stop_reason, x.stop_doctor, x.stop_state, x.parent_id, x.execution_time, x.execution_staff, x.execution_state, x.checker, x.check_state, x.check_time, x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Scan(&doctoradvice).Error
	return
}

func GetDryWeight(patientid int64, startime int64, endtime int64, limit int64, page int64, orgId int64) (dryWeight []*models.XtPatientDryweight, total int64, err error) {
	db := XTReadDB().Table("xt_patient_dryweight as x").Where("x.status = 1")
	if orgId > 0 {
		db = db.Where("x.user_org_id = ?", orgId)
	}
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if startime > 0 {
		db = db.Where("x.ctime >= ?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.ctime <=?", endtime)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.ctime desc").Offset(offset).Limit(limit).Group("x.id").
		Select("x.id,x.dry_weight,x.creator,x.remakes,x.patient_id,x.ctime,x.adjusted_value,x.user_id,x.user_org_id,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.creator").Scan(&dryWeight).Error
	return dryWeight, total, err
}

func ToSearch(orgId int64, name string) (patient []*models.XtPatientsNew, err error) {
	likeKey := "%" + name + "%"
	err = XTReadDB().Where("name like ? and user_org_id = ?", likeKey, orgId).Find(&patient).Error
	return patient, err
}

func GetCourseManagement(patientid int64, startime int64, endtime int64, limit int64, page int64, orgid int64) (patientCourse []*models.PatientCourseOfDiseases, total int64, err error) {
	db := XTReadDB().Table("xt_patient_course_of_disease as x").Where("x.status = 1")
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	if startime > 0 {
		db = db.Where("x.record_time >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.record_time <= ?", endtime)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.ctime desc").Offset(offset).Limit(limit).Group("x.id").
		Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,x.title,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Scan(&patientCourse).Error
	return patientCourse, total, err
}

func DeleteCouseManagement(patientid int64) error {

	err := XTWriteDB().Model(models.PatientCourseOfDisease{}).Where("id = ?", patientid).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return err
}

func GetCouseManagentDetail(id int64) (models.PatientCourseOfDiseasess, error) {
	disease := models.PatientCourseOfDiseasess{}
	db := XTReadDB().Table("xt_patient_course_of_disease as x")
	err := db.Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,x.title,s.name,r.user_name").Joins("left join xt_patients as s on s.id = x.patient_id ").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Where("x.id = ?", id).Scan(&disease).Error
	return disease, err
}

func DeleteDryWeight(id int64) error {
	err := XTWriteDB().Model(models.SgjPatientDryweight{}).Where("id=?", id).Update(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return err
}

func GetDryWeightDetail(id int64) (models.SgjPatientDryweights, error) {
	dryweight := models.SgjPatientDryweights{}
	db := XTReadDB().Table("xt_patient_dryweight as x")
	err := db.Select("x.id,x.dry_weight,x.creator,x.remakes,x.patient_id,x.adjusted_value,x.user_org_id,x.user_id,x.ctime,s.name,r.user_name").Joins("left join xt_patients as s on s.id = x.patient_id").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.user_id").Where("x.id = ?", id).Scan(&dryweight).Error
	return dryweight, err
}

func GetlongDialysisrecord(patientid int64, startime int64, endtime int64, limit int64, page int64, orgid int64) (prescription []*models.XtDialysisSolution, total int64, err error) {
	db := XTReadDB().Table("xt_dialysis_solution as x").Where("x.status = 1")
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	if startime > 0 {
		db = db.Where("x.created_time >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.created_time <= ?", endtime)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.created_time desc").Offset(offset).Limit(limit).Group("x.id").
		Select("x.id,x.name,x.sub_name,x.user_org_id,x.patient_id,x.parent_id,x.type,x.period,x.times,x.anticoagulant,x.anticoagulant_shouji,x.anticoagulant_weichi,x.anticoagulant_zongliang,x.anticoagulant_gaimingcheng,x.anticoagulant_gaijiliang,x.mode_name,x.mode_id,x.dialysis_duration,x.replacement_way,x.hemodialysis_machine,x.blood_filter,x.perfusion_apparatus,x.blood_flow_volume,x.dewater,x.displace_liqui,x.glucose,x.dry_weight,x.dialysate_flow,x.kalium,x.sodium,x.calcium,x.bicarbonate,x.doctor,x.first_dialysis,x.remark,x.initiate_mode,x.affirm_state,x.use_state,x.status,x.registrars_id,x.created_time,x.updated_time,x.solution_type,x.dialysate_temperature,x.conductivity,x.dialysis_duration_hour,x.dialysis_duration_minute,x.target_ultrafiltration,x.dialysate_formulation,x.dialyzer,x.replacement_total,x.dialyzer_perfusion_apparatus,x.body_fluid,x.special_medicine,x.special_medicine_other,x.displace_liqui_part,x.displace_liqui_value,x.blood_access,x.ultrafiltration,x.body_fluid_other,x.target_ktv").Find(&prescription).Error

	return
}

func GetRescuerecord(patientid int64, startime int64, endtime int64, limit int64, page int64, orgid int64) (rescuerecord []*models.XtPatientRescueRecords, total int64, err error) {
	db := XTReadDB().Table("xt_patient_rescue_record as x").Where("x.status = 1")
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	if startime > 0 {
		db = db.Where("x.record_time >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.record_time <= ?", endtime)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.record_time desc").Offset(offset).Limit(limit).Group("x.id").
		Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,x.status,r.user_name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Scan(&rescuerecord).Error
	return
}

func GetScheduling(patientid int64, startime int64, endtime int64, limit int64, page int64, orgid int64, modeType int64) (schedules []*models.XtSchedules, total int64, err error) {
	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	if startime > 0 {
		db = db.Where("x.schedule_date >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.schedule_date <= ?", endtime)
	}
	if modeType > 0 {
		db = db.Where("x.mode_id = ?", modeType)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.schedule_date desc").Offset(offset).Limit(limit).Group("x.id").
		Select("x.id,x.user_org_id,x.partition_id,x.bed_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,x.status,x.created_time,x.updated_time,s.number,z.name").Joins("left join xt_device_number as s on s.id = x.bed_id").Joins("left join xt_device_zone as z on z.id = x.partition_id").Scan(&schedules).Error
	return
}

func GetEducation(patientid int64, startime int64, endtime int64, limit int64, page int64, orgid int64) (treatment []*models.XtTreatmentSummary, total int64, err error) {

	db := XTReadDB().Table("xt_treatment_summary as x").Where("x.status = 1")
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	if startime > 0 {
		db = db.Where("x.assessment_date >=?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.assessment_date <= ?", endtime)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Order("x.assessment_date").Offset(offset).Limit(limit).Group("x.id").
		Select("x.id,x.user_org_id,x.patient_id,x.assessment_date,x.dialysis_order_id,x.mission,x.dialysis_summary,x.change,x.sj_nurse,x.zl_nurse,x.hd_nurse,x.xj_nurse,x.zl_doctor,x.channel_image,x.puncture,x.puncture_needle,x.puncture_direction,x.status,x.created_time,x.updated_time,x.creater,x.modifier").Scan(&treatment).Error
	return
}

func GetSchedulingDetail(id int64) (models.XtScheduless, error) {
	schedules := models.XtScheduless{}
	db := XTReadDB().Table("xt_schedule as x")
	err := db.Select("x.id,x.user_org_id,x.partition_id,x.bed_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,n.number,z.name").Joins("left join xt_device_number as n on n.id = x.bed_id").Joins("left join xt_device_zone as z on z.id = x.partition_id").Where("x.id =?", id).Scan(&schedules).Error
	return schedules, err
}

func GetSchedulingTwo(id int64) (models.XtScheduless, error) {
	schedules := models.XtScheduless{}
	db := XTReadDB().Table("xt_schedule as x")
	err := db.Select("x.id,x.user_org_id,x.partition_id,x.bed_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,z.name").Joins("left join xt_patients as z on z.id = x.patient_id").Where("x.id =?", id).Scan(&schedules).Error
	return schedules, err
}

func DeleteScheduling(id int64) error {
	err := XTWriteDB().Model(models.XtSchedules{}).Where("id=?", id).Update(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()}).Error
	return err
}

func GetEducationDetailOne(id int64) (models.XtTreatmentSummarys, error) {
	summarys := models.XtTreatmentSummarys{}
	db := XTReadDB().Table("xt_treatment_summary as x")
	err := db.Select("x.id,x.user_org_id,x.patient_id,x.assessment_date,x.dialysis_order_id,x.mission,x.dialysis_summary,x.change,x.sj_nurse,x.zl_nurse,x.hd_nurse,x.xj_nurse,x.zl_doctor,x.channel_image,x.puncture,x.puncture_needle,x.puncture_direction,x.status,x.created_time,x.creater,x.modifier,s.name").Joins("left join xt_patients as s on s.id = x.patient_id").Where("x.id = ?", id).Scan(&summarys).Error
	return summarys, err
}

func DeleteEducation(id int64) error {
	err := XTWriteDB().Model(models.XtTreatmentSummary{}).Where("id=?", id).Update(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()}).Error
	return err
}

func GetRescueRecordDetail(id int64) (models.XtPatientRescueRecords, error) {
	records := models.XtPatientRescueRecords{}
	db := XTReadDB().Table("xt_patient_rescue_record as x")
	err := db.Select("x.id,x.org_id,x.patient_id,x.recorder,x.record_time,x.content,x.status,r.user_name,s.name").Joins("left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.recorder").Joins("left join xt_patients as s on s.id = x.patient_id").Where("x.id=?", id).Scan(&records).Error
	return records, err
}

func DeleteRescueRecord(id int64) error {
	err := XTWriteDB().Model(models.XtPatientRescueRecord{}).Where("id=?", id).Update(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()}).Error
	return err
}

func ToSearchePatient(keyword string, orgId int64) (paitents []*models.XtPatientsNew, err error) {
	likeKey := "%" + keyword + "%"
	err = XTReadDB().Where("name like ? or dialysis_no like ? and user_org_id = ?", likeKey, likeKey, orgId).Find(&paitents).Error
	return paitents, err
}

func SearchallPatient(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {
	likeKey := "%" + keyword + "%"
	err = XTReadDB().Where("name like ? or dialysis_no = ? and user_org_id = ?", likeKey, keyword, orgid).Find(&patients).Error
	return patients, err
}

func GetSearchallBlood(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {
	likeKey := "%" + keyword + "%"
	err = XTReadDB().Where("name like ? or dialysis_no = ? and user_org_id = ? and blood_patients = 1", likeKey, keyword, orgid).Find(&patients).Error
	return patients, err
}

func GetSlowSearchePatient(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {
	likeKey := "%" + keyword + "%"
	err = XTReadDB().Where("name like ? or dialysis_no = ? and user_org_id = ? and slow_patients = 1", likeKey, keyword, orgid).Find(&patients).Error
	return patients, err
}

func GetMemberSearchPatient(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {
	likeKey := "%" + keyword + "%"
	err = XTReadDB().Where("name like ? or dialysis_no = ? and user_org_id = ? and member_patients = 1", likeKey, keyword, orgid).Find(&patients).Error
	return patients, err
}
