package service

import (
	"Xcx_New/models"
	"strings"
	"time"

	"github.com/jinzhu/gorm"
)

func GetPublicDrugDics() (drugs []*models.DrugDic, total int64, err error) {
	err = readDb.Model(&models.DrugDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&drugs).Error
	return
}

func GetPublicDrugWayDics() (drugways []*models.DrugwayDic, total int64, err error) {
	err = readDb.Model(&models.DrugwayDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&drugways).Error
	return
}

func GetPublicExecutionFrequencyDics() (dics []*models.ExecutionFrequencyDic, total int64, err error) {
	err = readDb.Model(&models.ExecutionFrequencyDic{}).Where("org_id = 0 and status=1").Count(&total).Order("id desc").Find(&dics).Error
	return
}

func GetDrugDics(orgid int64) (drugs []*models.DrugDic, total int64, err error) {
	err = readDb.Model(&models.DrugDic{}).Where("org_id =? and status=1", orgid).Count(&total).Order("id desc").Find(&drugs).Error
	return
}

func GetAdviceTemplates(orgid int64) (templates []*models.DoctorAdviceTemplate, total int64, err error) {
	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("org_id =? and status=1", orgid).Count(&total).Order("id desc").Find(&templates).Error
	return
}

func GetDrugWayDics(orgid int64) (drugways []*models.DrugwayDic, total int64, err error) {
	err = readDb.Model(&models.DrugwayDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&drugways).Error
	return
}

func GetExecutionFrequencyDics(orgid int64) (dics []*models.ExecutionFrequencyDic, total int64, err error) {
	err = readDb.Model(&models.ExecutionFrequencyDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&dics).Error
	return
}

func CreateDrugDic(d *models.DrugDic) (err error) {
	err = readDb.Create(&d).Error
	return
}

func UpdateDrugDic(d *models.DrugDic) (err error) {
	err = readDb.Save(&d).Error
	return
}

func FindDrugDic(orgid, id int64) (*models.DrugDic, error) {
	var drugdic models.DrugDic
	err := readDb.Model(&models.DrugDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&drugdic).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

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

func CreateDrugWay(d *models.DrugwayDic) (err error) {
	err = readDb.Create(&d).Error
	return
}

func FindDrugWay(orgid, id int64) (*models.DrugwayDic, error) {
	var drugway models.DrugwayDic
	err := readDb.Model(&models.DrugwayDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&drugway).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

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

func UpdateDrugWay(d *models.DrugwayDic) (err error) {
	err = readDb.Save(&d).Error
	return
}

func CreateExecutionFrequency(d *models.ExecutionFrequencyDic) (err error) {
	err = readDb.Create(&d).Error
	return
}

func FindExecutionFrequency(orgid, id int64) (*models.ExecutionFrequencyDic, error) {
	var ef models.ExecutionFrequencyDic
	err := readDb.Model(&models.ExecutionFrequencyDic{}).Where("id=? and org_id =? and status=1", id, orgid).First(&ef).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

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

func UpdateExecutionFrequency(d *models.ExecutionFrequencyDic) (err error) {
	err = readDb.Save(&d).Error
	return
}

func CreateAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
	err = readDb.Create(&d).Error
	return
}

func CreateHisAdviceTemplate(d *models.HisDoctorAdviceTemplate) (err error) {
	err = readDb.Create(&d).Error
	return
}

func FindAdviceTemplate(orgid, id int64) (*models.DoctorAdviceTemplate, error) {
	var template models.DoctorAdviceTemplate
	err := readDb.Model(&models.DoctorAdviceTemplate{}).Where("id=? and org_id =? and status=1", id, orgid).First(&template).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

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

func FindHisAdviceTemplate(orgid, id int64) (*models.HisDoctorAdviceTemplate, error) {
	var template models.HisDoctorAdviceTemplate
	err := readDb.Model(&models.HisDoctorAdviceTemplate{}).Where("id=? and org_id =? and status=1", id, orgid).First(&template).Error
	if err == gorm.ErrRecordNotFound {
		return nil, nil
	}

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

func UpdateAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
	err = writeDb.Save(&d).Error
	return
}

func UpdateHisAdviceTemplate(d *models.HisDoctorAdviceTemplate) (err error) {
	err = writeDb.Save(&d).Error
	return
}

func UpdateAdviceAndSubAdviceTemplate(d *models.DoctorAdviceTemplate) (err error) {
	err = writeDb.Save(&d).Error
	err = writeDb.Model(&models.DoctorAdviceTemplate{}).Where("status=1 AND parent_id = ?", d.ID).Updates(map[string]interface{}{"status": 2, "updated_time": time.Now().Unix()}).Error
	return
}

func UpdateHisAdviceAndSubAdviceTemplate(d *models.HisDoctorAdviceTemplate) (err error) {
	err = writeDb.Save(&d).Error
	err = writeDb.Model(&models.HisDoctorAdviceTemplate{}).Where("status=1 AND parent_id = ?", d.ID).Updates(map[string]interface{}{"status": 2, "updated_time": time.Now().Unix()}).Error
	return
}

func CreateTemplate(template *models.DoctorAdviceParentTemplate) (err error) {
	err = readDb.Create(&template).Error
	return
}

func CreateHisDoctorAdviceTemplate(template *models.HisDoctorAdviceParentTemplate) (err error) {
	err = readDb.Create(&template).Error
	return
}

func CreateHisSubDoctorAdviceTemplate(template []*models.HisDoctorAdviceTemplate) (err error) {
	if len(template) > 0 {
		utx := writeDb.Begin()
		if len(template) > 0 {
			thisSQL := "INSERT INTO his_doctor_advice_template (org_id, advice_name, advice_desc, single_dose, single_dose_unit,prescribing_number," +
				"prescribing_number_unit,delivery_way,execution_frequency,advice_doctor,status,created_time,updated_time,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type,drug_id,way) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range template {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.OrgId)
				insertData = append(insertData, info.AdviceName)
				insertData = append(insertData, info.AdviceDesc)
				insertData = append(insertData, info.SingleDose)
				insertData = append(insertData, info.SingleDoseUnit)
				insertData = append(insertData, info.PrescribingNumber)
				insertData = append(insertData, info.PrescribingNumberUnit)
				insertData = append(insertData, info.DeliveryWay)
				insertData = append(insertData, info.ExecutionFrequency)
				insertData = append(insertData, info.AdviceDoctor)
				insertData = append(insertData, info.Status)
				insertData = append(insertData, info.CreatedTime)
				insertData = append(insertData, info.UpdatedTime)
				insertData = append(insertData, info.TemplateId)
				insertData = append(insertData, info.DrugSpec)
				insertData = append(insertData, info.DrugSpecUnit)
				insertData = append(insertData, info.AdviceType)
				insertData = append(insertData, info.DayCount)
				insertData = append(insertData, info.WeekDays)
				insertData = append(insertData, info.FrequencyType)
				insertData = append(insertData, info.DrugId)
				insertData = append(insertData, info.Way)
			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return

}

//func CreateBatchRecord(template []*models.DoctorAdviceTemplate) (err error) {
//	err = writeDb.Create(template).Error
//	return
//}

func CreateSubTemplate(template []*models.DoctorAdviceTemplate) (err error) {
	if len(template) > 0 {
		utx := writeDb.Begin()
		if len(template) > 0 {
			thisSQL := "INSERT INTO xt_doctor_advice_template (org_id, advice_name, advice_desc, single_dose, single_dose_unit,prescribing_number," +
				"prescribing_number_unit,delivery_way,execution_frequency,advice_doctor,status,created_time,updated_time,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type,drug_id,way) VALUES "
			insertParams := make([]string, 0)
			insertData := make([]interface{}, 0)
			for _, info := range template {
				insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
				insertData = append(insertData, info.OrgId)
				insertData = append(insertData, info.AdviceName)
				insertData = append(insertData, info.AdviceDesc)
				insertData = append(insertData, info.SingleDose)
				insertData = append(insertData, info.SingleDoseUnit)
				insertData = append(insertData, info.PrescribingNumber)
				insertData = append(insertData, info.PrescribingNumberUnit)
				insertData = append(insertData, info.DeliveryWay)
				insertData = append(insertData, info.ExecutionFrequency)
				insertData = append(insertData, info.AdviceDoctor)
				insertData = append(insertData, info.Status)
				insertData = append(insertData, info.CreatedTime)
				insertData = append(insertData, info.UpdatedTime)
				insertData = append(insertData, info.TemplateId)
				insertData = append(insertData, info.DrugSpec)
				insertData = append(insertData, info.DrugSpecUnit)
				insertData = append(insertData, info.AdviceType)
				insertData = append(insertData, info.DayCount)
				insertData = append(insertData, info.WeekDays)
				insertData = append(insertData, info.FrequencyType)
				insertData = append(insertData, info.DrugId)
				insertData = append(insertData, info.Way)
			}
			thisSQL += strings.Join(insertParams, ", ")
			err = utx.Exec(thisSQL, insertData...).Error
			if err != nil {
				utx.Rollback()
				return
			}
		}
		utx.Commit()
	}
	return

}

func FindDoctorAdviceTemplateById(id int64, org_id int64) (temps models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", "status = 1").Where("org_id = ? AND status=1 AND id = ?", org_id, id).Order("id desc").First(&temps).Error
	return
}

func FindHisDoctorAdviceTemplateById(id int64, org_id int64) (temps models.HisDoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.HisDoctorAdviceParentTemplate{}).Preload("HisDoctorAdviceTemplate", "status = 1").Where("org_id = ? AND status=1 AND id = ?", org_id, id).Order("id desc").First(&temps).Error
	return
}

func FindAllAdviceTemplate(org_id int64, advice_type int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,advice_name,advice_desc,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,status,created_time,updated_time,parent_id,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type,way,drug_id,drug_name_id, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
	}).Where("org_id = ? AND status=1 AND advice_type = ?", org_id, advice_type).Find(&temps).Error
	return
}

func GetAllAdviceSubTemplates(orgid int64, template_id int64) (total int64, err error) {
	err = readDb.Model(&models.DoctorAdviceTemplate{}).Where("org_id =? AND status=1 AND template_id = ?", orgid, template_id).Count(&total).Error
	return
}

func UpdateParentAdviceTemplates(orgid int64, tempelate_id int64) (err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("org_id =? AND status=1 AND id = ?", orgid, tempelate_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error
	return
}

func FindTemplateRecordByName(orgid int64, name string) (total int64) {
	readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("name = ? AND org_id = ? AND status= 1 ", name, orgid).Count(&total)
	return
}

func FindParentTemplateRecordById(orgid int64, template_id int64) (parentTemplate models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Where("id = ? AND org_id = ? AND status= 1 ", template_id, orgid).First(&parentTemplate).Error
	return
}

func FindParentHisTemplateRecordById(orgid int64, template_id int64) (parentTemplate models.HisDoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.HisDoctorAdviceParentTemplate{}).Where("id = ? AND org_id = ? AND status= 1 ", template_id, orgid).First(&parentTemplate).Error
	return
}

func DeleteParentDoctorAdviceByTemplateId(template_id int64, org_id int64) (err error) {

	ut := writeDb.Begin()
	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error

	if err != nil {
		ut.Rollback()
		return
	}
	err = writeDb.Model(&models.DoctorAdviceTemplate{}).Where("status=1 AND template_id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "2", "updated_time": time.Now().Unix()}).Error
	if err != nil {
		ut.Rollback()
		return
	}
	ut.Commit()
	return err
}

func DeleteHisParentDoctorAdviceByTemplateId(template_id int64, org_id int64) (err error) {

	ut := writeDb.Begin()
	err = writeDb.Model(&models.HisDoctorAdviceParentTemplate{}).Where("status=1 AND id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "0", "updated_time": time.Now().Unix()}).Error

	if err != nil {
		ut.Rollback()
		return
	}
	err = writeDb.Model(&models.HisDoctorAdviceTemplate{}).Where("status=1 AND template_id = ? AND org_id = ?", template_id, org_id).Updates(map[string]interface{}{"status": "2", "updated_time": time.Now().Unix()}).Error
	if err != nil {
		ut.Rollback()
		return
	}
	ut.Commit()
	return err
}

func ModifyTemplateName(id int64, template_name string) (err error) {
	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix()}).Error
	return err
}

func ModifyTemplateNameOne(id int64, template_name string, sort int64) (err error) {
	err = writeDb.Model(&models.DoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix(), "sort": sort}).Error
	return err
}

func ModifyHisTemplateName(id int64, template_name string) (err error) {
	err = writeDb.Model(&models.HisDoctorAdviceParentTemplate{}).Where("status=1 AND id = ?", id).Updates(map[string]interface{}{"name": template_name, "updated_time": time.Now().Unix()}).Error
	return err
}

func FindOtherAllAdviceTemplate(org_id int64) (temps []*models.DoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.DoctorAdviceParentTemplate{}).Preload("DoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,advice_name,advice_desc,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,status,created_time,updated_time,parent_id,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type,drug_id,way, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
	}).Where("org_id = ? AND status=1 ", org_id).Find(&temps).Error
	return
	//.Scan(&advices).Error

}

func FindHisAllAdviceTemplate(org_id int64) (temps []*models.HisDoctorAdviceParentTemplate, err error) {
	err = readDb.Model(&models.HisDoctorAdviceParentTemplate{}).Preload("HisDoctorAdviceTemplate", func(db *gorm.DB) *gorm.DB {
		return db.Select("id,advice_name,advice_desc,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,status,created_time,updated_time,parent_id,template_id,drug_spec,drug_spec_unit,advice_type,day_count,week_days,frequency_type,drug_id,way, IF(parent_id>0, parent_id, id) as advice_order").Where("status = 1").Order("advice_order desc, id")
	}).Where("org_id = ? AND status=1 ", org_id).Find(&temps).Error
	return
	//.Scan(&advices).Error

}

func GetHandleData(id int64) (models.ConfigViewModel, error) {
	config := models.ConfigViewModel{}
	err := readDb.Model(&config).Where("id=?", id).Find(&config).Error
	return config, err
}

func UpdateDataTwo(id int64, model models.ConfigViewModel) error {

	err := writeDb.Model(&model).Where("id=?", id).Update(map[string]interface{}{"name": model.Name, "orders": model.Order, "remark": model.Remark, "update_time": time.Now().Unix()}).Error
	return err
}

type AdviceDate struct {
	RecordDate int64
}

type DoctorAdvice struct {
	ID                    int64           `gorm:"column:id" json:"id" form:"id"`
	GroupNo               int64           `gorm:"column:groupno" json:"groupno" form:"groupno"`
	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"`
	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"`
	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"`
	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"`
	DialysisOrderId       int64           `gorm:"column:dialysis_order_id" json:"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"`
	AdviceId              int64           `gorm:"-"`
	RemindType            int64           `gorm:"column:remind_type" json:"remind_type"`
	FrequencyType         int64           `gorm:"column:frequency_type" json:"frequency_type"`
	DayCount              int64           `gorm:"column:day_count" json:"day_count"`
	WeekDay               string          `gorm:"column:week_day" json:"week_day"`
	DoctorAdvice          []*DoctorAdvice `gorm:"ForeignKey:ParentId;AssociationForeignKey:ID" json:"children"`
	TemplateId            string          `gorm:"column:template_id" json:"template_id"`
	Modifier              int64           `gorm:"column:modifier" json:"modifier" form:"modifier"`
	IsCheck               int64           `gorm:"-" json:"is_check" form:"is_check"`
	Way                   int64           `gorm:"column:way" json:"way" form:"way"`
	DrugId                int64           `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
	DrugNameId            int64           `gorm:"column:drug_name_id" json:"drug_name_id" form:"drug_name_id"`
}

func (DoctorAdvice) TableName() string {
	return "xt_doctor_advice"
}

func GetDoctorAdviceByType(change_type int64, record_time int64, org_id int64, patient_id int64) (advice []*DoctorAdvice, sch models.Schedule, err error) {
	if change_type == 1 { //根据日期取出上一方数据
		var Id AdviceDate
		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND status=1 AND record_date < ?", patient_id, org_id, record_time).Select("record_date").Group("record_date").Order("record_date asc").Scan(&Id).Error
		err = readDb.Model(&models.Schedule{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND schedule_date  = ?", patient_id, org_id, Id.RecordDate).Find(&sch).Error
		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND record_date  = ? AND parent_id= 0", patient_id, org_id, Id.RecordDate).Preload("DoctorAdvice", "status = 1 AND user_org_id = ? AND patient_id = ?", org_id, patient_id).Find(&advice).Error

	} else if change_type == 2 {
		var Id AdviceDate
		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND status=1 AND record_date > ?", patient_id, org_id, record_time).Select("record_date").Group("record_date").Order("record_date desc").Scan(&Id).Error
		err = readDb.Model(&models.Schedule{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND schedule_date  = ?", patient_id, org_id, Id.RecordDate).Find(&sch).Error
		err = readDb.Model(&DoctorAdvice{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND record_date  = ? AND parent_id= 0", patient_id, org_id, Id.RecordDate).Preload("DoctorAdvice", "status = 1 AND user_org_id = ? AND patient_id = ?", org_id, patient_id).Find(&advice).Error
	}
	return
}

func GetDict(orgid int64) (drugways []*models.DrugwayDic, total int64, err error) {
	err = readDb.Model(&models.DrugwayDic{}).Where("(org_id =? or org_id = 0) and status=1", orgid).Count(&total).Order("id desc").Find(&drugways).Error
	return
}
