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, lapseto int64, source 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)
	}
	if lapseto > 0 {
		db = db.Where("x.lapseto = ?", lapseto)
	}
	if source > 0 {
		db = db.Where("x.source = ?", source)
	}
	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 FindPatientByMobileFive(mobile string, orgID int64) (patient models.XtPatientsNew, err error) {
	err = readDb.Model(&models.Patients{}).Where("phone=? and user_org_id=? and status=1", mobile, orgID).First(&patient).Error
	return
}

func FindPatientByDialysisNoFive(orgID int64, dialysisNo string) (patient models.Patients, err error) {
	err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and dialysis_no=?", orgID, dialysisNo).First(&patient).Error
	return
}

func FindPatientByIdCardNoFive(orgID int64, idCardNo string) (patient models.XtPatientsNew, err error) {
	err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and id_card_no=?", orgID, idCardNo).First(&patient).Error
	return
}

func FindPatientByIdCardNoOne(orgID int64, idCardNo string, id int64) (patient models.XtPatientsNew, err error) {
	err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and id_card_no=? and id<>?", orgID, idCardNo, id).First(&patient).Error
	return
}

func FindPatientByDialysisNoOne(orgID int64, dialysisNo string, id int64) (patient models.Patients, err error) {
	err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and dialysis_no=? and id<>?", orgID, dialysisNo, id).First(&patient).Error
	return
}

func FindPatientByMobileOne(mobile string, orgID int64, id int64) (patient models.XtPatientsNew, err error) {
	//err = readDb.Model(&models.Patients{}).Where(" status=1 and user_org_id=? and   phone=? and id<>?", orgID, mobile, id).First(&patient).Error
	//return
	db := readDb.Table("xt_patients_new as x")
	err = db.Not("phone = ?", mobile).Where("user_org_id = ? and id = ? and status =1", orgID, id).Find(&patient).Error
	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, advice_type int64, start int64, end int64, limit int64, page int64, orgID int64) (doctoradvice []*models.DoctorAdvices, total int64, err error) {
	db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
	table := UserReadDB().Table("sgj_user_admin_role as r")
	fmt.Print("table", table)
	if orgID > 0 {
		db = db.Where("x.user_org_id=?", orgID)
	}
	if patientID > 0 {
		db = db.Where("x.patient_id = ?", patientID)
	}
	if advice_type == 1 {
		db = db.Where("x.advice_type = ?", advice_type)
	}
	if advice_type == 3 {
		db = db.Where("x.advice_type <> 1")
	}
	if start > 0 {
		db = db.Where("x.start_time>=?", start)
	}
	if end > 0 {
		db = db.Where("x.start_time<=?", end)
	}
	//offset := (page - 1) * limit
	err = db.Group("x.id").Count(&total).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.status, 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,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Order("start_time desc, groupno desc, advice_order desc, id asc").Scan(&doctoradvice).Error
	fmt.Print("err", err)
	return

}

func GetNewDoctorAdviceOne(patientID int64, advice_type int64, start int64, end int64, limit int64, page int64, orgID int64) (doctoradvice []*models.DoctorAdvice, total int64, err error) {
	fmt.Println("advicetype------------------------------", advice_type)
	db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
	table := UserReadDB().Table("sgj_user_admin_role as r")
	fmt.Println("table", table)
	if orgID > 0 {
		db = db.Where("x.user_org_id=?", orgID)
	}
	if patientID > 0 {
		db = db.Where("x.patient_id = ?", patientID)
	}
	if advice_type == 1 {
		db = db.Where("x.advice_type = ?", advice_type)
	}
	if advice_type == 3 {
		db = db.Where("x.advice_type <> 1")
	}

	if start > 0 {
		db = db.Where("x.start_time>=?", start)
	}
	if end > 0 {
		db = db.Where("x.start_time<=?", end)
	}
	offset := (page - 1) * limit
	err = db.Order("x.start_time desc").Group("x.start_time").Count(&total).Offset(offset).Limit(limit).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.status, 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,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Scan(&doctoradvice).Error
	fmt.Print("错误是什么", err)
	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 desc").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("user_org_id = ? and name like ? or dialysis_no like ?", orgId, likeKey, likeKey).Find(&paitents).Error
	return paitents, err
}

func SearchallPatient(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {
	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1")
	if len(keyword) > 0 {
		likeKey := "%" + keyword + "%"
		db = db.Where("x.name LIKE ? OR x.dialysis_no LIKE ?", likeKey, likeKey)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	err = db.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.infectious_next_record_time,x.is_infectious,x.remind_cycle,x.response_result,x.is_open_remind,x.first_treatment_date,x.dialysis_age,x.expense_kind,x.tell_phone,x.contact_name,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id,x.member_fistdate,x.member_patienttype,x.member_treatement,x.equitment_id").Find(&patients).Error
	return patients, err
}

func GetSearchallBlood(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {

	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1 and x.blood_patients = 1")
	if len(keyword) > 0 {
		likeKey := "%" + keyword + "%"
		db = db.Where("x.name LIKE ? OR x.dialysis_no LIKE ?", likeKey, likeKey)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	err = db.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.infectious_next_record_time,x.is_infectious,x.remind_cycle,x.response_result,x.is_open_remind,x.first_treatment_date,x.dialysis_age,x.expense_kind,x.tell_phone,x.contact_name,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id,x.member_fistdate,x.member_patienttype,x.member_treatement,x.equitment_id").Find(&patients).Error
	return patients, err
}

func GetSlowSearchePatient(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {

	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1 and x.slow_patients = 1")
	if len(keyword) > 0 {
		likeKey := "%" + keyword + "%"
		db = db.Where("x.name LIKE ? OR x.dialysis_no LIKE ?", likeKey, likeKey)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	err = db.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.infectious_next_record_time,x.is_infectious,x.remind_cycle,x.response_result,x.is_open_remind,x.first_treatment_date,x.dialysis_age,x.expense_kind,x.tell_phone,x.contact_name,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id,x.member_fistdate,x.member_patienttype,x.member_treatement,x.equitment_id").Find(&patients).Error
	return patients, err
}

func GetMemberSearchPatient(keyword string, orgid int64) (patients []*models.XtPatientsNew, err error) {
	db := XTReadDB().Table("xt_patients_new as x").Where("x.status = 1 and x.member_patients = 1")
	if len(keyword) > 0 {
		likeKey := "%" + keyword + "%"
		db = db.Where("x.name LIKE ? OR x.dialysis_no LIKE ?", likeKey, likeKey)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	err = db.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.infectious_next_record_time,x.is_infectious,x.remind_cycle,x.response_result,x.is_open_remind,x.first_treatment_date,x.dialysis_age,x.expense_kind,x.tell_phone,x.contact_name,x.blood_patients,x.slow_patients,x.member_patients,x.ecommer_patients,x.blood_id,x.slow_id,x.member_id,x.member_fistdate,x.member_patienttype,x.member_treatement,x.equitment_id").Find(&patients).Error
	return patients, err
}

func GetLongDialysisDetail(id int64) (models.XtDialysisSolution, error) {
	solution := models.XtDialysisSolution{}
	err := XTReadDB().Model(&solution).Where("id=? and status =1", id).Find(&solution).Error
	return solution, err
}

func GetPatientName(id int64) (models.Patients, error) {
	patientsNew := models.Patients{}
	err := XTReadDB().Model(&patientsNew).Where("id=? and status = 1", id).Find(&patientsNew).Error
	return patientsNew, err
}

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

func GetDialysisrecord(patientID int64, start int64, end int64, limit int64, page int64, orgID int64, mode_id int64) ([]*models.PatientDialysisRecord, int64, error) {
	offset := (page - 1) * limit
	var total int64
	var err error
	var orders []*models.PatientDialysisRecord

	db := readDb.Table("xt_dialysis_order as do").
		Preload("DialysisPrescription", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
		Preload("PredialysisEvaluation", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
		Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
			return readDb.Where("patient_id=? and user_org_id=? and status=1", patientID, orgID).Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
				return readUserDb.Where("status = 1")
			})
		}).
		Preload("AssessmentAfterDislysis", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
		Preload("TreatmentSummary", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
		Preload("Device", "org_id=? and status=1", orgID).
		Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
			return readUserDb.Where("org_id=? and status = 1", orgID)
		}).
		Joins("JOIN xt_schedule as s ON s.patient_id=? and FROM_UNIXTIME(s.schedule_date, '%Y-%m-%d')=FROM_UNIXTIME(do.dialysis_date, '%Y-%m-%d')", patientID).
		Joins("JOIN xt_device_zone as dz ON dz.org_id = ? and dz.id=s.partition_id", orgID).
		Where("do.patient_id=? and do.user_org_id=? and do.stage = 2 and do.status=1", patientID, orgID).Group("s.schedule_date")

	if start > 0 {
		db = db.Where("do.dialysis_date>=?", start)
	}
	if end > 0 {
		db = db.Where("do.dialysis_date<=?", end)
	}
	if mode_id > 0 {
		db = db.Joins("JOIN xt_dialysis_prescription as dp ON dp.record_id=do.id")
		db = db.Where("dp.mode_id=?", mode_id)
	}

	err = db.Count(&total).Offset(offset).Limit(limit).Order("do.dialysis_date desc").Select("do.bed_id, do.id, do.dialysis_date, do.user_org_id, do.patient_id, do.prescription_id, do.stage, do.remark, do.status, do.created_time, do.updated_time,do.start_nurse,do.finish_nurse ,s.schedule_type, s.partition_id, dz.name as partition_name").Find(&orders).Error

	if len(orders) > 0 {
		ids := make([]int64, 0)
		for _, order := range orders {
			dialyzer := order.DialysisPrescription.Dialyzer
			ids = append(ids, dialyzer)
		}
		if len(ids) > 0 {
			var dialyzers []*models.DeviceNumber
			err = readDb.Model(&models.DeviceNumber{}).Where("id IN (?) and org_id=? and status=1", ids, orgID).Find(&dialyzers).Error
			if err != nil {
				return nil, 0, err
			}

			dialyzerMap := make(map[int64]models.DeviceNumber, 0)
			for _, item := range dialyzers {
				dialyzerMap[item.ID] = *item
			}
			for orderIndex, order := range orders {
				if _, exist := dialyzerMap[order.DialysisPrescription.Dialyzer]; exist {
					orders[orderIndex].DeviceNumber = dialyzerMap[order.DialysisPrescription.Dialyzer].Number
				}
			}
		}
	}

	return orders, total, err
}

func GetAllDoctorTwo(orgid int64, appid int64) (appRole []*models.SgjUserAdminRole, err error) {

	err = UserReadDB().Where("org_id = ? and app_id = ? and status = ? ", orgid, appid, 1).Find(&appRole).Error
	return appRole, err
}

func GetDoctorAdviceDetail(state int64, id int64, orgid int64) (advices []*models.DoctorAdvices, err error) {

	db := XTReadDB().Table("xt_doctor_advice as x")
	err = db.Order("x.id desc").Select("x.id,x.user_org_id,x.patient_id,x.advice_type,x.advice_date,x.start_time,x.advice_name,x.advice_desc,x.reminder_date,x.single_dose,x.single_dose_unit,x.prescribing_number,x.prescribing_number_unit,x.delivery_way,x.execution_frequency,x.advice_doctor,x.status,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.record_date,x.dialysis_order_id,x.check_time,x.check_state,x.drug_spec,x.drug_spec_unit,x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,x.template_id,x.modifier,s.name").Joins("left join xt_patients as s on s.id=x.patient_id").Where("x.start_time = ? and x.patient_id = ? and x.user_org_id = ? and x.status = 1", state, id, orgid).Scan(&advices).Error

	return advices, err
}

func DeleteManagement(groupid int64, orgid int64) error {

	err := XTWriteDB().Model(models.DoctorAdvice{}).Where("start_time =? and user_org_id = ?", groupid, orgid).Update(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()}).Error
	return err
}

func DeleteChild(id int64) error {

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

func DeletePatient(id int64) error {

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

func GetNewPatient(id int64) (models.XtPatientsNew, error) {
	patientsNew := models.XtPatientsNew{}
	err := XTReadDB().Model(&patientsNew).Where("id=?", id).Find(&patientsNew).Error
	return patientsNew, err
}

func UpdatedPatient(patients models.Patients, id int64) error {

	err := XTWriteDB().Model(&patients).Where("id=?", id).Update(map[string]interface{}{"name": patients.Name, "gender": patients.Gender, "birthday": patients.Birthday, "age": patients.Age, "phone": patients.Phone, "lapseto": patients.Lapseto, "admission_number": patients.AdmissionNumber, "first_dialysis_date": patients.FirstDialysisDate, "diagnose": patients.Diagnose, "source": patients.Source, "dialysis_no": patients.DialysisNo, "avatar": patients.Avatar, "id_card_no": patients.IdCardNo, "is_infectious": patients.IsInfectious}).Error

	return err
}

func UpdateXtPatientNew(patients models.XtPatientsNew, id int64) error {

	err := XTWriteDB().Model(&patients).Where("id=?", id).Update(map[string]interface{}{"name": patients.Name, "gender": patients.Gender, "birthday": patients.Birthday, "age": patients.Age, "phone": patients.Phone, "lapseto": patients.Lapseto, "admission_number": patients.AdmissionNumber, "first_dialysis_date": patients.FirstDialysisDate, "diagnose": patients.Diagnose, "source": patients.Source, "dialysis_no": patients.DialysisNo, "avatar": patients.Avatar, "id_card_no": patients.IdCardNo, "is_infectious": patients.IsInfectious}).Error

	return err
}

func UpdateXtPatientNewOne(patients models.XtPatientsNew, id int64) error {

	err := XTWriteDB().Model(&patients).Where("id=?", id).Update(map[string]interface{}{"name": patients.Name, "gender": patients.Gender, "birthday": patients.Birthday, "age": patients.Age, "phone": patients.Phone, "lapseto": patients.Lapseto, "adminssion_number": patients.AdmissionNumber, "first_dialysis_date": patients.FirstDialysisDate, "diagnose": patients.Diagnose, "source": patients.Source, "dialysis_no": patients.DialysisNo, "avatar": patients.Avatar, "id_card_no": patients.IdCardNo, "is_infectious": patients.IsInfectious, "member_patienttype": patients.MemberPatienttype, "member_treatement": patients.MemberTreatement}).Error
	return err
}

func UpdateContagions(patientid int64) (models.XtPatientsInfectiousDiseases, error) {
	diseases := models.XtPatientsInfectiousDiseases{}
	err := XTWriteDB().Model(&diseases).Where("patient_id = ?", patientid).Update(map[string]interface{}{"status": 2, "updated_time": time.Now().Unix()}).Error
	return diseases, err
}

func UpdateCustomer(cdmpatient models.CdmPatients, id int64) error {

	err := PatientWriteDB().Model(&cdmpatient).Where("id=?", id).Update(map[string]interface{}{"name": cdmpatient.Name, "phone": cdmpatient.Phone, "gender": cdmpatient.Gender, "birthday": cdmpatient.Birthday, "diagnose": cdmpatient.Diagnose, "source": cdmpatient.Source, "avatar": cdmpatient.Avatar, "id_card_no": cdmpatient.IdCardNo, "updated_time": cdmpatient.UpdatedTime}).Error
	return err
}

func UpdatedCustomer(customer models.SgjUserCustomer, id int64) error {

	err := UserWriteDB().Model(&customer).Where("id = ?", id).Update(map[string]interface{}{"name": customer.Name, "mobile": customer.Mobile, "gender": customer.Gender, "birthday": customer.Birthday, "ill_date": customer.IllDate, "avatar": customer.Avatar, "illness_id": customer.IllnessId, "treat_type": customer.TreatType}).Error
	return err
}

func GetInspectionByOrgId(orgid int64) (*models.XtInspectionReference, error) {
	diseases := models.XtInspectionReference{}
	err := XTReadDB().Model(&diseases).Where("org_id = ? and status = 1", orgid).Find(&diseases).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &diseases, nil

}

func GetAllProjectName(date int64, orgid int64, patientid int64) (inspection []*models.XtInspection, err error) {

	err = XTReadDB().Model(&inspection).Where("inspect_date = ? and org_id = ? and patient_id = ? and status = 1", date, orgid, patientid).Order("inspect_date desc").Group("project_name").Find(&inspection).Error

	return inspection, err
}

func GetAllInspection(orgid int64) (inspection []*models.XtInspectionReference, err error) {

	err = XTReadDB().Model(&inspection).Where("org_id = ? and status = 1", orgid).Group("project_name").Find(&inspection).Error
	return inspection, err
}

func GetInspection(patientid int64, startime int64, endtime int64, limit int64, page int64, orgid int64, projectid int64) (inspection []*models.Inspection, total int64, err error) {

	db := XTReadDB().Table("xt_inspection as x").Where("x.status = 1")
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}
	if startime > 0 {
		db = db.Where("x.inspect_date >= ?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.inspect_date<=?", endtime)
	}
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	if projectid > 0 {
		db = db.Where("x.project_id = ?", projectid)
	}
	err = db.Count(&total).Order("x.inspect_date desc").Group("x.id").
		Select("x.id,x.patient_id,x.org_id,x.project_id,x.item_id,x.item_name,x.project_name,x.inspect_type,x.inspect_value,x.inspect_date,x.created_time").Find(&inspection).Error
	return inspection, total, err
}

func GetInspectionDetail(patientid int64, date int64, orgid int64, projectid int64) (inspection []*models.Inspections, err error) {

	db := XTReadDB().Table("xt_inspection as x").Where("x.status =1")
	table := XTReadDB().Table("xt_inspection_reference as r")
	fmt.Print("table", table)
	if patientid > 0 {
		db = db.Where("x.patient_id = ?", patientid)
	}

	if date > 0 {
		db = db.Where("x.inspect_date = ?", date)
	}
	if orgid > 0 {

		db = db.Where("x.org_id = ?", orgid)

	}
	if projectid > 0 {
		db = db.Where("x.project_id = ?", projectid)
	}
	err = db.Group("x.id").Select("x.id,x.patient_id,x.org_id,x.project_id,x.item_id,x.item_name,x.project_name,x.inspect_type,x.inspect_value,x.inspect_date,x.status,x.created_time,x.updated_time,r.range_type,r.range_min,r.range_max,r.range_value,r.range_options,r.unit").Joins("left join xt_inspection_reference as r on r.item_id = x.item_id ").Scan(&inspection).Error
	return inspection, err
}

func CreateFeedBack(feedback *models.XtPatientFeedback) error {

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

func DeleteInspection(date int64, orgid int64) error {

	err := XTWriteDB().Model(models.Inspection{}).Where("inspect_date = ? and org_id = ?", date, orgid).Update(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()}).Error
	return err
}

func DeleteChildInspection(name string, date int64, orgid int64) error {

	err := XTWriteDB().Model(models.Inspection{}).Where("project_name = ? and inspect_date = ? and org_id = ?", name, date, orgid).Update(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix()}).Error
	return err
}

func SaveMessage(id int64, orgid int64, role *models.SgjUserAdminRole) error {

	err := UserWriteDB().Model(models.SgjUserAdminRole{}).Where("admin_user_id = ? and org_id = ?", id, orgid).Update(map[string]interface{}{"message": role.Message, "mtime": time.Now().Unix()}).Error
	return err
}

func SaveSex(id int64, role *models.SgjUserAdminRole) error {
	err := UserWriteDB().Model(models.SgjUserAdminRole{}).Where("admin_user_id = ?", id).Update(map[string]interface{}{"sex": role.Sex, "mtime": time.Now().Unix()}).Error
	return err
}

func SaveBirthday(id int64, role *models.SgjUserAdminRole) error {
	err := UserWriteDB().Model(models.SgjUserAdminRole{}).Where("admin_user_id = ?", id).Update(map[string]interface{}{"birthday": role.Birthday, "mtime": time.Now().Unix()}).Error
	return err
}

func CreatedZone(zone *models.DeviceZone) error {

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

func GetAllZone(orgid int64, page int64, limit int64) (zone []*models.DeviceZones, total int64, err error) {

	db := XTReadDB().Table("xt_device_zone as x").Where("x.status =1")
	table := XTReadDB().Table("xt_device_number as n")
	fmt.Println("table", table)
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	offset := (page - 1) * limit
	err = db.Group("x.id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Select("x.id,x.org_id,x.name,x.type,n.number").Joins("left join xt_device_number as n on n.zone_id = x.id AND n.status = 1").Scan(&zone).Error
	return zone, total, err
}

func DeleteZoneById(id int64) error {

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

func SaveGroup(group *models.DeviceGroup) error {
	err := XTWriteDB().Model(&group).Create(&group).Error
	return err
}

func GetAllGroup(orgid int64, page int64, limit int64) (group []*models.DeviceGroups, total int64, err error) {
	db := XTReadDB().Table("xt_device_group as x").Where("x.status = 1")
	table := XTReadDB().Table("xt_device_number as n")
	fmt.Println("table", table)
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	offset := (page - 1) * limit
	err = db.Group("x.id").Count(&total).Offset(offset).Limit(limit).Order("x.ctime desc").Select("x.id,x.org_id,x.name,x.status,x.ctime,x.mtime,n.number").Joins("left join xt_device_number as n on n.group_id = x.id And n.status = 1").Scan(&group).Error
	return group, total, err
}

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

func GetAllZoneOne(orgid int64) (zone []*models.DeviceZone, err error) {

	err = XTReadDB().Model(&zone).Where("org_id = ?", orgid).Find(&zone).Error
	return zone, err
}

func GetAllGroupOne(orgid int64) (group []*models.DeviceGroup, err error) {

	err = XTReadDB().Model(&group).Where("org_id =?", orgid).Find(&group).Error
	return group, err
}

func CreateNumber(number *models.DeviceNumber) error {

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

func GetAllNumber(page int64, limit int64, orgid int64) (number []*models.DeviceNumber, total int64, err error) {

	db := XTReadDB().Table("xt_device_number as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	offset := (page - 1) * limit
	err = db.Count(&total).Offset(offset).Limit(limit).Order("x.ctime asc").Select("x.id,x.org_id,x.number,x.group_id,x.zone_id,x.status").Find(&number).Error

	return number, total, err
}

func GetSchedu(bedid int64, thetime int64, orgid int64) (*models.XtSchedule, error) {
	schedule := models.XtSchedule{}
	err := XTReadDB().Model(&schedule).Where("bed_id = ? and schedule_date = ? and user_org_id = ? and status = 1", bedid, thetime, orgid).Find(&schedule).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}
	if err != nil {
		return nil, err
	}
	return &schedule, nil

}

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

func GetMemberPatient(orgid int64) (patients []*models.XtPatientsNew, err error) {

	err = XTReadDB().Model(&patients).Where("user_org_id = ? AND member_patients = ? AND status = 1", orgid, 1).Find(&patients).Error
	return patients, err
}

func GetSlowPatient(orgid int64) (patients []*models.XtPatientsNew, err error) {

	err = XTReadDB().Model(&patients).Where("user_org_id = ? AND slow_patients = ? AND status = 1", orgid, 1).Find(&patients).Error
	return patients, err

}

func GetBloodPatient(orgid int64) (patients []*models.XtPatientsNew, err error) {
	err = XTReadDB().Model(&patients).Where("user_org_id = ? AND blood_patients = ? AND status = 1", orgid, 1).Find(&patients).Error
	return patients, err
}

func SaveName(id int64, admin *models.SgjUserAdmin) error {

	err = UserWriteDB().Model(models.SgjUserAdmin{}).Where("id=?", id).Update(map[string]interface{}{"name": admin.Name, "mtime": time.Now().Unix()}).Error
	return err
}

func GetAdminUserId(id int64) (models.SgjUserAdminRole, error) {

	role := models.SgjUserAdminRole{}
	err := UserReadDB().Where("id=? and status =1", id).Find(&role).Error
	return role, err
}

func GetMyOrganaziton(id int64) (org []*models.SgjUserOrg, err error) {

	db := UserReadDB().Table("sgj_user_org as x").Where("x.status = 1")
	table := UserReadDB().Table("sgj_user_admin as a")
	fmt.Println("table", table)
	err = db.Select("x.id,x.creator,x.org_name,x.org_short_name,x.org_logo,x.org_introduction,x.illness,x.province,x.city,x.district,x.address,x.longitude,x.latitude,x.org_type,x.comments,x.evaluate,x.gallery,x.business_week,x.business_time,x.contact_name,x.telephone,x.claim,x.operating_state,x.source,x.ttype,x.ttid,x.tuid,x.reason,x.level,x.website,x.import,x.sortno,a.is_super_admin").Joins("left join sgj_user_admin as a on a.id = x.creator").Where("x.creator = ?", id).Scan(&org).Error
	return org, err
}

func GetOrgInformation(id int64) (models.SgjUserOrg, error) {

	org := models.SgjUserOrg{}

	err := UserReadDB().Where("id=? and status = 1", id).Find(&org).Error
	return org, err
}

func GetShortName(orgtype int64) (models.SgjUserOrgType, error) {

	orgType := models.SgjUserOrgType{}
	err := UserReadDB().Model(&orgType).Where("id=? and status = 1", orgtype).Find(&orgType).Error
	return orgType, err
}

func GetTypeName(id int64) (models.SgjUserOrgType, error) {
	orgType := models.SgjUserOrgType{}
	err := UserReadDB().Model(&orgType).Where("id=? and status = 1", id).Find(&orgType).Error
	return orgType, err
}

func GetOrgProvince(id int64) (models.SgjUserDistrict, error) {

	district := models.SgjUserDistrict{}
	err := UserReadDB().Model(&district).Where("id=?", id).Find(&district).Error
	return district, err
}

func GetAllOrgType() (orgType []*models.SgjUserOrgType, err error) {

	err = UserReadDB().Model(&models.SgjUserOrgType{}).Where("status= ? AND id = ? OR id = ? OR id = ? OR id = ? OR id = ? OR id = ?", 1, 1, 7, 12, 16, 21, 26).Find(&orgType).Error
	return
}

func UpdateOrg(id int64, org models.SgjUserOrg) error {

	err := UserWriteDB().Model(&org).Where("id = ?", id).Update(map[string]interface{}{"org_name": org.OrgName, "org_short_name": org.OrgShortName, "province": org.Province, "city": org.City, "district": org.District, "address": org.Address, "org_type": org.OrgType, "telephone": org.Telephone, "contact_name": org.ContactName, "mtime": time.Now().Unix()}).Error
	return err
}

func GetMyInfoName(id int64) (models.SgjUserAdminRole, error) {
	role := models.SgjUserAdminRole{}
	err := UserReadDB().Model(&role).Where("id=? and status = 1", id).Find(&role).Error
	return role, err
}

func GetAdminName(id int64, orgid int64) (models.AdminUsers, error) {
	user := models.AdminUsers{}
	//err := UserReadDB().Model(&user).Where("id=? and status =1", id).Find(&user).Error
	//return user, err
	db := UserReadDB().Table("sgj_user_admin as x").Where("x.status = 1")
	table := UserReadDB().Table("sgj_user_admin_role as r")
	fmt.Println("table", table)
	err := db.Group("x.id").Select("x.id,x.mobile,x.password,x.is_super_admin,x.source,x.name,r.admin_user_id,r.org_id,r.app_id,r.role_id,r.user_name,r.avatar,r.message,r.sex,r.birthday").Where("x.id = ?", id).Joins("left join sgj_user_admin_role as r on r.admin_user_id = x.id and r.org_id = ?", orgid).Scan(&user).Error
	return user, err
}

func GetCreatByOrgId(orgid int64) (models.SgjUserOrg, error) {
	org := models.SgjUserOrg{}
	err := UserReadDB().Model(&org).Where("id=? and status = 1", orgid).Find(&org).Error
	return org, err
}

func GetMyOrgInformationFour(creator int64, orgid int64) (models.SgjUserAdminRole, error) {
	role := models.SgjUserAdminRole{}
	err := UserReadDB().Model(&role).Where("admin_user_id = ? and org_id = ? and status = 1", creator, orgid).Find(&role).Error
	return role, err
}

func GetPartionDetail(id int64) (models.DeviceZone, error) {

	zone := models.DeviceZone{}
	err := XTReadDB().Model(&zone).Where("id=? and status = 1", id).Find(&zone).Error
	return zone, err
}

func UpdatePartition(id int64, zone *models.DeviceZone) error {

	err := XTWriteDB().Model(&zone).Where("id=?", id).Update(map[string]interface{}{"name": zone.Name, "type": zone.Type, "mtime": time.Now().Unix()}).Error
	return err
}

func GetGroupDetail(id int64) (models.DeviceGroup, error) {
	group := models.DeviceGroup{}
	err := XTReadDB().Model(&group).Where("id=? and status = 1", id).Find(&group).Error
	return group, err
}

func UpdateGroup(id int64, group *models.DeviceGroup) error {

	err := XTWriteDB().Model(&group).Where("id=?", id).Update(map[string]interface{}{"name": group.Name, "mtime": time.Now().Unix()}).Error
	return err
}

func GetBedDetail(id int64) (models.DeviceNumber, error) {
	number := models.DeviceNumber{}
	err := XTReadDB().Model(&number).Where("id=? and status =1", id).Find(&number).Error
	return number, err
}

func UpdatedBed(id int64, number *models.DeviceNumber) error {

	err = XTWriteDB().Model(&number).Where("id=?", id).Update(map[string]interface{}{"number": number.Number, "zone_id": number.ZoneID, "group_id": number.GroupID, "mtime": time.Now().Unix()}).Error
	return err
}

func CreateLoginLod(log *models.SgjUserAdminLoginLog) error {

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

func GetAppId(orgid int64) (models.OrgApp, error) {
	app := models.OrgApp{}
	err := UserReadDB().Model(&app).Where("org_id = ? and status = 1 and app_type = 3", orgid).Find(&app).Error
	return app, err
}

func GetRoleName(adminid int64, orgid int64, appid int64) (models.Roles, error) {

	role := models.Roles{}
	err := UserReadDB().Model(&role).Where("creator = ? and org_id = ? and app_id = ? and status =1", adminid, orgid, appid).Find(&role).Error
	return role, err
}

func GetRole(id int64) (models.Role, error) {
	role := models.Role{}
	err := UserReadDB().Model(&role).Where("id = ? and status =1", id).Find(&role).Error
	return role, err
}

func GetPositionName(adminid int64, orgid int64, appid int64) (models.App_Role, error) {

	role := models.App_Role{}
	err := UserReadDB().Model(&role).Where("admin_user_id = ? and org_id = ? and app_id = ?", adminid, orgid, appid).Find(&role).Error
	return role, err
}

func GetAdmin(id int64) (models.SgjUserAdmin, error) {
	admin := models.SgjUserAdmin{}
	err := UserReadDB().Model(&admin).Where("id=? and status =1", id).Find(&admin).Error
	return admin, err
}

func GetPosition(id int64) (models.SgjUserAdminRole, error) {
	roles := models.SgjUserAdminRole{}
	err = UserReadDB().Model(&roles).Where("id=? and status = 1", id).Find(&roles).Error
	return roles, err
}

func GetPositionOne(id int64) (models.SgjUserAdmin, error) {

	admin := models.SgjUserAdmin{}
	err = UserReadDB().Model(&admin).Where("id=? and status = 1", id).Find(&admin).Error
	return admin, err
}

func GetMyOrgInformation(id int64, appid int64) (models.SgjUserAdminRole, error) {
	admin := models.SgjUserAdminRole{}
	err := UserReadDB().Model(&admin).Where("admin_user_id=? and  app_id = ? and status = 1", id, appid).First(&admin).Error
	return admin, err
}

func SaveNameTwo(id int64, orgid int64, role *models.SgjUserAdminRole) error {

	err := UserWriteDB().Model(models.SgjUserAdminRole{}).Where("admin_user_id =? and org_id = ?", id, orgid).Update(map[string]interface{}{"user_name": role.UserName, "mtime": time.Now().Unix()}).Error
	return err
}
