package service

import (
	"XT_New/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"`
}

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       string `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"`
}

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"`
	Name      string `gorm:"column:name" json:"name" form:"name"`
	Status    int64  `gorm:"column:status" json:"status" form:"status"`
}

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 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 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", "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")
		}).
		Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ?", org_id, record_date, patient_id).
		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"`
	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"`
	//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 GetAllProjectList(org_id int64) (list []*models.HisProject, err error) {
	err = readDb.Model(&models.HisProject{}).Where("user_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 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 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 UpDateAddtionNumber(user_org_id int64, ids []int64, number string) (err error) {
	err = writeDb.Model(&models.HisAdditionalCharge{}).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 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": 3, "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"`

	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          string                       `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"`
}

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) (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()}).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": 3, "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": 4, "mtime": time.Now().Unix()}).Error
	err = writeDb.Model(&models.HisAdditionalCharge{}).Where("status = 1 AND batch_number = ? AND user_org_id = ?", number, user_org_id).Updates(map[string]interface{}{"order_status": 3, "mtime": time.Now().Unix()}).Error

	return

}

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 GetHisOrderTwo(user_org_id int64, number string, patient_id int64) (order models.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).
		First(&order).Error
	return
}

func UpDateOrder(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 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"`

	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")
		}).
		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
}
