package service

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

func GetAppVersionByAppType(apptype int64) (*models.AppVersion, error) {
	var version models.AppVersion
	err := readDb.Model(&models.AppVersion{}).Where("app_type=?", apptype).First(&version).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

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

func GetAllAppOrg() ([]*models.OrgApp, error) {
	var app []*models.OrgApp
	err := readUserDb.Model(&models.OrgApp{}).Where("status = 1 AND org_id > 0").Group("org_id").Find(&app).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}
	return app, nil
}

func GetSystemApp() ([]*models.OrgApp, error) {
	var app []*models.OrgApp
	err := readDb.Model(&models.OrgApp{}).Where("status = 1 AND org_id = 0 ").Find(&app).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}
	return app, nil
}

func GetApp() ([]*models.OrgApp, error) {
	var app []*models.OrgApp
	err := readDb.Model(&models.OrgApp{}).Where("status = 1 AND org_id = 0").Find(&app).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

	if err != nil {
		return nil, err
	}
	return app, nil
}

func GetAppByType(orgID int64, app_type int) (*models.OrgApp, error) {
	var apps models.OrgApp
	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
	if err != nil {
		return nil, err
	}
	return &apps, nil
}

func CreateOrgApp(app *models.OrgApp) {
	writeUserDb.Create(&app)

}

func GetAllUserRole(org_id int64) (appRole []*models.App_Role) {
	if org_id == 0 {
		readUserDb.Model(&models.App_Role{}).Where("status = 1").Find(&appRole)

	} else {
		readUserDb.Model(&models.App_Role{}).Where("status = 1 AND org_id = ? ", org_id).Find(&appRole)

	}
	return
}

func GetAllUserRoleByUserTypeOne(org_id int) (appRole []*models.App_Role) {
	readUserDb.Model(&models.App_Role{}).Where("status = 1 AND user_type = 1").Find(&appRole)
	return
}

func GetAllUserRoleByUserTypeOther() (appRole []*models.App_Role) {
	//app, _ := GetOrgApp(int64(org_id), 3)

	//if org_id == 0 {
	readUserDb.Model(&models.App_Role{}).Where("status = 1 AND user_type > 1").Find(&appRole)
	//
	//} else {
	//	readUserDb.Model(&models.App_Role{}).Where("status = 1 AND org_id = ?  AND user_type > 1 AND app_id = ? ", org_id, app.Id).Find(&appRole)
	//
	//}
	return
}

func FindRoleByUserTypeOne(org_id int64) (role models.Role) {
	readUserDb.Model(&models.Role{}).Where("status = 1 AND org_id = ? AND is_system = 2 AND role_name = '医生'", org_id).First(&role)
	return
}

func FindRoleByUserTypeTwo(org_id int64) (role models.Role) {
	readUserDb.Model(&models.Role{}).Where("status = 1 AND org_id = ? AND is_system = 3 AND role_name = '护士'", org_id).First(&role)
	return
}

func GetAllRole() ([]*models.Role, error) {
	var app []*models.Role
	err := readUserDb.Model(&models.Role{}).Where("status = 1 AND org_id > 0").Group("org_id").Find(&app).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return app, nil
}

func UpdateRoleIds(id int64, ids string) {
	writeUserDb.Model(&models.App_Role{}).Where("status = 1 AND id = ?", id).Updates(map[string]interface{}{"role_ids": ids, "mtime": time.Now().Unix()})

}

func GetOrgAppA(orgID int64, app_type int) (*models.OrgApp, error) {
	var apps models.OrgApp
	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
	if err != nil {
		return nil, err
	}
	return &apps, nil
}

func GetOrgByIdB(orgID int64) (*models.Org, error) {
	var org models.Org
	err := readUserDb.Model(&models.Org{}).Where("id = ?", orgID).First(&org).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &org, nil
}

func GetOrgAppB(orgID int64, app_type int) (*models.OrgApp, error) {
	var apps models.OrgApp
	err := readUserDb.Where("app_type = ? AND org_id = ? AND status = 1", app_type, orgID).First(&apps).Error
	if err != nil {
		return nil, err
	}
	return &apps, nil
}

func CreateOrgRoleB(role *models.Role) (err error) {
	err = writeUserDb.Create(&role).Error
	return
}

func CreateRolePurviewB(purview *models.RolePurview) (err error) {
	err = writeUserDb.Create(&purview).Error
	return
}

func CreateFuncRolePurviewB(purview *models.SgjUserRoleFuncPurview) (err error) {
	err = writeUserDb.Create(&purview).Error
	return
}

func GetSystemRole(orgID int64) ([]*models.Role, error) {
	var roles []*models.Role
	err := readUserDb.Where(" org_id = ? AND status = 1 AND is_system > 1", orgID).First(&roles).Error
	if err != nil {
		return nil, err
	}
	return roles, nil
}

func HandleData() {
	var pe []*models.PredialysisEvaluation
	//readDb.Model(&models.DialysisPrescription{}).Where("user_org_id = 12 AND record_date <= 1587571200").Find(&prescription)
	//for _, item := range prescription {
	//	writeDb.Model(&models.AssessmentAfterDislysis{}).Where("user_org_id =12 AND assessment_date = ?", item.RecordDate).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "actual_ultrafiltration": item.Ultrafiltration})
	//}
	readDb.Model(&models.PredialysisEvaluation{}).Where("status = 1 AND user_org_id = 9538 AND dialysis_order_id > 0").Find(&pe)

	for _, item := range pe {
		var sch models.Schedule
		err := readDb.Model(&models.Schedule{}).Where("status = 1 AND schedule_date = ? AND patient_id = ? AND user_org_id = 9538", item.AssessmentDate, item.PatientId).First(&sch).Error

		if err == nil {
			if sch.ID > 0 {
				order := &models.DialysisOrder{
					DialysisDate:   sch.ScheduleDate,
					UserOrgId:      9538,
					PatientId:      sch.PatientId,
					Stage:          2,
					BedID:          sch.BedId,
					StartNurse:     554,
					FinishNurse:    554,
					Status:         1,
					CreatedTime:    sch.ScheduleDate,
					UpdatedTime:    sch.ScheduleDate,
					StartTime:      sch.ScheduleDate,
					EndTime:        sch.ScheduleDate,
					PunctureNurse:  554,
					Creator:        554,
					Modifier:       554,
					FinishCreator:  554,
					FinishModifier: 554,
					SchedualType:   sch.ScheduleType,
				}
				writeDb.Create(&order)
			}
		}

	}

}

func FindAllOrgByImportType() (org []*models.Org, err error) {
	err = readUserDb.Model(&models.Org{}).Where("status =1 AND import = 0").Find(&org).Error
	return
}

func FindAllPrescription(org_id int64) (prescription []*models.DialysisPrescription, err error) {
	err = readDb.Model(&models.DialysisPrescription{}).Where("user_org_id=? AND status= 1 AND record_date >= 1593446400", org_id).Find(&prescription).Error
	return
}

func AddSigleDialysisBeforePre(before *models.DialysisBeforePrepare) {
	writeDb.Create(&before)
}

func GetAllHisDoctorInfo(org_id int64) (his []*models.HisDoctorAdviceInfo, err error) {
	err = readDb.Model(&models.HisDoctorAdviceInfo{}).Where("user_org_id = ? AND status = 1", org_id).Find(&his).Error
	return
}

func GetAllHisInfo(org_id int64) (his []*models.HisPrescriptionProject, err error) {
	err = readDb.Model(&models.HisPrescriptionProject{}).Where("user_org_id = ? AND status = 1", org_id).Find(&his).Error
	return
}

func UpDateHis(his *models.HisDoctorAdviceInfo) {
	writeDb.Save(&his)
}

func UpDateHis2(his *models.HisPrescriptionProject) {
	writeDb.Save(&his)
}

func GetAllHisOrder(org_id int64) (his []*models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = ? AND status = 1 AND order_status = 2 AND fa_piao_code = '' AND fa_piao_number = '' ", org_id).Find(&his).Error
	return
}

func GetAllHisOrderTwo(org_id int64) (his models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = ? AND status = 1 AND order_status = 2 AND fa_piao_code <> '' AND fa_piao_number <> '' ", org_id).Last(&his).Error
	return
}

func GetLastHisOrder() (his models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = 10106 AND status = 1 AND order_status = 2").Last(&his).Error
	return
}

type HisPrescriptionAdviceTemplate struct {
	ID                    int64   `gorm:"column:id" json:"id" form:"id"`
	UserOrgId             int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	PatientId             int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	HisPatientId          int64   `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
	AdviceType            int64   `gorm:"column:advice_type" json:"advice_type" form:"advice_type"`
	AdviceDate            int64   `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
	StartTime             int64   `gorm:"column:start_time" json:"start_time" form:"start_time"`
	AdviceName            string  `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
	AdviceDesc            string  `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
	ReminderDate          int64   `gorm:"column:reminder_date" json:"reminder_date" form:"reminder_date"`
	SingleDose            float64 `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
	SingleDoseUnit        string  `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
	PrescribingNumber     float64 `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
	DeliveryWay           string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
	ExecutionFrequency    string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
	AdviceDoctor          int64   `gorm:"column:advice_doctor" json:"advice_doctor" form:"advice_doctor"`
	Status                int64   `gorm:"column:status" json:"status" form:"status"`
	CreatedTime           int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
	UpdatedTime           int64   `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
	AdviceAffirm          string  `gorm:"column:advice_affirm" json:"advice_affirm" form:"advice_affirm"`
	Remark                string  `gorm:"column:remark" json:"remark" form:"remark"`
	StopTime              int64   `gorm:"column:stop_time" json:"stop_time" form:"stop_time"`
	StopReason            string  `gorm:"column:stop_reason" json:"stop_reason" form:"stop_reason"`
	StopDoctor            int64   `gorm:"column:stop_doctor" json:"stop_doctor" form:"stop_doctor"`
	StopState             int64   `gorm:"column:stop_state" json:"stop_state" form:"stop_state"`
	ParentId              int64   `gorm:"column:parent_id" json:"parent_id" form:"parent_id"`
	ExecutionTime         int64   `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
	ExecutionStaff        int64   `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
	ExecutionState        int64   `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
	Checker               int64   `gorm:"column:checker" json:"checker" form:"checker"`
	RecordDate            int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
	DialysisOrderId       int64   `gorm:"column:dialysis_order_id" json:"dialysis_order_id" form:"dialysis_order_id"`
	CheckTime             int64   `gorm:"column:check_time" json:"check_time" form:"check_time"`
	CheckState            int64   `gorm:"column:check_state" json:"check_state" form:"check_state"`
	DrugSpec              float64 `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
	DrugSpecUnit          string  `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
	Groupno               int64   `gorm:"column:groupno" json:"groupno" form:"groupno"`
	RemindType            int64   `gorm:"column:remind_type" json:"remind_type" form:"remind_type"`
	FrequencyType         int64   `gorm:"column:frequency_type" json:"frequency_type" form:"frequency_type"`
	DayCount              int64   `gorm:"column:day_count" json:"day_count" form:"day_count"`
	WeekDay               string  `gorm:"column:week_day" json:"week_day" form:"week_day"`
	TemplateId            string  `gorm:"column:template_id" json:"template_id" form:"template_id"`
	Modifier              int64   `gorm:"column:modifier" json:"modifier" form:"modifier"`
	DrugId                int64   `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
	Price                 float64 `gorm:"column:price" json:"price" form:"price"`
	PrescriptionId        int64   `gorm:"column:prescription_id" json:"prescription_id" form:"prescription_id"`
	MedListCodg           string  `gorm:"column:med_list_codg" json:"med_list_codg" form:"med_list_codg"`
	FeedetlSn             string  `gorm:"column:feedetl_sn" json:"feedetl_sn" form:"feedetl_sn"`
	Day                   int64   `gorm:"column:day" json:"day" form:"day"`
	Diagnosis             int64   `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
	HospApprFlag          int64   `gorm:"column:hosp_appr_flag" json:"hosp_appr_flag" form:"hosp_appr_flag"`
	LmtUsedFlag           int64   `gorm:"column:lmt_used_flag" json:"lmt_used_flag" form:"lmt_used_flag"`
}

func (HisPrescriptionAdviceTemplate) TableName() string {
	return "his_prescription_advice_template"
}

type HisPrescriptionInfoTemplateTwo struct {
	ID                            int64                           `gorm:"column:id" json:"id" form:"id"`
	UserOrgId                     int64                           `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	RecordDate                    int64                           `gorm:"column:record_date" json:"record_date" form:"record_date"`
	PatientId                     int64                           `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	Status                        int64                           `gorm:"column:status" json:"status" form:"status"`
	Ctime                         int64                           `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime                         int64                           `gorm:"column:mtime" json:"mtime" form:"mtime"`
	Type                          int64                           `gorm:"column:type" json:"type" form:"type"`
	Creator                       int64                           `gorm:"column:creator" json:"creator" form:"creator"`
	Modifier                      int64                           `gorm:"column:modifier" json:"modifier" form:"modifier"`
	PType                         int64                           `gorm:"column:p_type" json:"p_type" form:"p_type"`
	PTemplateId                   int64                           `gorm:"column:p_template_id" json:"p_template_id" form:"p_template_id"`
	HisPrescriptionAdviceTemplate []HisPrescriptionAdviceTemplate `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"advices"`
	MedType                       string                          `gorm:"column:med_type" json:"med_type" form:"med_type"`
}

func (HisPrescriptionInfoTemplateTwo) TableName() string {
	return "his_prescription_info_template"
}

func GetHisPrescriptionTemplateTwo() (prescription []*HisPrescriptionInfoTemplateTwo, err error) {
	err = readDb.Model(&HisPrescriptionInfoTemplateTwo{}).
		Preload("HisPrescriptionAdviceTemplate", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1")
		}).
		Where("status = 1 ").
		Find(&prescription).Error
	return
}

func SaveAdviceTemplate(advice HisPrescriptionAdviceTemplate) {
	writeDb.Save(&advice)
}

func GetAllPT(org_id int64) (his []*models.HisPrescriptionTemplate, err error) {
	err = readDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND status = 1", org_id).Find(&his).Error
	return
}

type HisPrescriptionProjectTemplate struct {
	ID                 int64   `gorm:"column:id" json:"id" form:"id"`
	ProjectId          int64   `gorm:"column:project_id" json:"project_id" form:"project_id"`
	Price              float64 `gorm:"column:price" json:"price" form:"price"`
	UserOrgId          int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	Status             int64   `gorm:"column:status" json:"status" form:"status"`
	Ctime              int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime              int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
	PatientId          int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	HisPatientId       int64   `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
	RecordDate         int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
	Count              string  `gorm:"column:count" json:"count" form:"count"`
	FeedetlSn          string  `gorm:"column:feedetl_sn" json:"feedetl_sn" form:"feedetl_sn"`
	MedListCodg        string  `gorm:"column:med_list_codg" json:"med_list_codg" form:"med_list_codg"`
	SingleDose         string  `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
	DeliveryWay        string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
	ExecutionFrequency string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
	Day                string  `gorm:"column:day" json:"day" form:"day"`
	Remark             string  `gorm:"column:remark" json:"remark" form:"remark"`
	Unit               string  `gorm:"column:unit" json:"unit" form:"unit"`
	Type               int64   `gorm:"column:type" json:"type" form:"type"`
	PrescriptionId     int64   `gorm:"column:prescription_id" json:"prescription_id" form:"prescription_id"`
	FrequencyType      int64   `gorm:"column:frequency_type" json:"frequency_type" form:"frequency_type"`
	DayCount           int64   `gorm:"column:day_count" json:"day_count" form:"day_count"`
	WeekDay            string  `gorm:"column:week_day" json:"week_day" form:"week_day"`
}

func (HisPrescriptionProjectTemplate) TableName() string {
	return "his_prescription_project_template"
}

type HisPrescriptionInfoTemplateTHree struct {
	ID                             int64                            `gorm:"column:id" json:"id" form:"id"`
	UserOrgId                      int64                            `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	RecordDate                     int64                            `gorm:"column:record_date" json:"record_date" form:"record_date"`
	PatientId                      int64                            `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	Status                         int64                            `gorm:"column:status" json:"status" form:"status"`
	Ctime                          int64                            `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime                          int64                            `gorm:"column:mtime" json:"mtime" form:"mtime"`
	Type                           int64                            `gorm:"column:type" json:"type" form:"type"`
	Creator                        int64                            `gorm:"column:creator" json:"creator" form:"creator"`
	Modifier                       int64                            `gorm:"column:modifier" json:"modifier" form:"modifier"`
	PType                          int64                            `gorm:"column:p_type" json:"p_type" form:"p_type"`
	PTemplateId                    int64                            `gorm:"column:p_template_id" json:"p_template_id" form:"p_template_id"`
	HisPrescriptionAdviceTemplate  []HisPrescriptionAdviceTemplate  `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"advices"`
	HisPrescriptionProjectTemplate []HisPrescriptionProjectTemplate `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"project"`
	MedType                        string                           `gorm:"column:med_type" json:"med_type" form:"med_type"`
}

func (HisPrescriptionInfoTemplateTHree) TableName() string {
	return "his_prescription_info_template"
}

func GetAllPTInfo(org_id int64, p_template_id int64) (his []*HisPrescriptionInfoTemplateTHree, err error) {
	err = readDb.Model(&HisPrescriptionInfoTemplateTHree{}).Preload("HisPrescriptionAdviceTemplate", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1")
	}).Preload("HisPrescriptionProjectTemplate", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1")
	}).Where("user_org_id = ? AND status = 1 AND p_template_id = ?", org_id, p_template_id).Find(&his).Error
	return
}

func GetAllInfo(org_id int64, project_id int64) (his []*HisPrescriptionProjectTemplate, err error) {
	err = readDb.Model(&HisPrescriptionProjectTemplate{}).Where("user_org_id = ? AND status = 1 AND project_id = ? ", org_id, project_id).Find(&his).Error
	return
}
func UpdateStatus(project_id int64, p_id int64) {
	writeDb.Model(&HisPrescriptionProjectTemplate{}).Where("id = ?", project_id).Updates(map[string]interface{}{"status": 0})
	writeDb.Model(&HisPrescriptionInfoTemplateTwo{}).Where("id = ?", p_id).Updates(map[string]interface{}{"status": 0})
}

func SaveOrder(order *models.HisOrder) {
	writeDb.Save(&order)
}

func GetAllPrivateHis(org_id int64) (his []*models.HisPatient) {
	readDb.Model(&models.HisPatient{}).Where("user_org_id = ? AND balance_accounts_type = 2 AND status = 1", org_id).Find(&his)
	return
}

func SaveHis(his *models.HisPatient) {
	writeDb.Save(his)
	return
}
