package service

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

func GetHisProjectIsExist(projectName string, orgid int64) (*models.XtHisProject, error) {

	var project models.XtHisProject
	var err error
	err = XTReadDB().Model(&project).Where("project_name = ? and user_org_id = ? and status = 1", projectName, orgid).Find(&project).Error
	if err == gorm.ErrRecordNotFound {
		return nil, err
	}

	if err != nil {
		return nil, err
	}

	return &project, nil
}

func CreateHisProject(project *models.XtHisProject) error {

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

func GetHisProjectList(orgid int64, limit int64, page int64, charge int64, start int64, keyword string, isMark int64) (hisproject []*models.XtHisProject, total int64, err error) {
	offset := (page - 1) * limit
	likeKey := "%" + keyword + "%"
	db := XTReadDB().Table("xt_his_project as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	if start > 0 {
		db = db.Where("x.medical_status = ?", start)
	}
	if charge > 0 {
		db = db.Where("x.is_estimate = ? ", charge)
	}
	if len(keyword) > 0 {
		db = db.Where("x.project_name like ?", likeKey)
	}
	if isMark > 0 {
		db = db.Where("x.is_mark = ?", isMark)
	}
	err = db.Select("x.id,x.project_name,x.pinyin,x.wubi,x.price,x.unit,x.cost_classify,x.executive_section,x.medical_coverage,x.statistical_classification,x.disease_directory,x.is_record,x.medical_code,x.tube_color,x.medical_status,x.remark,x.sign,x.default_number,x.is_default,x.is_charge,x.is_estimate,x.is_workload,x.sort,x.doctor_advice,x.user_org_id,x.status,x.created_time,x.is_mark").Count(&total).Offset(offset).Limit(limit).Order("created_time desc").Find(&hisproject).Error
	return hisproject, total, err
}

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

func UpdatedProject(id int64, pro *models.XtHisProject) error {

	err := XTWriteDB().Model(&pro).Where("id=?", id).Updates(map[string]interface{}{"project_name": pro.ProjectName, "pinyin": pro.Pinyin, "wubi": pro.Pinyin, "price": pro.Price, "unit": pro.Unit, "cost_classify": pro.CostClassify, "executive_section": pro.ExecutiveSection, "medical_coverage": pro.MedicalCoverage, "statistical_classification": pro.StatisticalClassification, "disease_directory": pro.DiseaseDirectory, "is_record": pro.IsRecord, "medical_code": pro.MedicalCode, "tube_color": pro.TubeColor, "medical_status": pro.MedicalStatus, "remark": pro.Remark, "sign": pro.Sign, "default_number": pro.DefaultNumber, "is_default": pro.IsDefault, "is_charge": pro.IsCharge, "is_estimate": pro.IsEstimate, "is_workload": pro.IsWorkload, "sort": pro.Sort, "doctor_advice": pro.DoctorAdvice, "single_dose": pro.SingleDose, "execution_frequency": pro.ExecutionFrequency, "delivery_way": pro.DeliveryWay, "number_days": pro.NumberDays, "total": pro.Total, "updated_time": pro.UpdatedTime, "category": pro.Category, "specail_project": pro.SpecailProject, "social_security_directory_code": pro.SocialSecurityDirectoryCode, "record_date": pro.RecordDate}).Error
	return err
}

func DeleteHisProject(id int64) error {
	project := models.XtHisProject{}
	err := XTWriteDB().Model(&project).Where("id=?", id).Updates(map[string]interface{}{"status": 0}).Error
	return err
}

func GetHisProjectByNameOne(projectName string, orgid int64) (*models.XtHisProjectTeam, error) {

	projectTeam := models.XtHisProjectTeam{}
	err := XTReadDB().Model(&projectTeam).Where("project_team = ? and user_org_id = ? and status = 1", projectName, orgid).First(&projectTeam).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &projectTeam, nil

}

func CreatedProjectTeam(team *models.XtHisProjectTeam) error {

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

func GetProjectTeamList(limit int64, page int64, orgid int64, keyword string) (projectTeam []*models.XtHisProjectTeam, total int64, err error) {
	offset := (page - 1) * limit
	likeKey := "%" + keyword + "%"
	db := XTReadDB().Model(&projectTeam)
	if len(keyword) > 0 {
		db = db.Where("project_team like ?", likeKey)
	}
	err = db.Where("user_org_id = ? and status = 1", orgid).Count(&total).Offset(offset).Limit(limit).Order("created_time desc").Find(&projectTeam).Error
	return projectTeam, total, err
}

func GetProjectTeamDetail(id int64) (models.XtHisProjectTeam, error) {

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

func UpdatedProjectTeam(id int64, team *models.XtHisProjectTeam) error {

	err := XTWriteDB().Model(&team).Where("id=? and status = 1", id).Updates(map[string]interface{}{"project_team": team.ProjectTeam, "price": team.Price, "pinyin": team.Pinyin, "wubi": team.Wubi, "tube_color": team.TubeColor, "team_type": team.TeamType, "remark": team.Remark, "project_id": team.ProjectId, "item_id": team.ItemId}).Error
	return err
}

func DeleteProjectTeam(id int64) error {

	team := models.XtHisProjectTeam{}
	err := XTWriteDB().Model(&team).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
	return err
}

func CreateDePartment(department *models.XtHisDepartment) error {

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

func GetDepartMentList(limit int64, page int64, orgid int64) (departMent []*models.XtHisDepartment, total int64, err error) {

	offset := (page - 1) * limit
	err = XTReadDB().Model(&departMent).Where("user_org_id = ? and status = 1", orgid).Count(&total).Offset(offset).Limit(limit).Order("created_time desc").Find(&departMent).Error
	return departMent, total, err
}

func GetDepartMentDetail(id int64) (models.XtHisDepartment, error) {

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

func UpdatedDepartment(id int64, department *models.XtHisDepartment) error {

	err := XTWriteDB().Model(&department).Where("id=? and status = 1", id).Updates(map[string]interface{}{"name": department.Name, "number": department.Number, "updated_time": time.Now().Unix()}).Error
	return err
}

func DeleteDepartment(id int64) error {
	department := models.XtHisDepartment{}
	err := XTReadDB().Model(&department).Where("id=? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
	return err
}

func GetBloodPatientList(orgid int64, startime int64) (schedule []*models.SchedulesVm, err error) {

	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	if startime > 0 {
		db = db.Where("x.schedule_date = ?", startime)
	}
	err = db.Select("x.id,x.user_org_id,x.patient_id,x.schedule_date,x.schedule_type,x.schedule_week,x.mode_id,p.name,p.id_card_no").Joins("left join xt_patients as p on p.id = x.patient_id").Scan(&schedule).Error
	return schedule, err
}

func GetHisPatient(orgid int64, recorddate int64) (paitent []*models.HisPatient, err error) {

	err = XTReadDB().Model(&paitent).Where("user_org_id = ?  and record_date = ? and status = 1", orgid, recorddate).Find(&paitent).Error
	return paitent, err
}

func GetHisPrescriptionOther(orgid int64, recorddate int64) (prescription []*models.HisPrescriptionVm, err error) {

	db := XTReadDB().Table("his_prescription as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	if recorddate > 0 {
		db = db.Where("x.record_date = ? ", recorddate)
	}
	err = db.Select("x.id,x.user_org_id,x.record_date,x.patient_id,x.his_patient_id,x.number,x.type,x.doctor,x.creator,x.modifier,t.name").Joins("left join his_patient as t on t.id = x.his_patient_id").Scan(&prescription).Error
	return prescription, err
}

func GetHisPrescriptionByPatientId(id int64, recordate int64) (prescription []*models.HisPrescription, err error) {

	err = XTReadDB().Model(&prescription).Where("his_patient_id = ? and record_date = ? and status= 1", id, recordate).Find(&prescription).Error
	return prescription, err
}

func CreateAdditionalCharge(charge *models.HisAdditionalCharge) error {

	err = XTWriteDB().Model(&charge).Save(&charge).Error
	return err
}

func GetTreatmentList(id int64, startime int64) (prescription []*models.HisPrescription, err error) {

	err = XTReadDB().Model(&prescription).Where("id = ? and record_date = ? and status = 1", id, startime).Find(&prescription).Error
	return prescription, err
}

//func GetAllProjectList(orgid int64) (project []*models.XtHisProject, err error) {
//
//	err = XTReadDB().Model(&project).Where("user_org_id = ? and status = 1", orgid).Find(&project).Error
//	return project, err
//}

func CreateProjectList(list *models.XtHisProjectList) error {

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

func GetHisProjectListByOrgId(orgid int64) (projectlist []*models.HisProjectListVm, err error) {

	db := XTReadDB().Table("xt_his_project_list as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ? ", orgid)
	}
	err = db.Select("x.id,x.number,x.user_org_id,x.project_id,t.price,t.unit,t.cost_classify,t.project_name").Joins("left join xt_his_project as t on t.id = x.project_id").Scan(&projectlist).Error
	return projectlist, err
}

func GetHisPatientInformation(id int64) (models.HisPatient, error) {

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

func DeleteProjectList(id int64) error {
	list := models.XtHisProjectList{}
	err := XTWriteDB().Model(&list).Where("id=? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
	return err
}

func GetHisProject(orgid int64) (project []*models.XtHisProject, err error) {

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

func GetProjectTeam(ids []string, orgid int64) (project []*models.XtHisProject, err error) {

	err = XTReadDB().Model(&project).Where("user_org_id = ? and id in (?)", orgid, ids).Find(&project).Error
	return project, err
}

func GetAllDepartMent(orgid int64) (department []*models.XtHisDepartment, err error) {

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

func CreateHisPatient(patient *models.XtHisPatient) error {

	err := XTReadDB().Model(&patient).Create(&patient).Error
	return err
}

func UpdateHisPrescriptionHisID(his_patient_id int64, patient_id int64, record_time int64, org_id int64) {
	XTWriteDB().Model(&models.HisPrescription{}).Where("record_date = ? AND user_org_id = ? AND patient_id = ? AND his_patient_id = 0", record_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})
	XTWriteDB().Model(&models.HisPrescriptionInfo{}).Where("record_date = ? AND user_org_id = ? AND patient_id = ?  AND his_patient_id = 0", record_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})

	return
}

func UpdateHisPrescriptionHisIDTwo(his_patient_id int64, patient_id int64, record_time int64, org_id int64, start_time int64) {
	XTWriteDB().Model(&models.HisPrescription{}).Where("record_date <= ? AND record_date >= ? AND user_org_id = ? AND patient_id = ? AND his_patient_id = 0 AND order_status <> 2", record_time, start_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})
	XTWriteDB().Model(&models.HisPrescriptionInfo{}).Where("record_date = ? AND user_org_id = ? AND patient_id = ? AND his_patient_id = 0 AND order_status <> 2", record_time, start_time, org_id, patient_id).Updates(map[string]interface{}{"his_patient_id": his_patient_id})
	return
}

func GetBloodPatientByIdCard(idcard string, orgid int64) (*models.XtPatients, error) {
	var patients models.XtPatients
	var err error
	err = XTReadDB().Model(&patients).Where("id_card_no = ? and user_org_id = ? and status = 1", idcard, orgid).Find(&patients).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &patients, nil
}

func GetAllProjectTeam(orgid int64) (project []*models.XtHisProjectTeam, err error) {

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

func GetProjectListById(orgid int64, ids []string) (project []*models.XtHisProjectList, err error) {
	err = XTReadDB().Model(&project).Preload("XtHisProject", "status = 1").Preload("GoodInfo", "status=1").Where("user_org_id = ? and id in (?)", orgid, ids).Find(&project).Error
	return project, err
}

func GetHisPatientHistory(keyword string, startime int64, endtime int64, registtype int64, limit int64, page int64, orgid int64) (hisPatient []*models.XtHisPatient, total int64, err error) {
	offset := (page - 1) * limit
	likeKey := "%" + keyword + "%"
	db := XTReadDB().Table("his_patient as x")
	if len(keyword) > 0 {
		db = db.Where("x.name like ?", likeKey)
	}
	if startime > 0 {
		db = db.Where("x.record_date >= ?", startime)
	}
	if endtime > 0 {
		db = db.Where("x.record_date<=?", endtime)
	}
	if registtype > 0 {
		db = db.Where("x.register_type = ?", registtype)
	}
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	err = db.Select("x.id,x.balance_accounts_type,x.medical_insurance_number,x.name,x.gender,x.id_type,x.medical_treatment_type,x.birthday,x.record_date,x.age,x.phone_number,x.id_card_no,x.register_type,x.admin_user_id,x.departments,x.is_need_cost_of_production,x.register_cost,x.treatment_cost,x.cost_of_production,x.total,x.user_org_id,x.patient_id,x.number,x.is_return,x.doctor,x.ctime,x.social_type,x.phone,x.status").Count(&total).Offset(offset).Limit(limit).Order("x.id desc").Find(&hisPatient).Error
	return hisPatient, total, err
}

func ChangePatient(id int64) error {
	patient := models.XtHisPatient{}

	err := XTWriteDB().Model(&patient).Where("id = ?", id).Updates(map[string]interface{}{"is_return": 2}).Error
	return err
}

func GetHisPrescriptionTwo(patientid int64, orgid int64, recorddate int64) (*models.HisPrescription, error) {
	prescription := models.HisPrescription{}
	err := XTReadDB().Model(&prescription).Where("his_patient_id = ? and user_org_id = ? and record_date = ? and status = 1", patientid, orgid, recorddate).Find(&prescription).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &prescription, nil
}

func UpdatedHisPatient(hispatientid int64, orgid int64, recorddate int64) error {
	hisPatient := models.HisPatient{}
	err := XTWriteDB().Model(&hisPatient).Where("id = ? and user_org_id = ? and record_date = ?", hispatientid, orgid, recorddate).Updates(map[string]interface{}{"is_return": 3}).Error
	return err
}

func GetBloodPatientInfoById(patientid int64) (models.XtPatients, error) {

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

func GetPatientCaseHistory(patientid int64) (models.HisPatientCaseHistory, error) {

	history := models.HisPatientCaseHistory{}
	err := XTReadDB().Model(&history).Where("patient_id = ? and status = 1", patientid).Last(&history).Error
	return history, err
}

func GetBloodPatientByPatient(id int64) (models.XtPatients, error) {

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

func GetHisPatientByIdTwo(patientid int64) (models.XtHisPatient, error) {

	patient := models.XtHisPatient{}
	err := XTReadDB().Model(&patient).Where("patient_id = ? and status=1", patientid).Find(&patient).Error
	return patient, err
}

func GetHisPatientById(patientid int64) (models.VMHisPatient, error) {
	patient := models.VMHisPatient{}
	err := XTReadDB().Model(&patient).Where("patient_id = ? and status = 1", patientid).Find(&patient).Error
	return patient, err
}

func GetTemplateDetail(id int64) (models.HisCaseHistoryTemplate, error) {

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

func UpdateCaseHistoryTemplate(tem *models.HisCaseHistoryTemplate, id int64) error {

	err := XTWriteDB().Model(&tem).Where("id = ? ", id).Updates(map[string]interface{}{"history_of_present_illness": tem.HistoryOfPresentIllness, "past_history": tem.PastHistory, "chief_conplaint": tem.ChiefConplaint, "personal_history": tem.PersonalHistory, "family_history": tem.FamilyHistory, "diagnostic": tem.Diagnostic, "template_name": tem.TemplateName, "template_remark": tem.TemplateRemark, "modifier": tem.Modifier, "doctor_advice": tem.DoctorAdvice, "remark": tem.Remark}).Error
	return err
}

func GetHistPatient(orgid int64, keyword string) (hisPatient []*models.HisPatient, err error) {
	likeKey := "%" + keyword + "%"
	err = XTReadDB().Model(&hisPatient).Where("user_org_id = ? and name like ?", orgid, likeKey).Find(&hisPatient).Error
	return hisPatient, err
}

func GetDoctorAdvicePrint(his_patient_id int64, recorddate int64, schIDs []string, orgid int64) (prescription []*models.HisPrescription, err error) {

	err = XTReadDB().Model(&prescription).Where("patient_id = ? and record_date = ? and id in(?) and  status = 1 ", his_patient_id, recorddate, schIDs).Preload("Patients", "status = 1 and user_org_id = ?", orgid).Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 and user_org_id = ?", orgid).Preload("Drug", "status = 1")
	}).Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ?", orgid).Preload("HisProject").Preload("GoodInfo", "status=1")
	}).Preload("HisPrescriptionInfo", "status =1 and user_org_id = ?", orgid).Preload("HisAdditionalCharge", "status = 1 and user_org_id = ?", orgid).Find(&prescription).Error

	return prescription, err
}

func GetProjectPrint(his_patient_id int64) (models.HisPrescriptionProject, error) {
	project := models.HisPrescriptionProject{}
	err := XTReadDB().Model(&project).Where("his_patient_id = ? and status = 1", his_patient_id).Find(&project).Error
	return project, err
}

func GetHisTemplateId(templateid int64, orgid int64) (*models.XtHisTemplate, error) {

	template := models.XtHisTemplate{}
	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &template, nil
}

func CreateHisTemplate(template *models.XtHisTemplate) error {

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

func UpdateHisTemplate(template *models.XtHisTemplate) error {

	err := XTWriteDB().Save(&template).Error
	return err
}

func GetHisPrintTemplate(orgid int64) (models.XtHisTemplate, error) {

	template := models.XtHisTemplate{}
	err := XTReadDB().Model(&template).Where("user_org_id = ? and status = 1", orgid).Find(&template).Error
	return template, err
}

func GetPrescriptionTemplate(templateid int64, orgid int64) (*models.XtHisAdviceTemplate, error) {

	template := models.XtHisAdviceTemplate{}
	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &template, nil
}

func CreatePrescriptionTemplate(template *models.XtHisAdviceTemplate) error {

	err = XTWriteDB().Create(&template).Error
	return err
}

func UpdatePrescriptionTemplate(template *models.XtHisAdviceTemplate) error {

	err := XTWriteDB().Save(&template).Error
	return err
}

func GetPrescriptionTemplateById(orgid int64) (models.XtHisAdviceTemplate, error) {

	template := models.XtHisAdviceTemplate{}
	err := XTReadDB().Model(&template).Where("user_org_id = ? and status = 1", orgid).Find(&template).Error
	return template, err
}

func GetTreatPrintTemplate(templateid int64, orgid int64) (*models.XtHisTreatmentTemplate, error) {

	template := models.XtHisTreatmentTemplate{}
	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &template, nil
}

func CreateTreatPrintTemplate(template *models.XtHisTreatmentTemplate) error {

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

func UpdatedTreateTemplate(template *models.XtHisTreatmentTemplate) error {

	err := XTWriteDB().Save(&template).Error
	return err
}

func GetTreatTtreatPrintTemplate(orgid int64) (models.XtHisTreatmentTemplate, error) {
	template := models.XtHisTreatmentTemplate{}
	err := XTReadDB().Where("user_org_id = ? and status =1", orgid).Find(&template).Error
	return template, err
}

func GetChargeTemplate(templateid int64, orgid int64) (*models.XtHisChargeTemplate, error) {

	template := models.XtHisChargeTemplate{}
	err := XTReadDB().Model(&template).Where("template_id = ? and user_org_id = ? and status = 1", templateid, orgid).Find(&template).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &template, nil
}

func CreateChargePrintTemplate(template *models.XtHisChargeTemplate) error {

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

func UpdateChargePrintTemplate(template *models.XtHisChargeTemplate) error {

	err := XTWriteDB().Save(&template).Error
	return err
}

func GetChargePrintTemplate(orgid int64) (models.XtHisChargeTemplate, error) {
	template := models.XtHisChargeTemplate{}
	err := XTReadDB().Model(&template).Where("user_org_id = ? and status = 1", orgid).Find(&template).Error
	return template, err
}

func GetDoctorProjectItem(patientid int64, record_date int64) (models.HisPrescriptionProject, error) {

	project := models.HisPrescriptionProject{}
	err := XTReadDB().Model(&project).Where("patient_id = ? and record_date = ? and status = 1", patientid, record_date).Preload("HisProject").Find(&project).Error
	return project, err
}

func GetChargePrint(record int64, patient_id int64, user_org_id int64) (order XtHisOrder, err error) {

	err = readDb.Model(&HisOrder{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND settle_accounts_date=?", user_org_id, patient_id, record).
		Preload("HisOrderInfo", "status = 1 AND user_org_id = ?", user_org_id).
		Preload("HisPatient", "status = 1 AND user_org_id = ?", user_org_id).
		Preload("HisPrescriptionInfo", "status = 1 AND user_org_id = ?", user_org_id).
		Order("ctime desc").
		Find(&order).Error
	return

}

func GetLastPatient(orgid int64) (models.HisPatient, error) {

	patient := models.HisPatient{}
	err := XTReadDB().Model(&patient).Where("user_org_id = ? and status = 1", orgid).Last(&patient).Error
	return patient, err
}

func UpdateHisPatient(id int64, patient models.HisPatient) error {

	err := XTWriteDB().Model(&patient).Where("id = ? and status = 1", id).Update(map[string]interface{}{"number": patient.Number}).Error
	return err
}

func GetTodaySchedulePatient(orgid int64, scheduledata int64) (schedule []*models.Schedules, err error) {

	db := XTReadDB().Table("xt_schedule as x").Where("x.status = 1")
	if orgid > 0 {
		db = db.Where("x.user_org_id = ?", orgid)
	}
	if scheduledata > 0 {
		db = db.Where("x.schedule_date = ?", scheduledata)
	}

	err = db.Select("x.id,x.patient_id,x.schedule_date,t.name").Joins("left join xt_patients as t on t.id = x.patient_id").Scan(&schedule).Error
	return schedule, err
}

func GetPrscriptionInfo(patientid int64, recorddata int64) (info []*models.HisPrescriptionInfo, err error) {

	err = XTReadDB().Model(&info).Where("patient_id = ? and status = 1 and record_date = ?", patientid, recorddata).Find(&info).Error
	return info, err

}

func GetPrescriptionByPatientId(patient_id int64, startime int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1").Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 ").Preload("Drug", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 ").Preload("HisProject").Preload("GoodInfo", "status=1")
		}).
		Where("patient_id = ? AND record_date =? AND p_type = ? AND status = 1", patient_id, startime, p_type).
		Find(&prescription).Error
	return
}

// func GetPrescriptionByPatientId(patient_id int64, startime int64, p_type int64) (prescritpion []*models.HisPrescription, err error) {
// // 	err = XTReadDB().Model(&prescritpion).Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
// // 		return db.Where("status = 1 and user_org_id = ?", orgid).Preload("Drug", "status = 1")
// // }).Where("patient_id = ? AND record_date =? AND p_type = ? AND status = 1", patient_id, startime, p_type).Find(&prescritpion).Error
// // 	return prescritpion, err
// }

func GetTodayHisPatient(recod_date int64, patientid int64, user_org_id int64) (*models.XtHisPatient, error) {

	patient := models.XtHisPatient{}
	err := XTReadDB().Model(&patient).Where("record_date = ? and patient_id = ? and user_org_id = ? and is_return = 1 and status = 1", recod_date, patientid, user_org_id).Find(&patient).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &patient, nil
}

func CreateHisMedicalTemplate(template *models.XtHisMedicalTemplate) error {

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

func GetMedicalTemplateList(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 1", orgid).Find(&template).Error
	return template, err
}

func GetMedicalTemplateListOne(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 2", orgid).Find(&template).Error
	return template, err
}

func GetMedicalTemplateListTwo(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 3", orgid).Find(&template).Error
	return template, err
}

func GetMedicalTemplateListThree(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 4", orgid).Find(&template).Error
	return template, err
}

func GetMedicalTemplateListFour(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 5", orgid).Find(&template).Error
	return template, err
}

func GetMedicalTemplateListFive(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 6", orgid).Find(&template).Error
	return template, err
}

func GetMedicalTemplateListSix(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 7", orgid).Find(&template).Error
	return template, err
}

func GetMedicalTemplateListSeven(orgid int64) (template []*models.XtHisMedicalTemplate, err error) {

	err = XTReadDB().Model(&template).Where("user_org_id =? and status = 1 and template_id = 8", orgid).Find(&template).Error
	return template, err
}

func GetMainTemplateById(id int64) (models.XtHisMedicalTemplate, error) {

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

func UpdateMainTemplate(template *models.XtHisMedicalTemplate, id int64) error {

	err := XTWriteDB().Model(&template).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"title": template.Title, "content": template.Content, "remark": template.Remark, "mtime": time.Now().Unix()}).Error
	return err
}

func DeleteMainTemplateById(id int64) error {

	template := models.XtHisMedicalTemplate{}
	err := XTWriteDB().Model(&template).Where("id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
	return err

}

func GetProjectHisList(orgid int64) (hisProjectList []*models.XtHisProjectList, error error) {

	error = XTReadDB().Model(&hisProjectList).Where("user_org_id = ? and status = 1", orgid).Group("project_id").Find(&hisProjectList).Error
	return hisProjectList, error
}

func GetLastItem(orgid int64) (models.XtHisProjectList, error) {

	list := models.XtHisProjectList{}
	err := XTReadDB().Model(&list).Where("user_org_id = ? and status = 1", orgid).Last(&list).Error
	return list, err
}

func SaveProjectTeam(team *models.XtHisProjectTeam) error {

	err := XTWriteDB().Model(&team).Save(&team).Error
	return err
}

func GetProjectHisListByIds(ids []string) (hisProjectList []*models.XtHisProjectList, error error) {
	error = XTReadDB().Model(&hisProjectList).Preload("XtHisProject").Preload("GoodInfo", "status = 1").Where(" status = 1 and id in (?)", ids).Find(&hisProjectList).Error
	return hisProjectList, error
}

func GetHisPatientByIdThree(id int64) (models.HisPatient, error) {
	patient := models.HisPatient{}
	err := XTReadDB().Model(&patient).Where("id = ? and status = 1", id).First(&patient).Error
	return patient, err
}

func GetLastHisPatient(patient_id int64, org_id int64) (his models.HisPatient, err error) {
	err = XTReadDB().Model(&models.HisPatient{}).Where("user_org_id = ? AND patient_id = ? and status = 1 AND patient_info <> ''", org_id, patient_id).First(&his).Error
	return
}
