package service

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

type HisPatient struct {
	ID              int64              `gorm:"column:id" json:"id" form:"id"`
	Name            string             `gorm:"column:name" json:"name" form:"name"`
	Gender          int64              `gorm:"column:gender" json:"gender" form:"gender"`
	Total           float64            `gorm:"column:total" json:"total" form:"total"`
	UserOrgId       int64              `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	Status          int64              `gorm:"column:status" json:"status" form:"status"`
	RecordDate      int64              `gorm:"column:record_date" json:"record_date" form:"record_date"`
	HisPrescription []*HisPrescription `gorm:"ForeignKey:PatientId,RecordDate;AssociationForeignKey:ID,RecordDate" json:"prescription"`
	PatientId       int64              `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	Number          string             `gorm:"column:number" json:"number" form:"number"`
	PatientInfo     string             `gorm:"column:patient_info" json:"patient_info" form:"patient_info"`
	Insutype        string             `gorm:"column:insutype" json:"insutype" form:"insutype"`
}

func (HisPatient) TableName() string {
	return "his_patient"
}

type Schedule 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"`
	Status                int64                 `gorm:"column:status" json:"status" form:"status"`
	ScheduleDate          int64                 `gorm:"column:schedule_date" json:"schedule_date" form:"schedule_date"`
	Patients              Patients              `gorm:"ForeignKey:ID;AssociationForeignKey:PatientId" json:"patients"`
	HisPatient            HisPatient            `gorm:"ForeignKey:PatientId,RecordDate;AssociationForeignKey:PatientId,ScheduleDate" json:"his_patient"`
	HisPrescription       []*HisPrescription    `gorm:"ForeignKey:PatientId,RecordDate;AssociationForeignKey:PatientId,ScheduleDate" json:"prescription"`
	VMHisPrescriptionInfo VMHisPrescriptionInfo `gorm:"ForeignKey:PatientId,RecordDate;AssociationForeignKey:PatientId,ScheduleDate" json:"info"`
}

func (Schedule) TableName() string {
	return "xt_schedule"
}

type VMHisPrescriptionInfo 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"`
	HisPatientId       int64  `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_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"`
	Creator            int64  `gorm:"column:creator" json:"creator" form:"creator"`
	Modifier           int64  `gorm:"column:modifier" json:"modifier" form:"modifier"`
	Diagnosis          string `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
	RegisterType       int64  `gorm:"column:register_type" json:"register_type" form:"register_type"`
	Doctor             string `gorm:"column:doctor" json:"doctor" form:"doctor"`
	Departments        string `gorm:"column:departments" json:"departments" form:"departments"`
	SickHistory        string `gorm:"column:sick_history" json:"sick_history" form:"sick_history"`
	PrescriptionNumber string `gorm:"column:prescription_number" json:"prescription_number" form:"prescription_number"`
	BatchNumber        string `gorm:"column:batch_number" json:"batch_number" form:"batch_number"`
	PrescriptionStatus int64  `gorm:"column:prescription_status" json:"prescription_status" form:"prescription_status"`
	DoctorId           int64  `gorm:"column:doctor_id" json:"doctor_id" form:"doctor_id"`
	DepartmentId       int64  `gorm:"column:department_id" json:"department_id" form:"department_id"`
	SickType           int64  `gorm:"column:sick_type" json:"sick_type" form:"sick_type"`
}

func (VMHisPrescriptionInfo) TableName() string {
	return "his_prescription_info"
}

type Patients 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"`
	UserId                       int64   `gorm:"column:user_id" json:"user_id" form:"user_id"`
	Avatar                       string  `gorm:"column:avatar" json:"avatar" form:"avatar"`
	PatientType                  int64   `gorm:"column:patient_type" json:"patient_type" form:"patient_type"`
	DialysisNo                   string  `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
	AdmissionNumber              string  `gorm:"column:admission_number" json:"admission_number" form:"admission_number"`
	Source                       int64   `gorm:"column:source" json:"source" form:"source"`
	Lapseto                      int64   `gorm:"column:lapseto" json:"lapseto" form:"lapseto"`
	PartitionId                  int64   `gorm:"column:partition_id" json:"partition_id" form:"partition_id"`
	BedId                        int64   `gorm:"column:bed_id" json:"bed_id" form:"bed_id"`
	Name                         string  `gorm:"column:name" json:"name" form:"name"`
	Alias                        string  `gorm:"column:alias" json:"alias" form:"alias"`
	Gender                       int64   `gorm:"column:gender" json:"gender" form:"gender"`
	MaritalStatus                int64   `gorm:"column:marital_status" json:"marital_status" form:"marital_status"`
	IdCardNo                     string  `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
	Birthday                     int64   `gorm:"column:birthday" json:"birthday" form:"birthday"`
	ReimbursementWayId           int64   `gorm:"column:reimbursement_way_id" json:"reimbursement_way_id" form:"reimbursement_way_id"`
	HealthCareType               int64   `gorm:"column:health_care_type" json:"health_care_type" form:"health_care_type"`
	HealthCareNo                 string  `gorm:"column:health_care_no" json:"health_care_no" form:"health_care_no"`
	HealthCareDueDate            int64   `gorm:"column:health_care_due_date" json:"health_care_due_date" form:"health_care_due_date"`
	Height                       int64   `gorm:"column:height" json:"height" form:"height"`
	BloodType                    int64   `gorm:"column:blood_type" json:"blood_type" form:"blood_type"`
	Rh                           int64   `gorm:"column:rh" json:"rh" form:"rh"`
	HealthCareDueAlertDate       int64   `gorm:"column:health_care_due_alert_date" json:"health_care_due_alert_date" form:"health_care_due_alert_date"`
	EducationLevel               int64   `gorm:"column:education_level" json:"education_level" form:"education_level"`
	Profession                   int64   `gorm:"column:profession" json:"profession" form:"profession"`
	Phone                        string  `gorm:"column:phone" json:"phone" form:"phone"`
	HomeTelephone                string  `gorm:"column:home_telephone" json:"home_telephone" form:"home_telephone"`
	RelativePhone                string  `gorm:"column:relative_phone" json:"relative_phone" form:"relative_phone"`
	RelativeRelations            string  `gorm:"column:relative_relations" json:"relative_relations" form:"relative_relations"`
	HomeAddress                  string  `gorm:"column:home_address" json:"home_address" form:"home_address"`
	WorkUnit                     string  `gorm:"column:work_unit" json:"work_unit" form:"work_unit"`
	UnitAddress                  string  `gorm:"column:unit_address" json:"unit_address" form:"unit_address"`
	Children                     int64   `gorm:"column:children" json:"children" form:"children"`
	ReceivingDate                int64   `gorm:"column:receiving_date" json:"receiving_date" form:"receiving_date"`
	IsHospitalFirstDialysis      int64   `gorm:"column:is_hospital_first_dialysis" json:"is_hospital_first_dialysis" form:"is_hospital_first_dialysis"`
	FirstDialysisDate            int64   `gorm:"column:first_dialysis_date" json:"first_dialysis_date" form:"first_dialysis_date"`
	FirstDialysisHospital        string  `gorm:"column:first_dialysis_hospital" json:"first_dialysis_hospital" form:"first_dialysis_hospital"`
	PredialysisCondition         string  `gorm:"column:predialysis_condition" json:"predialysis_condition" form:"predialysis_condition"`
	PreHospitalDialysisFrequency string  `gorm:"column:pre_hospital_dialysis_frequency" json:"pre_hospital_dialysis_frequency" form:"pre_hospital_dialysis_frequency"`
	PreHospitalDialysisTimes     int64   `gorm:"column:pre_hospital_dialysis_times" json:"pre_hospital_dialysis_times" form:"pre_hospital_dialysis_times"`
	HospitalFirstDialysisDate    int64   `gorm:"column:hospital_first_dialysis_date" json:"hospital_first_dialysis_date" form:"hospital_first_dialysis_date"`
	InductionPeriod              int64   `gorm:"column:induction_period" json:"induction_period" form:"induction_period"`
	InitialDialysis              int64   `gorm:"column:initial_dialysis" json:"initial_dialysis" form:"initial_dialysis"`
	TotalDialysis                int64   `gorm:"column:total_dialysis" json:"total_dialysis" form:"total_dialysis"`
	AttendingDoctorId            int64   `gorm:"column:attending_doctor_id" json:"attending_doctor_id" form:"attending_doctor_id"`
	HeadNurseId                  int64   `gorm:"column:head_nurse_id" json:"head_nurse_id" form:"head_nurse_id"`
	Evaluate                     string  `gorm:"column:evaluate" json:"evaluate" form:"evaluate"`
	Diagnose                     string  `gorm:"column:diagnose" json:"diagnose" form:"diagnose"`
	Remark                       string  `gorm:"column:remark" json:"remark" form:"remark"`
	RegistrarsId                 int64   `gorm:"column:registrars_id" json:"registrars_id" form:"registrars_id"`
	Registrars                   string  `gorm:"column:registrars" json:"registrars" form:"registrars"`
	QrCode                       string  `gorm:"column:qr_code" json:"qr_code" form:"qr_code"`
	BindingState                 int64   `gorm:"column:binding_state" json:"binding_state" form:"binding_state"`
	PatientComplains             string  `gorm:"column:patient_complains" json:"patient_complains" form:"patient_complains"`
	PresentHistory               string  `gorm:"column:present_history" json:"present_history" form:"present_history"`
	PastHistory                  string  `gorm:"column:past_history" json:"past_history" form:"past_history"`
	Temperature                  float64 `gorm:"column:temperature" json:"temperature" form:"temperature"`
	Pulse                        int64   `gorm:"column:pulse" json:"pulse" form:"pulse"`
	Respiratory                  int64   `gorm:"column:respiratory" json:"respiratory" form:"respiratory"`
	Sbp                          int64   `gorm:"column:sbp" json:"sbp" form:"sbp"`
	Dbp                          int64   `gorm:"column:dbp" json:"dbp" form:"dbp"`
	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"`
	Nation                       string  `gorm:"column:nation" json:"nation" form:"nation"`
	NativePlace                  string  `gorm:"column:native_place" json:"native_place" form:"native_place"`
	Age                          int64   `gorm:"column:age" json:"age" form:"age"`
	InfectiousNextRecordTime     int64   `gorm:"column:infectious_next_record_time" json:"infectious_next_record_time" form:"infectious_next_record_time"`
	IsInfectious                 int64   `gorm:"column:is_infectious" json:"is_infectious" form:"is_infectious"`
	IsOpenRemind                 int64   `gorm:"column:is_open_remind" json:"is_open_remind" form:"is_open_remind"`
	RemindCycle                  int64   `gorm:"column:remind_cycle" json:"remind_cycle" form:"remind_cycle"`
	ResponseResult               string  `gorm:"column:response_result" json:"response_result" form:"response_result"`
	FirstTreatmentDate           int64   `gorm:"column:first_treatment_date" json:"first_treatment_date" form:"first_treatment_date"`
	DialysisAge                  int64   `gorm:"column:dialysis_age" json:"dialysis_age" form:"dialysis_age"`
	ExpenseKind                  int64   `gorm:"column:expense_kind" json:"expense_kind" form:"expense_kind"`
	TellPhone                    string  `gorm:"column:tell_phone" json:"tell_phone" form:"tell_phone"`
	ContactName                  string  `gorm:"column:contact_name" json:"contact_name" form:"contact_name"`
	UserSysBeforeCount           int64   `gorm:"column:user_sys_before_count" json:"user_sys_before_count" form:"user_sys_before_count"`
	IsExcelExport                int64   `gorm:"column:is_excel_export" json:"is_excel_export" form:"is_excel_export"`
	SchRemark                    string  `gorm:"column:sch_remark" json:"sch_remark" form:"sch_remark"`
	OutReason                    string  `gorm:"column:out_reason" json:"out_reason" form:"out_reason"`
}

func (Patients) TableName() string {
	return "xt_patients"
}

type HisPrescription 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"`
	HisPatientId int64 `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
	Status       int64 `gorm:"column:status" json:"status" form:"status"`
}

func (HisPrescription) TableName() string {
	return "his_prescription"
}

func GetHisPatientList(org_id int64, keywords string, record_date int64) (patients []*Schedule, err error) {
	db := readDb.Model(&Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date = ?", org_id, record_date)
	db = db.Preload("Patients", "user_org_id = ? AND status = 1", org_id)
	db = db.Preload("HisPatient", "user_org_id = ? AND status = 1", org_id)
	err = db.Preload("HisPrescription", "user_org_id = ? AND status = 1", org_id).Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1", org_id).Find(&patients).Error
	return
}

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

func GetHisPatientInfo(org_id int64, patient_id int64, record_date int64) (info models.HisPatient, err error) {
	err = readDb.Model(&models.HisPatient{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).First(&info).Error
	return
}

func GetNewHisPatientInfo(org_id int64, id int64, record_date int64) (info models.HisPatient, err error) {
	err = readDb.Model(&models.HisPatient{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND id = ?", org_id, record_date, id).First(&info).Error
	return
}

func GetXTPatientInfo(org_id int64, patient_id int64) (info models.Patients, err error) {
	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? AND status = 1  AND id = ?", org_id, patient_id).First(&info).Error
	return
}

func GetHisPatientCaseHistoryInfo(org_id int64, patient_id int64, record_date int64) (info models.HisPatientCaseHistory, err error) {
	err = readDb.Model(&models.HisPatientCaseHistory{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).First(&info).Error
	return
}

func GetHisPatientCaseHistoryList(org_id int64, patient_id int64) (caseHistorys []*models.HisPatientCaseHistory, err error) {
	db := readDb.Model(&models.HisPatientCaseHistory{}).Where("user_org_id = ? AND status = 1  AND his_patient_id = ?", org_id, patient_id)
	err = db.Find(&caseHistorys).Error
	return
}

func GetHisPatientCaseHistoryTemplate(org_id int64, startime int64, endtime int64, keyword string) (caseHistorys []*models.HisCaseHistoryTemplate, err error) {
	likekey := "%" + keyword + "%"
	db := readDb.Model(&models.HisCaseHistoryTemplate{}).Where("user_org_id = ? AND status = 1", org_id)
	if startime > 0 {
		db = db.Where("record_date>=?", startime)
	}
	if endtime > 0 {
		db = db.Where("record_date<=?", endtime)
	}
	if len(keyword) > 0 {
		db = db.Where("template_name like ? ", likekey)
	}
	err = db.Find(&caseHistorys).Error
	return
}

func GetHisPatientCaseHistory(org_id int64) (caseHistory []*models.HisPatientCaseHistory, err error) {

	err = readDb.Model(&models.HisPatientCaseHistory{}).Where("user_org_id = ? and status = 1", org_id).Find(&caseHistory).Error
	return caseHistory, err
}

func SaveHisPatientCaseHistoryTemplate(template models.HisCaseHistoryTemplate) (err error) {
	err = writeDb.Create(&template).Error
	return
}

func GetHisPatientCaseHistoryById(hispatientid int64) (*models.HisPatientCaseHistory, error) {
	history := models.HisPatientCaseHistory{}
	err := XTReadDB().Model(&history).Where("his_patient_id = ? and status = 1", hispatientid).Find(&history).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, err
		} else {
			return nil, err
		}
	}
	return &history, nil
}

func SaveHisPatientCaseHistory(caseHistory *models.HisPatientCaseHistory) error {
	err := writeDb.Create(&caseHistory).Error
	return err
}

func SaveHisPrescription(prescription *models.HisPrescription) (err error) {
	err = writeDb.Save(&prescription).Error
	return
}

func DelelteHisPrescription(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescription{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisDoctorAdviceInfo{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionProject{}).Where("user_org_id = ? AND prescription_id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func DelelteDoctorAdvice(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisDoctorAdviceInfo{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error

	return
}

func DelelteProject(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionProject{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error

	return
}

func GetHisPrescription(org_id int64, patient_id int64, record_date int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status <> 2 AND p_type <> 1", org_id, record_date, patient_id).
		Find(&prescription).Error
	return
}

func GetNewHisPrescription(org_id int64, his_patient_id int64, record_date int64, reg_type string) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1").Preload("GoodInfo", "status=1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND his_patient_id = ? AND order_status <> 2 AND p_type <> 1 AND med_type = ?", org_id, record_date, his_patient_id, reg_type).
		Find(&prescription).Error
	return
}

type OtherDrugWarehouseInfo struct {
	ID               int64 `gorm:"column:id" json:"id" form:"id"`
	DrugId           int64 `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
	WarehousingCount int64 `gorm:"column:warehousing_count" json:"warehousing_count" form:"warehousing_count"`
	Status           int64 `gorm:"column:status" json:"status" form:"status"`
	OrgId            int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
}

func (OtherDrugWarehouseInfo) TableName() string {
	return "xt_drug_warehouse_info"
}

type VMDrugSalesReturnInfo struct {
	ID     int64 `gorm:"column:id" json:"id" form:"id"`
	DrugId int64 `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
	Count  int64 `gorm:"column:count" json:"count" form:"count"`
	Status int64 `gorm:"column:status" json:"status" form:"status"`
	OrgId  int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
}

func (VMDrugSalesReturnInfo) TableName() string {
	return "xt_drug_sales_return_info"
}

type VMDrugWarehouseOutInfo struct {
	ID     int64 `gorm:"column:id" json:"id" form:"id"`
	DrugId int64 `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
	Count  int64 `gorm:"column:count" json:"count" form:"count"`
	Status int64 `gorm:"column:status" json:"status" form:"status"`
	OrgId  int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
}

func (VMDrugWarehouseOutInfo) TableName() string {
	return "xt_drug_warehouse_out_info"
}

type VMDrugCancelStockInfo struct {
	ID     int64 `gorm:"column:id" json:"id" form:"id"`
	DrugId int64 `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
	Count  int64 `gorm:"column:count" json:"count" form:"count"`
	Status int64 `gorm:"column:status" json:"status" form:"status"`
	OrgId  int64 `gorm:"column:org_id" json:"org_id" form:"org_id"`
}

func (VMDrugCancelStockInfo) TableName() string {
	return "xt_drug_cancel_stock_info"
}

type BaseDrugLib struct {
	ID                     int64   `gorm:"column:id" json:"id" form:"id"`
	DrugName               string  `gorm:"column:drug_name" json:"drug_name" form:"drug_name"`
	Pinyin                 string  `gorm:"column:pinyin" json:"pinyin" form:"pinyin"`
	Wubi                   string  `gorm:"column:wubi" json:"wubi" form:"wubi"`
	DrugAlias              string  `gorm:"column:drug_alias" json:"drug_alias" form:"drug_alias"`
	DrugAliasPinyin        string  `gorm:"column:drug_alias_pinyin" json:"drug_alias_pinyin" form:"drug_alias_pinyin"`
	DrugAliasWubi          string  `gorm:"column:drug_alias_wubi" json:"drug_alias_wubi" form:"drug_alias_wubi"`
	DrugCategory           int64   `gorm:"column:drug_category" json:"drug_category" form:"drug_category"`
	DrugSpec               string  `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
	DrugType               int64   `gorm:"column:drug_type" json:"drug_type" form:"drug_type"`
	DrugStockLimit         string  `gorm:"column:drug_stock_limit" json:"drug_stock_limit" form:"drug_stock_limit"`
	DrugOriginPlace        string  `gorm:"column:drug_origin_place" json:"drug_origin_place" form:"drug_origin_place"`
	DrugDosageForm         int64   `gorm:"column:drug_dosage_form" json:"drug_dosage_form" form:"drug_dosage_form"`
	MedicalInsuranceLevel  int64   `gorm:"column:medical_insurance_level" json:"medical_insurance_level" form:"medical_insurance_level"`
	MaxUnit                string  `gorm:"column:max_unit" json:"max_unit" form:"max_unit"`
	MinUnit                string  `gorm:"column:min_unit" json:"min_unit" form:"min_unit"`
	UnitMatrixing          string  `gorm:"column:unit_matrixing" json:"unit_matrixing" form:"unit_matrixing"`
	RetailPrice            float64 `gorm:"column:retail_price" json:"retail_price" form:"retail_price"`
	LastPrice              float64 `gorm:"column:last_price" json:"last_price" form:"last_price"`
	DrugControl            int64   `gorm:"column:drug_control" json:"drug_control" form:"drug_control"`
	Number                 string  `gorm:"column:number" json:"number" form:"number"`
	DrugClassify           string  `gorm:"column:drug_classify" json:"drug_classify" form:"drug_classify"`
	DrugDose               float64 `gorm:"column:drug_dose" json:"drug_dose" form:"drug_dose"`
	DrugDoseUnit           int64   `gorm:"column:drug_dose_unit" json:"drug_dose_unit" form:"drug_dose_unit"`
	MedicalInsuranceNumber string  `gorm:"column:medical_insurance_number" json:"medical_insurance_number" form:"medical_insurance_number"`
	ProvincesCode          string  `gorm:"column:provinces_code" json:"provinces_code" form:"provinces_code"`

	Manufacturer         int64   `gorm:"column:manufacturer" json:"manufacturer" form:"manufacturer"`
	PharmacologyCategory int64   `gorm:"column:pharmacology_category" json:"pharmacology_category" form:"pharmacology_category"`
	StatisticsCategory   int64   `gorm:"column:statistics_category" json:"statistics_category" form:"statistics_category"`
	Code                 string  `gorm:"column:code" json:"code" form:"code"`
	IsSpecialDiseases    int64   `gorm:"column:is_special_diseases" json:"is_special_diseases" form:"is_special_diseases"`
	IsRecord             int64   `gorm:"column:is_record" json:"is_record" form:"is_record"`
	Agent                string  `gorm:"column:agent" json:"agent" form:"agent"`
	DrugStatus           string  `gorm:"column:drug_status" json:"drug_status" form:"drug_status"`
	LimitRemark          string  `gorm:"column:limit_remark" json:"limit_remark" form:"limit_remark"`
	DeliveryWay          string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
	ExecutionFrequency   string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
	SingleDose           float64 `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
	PrescribingNumber    float64 `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
	Label                int64   `gorm:"column:label" json:"label" form:"label"`
	Sort                 int64   `gorm:"column:sort" json:"sort" form:"sort"`
	IsUseDoctorAdvice    int64   `gorm:"column:is_use_doctor_advice" json:"is_use_doctor_advice" form:"is_use_doctor_advice"`
	IsDefault            int64   `gorm:"column:is_default" json:"is_default" form:"is_default"`
	IsChargePredict      int64   `gorm:"column:is_charge_predict" json:"is_charge_predict" form:"is_charge_predict"`
	IsStatisticsWork     int64   `gorm:"column:is_statistics_work" json:"is_statistics_work" form:"is_statistics_work"`
	IsChargeUse          int64   `gorm:"column:is_charge_use" json:"is_charge_use" form:"is_charge_use"`
	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"`
	OrgId                int64   `gorm:"column:org_id" json:"org_id" form:"org_id"`
	DrugCode             string  `gorm:"column:drug_code" json:"drug_code" form:"drug_code"`
	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"`
	IsUser               int64   `gorm:"column:is_user" json:"is_user" form:"is_user"`

	//MedicineInsurancePercentage []*MedicineInsurancePercentage `gorm:"ForeignKey:PatientId;AssociationForeignKey:PatientId" json:"monitoring_record"`
	OtherDrugWarehouseInfo []*OtherDrugWarehouseInfo `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"stock_in"`
	VMDrugSalesReturnInfo  []*VMDrugSalesReturnInfo  `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"sales_return"`
	VMDrugWarehouseOutInfo []*VMDrugWarehouseOutInfo `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"stock_out"`
	VMDrugCancelStockInfo  []*VMDrugCancelStockInfo  `gorm:"ForeignKey:DrugId;AssociationForeignKey:ID" json:"cancel_stock"`
}

func (BaseDrugLib) TableName() string {
	return "xt_base_drug"
}

func GetAllDrugLibList(org_id int64) (list []*BaseDrugLib, err error) {
	err = readDb.Model(&BaseDrugLib{}).Preload("OtherDrugWarehouseInfo", "status = 1 AND org_id = ?", org_id).
		Preload("VMDrugSalesReturnInfo", "status = 1 AND org_id = ?", org_id).
		Preload("VMDrugWarehouseOutInfo", "status = 1 AND org_id = ?", org_id).
		Preload("VMDrugCancelStockInfo", "status = 1 AND org_id = ?", org_id).
		Where("org_id = ?  AND status = 1", org_id).Find(&list).Error
	return
}

func CreateAddtionalCharge(charge *models.HisAdditionalCharge) (err error) {
	err = writeDb.Create(&charge).Error
	return
}

func FindAllHisAdviceTemplate(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,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 ", org_id).Find(&temps).Error
	return
}

func GetHisAdminUserDoctors(org_id int64) (doctors []*models.UserAdminRole, err error) {
	err = readUserDb.Model(&models.UserAdminRole{}).Preload("XtHisDepartment", func(db *gorm.DB) *gorm.DB {
		return readDb.Model(&models.XtHisDepartment{}).Where("status = 1 AND user_org_id = ?", org_id)
	}).Where("org_id = ? AND status = 1 AND (user_type = 1 OR user_type = 2)", org_id).Find(&doctors).Error
	return
}

func CreateHisDoctorAdvice(s *models.HisDoctorAdviceInfo) (err error) {
	err = writeDb.Save(s).Error
	return
}

func CreateHisProjectTwo(project *models.HisPrescriptionProject) (err error) {
	err = writeDb.Save(project).Error
	return
}

func SaveHisProjectTwo(project *models.HisPrescriptionProject) (err error) {
	err = writeDb.Model(&models.HisPrescriptionProject{}).Where("user_org_id = ? AND id = ?", project.UserOrgId, project.ID).Updates(map[string]interface{}{"feedetl_sn": project.FeedetlSn, "mtime": time.Now().Unix()}).Error
	return
}

func CreateHisPatientTwo(patient *models.VMHisPatient) error {
	err := writeDb.Create(&patient).Error
	return err
}

func GetVMHisPatientInfo(org_id int64, patient_id int64, record_date int64) (info models.VMHisPatient, err error) {
	err = readDb.Model(&models.VMHisPatient{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).First(&info).Error
	return
}

func GetNewVMHisPatientInfo(org_id int64, his_patient_id int64, record_date int64) (info models.VMHisPatient, err error) {
	err = readDb.Model(&models.VMHisPatient{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND id = ?", org_id, record_date, his_patient_id).First(&info).Error
	return
}

func GetNewHisPatientRecord(org_id int64, id int64) (info models.VMHisPatient, err error) {
	err = readDb.Model(&models.VMHisPatient{}).Where("user_org_id = ? AND status = 1 AND patient_id = ?", org_id, id).First(&info).Error
	return
}

func GetHisPatientRecord(org_id int64, id int64) (info models.VMHisPatient, err error) {
	err = readDb.Model(&models.VMHisPatient{}).Where("user_org_id = ? AND status = 1 AND id = ?", org_id, id).First(&info).Error
	return
}

func CreateOrder(order *models.HisOrder) (err error) {
	err = writeDb.Create(&order).Error
	return
}

func CreateOrderInfo(order *models.HisOrderInfo) (err error) {
	err = writeDb.Create(&order).Error
	return
}
func FindPatientPrescriptionInfo(org_id int64, patient_id int64, record_date int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).First(&info).Error
	return
}
func FindHisPatientPrescriptionInfo(org_id int64, his_patient_id int64, record_date int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND his_patient_id = ?", org_id, record_date, his_patient_id).First(&info).Error
	return
}

func FindLastPatientPrescriptionInfo(org_id int64, patient_id int64, record_date int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date < ? AND patient_id = ?", org_id, record_date, patient_id).Order("record_date desc").First(&info).Error
	return
}

func SavePatientPrescriptionInfo(info models.HisPrescriptionInfo) (err error) {
	err = writeDb.Save(&info).Error
	return
}

func GetHisOrderList(user_org_id int64, page int64, limit int64, start_time int64, end_time int64, doctor_id int64, keywords string) (order []*models.HisOrder, err error, total int64) {
	offset := (page - 1) * limit
	db := readDb.Model(&models.HisOrder{})

	if doctor_id > 0 {
		db = db.Joins("join his_prescription_info as info on info.patient_id = his_order.patient_id AND info.record_date = his_order.settle_accounts_date AND info.doctor_id = ? AND info.user_org_id = ?", doctor_id, user_org_id)
	}

	if len(keywords) > 0 {
		keywords = "%" + keywords + "%"
		db = db.Joins("join xt_patients as patient on patient.id = his_order.patient_id  AND patient.name like ? AND patient.user_org_id = ?", keywords, user_org_id)

	}

	if start_time != 0 {
		db = db.Where("his_order.settle_accounts_date>=?", start_time)
	}
	if end_time != 0 {
		db = db.Where("his_order.settle_accounts_date<=?", end_time)
	}

	db = db.Where("his_order.status = 1 AND his_order.user_org_id = ?", user_org_id)

	db = db.Preload("HisOrderInfo", "status = 1 AND user_org_id = ?", user_org_id).
		Preload("Patients", "status = 1 AND user_org_id = ?", user_org_id).
		Preload("HisPatient", "status = 1 AND user_org_id = ?", user_org_id).
		Preload("HisPrescriptionInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", user_org_id).Preload("XtHisDepartment", "status = 1")
		})
	db = db.Count(&total)
	err = db.Limit(limit).Offset(offset).Order("ctime desc").Find(&order).Error
	return
}

func UpDatePrescriptionNumber(user_org_id int64, ids []int64, number string) (err error) {
	err = writeDb.Model(&models.HisPrescription{}).Where("user_org_id = ? AND status = 1 AND id in (?)", user_org_id, ids).Updates(map[string]interface{}{"batch_number": number, "mtime": time.Now().Unix()}).Error
	return
}

func UpDatePrescriptionOrderStatus(user_org_id int64, ids []int64) (err error) {
	err = writeDb.Model(&models.HisPrescription{}).Where("user_org_id = ? AND status = 1 AND id in (?)", user_org_id, ids).Updates(map[string]interface{}{"order_status": 4, "mtime": time.Now().Unix()}).Error
	return
}

func UpDatePrescriptionInfoNumber(user_org_id int64, id int64, number string, record_time int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND patient_id = ? AND record_date = ?", user_org_id, id, record_time).Updates(map[string]interface{}{"batch_number": number, "prescription_status": 2, "mtime": time.Now().Unix()}).Error
	return
}

func UpDateHisPrescriptionInfoNumber(user_org_id int64, his_patient_id int64, number string, record_time int64) (err error) {
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND his_patient_id = ? AND record_date = ?", user_org_id, his_patient_id, record_time).Updates(map[string]interface{}{"batch_number": number, "prescription_status": 2, "mtime": time.Now().Unix()}).Error
	return
}

type HisOrder 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"`
	HisPatientId            int64   `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
	SettleAccountsDate      int64   `gorm:"column:settle_accounts_date" json:"settle_accounts_date" form:"settle_accounts_date"`
	Ctime                   int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime                   int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
	Status                  int64   `gorm:"column:status" json:"status" form:"status"`
	Number                  string  `gorm:"column:number" json:"number" form:"number"`
	PatientId               int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	MedfeeSumamt            float64 `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
	OrderStatus             float64 `gorm:"column:order_status" json:"order_status" form:"order_status"`
	PayWay                  int64   `gorm:"column:pay_way" json:"pay_way" form:"pay_way"`
	PayPrice                float64 `gorm:"column:pay_price" json:"pay_price" form:"pay_price"`
	PayCardNo               string  `gorm:"column:pay_card_no" json:"pay_card_no" form:"pay_card_no"`
	DiscountPrice           float64 `gorm:"column:discount_price" json:"discount_price" form:"discount_price"`
	PreferentialPrice       float64 `gorm:"column:preferential_price" json:"preferential_price" form:"preferential_price"`
	RealityPrice            float64 `gorm:"column:reality_price" json:"reality_price" form:"reality_price"`
	FoundPrice              float64 `gorm:"column:found_price" json:"found_price" form:"found_price"`
	MedicalInsurancePrice   float64 `gorm:"column:medical_insurance_price" json:"medical_insurance_price" form:"medical_insurance_price"`
	PrivatePrice            float64 `gorm:"column:private_price" json:"private_price" form:"private_price"`
	Creator                 int64   `gorm:"column:creator" json:"creator" form:"creator"`
	Modify                  int64   `gorm:"column:modify" json:"modify" form:"modify"`
	IsPre                   int64   `gorm:"column:is_pre" json:"is_pre" form:"is_pre"`
	SzChargeInfo            string  `gorm:"column:sz_charge_info" json:"sz_charge_info" form:"sz_charge_info"`
	SzProjectInfo           string  `gorm:"column:sz_project_info" json:"sz_project_info" form:"sz_project_info"`
	SzMedicineInsuranceInfo string  `gorm:"column:sz_medicine_insurance_info" json:"sz_medicine_insurance_info" form:"sz_medicine_insurance_info"`
	MzNumber                string  `gorm:"column:mz_number" json:"mz_number" form:"mz_number"`
	OrgSetlNumber           string  `gorm:"column:org_setl_number" json:"org_setl_number" form:"org_setl_number"`

	HisOrderInfo        models.HisOrderInfo        `gorm:"ForeignKey:ID;AssociationForeignKey:OrderId" json:"order_info"`
	Patients            models.Patients            `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"patient"`
	HisPatient          models.HisPatient          `gorm:"ForeignKey:HisPatientId;AssociationForeignKey:ID" json:"his_patient"`
	HisPrescriptionInfo models.HisPrescriptionInfo `gorm:"ForeignKey:PatientId,SettleAccountsDate;AssociationForeignKey:PatientId,RecordDate" json:"p_info"`
	HisPrescription     []*models.HisPrescription  `gorm:"ForeignKey:SettleAccountsDate;AssociationForeignKey:RecordDate" json:"prescriptions"`
}

func (HisOrder) TableName() string {
	return "his_order"
}

func GetHisOrder(user_org_id int64, number string, patient_id int64) (order HisOrder, err error) {
	err = readDb.Model(&HisOrder{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND number=?", user_org_id, patient_id, number).
		Preload("HisOrderInfo", "status = 1 AND user_org_id = ?", user_org_id).
		Preload("Patients", "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 GetHisPrescriptionThree(org_id int64, patient_id int64, record_date int64, number string) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisDoctorAdviceInfo", "status = 1 AND user_org_id = ?", org_id).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1")
		}).
		Preload("HisAdditionalCharge", "status = 1 AND user_org_id = ?", org_id).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND batch_number=?", org_id, record_date, patient_id, number).
		Find(&prescription).Error
	return
}

type HisPrescriptionInfo 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"`
	HisPatientId          int64                        `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_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"`
	Creator               int64                        `gorm:"column:creator" json:"creator" form:"creator"`
	Modifier              int64                        `gorm:"column:modifier" json:"modifier" form:"modifier"`
	Diagnosis             string                       `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
	RegisterType          int64                        `gorm:"column:register_type" json:"register_type" form:"register_type"`
	Doctor                string                       `gorm:"column:doctor" json:"doctor" form:"doctor"`
	Departments           int64                        `gorm:"column:departments" json:"departments" form:"departments"`
	SickHistory           string                       `gorm:"column:sick_history" json:"sick_history" form:"sick_history"`
	Patients              models.Patients              `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"patient"`
	HisPatient            models.HisPatient            `gorm:"ForeignKey:HisPatientId,RecordDate;AssociationForeignKey:ID,RecordDate" json:"his_patient"`
	HisPatientCaseHistory models.HisPatientCaseHistory `gorm:"ForeignKey:PatientId,RecordDate;AssociationForeignKey:PatientId,RecordDate" json:"case_history"`
	PrescriptionNumber    string                       `gorm:"column:prescription_number" json:"prescription_number" form:"prescription_number"`
	BatchNumber           string                       `gorm:"column:batch_number" json:"batch_number" form:"batch_number"`
	PrescriptionStatus    int64                        `gorm:"column:prescription_status" json:"prescription_status" form:"prescription_status"`
	DoctorId              int64                        `gorm:"column:doctor_id" json:"doctor_id" form:"doctor_id"`
	DepartmentId          int64                        `gorm:"column:department_id" json:"department_id" form:"department_id"`
	SickType              int64                        `gorm:"column:sick_type" json:"sick_type" form:"sick_type"`
}

func (HisPrescriptionInfo) TableName() string {
	return "his_prescription_info"
}

func GetHisPrescriptionOrderList(org_id int64) (prescriptionOrder []*HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND user_org_id = ?", org_id).
		Preload("Patients", "status = 1 AND user_org_id = ?", org_id).
		Preload("HisPatient", "status = 1 AND user_org_id = ?", org_id).
		Preload("HisPatientCaseHistory", "status = 1 AND user_org_id = ?", org_id).
		Order("ctime desc").Find(&prescriptionOrder).Error
	return

}

func GetHisPrescriptionOrderInfo(id int64, org_id int64) (prescriptionOrder HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND id = ? AND user_org_id = ? ", id, org_id).
		Preload("Patients", "status = 1 AND user_org_id = ?", org_id).
		Preload("HisPatient", "status = 1 AND user_org_id = ?", org_id).
		Preload("HisPatientCaseHistory", "status = 1 AND user_org_id = ?", org_id).First(&prescriptionOrder).Error
	return

}

func GetHisPrescriptionFour(org_id int64, patient_id int64, record_date int64, number string) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisDoctorAdviceInfo", "status = 1 AND user_org_id = ?", org_id).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND prescription_number=?", org_id, record_date, patient_id, number).
		Find(&prescription).Error
	return
}

func GetMedicalInsuranceConfig(org_id int64) (medicalInsuranceConfig models.MedicalInsuranceConfig, err error) {
	err = readDb.Model(&models.MedicalInsuranceConfig{}).Where("status = 1 AND user_org_id = ?", org_id).Find(&medicalInsuranceConfig).Error
	return

}

func UpdataOrderStatus(id int64, number string, user_org_id int64, log string, result string) (err error) {
	err = writeDb.Model(&models.HisOrder{}).Where("status = 1 AND id = ? AND user_org_id = ?", id, user_org_id).Updates(map[string]interface{}{"order_status": 3, "mtime": time.Now().Unix(), "refund_request_log": log, "refund_log": result, "status": 0}).Error
	err = writeDb.Model(&models.HisPrescription{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"order_status": 1, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"prescription_status": 1, "mtime": time.Now().Unix()}).Error
	return

}

func UpdataOrderStatusThree(id int64, number string, user_org_id int64, log string, result string) (err error) {
	err = writeDb.Model(&models.HisOrder{}).Where("status = 1 AND id = ? AND user_org_id = ?", id, user_org_id).Updates(map[string]interface{}{"order_status": 3, "mtime": time.Now().Unix(), "refund_request_log": log, "refund_log": result, "status": 0}).Error
	err = writeDb.Model(&models.HisPrescription{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"order_status": 4, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"prescription_status": 1, "mtime": time.Now().Unix()}).Error
	return

}

func UpdataRegStatus(patient_id int64, record_time int64, org_id int64) {
	writeDb.Model(&models.HisPatient{}).Where("patient_id = ? AND status = 1 AND record_date =? AND user_org_id = ?", patient_id, record_time, org_id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()})
	//writeDb.Model(&models.HisPrescription{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"order_status": 1, "mtime": time.Now().Unix()}).Error
	//writeDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"prescription_status": 1, "mtime": time.Now().Unix()}).Error
}

func UpdataRegStatusTwo(his_patient_id int64, record_time int64, org_id int64) {
	writeDb.Model(&models.HisPatient{}).Where("status = 1 AND record_date =? AND user_org_id = ? AND id = ?", record_time, org_id, his_patient_id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()})
	writeDb.Model(&models.HisPrescription{}).Where("status = 1 AND user_org_id = ? AND his_patient_id = ?", org_id, his_patient_id).Updates(map[string]interface{}{"his_patient_id": 0, "mtime": time.Now().Unix()})
	writeDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1  AND user_org_id = ? AND his_patient_id = ?", org_id, his_patient_id).Updates(map[string]interface{}{"his_patient_id": 0, "mtime": time.Now().Unix()})

}

func UpdataRegStatus2(id int64) error {
	err := writeDb.Model(&models.HisPatient{}).Where("id = ?", id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return err
}
func GetAdminUserInfoByID(org_id int64, admin_user_id int64) (role models.UserAdminRole, err error) {
	err = readUserDb.Model(&models.UserAdminRole{}).Where("org_id = ? AND status = 1 AND admin_user_id = ?", org_id, admin_user_id).First(&role).Error
	return
}

func GetAdminUserInfo(org_id int64) (role models.UserAdminRole, err error) {
	err = readUserDb.Model(&models.UserAdminRole{}).Where("org_id = ? AND status = 1", org_id).First(&role).Error
	return
}

func GetHisOrderTwo(user_org_id int64, number string, patient_id int64) (order models.HisOrder, err error) {
	err = readDb.Model(&HisOrder{}).Where("user_org_id = ? AND patient_id = ? AND number=?", user_org_id, patient_id, number).
		First(&order).Error
	return
}

func UpDateOrder(order models.HisOrder) (err error) {
	err = writeDb.Save(&order).Error
	return
}

func UpDateOrderTwo(order *models.HisOrder) (err error) {
	err = writeDb.Save(&order).Error
	return
}

func UpdataOrderStatusTwo(number string, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisPrescription{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"order_status": 2, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"prescription_status": 3, "mtime": time.Now().Unix()}).Error
	return
}

func CreateErrMsgLog(log *models.HisOrderError) {
	writeDb.Model(&models.HisOrderError{}).Create(&log)

}

func FindHisRegisterRecord(record_time int64, patient_id int64, org_id int64) (total int64, err error) {

	err = readDb.Model(&models.VMHisPatient{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND record_date = ?", org_id, patient_id, record_time).Count(&total).Error

	return
}

func FindMedicalInsuranceInfo(org_id int64) (config models.MedicalInsuranceOrgConfig, err error) {
	err = readDb.Model(&models.MedicalInsuranceOrgConfig{}).Where("status = 1 AND user_org_id = ?", org_id).First(&config).Error
	return
}

func FindAllSick(orgId int64) (list []*models.OutpatientServiceSick, err error) {
	db := readDb.Model(&models.OutpatientServiceSick{})
	db = db.Where("user_org_id = ? AND status = 1", orgId)
	err = db.Order("ctime desc").Find(&list).Error
	return

}

func FindAllDiagnose(orgId int64) (list []*models.HisXtDiagnoseConfig, err error) {
	db := readDb.Model(&models.HisXtDiagnoseConfig{})
	db = db.Where("user_org_id = ? AND status = 1", orgId)
	err = db.Order("ctime desc").Find(&list).Error
	return
}

func FindAllAddition(orgId int64) (list []*models.XtHisAddtionConfig, err error) {
	db := readDb.Model(&models.XtHisAddtionConfig{})
	db = db.Where("user_org_id = ? AND status = 1", orgId)
	err = db.Order("ctime desc").Find(&list).Error
	return

}

type XtHisOrder 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"`
	HisPatientId       int64  `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
	SettleAccountsDate int64  `gorm:"column:settle_accounts_date" json:"settle_accounts_date" form:"settle_accounts_date"`
	Ctime              int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime              int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
	Status             int64  `gorm:"column:status" json:"status" form:"status"`
	Number             string `gorm:"column:number" json:"number" form:"number"`
	PatientId          int64  `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	Creator            int64  `gorm:"column:creator" json:"creator" form:"creator"`
	Modify             int64  `gorm:"column:modify" json:"modify" form:"modify"`

	FaPiaoCode   string `gorm:"column:fa_piao_code" json:"fa_piao_code" form:"fa_piao_code"`
	FaPiaoNumber string `gorm:"column:fa_piao_number" json:"fa_piao_number" form:"fa_piao_number"`

	HisOrderInfo        models.HisOrderInfo        `gorm:"ForeignKey:ID;AssociationForeignKey:OrderId" json:"order_info"`
	Patients            models.Patients            `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"patient"`
	HisPatient          models.HisPatient          `gorm:"ForeignKey:HisPatientId;AssociationForeignKey:ID" json:"his_patient"`
	HisPrescriptionInfo models.HisPrescriptionInfo `gorm:"ForeignKey:PatientId,SettleAccountsDate;AssociationForeignKey:PatientId,RecordDate" json:"p_info"`
	HisPrescription     []*models.HisPrescription  `gorm:"ForeignKey:SettleAccountsDate;AssociationForeignKey:RecordDate" json:"prescriptions"`
}

func (XtHisOrder) TableName() string {
	return "his_order"
}

func GetHisPrescriptionNight(org_id int64, patient_id int64, record_date int64, prescription_id int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisDoctorAdviceInfo", "status = 1 AND user_org_id = ? and prescription_id =?", org_id, prescription_id).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1")
		}).
		Preload("HisAdditionalCharge", "status = 1 AND user_org_id = ?", org_id).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).
		Find(&prescription).Error
	return
}

func GetAllAdditionCharge(org_id int64, patient_id int64, record_time int64) (addition []*models.HisAdditionalCharge, err error) {
	err = readDb.Model(&models.HisAdditionalCharge{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND record_date = ?", org_id, patient_id, record_time).Find(&addition).Error
	return

}

func DelelteAddition(id int64, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisAdditionalCharge{}).Where("user_org_id = ? AND id = ?", user_org_id, id).Updates(map[string]interface{}{"status": 0, "mtime": time.Now().Unix()}).Error
	return
}

func GetHisPatientPrescriptionList(org_id int64, keywords string, record_date int64, page int64, limit int64) (patients []*Schedule, err error, total int64) {
	offset := (page - 1) * limit
	db := readDb.Model(&Schedule{}).Where("user_org_id = ? AND status = 1 AND schedule_date = ?", org_id, record_date)
	if len(keywords) > 0 {
		keywords = "%" + keywords + "%"
		db = db.Joins("JOIN xt_patients as p On xt_schedule.patient_id = p.id AND p.user_org_id = ? AND p.name like ?", org_id, keywords)
		db = db.Joins("JOIN his_prescription_info as info On xt_schedule.patient_id = info.patient_id  AND info.user_org_id = ? AND  info.record_date = ? AND info.prescription_number like ?", org_id, record_date, keywords)
	}
	db = db.Preload("Patients", "user_org_id = ? AND status = 1", org_id)
	db = db.Preload("HisPatient", "user_org_id = ? AND status = 1", org_id)
	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1", org_id).
		Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1", org_id)
	db = db.Count(&total)
	err = db.Limit(limit).Offset(offset).Find(&patients).Error
	return
}

func UpdateHisPatientIsReturn(patientid int64, recorddate int64, orgid int64) (models.VMHisPatient, error) {

	patient := models.VMHisPatient{}
	err := XTWriteDB().Model(&patient).Where("patient_id = ? and record_date = ? and user_org_id = ? and status = 1", patientid, recorddate, orgid).Updates(map[string]interface{}{"is_return": 3}).Error
	return patient, err
}

type VMOtherHisPrescriptionInfo 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"`
	CheckGroup        []int64              `gorm:"-" json:"check_group" form:"check_group"`
	VMHisPrescription []*VMHisPrescription `gorm:"ForeignKey:RecordDate,PatientId;AssociationForeignKey:RecordDate,PatientId" json:"prescriptions"`
}

func (VMOtherHisPrescriptionInfo) TableName() string {
	return "his_prescription_info"
}

type VMHisPrescription 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"`
	OrderStatus            int64                            `gorm:"column:order_status" json:"order_status" form:"order_status"`
	BatchNumber            string                           `gorm:"column:batch_number" json:"batch_number" form:"batch_number"`
	PrescriptionNumber     string                           `gorm:"column:prescription_number" json:"prescription_number" form:"prescription_number"`
	Type                   int64                            `gorm:"column:type" json:"type" form:"type"`
	HisDoctorAdviceInfo    []*models.HisDoctorAdviceInfo    `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"doctor_advice"`
	HisPrescriptionProject []*models.HisPrescriptionProject `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"project"`
}

func (VMHisPrescription) TableName() string {
	return "his_prescription"
}

func GetCallHisPrescriptions(start_time int64, end_time int64, org_id int64, patient_id int64) (advice []*VMOtherHisPrescriptionInfo, err error) {
	err = readDb.Model(&VMOtherHisPrescriptionInfo{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND record_date >= ? AND record_date <= ?", patient_id, org_id, start_time, end_time).
		Preload("VMHisPrescription", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).
				Preload("HisDoctorAdviceInfo", "status = 1 AND user_org_id = ?", org_id).
				Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
					return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1")
				})
		}).Find(&advice).Error

	return
}

func GetHisOrderByID(order_id int64) (order models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("id = ? AND status = 1", order_id).First(&order).Error
	return
}

func GetHisOrderByIDTwo(order_id int64) (order models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Preload("HisOrderInfo", "status = 1").Preload("HisPatient", "status = 1").Where("id = ? AND status = 1", order_id).First(&order).Error
	return
}

func GetHisOrderInfoByNumber(order_number string) (order []*models.HisOrderInfo, err error) {
	db := readDb.Model(&models.HisOrderInfo{}).Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
		return db.Preload("BaseDrugLib", "status = 1").Where("status = 1")
	})
	err = db.Where("order_number = ? AND status = 1 AND advice_id > 0", order_number).Find(&order).Error
	return
}

func GetHisOrderInfoByNumberTwo(order_number string) (order []*models.HisOrderInfo, err error) {
	db := readDb.Model(&models.HisOrderInfo{})
	//db = db.Joins("Join his_prescription_project as p  On p.id = his_order_info.project_id")
	db = db.Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
		return db.Preload("XtHisProjectTeam", "status = 1").Preload("HisProject", "status = 1").Preload("GoodInfo", "status = 1").Where("status = 1")
	})
	err = db.Where("order_number = ? AND status = 1 AND project_id > 0", order_number).Find(&order).Error
	return
}

func GetHisOrderInfoByNumberThree(order_number string) (order []*models.HisOrderInfo, err error) {
	db := readDb.Model(&models.HisOrderInfo{})
	//db = db.Joins("Join his_prescription_project as p  On p.id = his_order_info.project_id AND p.team_id > 0")

	db = db.Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
		return db.Preload("XtHisProjectTeam", "status = 1").Preload("HisProject", "status = 1").Preload("GoodInfo", "status = 1").Where("status = 1")
	})
	err = db.Where("order_number = ? AND status = 1 AND project_id > 0", order_number).Find(&order).Error
	return
}

func GetOrderByTime(start_time int64, end_time int64, org_id int64, insutype string, clr_org string, clr_type string) (orders []*models.HisOrder, err error) {
	db := readDb.Model(&models.HisOrder{})
	db = db.Where("user_org_id = ? AND status = 1 AND order_status = 2 AND is_medicine_insurance = 1 AND UNIX_TIMESTAMP(setl_time)  <= ? AND UNIX_TIMESTAMP(setl_time) >= ? AND insutype = ?", org_id, end_time, start_time, insutype)
	if len(clr_org) > 0 {
		db = db.Where("clr_optins = ?", clr_org)
	}
	if len(clr_type) > 0 {
		db = db.Where("clr_type = ?", clr_type)
	}
	err = db.Find(&orders).Error
	return
}

func GetOrderByTimeThree(start_time int64, end_time int64, org_id int64, insutype string, clr_type string) (orders []*models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = ? AND status = 1  AND is_medicine_insurance = 1 AND UNIX_TIMESTAMP(setl_time) <= ? AND UNIX_TIMESTAMP(setl_time) >= ? AND insutype = ?", org_id, end_time, start_time, insutype).Find(&orders).Error
	return
}

func GetOrderByTimeTwo(start_time int64, end_time int64, org_id int64) (orders []*models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = ? AND status = 1 AND is_medicine_insurance = 1 AND UNIX_TIMESTAMP(setl_time)  <= ? AND UNIX_TIMESTAMP(setl_time) >= ?", org_id, end_time, start_time).Find(&orders).Error
	return
}

func GetPatientByID(orgID int64, patientID int64) (*models.Patients, error) {
	var patient models.Patients
	err := readDb.Model(&models.Patients{}).Where("id = ? and user_org_id=? and status=1", patientID, orgID).First(&patient).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return nil, nil
		} else {
			return nil, err
		}
	}
	return &patient, nil
}

func FindDiagnoseById(id int64) (models.HisXtDiagnoseConfig, error) {
	dealer := models.HisXtDiagnoseConfig{}
	err := readDb.Model(&models.HisXtDiagnoseConfig{}).Where("id = ? AND status = 1", id).First(&dealer).Error
	return dealer, err
}

func FindDiagnoseByIds(ids []string) ([]*models.HisXtDiagnoseConfig, error) {
	dealer := []*models.HisXtDiagnoseConfig{}
	err := readDb.Model(&models.HisXtDiagnoseConfig{}).Where("id IN (?) AND status = 1", ids).Find(&dealer).Error
	return dealer, err
}

func FindSickById(id int64) (*models.OutpatientServiceSick, error) {
	outPatient := &models.OutpatientServiceSick{}
	err := readDb.Model(&models.OutpatientServiceSick{}).Where("id = ? AND status = 1", id).First(&outPatient).Error
	return outPatient, err
}

//
//type MonthHisPrescription 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"`
//	HisPatientId           int64                            `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_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"`
//	Number                 string                           `gorm:"column:number" json:"number" form:"number"`
//	Type                   int64                            `gorm:"column:type" json:"type" form:"type"`
//	Doctor                 string                           `gorm:"column:doctor" json:"doctor" form:"doctor"`
//	Creator                int64                            `gorm:"column:creator" json:"creator" form:"creator"`
//	Modifier               int64                            `gorm:"column:modifier" json:"modifier" form:"modifier"`
//	OrderStatus            int64                            `gorm:"column:order_status" json:"order_status" form:"order_status"`
//	BatchNumber            string                           `gorm:"column:batch_number" json:"batch_number" form:"batch_number"`
//	PrescriptionNumber     string                           `gorm:"column:prescription_number" json:"prescription_number" form:"prescription_number"`
//	Patients               Patients                         `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"patient"`
//	HisPatient             models.VMHisPatient              `gorm:"ForeignKey:PatientId;AssociationForeignKey:patient_id" json:"hisPatient"`
//	HisDoctorAdviceInfo    []*models.HisDoctorAdviceInfo    `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"advices"`
//	HisPrescriptionProject []*models.HisPrescriptionProject `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"project"`
//	HisAdditionalCharge    []*models.HisAdditionalCharge    `gorm:"ForeignKey:PrescriptionId;AssociationForeignKey:ID" json:"addition"`
//	VMHisPrescriptionInfo  models.HisPrescriptionInfo              `gorm:"ForeignKey:PatientId,RecordDate;AssociationForeignKey:PatientId,ScheduleDate" json:"info"`
//}
//
//func (MonthHisPrescription) TableName() string {
//	return "his_prescription"
//}

func GetMonthHisPrescription(org_id int64, patient_id int64, start_time int64, end_time int64, reg_type string) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1").Preload("GoodInfo", "status=1")
		}).
		Where("user_org_id = ? AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status <> 2 AND status = 1  AND p_type <> 1 AND med_type = ?", org_id, start_time, end_time, patient_id, reg_type).
		Find(&prescription).Error
	return
}

func GetPatientByNumber(number string, user_org_id int64) (patient Patients, err error) {
	err = readDb.Model(&Patients{}).Where("(health_care_no = ? OR id_card_no = ?)  AND user_org_id = ?", number, number, user_org_id).First(&patient).Error
	return
}

func GetPatientByIDCard(id_card_no string, user_org_id int64) (patient Patients, err error) {
	err = readDb.Model(&Patients{}).Where("id_card_no = ? AND user_org_id = ?", id_card_no, user_org_id).First(&patient).Error
	return
}

func GetHisOrderThree(record_time int64, patient_id int64, user_org_id int64) (order models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("patient_id = ? AND user_org_id = ? AND settle_accounts_date = ? AND status = 1", patient_id, user_org_id, record_time).First(&order).Error
	return
}

func GetAppRole(orgID int64) (models.App_Role, error) {
	var appRole models.App_Role
	err := readUserDb.Model(models.App_Role{}).Where("org_id = ? AND user_type = 2", orgID).First(&appRole).Error
	return appRole, err
}

func GetPatientByIDTwo(orgID int64, patientID int64) (Patients, error) {
	var patient Patients
	err := readDb.Model(&Patients{}).Where("id = ? and user_org_id=? and status=1", patientID, orgID).First(&patient).Error
	return patient, err
}

func GetDrugList(orgID int64) (drug []*models.BaseDrugList, err error) {

	db := XTReadDB().Table("xt_base_drug as x").Where("x.status = 1")
	table := XTReadDB().Table("xt_manufacturer as m")
	fmt.Print(table)
	if orgID > 0 {
		db = db.Where("x.org_id = ? and x.id = 397", orgID)
	}
	err = db.Select("x.id,x.medical_insurance_number,x.code,x.drug_name,x.drug_spec,x.drug_type,x.min_unit,x.last_price,x.retail_price,x.limit_remark,x.drug_dosage_form,m.manufacturer_name").Joins("left join xt_manufacturer as m on m.id = x.manufacturer").Scan(&drug).Error

	return drug, err
}

func GetDrugDosageForm(orgid int64) (dataconfig []*models.XtDrugDataConfig, err error) {

	err = XTReadDB().Where("(org_id = ? or org_id = 0) and parent_id = 4 and status = 1", orgid).Find(&dataconfig).Error
	return dataconfig, err
}

func GetDoctorList(orgid int64) (role []*models.SgjUserAdminRole, err error) {

	//err = UserReadDB().Model(&role).Where("org_id = ? and status = 1 and user_type = 2", orgid).Find(&role).Error
	//return role, err

	db := UserReadDB().Table("sgj_user_admin_role as x").Where("x.status =1")
	table := UserReadDB().Table("sgj_user_admin as a")
	fmt.Println(table)
	err = db.Select("x.id,x.admin_user_id,x.org_id,x.app_id,x.role_id,x.user_name,x.avatar,x.user_type,x.user_title,x.intro,x.user_title_name,x.role_ids,x.message,x.sex,x.birthday,x.sort,x.is_sort,x.department,x.department_id,x.age,x.nation,x.card_type,x.id_card,x.education,x.study_major_name,x.work_major_name,x.role_type,x.medical_code,x.doctor_code,x.licensing,x.job_number,x.prescription_qualification_identification,x.identification_outpatients,x.start_time,x.medical_range_code,x.medical_level,x.medical_type_job,x.pharmacist_registration_number,x.doctor_range_code,x.doctor_level,x.doctor_type_job,x.doctor_number,x.outpatient_illness_category,x.is_active,x.active_status,a.mobile").Joins("left join sgj_user_admin as a on a.id = x.admin_user_id").Scan(&role).Error
	return role, err
}

func GetPrescriptionByIds(ids []string, org_id int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject").Preload("GoodInfo", "status=1")
		}).
		Where("id in (?) AND user_org_id = ? AND status = 1", ids, org_id).
		Find(&prescription).Error

	return
}

func GetDoctorListTwo(orgid int64) (role []*models.SgjUserAdminRole, err error) {

	db := UserReadDB().Table("sgj_user_admin_role as x").Where("x.status =1 AND x.user_type = 2 AND x.org_id = ?", orgid)
	//table := UserReadDB().Table("sgj_user_admin as a")
	//fmt.Println(table)
	err = db.Select("x.id,x.admin_user_id,x.org_id,x.app_id,x.role_id,x.user_name,x.avatar,x.user_type,x.user_title,x.intro,x.user_title_name,x.role_ids,x.message,x.sex,x.birthday,x.sort,x.is_sort,x.department,x.department_id,x.age,x.nation,x.card_type,x.id_card,x.education,x.study_major_name,x.work_major_name,x.role_type,x.medical_code,x.doctor_code,x.licensing,x.job_number,x.prescription_qualification_identification,x.identification_outpatients,x.start_time,x.medical_range_code,x.medical_level,x.medical_type_job,x.pharmacist_registration_number,x.doctor_range_code,x.doctor_level,x.doctor_type_job,x.doctor_number,x.outpatient_illness_category,x.is_active,x.active_status,a.mobile").Joins("left join sgj_user_admin as a on a.id = x.admin_user_id").Scan(&role).Error
	return role, err
}

func GetRoleList(orgid int64) (role []*models.SgjUserRole, err error) {

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

func GetDrugListByDetail(orgID int64, id int64) (drug []*models.BaseDrugList, err error) {

	db := XTReadDB().Table("xt_base_drug as x").Where("x.status = 1")
	table := XTReadDB().Table("xt_manufacturer as m")
	fmt.Print(table)
	if orgID > 0 {
		db = db.Where("x.org_id = ? and x.id = ?", orgID, id)
	}
	err = db.Select("x.id,x.medical_insurance_number,x.code,x.drug_name,x.drug_spec,x.drug_type,x.min_unit,x.last_price,x.retail_price,x.limit_remark,x.drug_dosage_form,m.manufacturer_name").Joins("left join xt_manufacturer as m on m.id = x.manufacturer").Scan(&drug).Error

	return drug, err
}

func GetGoodInformationList(orgid int64) (good []*models.GoodInformation, err error) {

	db := XTReadDB().Table("xt_good_information as x").Where("x.status=1")
	table := XTReadDB().Table("xt_manufacturer as m")
	fmt.Println(table)
	if orgid > 0 {
		db = db.Where("x.org_id = ?", orgid)
	}
	err = db.Select("x.id,x.social_security_directory_code,x.good_name,x.specification_name,x.production_type,x.special_medical,x.good_unit,x.buy_price,x.sell_price,x.remark,m.manufacturer_name").Joins("left join xt_manufacturer as m on m.id = x.manufacturer").Scan(&good).Error
	return good, err
}

func GetGoodListByDetail(orgid int64, id int64) (good []*models.GoodInformation, err error) {
	db := XTReadDB().Table("xt_good_information as x").Where("x.status=1")
	table := XTReadDB().Table("xt_manufacturer as m")
	fmt.Println(table)
	if orgid > 0 {
		db = db.Where("x.org_id = ? and x.id= ?", orgid, id)
	}
	err = db.Select("x.id,x.social_security_directory_code,x.good_name,x.specification_name,x.production_type,x.special_medical,x.good_unit,x.buy_price,x.sell_price,x.remark,m.manufacturer_name").Joins("left join xt_manufacturer as m on m.id = x.manufacturer").Scan(&good).Error
	return good, err
}

func GetDoctorListByDetail(orgid int64, id int64) (role []*models.SgjUserAdminRole, err error) {

	db := UserReadDB().Table("sgj_user_admin_role as x").Where("x.status =1")
	table := UserReadDB().Table("sgj_user_admin as a")
	fmt.Println(table)
	if id > 0 {
		db = db.Where("x.status = 1 and x.admin_user_id = ? and x.org_id = ?", id, orgid)
	}
	err = db.Select("x.age,x.id,x.admin_user_id,x.org_id,x.app_id,x.role_id,x.user_name,x.avatar,x.user_type,x.user_title,x.intro,x.user_title_name,x.role_ids,x.message,x.sex,x.birthday,x.sort,x.is_sort,x.department,x.department_id,x.nation,x.card_type,x.id_card,x.education,x.study_major_name,x.work_major_name,x.role_type,x.medical_code,x.doctor_code,x.licensing,x.job_number,x.prescription_qualification_identification,x.identification_outpatients,x.start_time,x.medical_range_code,x.medical_level,x.medical_type_job,x.pharmacist_registration_number,x.doctor_range_code,x.doctor_level,x.doctor_type_job,x.doctor_number,x.outpatient_illness_category,x.is_active,x.active_status,a.mobile").Joins("left join sgj_user_admin as a on a.id = x.admin_user_id").Scan(&role).Error
	return role, err
}

func GetMyPorjecgList(orgid int64) (project []*models.MyHisProject, err error) {

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

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

func GetBathchMyPorjecgList(idss []int64) (project []*models.MyHisProject, err error) {
	db := XTReadDB().Table("xt_his_project")
	if len(idss) == 1 {
		err = db.Where("status = 1 and id = ?", idss[0]).Find(&project).Error
	} else {
		err = db.Where("status = 1 and id IN(?)", idss).Find(&project).Error
	}

	return project, err
}

func GetBatchDoctorList(idss []int64) (role []*models.SgjUserAdminRole, err error) {

	db := UserReadDB().Table("sgj_user_admin_role as x").Where("x.status =1")
	table := UserReadDB().Table("sgj_user_admin as a")
	fmt.Println(table)
	if len(idss) == 1 {
		db = db.Where("x.status = 1 and x.admin_user_id = ?", idss[0])
	} else {
		db = db.Where("x.status = 1 and x.admin_user_id IN(?)", idss)
	}
	err = db.Select("x.age,x.id,x.admin_user_id,x.org_id,x.app_id,x.role_id,x.user_name,x.avatar,x.user_type,x.user_title,x.intro,x.user_title_name,x.role_ids,x.message,x.sex,x.birthday,x.sort,x.is_sort,x.department,x.department_id,x.nation,x.card_type,x.id_card,x.education,x.study_major_name,x.work_major_name,x.role_type,x.medical_code,x.doctor_code,x.licensing,x.job_number,x.prescription_qualification_identification,x.identification_outpatients,x.start_time,x.medical_range_code,x.medical_level,x.medical_type_job,x.pharmacist_registration_number,x.doctor_range_code,x.doctor_level,x.doctor_type_job,x.doctor_number,x.outpatient_illness_category,x.is_active,x.active_status,a.mobile").Joins("left join sgj_user_admin as a on a.id = x.admin_user_id").Scan(&role).Error
	return role, err

}

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

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 GetHisPatientInfoList(org_id int64, patient_id int64, record_date int64) (info []*models.HisPatient, err error) {
	err = readDb.Model(&models.HisPatient{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).Find(&info).Error
	return
}

func GetHisPatientByNumber(number string) (his models.HisPatient, err error) {
	err = readDb.Model(&models.HisPatient{}).Where("number = ? AND status = 1", number).First(&his).Error
	return
}

func CreateUploadRecord(result *models.HisFundSettleListResult) (err error) {
	err = writeDb.Create(&result).Error
	return
}

func GetDeviceNumberByID(bed_id int64, org_id int64) (device_number models.DeviceNumber, err error) {
	err = readDb.Model(&models.DeviceNumber{}).Where("id = ? AND org_id = ?", bed_id, org_id).First(&device_number).Error
	return
}

func UpdateHisPatientStatus(his *models.VMHisPatient) {
	writeDb.Save(&his)
}

func GetLastHisOrder(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 GetLastHisOrderTwo(org_id int64) (his models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Select("max(convert(fa_piao_number,signed)) as fa_piao_number").Where("user_org_id = ? AND status = 1 AND order_status = 2 ", org_id).Find(&his).Error
	return
}

func GetHisPatientInfoTwo(org_id int64, patient_id int64, record_date int64) (info []*models.HisPatient, err error) {
	err = readDb.Model(&models.HisPatient{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).Find(&info).Error
	return
}

func GetNewHisOrderTwo(user_org_id int64, mdtrt_id string, patient_id int64, record_time int64) (order HisOrder, err error) {
	err = readDb.Model(&HisOrder{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND mdtrt_id=? AND settle_accounts_date = ? ", user_org_id, patient_id, mdtrt_id, record_time).
		Order("ctime desc").
		Find(&order).Error
	return
}

func GetNewHisOrderThree(mdtrt_id string) (order HisOrder, err error) {
	err = readDb.Model(&HisOrder{}).Where("status = 1 AND mdtrt_id=?  ", mdtrt_id).First(&order).Error
	return
}

func UpdateHisPatientThree(his *models.HisPatient) {
	writeDb.Save(&his)
}

func GetNewHisPrescriptionTwo(org_id int64, his_patient_id int64, record_date int64, med_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 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1").Preload("GoodInfo", "status=1")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND his_patient_id = ? AND order_status <> 2 AND p_type <> 1 AND med_type = ?", org_id, record_date, his_patient_id, med_type).
		Find(&prescription).Error
	return
}

func GetMonthHisPrescriptionTwo(org_id int64, patient_id int64, start_time int64, end_time int64, med_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 AND user_org_id = ?", org_id).Preload("XtHisAddtionConfig", "status=1")
		}).
		Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("BaseDrugLib", "status=1")
		}).
		Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("HisProject", "status=1").Preload("GoodInfo", "status=1")
		}).
		Where("user_org_id = ? AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status <> 2 AND status = 1  AND p_type <> 1 AND med_type = ?", org_id, start_time, end_time, patient_id, med_type).
		Find(&prescription).Error
	return
}

func GetNewHisPatientInfoFour(org_id int64, id int64) (info models.HisPatient, err error) {
	err = readDb.Model(&models.HisPatient{}).Where("user_org_id = ? AND status = 1 AND id = ?", org_id, id).First(&info).Error
	return
}

func GetTodayHisOrder(org_id int64, patient_id int64, record_time int64, number string) (order models.HisOrder, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = ? AND status = 1 AND patient_id = ? AND settle_accounts_date = ? AND order_status = 1 AND mdtrt_id = ?", org_id, patient_id, record_time, number).First(&order).Error
	return
}

func GetOrderCountByNumber(org_id int64, patient_id int64, record_time int64, number string) (count int64, err error) {
	err = readDb.Model(&models.HisOrder{}).Where("user_org_id = ? AND status = 1 AND patient_id = ? AND settle_accounts_date = ? AND order_status = 2 AND mdtrt_id = ?", org_id, patient_id, record_time, number).Count(&count).Error

	return
}

func CreateHisPsn(psn *models.HisPsn) {
	writeDb.Save(&psn)
}

func GetPsnByPatientId(patient_id int64) (psn models.HisPsn, err error) {
	err = readDb.Model(&models.HisPsn{}).Where("patient_id = ?", patient_id).Last(&psn).Error
	return
}

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 setl_id <> '' AND  fa_piao_code <> '' AND setl_time >= '2022-03-01 00:00:00'", org_id).Order("setl_time asc").Find(&his).Error
	return
}
func GetAllHisOrderErr(org_id int64, stage int64) (his []*models.HisOrderError, err error) {
	err = readDb.Model(&models.HisOrderError{}).Where("user_org_id = ? AND status = 1 AND stage = ?", org_id, stage).Find(&his).Error
	return
}

func GetHisOrderInfoByNumberFour(order_number string) (order []*models.HisOrderInfo, err error) {
	db := readDb.Model(&models.HisOrderInfo{})
	err = db.Where("order_number = ? AND status = 1", order_number).Find(&order).Error
	return
}

func UpdataOrderStatusByNumber(number string) (err error) {
	err = writeDb.Model(&models.HisOrder{}).Where("status = 1 AND number = ?", number).Updates(map[string]interface{}{"order_status": 3, "mtime": time.Now().Unix(), "status": 0}).Error
	return

}

func UpdataHospitalOrderStatus(number string, user_org_id int64) (err error) {
	err = writeDb.Model(&models.HisOrderInfo{}).Where("status = 1 AND order_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"status": 0}).Error
	err = writeDb.Model(&models.HisPrescription{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"order_status": 1, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisPrescriptionInfo{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"prescription_status": 1, "mtime": time.Now().Unix()}).Error
	return

}

func GetHisFundSettleListResult(order_id int64) (result models.HisFundSettleListResult, err error) {
	db := readDb.Model(&models.HisFundSettleListResult{})
	err = db.Where("order_id = ? AND status = 1", order_id).First(&result).Error
	return
}

func SaveClearRecord(record *models.HisYidiClearRecord) {
	writeDb.Save(&record)
}

func GetClearRecordById(id int64) (record models.HisYidiClearRecord, err error) {
	err = readDb.Model(&models.HisYidiClearRecord{}).Where("id = ? AND status = 1").First(&record).Error
	return
}

func UpdateOrder(order models.HisOrder) (err error) {
	err = writeDb.Save(&order).Error
	return
}
