package service

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

type VMSchedule 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 (VMSchedule) TableName() string {
	return "xt_schedule"
}

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:HisPatientId,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"`
	VMHisOrders     []*VMHisOrder      `gorm:"ForeignKey:MdtrtId,PatientId;AssociationForeignKey:Number,PatientId" json:"orders"`
	VMHisOrder      VMHisOrder         `gorm:"ForeignKey:MdtrtId,PatientId;AssociationForeignKey:Number,PatientId" json:"order"`
}

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

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 VMHisOrder 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"`
	MdtrtId               string  `gorm:"column:mdtrt_id" json:"mdtrt_id" form:"mdtrt_id"`
	MzNumber              string  `gorm:"column:mz_number" json:"mz_number" form:"mz_number"`

	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"`
	IsPre        int64  `gorm:"column:is_pre" json:"is_pre" form:"is_pre"`
	Diagnosis    string `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
}

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

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"`
	IdCardNo     string `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
	ScheduleType int64  `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`

	Schedule              Schedule              `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"schedule"`
	HisPatient            HisPatient            `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"his_patient"`
	HisPrescription       []*HisPrescription    `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"prescription"`
	VMHisPrescriptionInfo VMHisPrescriptionInfo `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"info"`
	VMHisOrder            VMHisOrder            `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"order"`
}

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"`
	MedType      string `gorm:"column:med_type" json:"med_type" form:"med_type"`
	OrderStatus  int64  `gorm:"column:order_status" json:"order_status" form:"order_status"`
}

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

func GetScheduleHisPatientList(org_id int64, keywords string, record_date int64, sch_type int64) (patients []*Patients, err error) {
	db := readDb.Model(&Patients{}).Select("xt_patients.id,xt_patients.user_org_id,xt_patients.name,xt_patients.status,xt_patients.id_card_no,sch.schedule_type as sch_type").Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)

	if sch_type != 0 {
		db = db.Joins("join xt_schedule as sch ON sch.patient_id = xt_patients.id AND sch.schedule_date = ? AND sch.status = 1 AND sch.user_org_id = ? AND sch.schedule_type = ?", record_date, org_id, sch_type)
	} else {
		db = db.Joins("join xt_schedule as sch ON sch.patient_id = xt_patients.id AND sch.schedule_date = ? AND sch.status = 1 AND sch.user_org_id = ? ", record_date, org_id)
	}

	db = db.Preload("HisPatient", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date)
	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1", org_id, record_date)
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1", org_id, record_date).Group("xt_patients.id").Order("sch_type").Find(&patients).Error
	return
}

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

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

func GetChargeHisPatientListTwo(org_id int64, keywords string, record_date int64) (patients []*Patients, err error) {
	db := readDb.Model(&Patients{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id).
		Joins("join his_patient as hp ON hp.patient_id = xt_patients.id AND hp.record_date = ? AND hp.status = 1 AND hp.user_org_id = ?", record_date, org_id)
	db = db.Preload("HisPatient", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date)
	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date)
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date).Find(&patients).Error
	return
}

func GetHisPatientList(org_id int64, keywords string, record_date int64) (patients []*Patients, err error) {
	db := readDb.Model(&Patients{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id).
		Joins("join his_patient as hp ON hp.patient_id = xt_patients.id AND hp.record_date = ? AND hp.status = 1 AND hp.user_org_id = ?", record_date, org_id)
	db = db.Preload("HisPatient", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date)
	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1", org_id, record_date)
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ?  AND p_type <> 1", org_id, record_date).Find(&patients).Error
	return
}

type PatientTwo 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"`
	IdCardNo              string                `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
	ScheduleType          int64                 `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`
	Schedule              Schedule              `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"schedule"`
	HisPatient            []*HisPatientTwo      `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"his_patient"`
	VMHisPrescriptionInfo VMHisPrescriptionInfo `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"info"`
}

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

type HisPatientTwo 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"`
	HisPrescriptionTwo []*HisPrescriptionTwo `gorm:"ForeignKey:PatientId,HisPatientId;AssociationForeignKey:PatientId,ID" json:"prescription"`
	PatientId          int64                 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	Number             string                `gorm:"column:number" json:"number" form:"number"`
}

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

type HisPrescriptionTwo 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"`
	PreTime            int64  `gorm:"column:pre_time" json:"pre_time" form:"pre_time"`
	BatchNumber        string `gorm:"column:batch_number" json:"batch_number" form:"batch_number"`
	PrescriptionNumber string `gorm:"column:prescription_number" json:"prescription_number" form:"prescription_number"`
	MedType            string `gorm:"column:med_type" json:"med_type" form:"med_type"`
}

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

func GetNewHisPatientList(org_id int64, record_date int64) (patients []*PatientTwo, err error) {
	db := readDb.Model(&PatientTwo{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id).
		Joins("join his_patient as hp ON hp.patient_id = xt_patients.id AND hp.record_date = ? AND hp.status = 1 AND hp.user_org_id = ?", record_date, org_id)
	db = db.Preload("HisPatient", func(db *gorm.DB) *gorm.DB {
		return db.Preload("HisPrescriptionTwo", "status = 1 AND user_org_id = ?  AND record_date = ?", org_id, record_date).Where("user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date)
	})
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date).Group("id").Find(&patients).Error
	return
}

func GetNewScheduleHisPatientList(org_id int64, keywords string, record_date int64, sch_type int64) (patients []*PatientTwo, err error) {
	db := readDb.Model(&PatientTwo{}).Select("xt_patients.id,xt_patients.user_org_id,xt_patients.name,xt_patients.status,xt_patients.id_card_no,sch.schedule_type as sch_type").Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)

	if sch_type != 0 {
		db = db.Joins("join xt_schedule as sch ON sch.patient_id = xt_patients.id AND sch.schedule_date = ? AND sch.status = 1 AND sch.user_org_id = ? AND sch.schedule_type = ?", record_date, org_id, sch_type)
	} else {
		db = db.Joins("join xt_schedule as sch ON sch.patient_id = xt_patients.id AND sch.schedule_date = ? AND sch.status = 1 AND sch.user_org_id = ? ", record_date, org_id)
	}

	db = db.Preload("HisPatient", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date)
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ?", org_id, record_date).Group("xt_patients.id").Order("sch_type").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 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 GetHisPatientInfoThree(org_id int64, number string) (info models.HisPatient, err error) {
	err = readDb.Model(&models.HisPatient{}).Where("user_org_id = ? AND status = 1 AND number = ?", org_id, number).First(&info).Error
	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 GetNewHisPatientInfoTwo(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 GetHisPatientCount(org_id int64, patient_id int64, record_date int64) (total int64, 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).Count(&total).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(id int64) (*models.HisPatientCaseHistory, error) {
	history := models.HisPatientCaseHistory{}
	err := XTReadDB().Model(&history).Where("id = ? and status = 1", id).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 UpdatePatientCaseHistory(id int64, his *models.HisPatientCaseHistory) error {

	err := XTWriteDB().Model(&his).Where("id = ? and status  =1", id).Updates(map[string]interface{}{"temperature": his.Temperature, "blood_sugar": his.BloodSugar, "pulse": his.BloodSugar, "allergic_history": his.AllergicHistory, "diagnose": his.AllergicHistory, "sick": his.Sick, "remark": his.Remark, "doctor_advice": his.DoctorAdvice, "breathing": his.Breathing, "delivery_way": his.DeliveryWay, "diagnostic": his.Diagnostic, "family_history": his.FamilyHistory, "personal_history": his.PersonalHistory, "chief_conplaint": his.ChiefConplaint, "doctor": his.Doctor, "past_history": his.PastHistory, "history_of_present_illness": his.HistoryOfPresentIllness, "is_infect": his.IsInfect, "sick_date": his.SickDate, "symptom": his.Symptom, "sick_type": his.SickType, "blood_fat": his.BloodFat}).Error
	return err
}

func SaveHisPrescription(prescription *models.HisPrescription) (err error) {
	tx := writeDb.Begin()

	if err = tx.Model(&models.HisPrescription{}).Save(prescription).Error; err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()
	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, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND p_type = ?", org_id, record_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

func GetNewHisPrescription(org_id int64, patient_id int64, his_patient_id int64, record_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND his_patient_id = ? AND p_type = ? ", org_id, record_date, patient_id, his_patient_id, p_type).
		Find(&prescription).Error
	return
}

func GetChargeHisPrescriptionFive(org_id int64, patient_id int64, his_patient_id int64, record_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status = 2 AND his_patient_id = ? AND p_type = ?", org_id, record_date, patient_id, his_patient_id, p_type).
		Find(&prescription).Error
	return
}

func GetUnChargeHisPrescriptionFive(org_id int64, patient_id int64, his_patient_id int64, record_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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")
		}).Preload("TempHisOrder", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ? AND order_status <> 3  AND order_status <> 2  ", org_id)
	}).
		Where("(user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status <> 2 AND order_status <> 3 AND p_type = ?) AND  (his_patient_id = ? OR his_patient_id = 0)", org_id, record_date, patient_id, p_type, his_patient_id).
		Find(&prescription).Error
	return
}

func GetSettleHisPrescription(org_id int64, patient_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("Drug", "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("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND order_status <> 2 AND his_patient_id = ? AND p_type <> 1 AND med_type = ?", org_id, record_date, patient_id, his_patient_id, med_type).
		Find(&prescription).Error
	return
}

func GetMonthHisPrescription(org_id int64, patient_id int64, start_date int64, end_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("Drug", "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("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status <> 2 AND p_type <> 1 AND med_type = ?", org_id, start_date, end_date, patient_id, med_type).
		Find(&prescription).Error
	return
}

func GetMonthHisPrescriptionTwo(org_id int64, patient_id int64, start_date int64, end_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ? AND p_type = ?", org_id, start_date, end_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

func GetMonthHisPrescriptionThree(org_id int64, patient_id int64, start_date int64, end_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ?  AND p_type = ? ", org_id, start_date, end_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

//未收费
func GetUnChargeMonthHisPrescriptionThree(org_id int64, patient_id int64, start_date int64, end_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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")
		}).Preload("TempHisOrder", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ?", org_id)
	}).
		Where("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ?  AND  order_status <> 2 AND order_status <> 3  AND p_type = ?", org_id, start_date, end_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

//已收费
func GetChargeMonthHisPrescriptionFour(org_id int64, patient_id int64, start_date int64, end_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ? AND order_status = 2 AND p_type = ?", org_id, start_date, end_date, patient_id, p_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"`
	MinNumber                   int64   `gorm:"column:min_number" json:"min_number" form:"min_number"`
	MinUnit                     string  `gorm:"column:min_unit" json:"min_unit" form:"min_unit"`
	Dose                        float64 `gorm:"column:dose" json:"dose" form:"dose"`
	DoseUnit                    string  `gorm:"column:dose_unit" json:"dose_unit" form:"dose_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"`
	MinPrice                    float64 `gorm:"column:min_price" json:"min_price" form:"min_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"`
	Dealer                      int64   `gorm:"column:dealer" json:"dealer" form:"dealer"`
	PrescriptionMark            int64   `gorm:"column:prescription_mark" json:"prescription_mark" form:"prescription_mark"`
	RecordDate                  int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
	DrugRemark                  string  `gorm:"column:drug_remark" json:"drug_remark" form:"drug_remark"`
	SocialSecurityDirectoryCode string  `gorm:"column:social_security_directory_code" json:"social_security_directory_code" form:"social_security_directory_code"`
	DoseCode                    string  `gorm:"column:dose_code" json:"dose_code" form:"dose_code"`
	IsMark                      int64   `gorm:"column:is_mark" json:"is_mark" form:"is_mark"`
	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"`
	Dosage                      string  `gorm:"column:dosage" json:"dosage" form:"dosage"`
	Unval                       string  `gorm:"column:unval" json:"unval" form:"unval"`
	PackingUnit                 string  `gorm:"column:packing_unit" json:"packing_unit" form:"packing_unit"`
	PackingPrice                float64 `gorm:"column:packing_price" json:"packing_price" form:"packing_price"`
	DrugDay                     string  `gorm:"column:drug_day" json:"drug_day" form:"drug_day"`
	Total                       float64 `gorm:"column:total" json:"total" form:"total"`
	PrescribingNumberUnit       string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`

	//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 AND  find_in_set('停用',drug_status) = 0", org_id).Find(&list).Error
	return
}

func GetAllDrugLibs(org_id int64) (drugs []*Drugs, err error) {
	db := readDb.Model(&models.BaseDrugLib{}).Preload("Drugs", "status = 1 AND org_id = ? AND find_in_set('停用',drug_status) = 0", org_id).Where("org_id = ?  AND status = 1 AND find_in_set('停用',drug_status) = 0", org_id).Group("drug_name")
	err = db.Find(&drugs).Error
	return
}

func GetAllProjectList(org_id int64, keyword string) (list []*models.HisProject, err error) {
	if len(keyword) != 0 {
		key := "%" + keyword + "%"
		err = readDb.Model(&models.HisProject{}).Where("user_org_id = ?  AND status = 1 AND project_name Like ?", org_id, key).Find(&list).Error
	} else {
		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 = 2", org_id).Find(&doctors).Error
	return
}

func CreateHisDoctorAdvice(s *models.HisDoctorAdviceInfo) (err error) {

	tx := writeDb.Begin()
	if err = tx.Model(&models.HisDoctorAdviceInfo{}).Save(s).Error; err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()

	return
}

func CreateHisProjectTwo(project *models.HisPrescriptionProject) (err error) {
	tx := writeDb.Begin()
	if err = tx.Model(&models.HisPrescriptionProject{}).Save(project).Error; err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()

	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, 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, 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, p_type int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND p_type = ? ", org_id, record_date, patient_id, p_type).First(&info).Error
	return

}

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

}

func FindHisPatientPrescriptionInfo(org_id int64, patient_id int64, record_date int64, p_type int64, his_patient_id int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND status = 1 AND record_date = ? AND patient_id = ? AND p_type = ? AND his_patient_id = ? ", org_id, record_date, patient_id, p_type, 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) {
	tx := writeDb.Begin()

	if err = tx.Model(&models.HisPrescription{}).Save(&info).Error; err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()
	return
}

func GetHisOrderList(user_org_id int64, page int64, limit int64, start_time int64, end_time int64, doctor_id int64, keywords string, p_type int64) (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 = ? AND his_order.p_type = ?", user_org_id, p_type)

	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("HisHospitalCheckRecord", "status = 1 AND user_org_id = ?", user_org_id)
	db = db.Preload("HisFundSettleListResult", "status = 1")
	db = db.Count(&total)
	err = db.Limit(limit).Offset(offset).Order("settle_accounts_date desc,ctime").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
}

func UpDateHisPrescriptionInfoNumber(user_org_id int64, id int64, number string, record_time int64, his_patient_id 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": 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"`
	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"`

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

	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"`
	IsPre        int64  `gorm:"column:is_pre" json:"is_pre" form:"is_pre"`
	Diagnosis    string `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
}

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, 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").Preload("GoodInfo", "status=1")
		}).
		Preload("HisAdditionalCharge", "status = 1 AND user_org_id = ?", org_id).
		Where("user_org_id = ? AND status = 1  AND patient_id = ? AND batch_number=?", org_id, 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").Preload("GoodInfo", "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(), "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 UpdataOrderInfoStatus(id int64, number string, user_org_id int64) {
	err = writeDb.Model(&models.HisOrder{}).Where("status = 1 AND id = ? AND user_org_id = ?", id, user_org_id).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error
	err = writeDb.Model(&models.HisOrderInfo{}).Where("status = 1 AND user_org_id = ? AND order_number = ?", user_org_id, number).Updates(map[string]interface{}{"mtime": time.Now().Unix(), "status": 0}).Error

	return

}

func SaveHisPatient(his models.HisPatient) (err error) {
	writeDb.Model(&models.HisPatient{}).Where("status = 1 AND record_date =? AND user_org_id = ? AND id = ?", his.RecordDate, his.UserOrgId, his.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 = ?", his.UserOrgId, his.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 = ?", his.UserOrgId, his.ID).Updates(map[string]interface{}{"his_patient_id": 0, "mtime": time.Now().Unix()})

	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()})

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

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

	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"`
	IsPre        int64  `gorm:"column:is_pre" json:"is_pre" form:"is_pre"`
	Diagnosis    string `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
}

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").Preload("GoodInfo", "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 GetNewHisPatientPrescriptionList(org_id int64, keywords string, record_date int64, page int64, limit int64) (patients []*VMHisHospitalPrescriptionInfo, err error, total int64) {
	offset := (page - 1) * limit
	db := readDb.Model(&VMHisHospitalPrescriptionInfo{}).Where("his_prescription_info.user_org_id = ? AND his_prescription_info.status = 1 AND his_prescription_info.record_date = ? AND his_prescription_info.p_type <> 1 ", org_id, record_date)
	if len(keywords) > 0 {
		keywords = "%" + keywords + "%"
		db = db.Joins("JOIN xt_patients  On his_prescription_info.patient_id = xt_patients.id  AND xt_patients.name like ?", keywords)
	}
	db = db.Preload("Patients", "xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)
	db = db.Preload("HisPrescription", "his_prescription.user_org_id = ? AND his_prescription.status = 1 AND his_prescription.p_type <> 1", org_id)
	db = db.Count(&total)
	err = db.Limit(limit).Offset(offset).Find(&patients).Error
	return
}

func GetHisPatientPrescriptionList(org_id int64, keywords string, record_date int64, page int64, limit int64) (patients []*VMSchedule, err error, total int64) {
	offset := (page - 1) * limit
	db := readDb.Model(&VMSchedule{}).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 ? AND info.p_type <> 1", 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 AND p_type <> 1", org_id).
		Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND p_type <> 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"`
	DoctorId          int64                `gorm:"column:doctor_id" json:"doctor_id" form:"doctor_id"`
	Departments       int64                `gorm:"column:departments" json:"departments" form:"departments"`
	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"`
	MedType                string                           `gorm:"column:med_type" json:"med_type" form:"med_type"`
}

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

func GetHisPrescriptionByType(change_type int64, record_time int64, org_id int64, patient_id int64, p_type int64) (advice []*VMOtherHisPrescriptionInfo, err error) {
	if change_type == 1 { //根据日期取出上一方数据
		var Id AdviceDate
		err = readDb.Model(&VMOtherHisPrescriptionInfo{}).Where("patient_id = ? AND user_org_id = ? AND status=1 AND record_date < ? AND p_type = ?", patient_id, org_id, record_time, p_type).Select("record_date").Group("record_date").Order("record_date asc").Scan(&Id).Error
		err = readDb.Model(&VMOtherHisPrescriptionInfo{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND record_date  = ? AND p_type = ?", patient_id, org_id, Id.RecordDate, p_type).
			Preload("VMHisPrescription", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", org_id).
					Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
						return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "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")
					})
			}).Find(&advice).Error

	} else if change_type == 2 {
		var Id AdviceDate
		err = readDb.Model(&VMOtherHisPrescriptionInfo{}).Where("patient_id = ? AND user_org_id = ? AND status=1 AND record_date > ? AND p_type = ?", patient_id, org_id, record_time, p_type).Select("record_date").Group("record_date").Order("record_date desc").Scan(&Id).Error
		err = readDb.Model(&VMOtherHisPrescriptionInfo{}).Where("patient_id = ? AND user_org_id = ? AND  status=1 AND record_date  = ? AND p_type = ?", patient_id, org_id, Id.RecordDate, p_type).
			Preload("VMHisPrescription", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", org_id).
					Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
						return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "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")
					})
			}).Find(&advice).Error
	}
	return
}

func GetCallHisPrescriptions(start_time int64, end_time int64, org_id int64, patient_id int64, p_type 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 <= ? AND p_type = ?", patient_id, org_id, start_time, end_time, p_type).
		Preload("VMHisPrescription", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).
				Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
					return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "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")
				})
		}).Find(&advice).Error

	return
}

func GetMobileCallHisPrescriptions(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", func(db *gorm.DB) *gorm.DB {
					return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "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")
				})
		}).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 GetHisOrderInfoByNumber(order_number string) (order []*models.HisOrderInfo, err error) {
	err = readDb.Model(&models.HisOrderInfo{}).Where("order_number = ? AND status = 1", order_number).Find(&order).Error
	return
}

func GetOrderByTime(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 settle_accounts_date <= ? AND settle_accounts_date >= ? AND insutype = ? AND clr_type = ? ", org_id, end_time, start_time, insutype, clr_type).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 settle_accounts_date <= ? AND settle_accounts_date >= ? ", org_id, end_time, start_time).Find(&orders).Error
	return
}

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

}

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

}

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

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

func GetHisAdditionByID(id int64) (addition models.HisAdditionalCharge, err error) {
	err = readDb.Model(&models.HisAdditionalCharge{}).Where("status = 1  AND id = ?", id).First(&addition).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 GetPatientByIDCardAndName(id_card_no string, user_org_id int64, name string) (patient Patients, err error) {
	err = readDb.Model(&Patients{}).Where("id_card_no = ? AND user_org_id = ? AND name = ?", id_card_no, user_org_id, name).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 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 GetHisPrescriptionByPatientID(patientID int64, orgID int64) (info models.HisPrescriptionInfo, err error) {
	err = readDb.Model(&models.HisPrescriptionInfo{}).Where("user_org_id = ? AND patient_id = ? AND status = 1", orgID, patientID).Preload("XtHisDepartment", "status = 1").Last(&info).Error
	return
}

type VMHisProjectTeam struct {
	ID                int64                `gorm:"column:id" json:"id" form:"id"`
	ProjectTeam       string               `gorm:"column:project_team" json:"project_team" form:"project_team"`
	Price             float64              `gorm:"column:price" json:"price" form:"price"`
	Pinyin            string               `gorm:"column:pinyin" json:"pinyin" form:"pinyin"`
	Wubi              string               `gorm:"column:wubi" json:"wubi" form:"wubi"`
	TubeColor         int64                `gorm:"column:tube_color" json:"tube_color" form:"tube_color"`
	TeamType          int64                `gorm:"column:team_type" json:"team_type" form:"team_type"`
	Remark            string               `gorm:"column:remark" json:"remark" form:"remark"`
	UserOrgId         int64                `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	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"`
	ProjectId         string               `gorm:"column:project_id" json:"project_id" form:"project_id"`
	VMItemProjectList []*VMItemProjectList `gorm:"-" json:"list" form:"list"`
	ItemId            string               `gorm:"column:item_id" json:"item_id" form:"item_id"`
}

func (VMHisProjectTeam) TableName() string {
	return "xt_his_project_team"
}

type VMHisProject struct {
	ID                        int64   `gorm:"column:id" json:"id" form:"id"`
	ProjectName               string  `gorm:"column:project_name" json:"project_name" form:"project_name"`
	Price                     float64 `gorm:"column:price" json:"price" form:"price"`
	Unit                      string  `gorm:"column:unit" json:"unit" form:"unit"`
	CostClassify              int64   `gorm:"column:cost_classify" json:"cost_classify" form:"cost_classify"`
	StatisticalClassification int64   `gorm:"column:statistical_classification" json:"statistical_classification" form:"statistical_classification"`
	UserOrgId                 int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	Status                    int64   `gorm:"column:status" json:"status" form:"status"`
	SingleDose                string  `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
	ExecutionFrequency        string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
	DeliveryWay               string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
	NumberDays                string  `gorm:"column:number_days" json:"number_days" form:"number_days"`
	MedicalCode               string  `gorm:"column:medical_code" json:"medical_code" form:"medical_code"`
}

func (VMHisProject) TableName() string {
	return "xt_his_project"
}

type VMItemProjectList struct {
	ID           int64        `gorm:"column:id" json:"id" form:"id"`
	Number       int64        `gorm:"column:number" json:"number" form:"number"`
	UserOrgId    int64        `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	ProjectId    int64        `gorm:"column:project_id" json:"project_id" form:"project_id"`
	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"`
	TeamId       int64        `gorm:"column:team_id" json:"team_id" form:"team_id"`
	Type         int64        `gorm:"column:type" json:"type" form:"type"`
	VMHisProject VMHisProject `gorm:"ForeignKey:ID;AssociationForeignKey:ProjectId" json:"project"`
	GoodInfo     GoodInfo     `gorm:"ForeignKey:ID;AssociationForeignKey:ProjectId" json:"good_info"`
}

func (VMItemProjectList) TableName() string {
	return "xt_his_project_list"
}

type VMHisPrescriptionTwo 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"`
	Ctime     int64  `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime     int64  `gorm:"column:mtime" json:"mtime" form:"mtime"`
	Type      int64  `gorm:"column:type" json:"type" form:"type"`
	MedType   string `gorm:"column:med_type" json:"med_type" form:"med_type"`
}

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

func GetAllProjectTeamList(orgid int64) (project []*VMHisProjectTeam, err error) {
	err = XTReadDB().Model(&VMHisProjectTeam{}).Where("user_org_id = ? and status = 1", orgid).Find(&project).Error
	for _, item := range project {
		var project_item []*VMItemProjectList
		ids := strings.Split(item.ItemId, ",")
		XTReadDB().Model(&VMItemProjectList{}).Where("status = 1 AND id IN (?)", ids).Preload("VMHisProject", "status = 1 AND user_org_id = ?", orgid).Preload("GoodInfo", "status = 1 AND org_id = ?", orgid).Find(&project_item)
		item.VMItemProjectList = append(item.VMItemProjectList, project_item...)
	}
	return
}

type HisDoctorAdviceInfo 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"`
	AdviceDate            int64   `gorm:"column:advice_date" json:"advice_date" form:"advice_date"`
	AdviceName            string  `gorm:"column:advice_name" json:"advice_name" form:"advice_name"`
	AdviceDesc            string  `gorm:"column:advice_desc" json:"advice_desc" form:"advice_desc"`
	SingleDose            float64 `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
	SingleDoseUnit        string  `gorm:"column:single_dose_unit" json:"single_dose_unit" form:"single_dose_unit"`
	PrescribingNumber     float64 `gorm:"column:prescribing_number" json:"prescribing_number" form:"prescribing_number"`
	PrescribingNumberUnit string  `gorm:"column:prescribing_number_unit" json:"prescribing_number_unit" form:"prescribing_number_unit"`
	DeliveryWay           string  `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
	ExecutionFrequency    string  `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
	Status                int64   `gorm:"column:status" json:"status" form:"status"`
	CreatedTime           int64   `gorm:"column:created_time" json:"created_time" form:"created_time"`
	RecordDate            int64   `gorm:"column:record_date" json:"record_date" form:"record_date"`
	DrugSpec              float64 `gorm:"column:drug_spec" json:"drug_spec" form:"drug_spec"`
	DrugSpecUnit          string  `gorm:"column:drug_spec_unit" json:"drug_spec_unit" form:"drug_spec_unit"`
	PrescriptionId        int64   `gorm:"column:prescription_id" json:"prescription_id" form:"prescription_id"`

	Price                float64              `gorm:"column:price" json:"price" form:"price"`
	DrugId               int64                `gorm:"column:drug_id" json:"drug_id" form:"drug_id"`
	Drug                 Drug                 `gorm:"ForeignKey:ID;AssociationForeignKey:DrugId" json:"drug"`
	VMHisPrescriptionTwo VMHisPrescriptionTwo `gorm:"ForeignKey:ID;AssociationForeignKey:PrescriptionId" json:"prescription"`
}

func (HisDoctorAdviceInfo) TableName() string {
	return "his_doctor_advice_info"
}

type HisPrescriptionProject struct {
	ID                 int64        `gorm:"column:id" json:"id" form:"id"`
	ProjectId          int64        `gorm:"column:project_id" json:"project_id" form:"project_id"`
	Price              float64      `gorm:"column:price" json:"price" form:"price"`
	UserOrgId          int64        `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	Status             int64        `gorm:"column:status" json:"status" form:"status"`
	Ctime              int64        `gorm:"column:ctime" json:"ctime" form:"ctime"`
	Mtime              int64        `gorm:"column:mtime" json:"mtime" form:"mtime"`
	PatientId          int64        `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	HisPatientId       int64        `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
	RecordDate         int64        `gorm:"column:record_date" json:"record_date" form:"record_date"`
	PrescriptionId     int64        `gorm:"column:prescription_id" json:"prescription_id" form:"prescription_id"`
	Count              int64        `gorm:"column:count" json:"count" form:"count"`
	FeedetlSn          string       `gorm:"column:feedetl_sn" json:"feedetl_sn" form:"feedetl_sn"`
	MedListCodg        string       `gorm:"column:med_list_codg" json:"med_list_codg" form:"med_list_codg"`
	SingleDose         string       `gorm:"column:single_dose" json:"single_dose" form:"single_dose"`
	DeliveryWay        string       `gorm:"column:delivery_way" json:"delivery_way" form:"delivery_way"`
	ExecutionFrequency string       `gorm:"column:execution_frequency" json:"execution_frequency" form:"execution_frequency"`
	Day                string       `gorm:"column:day" json:"day" form:"day"`
	VMHisProject       VMHisProject `gorm:"ForeignKey:ProjectId;AssociationForeignKey:ID" json:"project"`
	VMGoodInfo         VMGoodInfo   `gorm:"ForeignKey:ProjectId;AssociationForeignKey:ID" json:"good_info"`

	Remark               string               `gorm:"column:remark" json:"remark" form:"remark"`
	Unit                 string               `gorm:"column:unit" json:"unit" form:"unit"`
	VMHisPrescriptionTwo VMHisPrescriptionTwo `gorm:"ForeignKey:ID;AssociationForeignKey:PrescriptionId" json:"prescription"`
	Type                 int64                `gorm:"column:type" json:"type" form:"type"`

	Doctor         int64 `gorm:"column:doctor" json:"doctor" form:"doctor"`
	ExecutionTime  int64 `gorm:"column:execution_time" json:"execution_time" form:"execution_time"`
	ExecutionStaff int64 `gorm:"column:execution_staff" json:"execution_staff" form:"execution_staff"`
	ExecutionState int64 `gorm:"column:execution_state" json:"execution_state" form:"execution_state"`
	CheckTime      int64 `gorm:"column:check_time" json:"check_time" form:"check_time"`
	CheckState     int64 `gorm:"column:check_state" json:"check_state" form:"check_state"`
	Checker        int64 `gorm:"column:checker" json:"checker" form:"checker"`
	StartTime      int64 `gorm:"column:start_time" json:"start_time" form:"start_time"`
}

func (HisPrescriptionProject) TableName() string {
	return "his_prescription_project"
}

type HisOrderInfo struct {
	ID               int64   `gorm:"column:id" json:"id" form:"id"`
	OrderNumber      string  `gorm:"column:order_number" json:"order_number" form:"order_number"`
	UploadDate       int64   `gorm:"column:upload_date" json:"upload_date" form:"upload_date"`
	AdviceId         int64   `gorm:"column:advice_id" json:"advice_id" form:"advice_id"`
	DetItemFeeSumamt float64 `gorm:"column:det_item_fee_sumamt" json:"det_item_fee_sumamt" form:"det_item_fee_sumamt"`
	Cnt              float64 `gorm:"column:cnt" json:"cnt" form:"cnt"`
	Pric             float64 `gorm:"column:pric" json:"pric" form:"pric"`
	PatientId        int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	MedChrgitmType   string  `gorm:"column:med_chrgitm_type" json:"med_chrgitm_type" form:"med_chrgitm_type"`
	Status           int64   `gorm:"column:status" json:"status" form:"status"`
	FeedetlSn        string  `gorm:"column:feedetl_sn" json:"feedetl_sn" form:"feedetl_sn"`
	ChldMedcFlag     string  `gorm:"column:chld_medc_flag" json:"chld_medc_flag" form:"chld_medc_flag"`
	ChrgitmLv        string  `gorm:"column:chrgitm_lv" json:"chrgitm_lv" form:"chrgitm_lv"`
	UserOrgId        int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	ProjectId        int64   `gorm:"column:project_id" json:"project_id" form:"project_id"`
	ItemId           int64   `gorm:"column:item_id" json:"item_id" form:"item_id"`
	FulamtOwnpayAmt  float64 `gorm:"column:fulamt_ownpay_amt" json:"fulamt_ownpay_amt" form:"fulamt_ownpay_amt"`

	HisPrescriptionProject HisPrescriptionProject `gorm:"ForeignKey:ID;AssociationForeignKey:ProjectId" json:"project"`
	HisDoctorAdviceInfo    HisDoctorAdviceInfo    `gorm:"ForeignKey:ID;AssociationForeignKey:AdviceId" json:"advice"`
}

func (HisOrderInfo) TableName() string {
	return "his_order_info"
}

func GetHisOrderDetailByNumber(order_number string, org_id int64) (order []*HisOrderInfo, err error) {
	err = readDb.Model(&HisOrderInfo{}).Where("order_number = ? AND status = 1", order_number).Preload("HisPrescriptionProject", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("VMHisPrescriptionTwo", "status = 1 AND user_org_id = ?", org_id).Preload("VMHisProject", "status = 1 AND user_org_id = ?", org_id).Preload("VMGoodInfo", "status = 1 AND org_id = ?", org_id)
	}).Preload("HisDoctorAdviceInfo", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("VMHisPrescriptionTwo", "status = 1 AND user_org_id = ?", org_id).Preload("Drug", "status = 1 AND org_id = ?", org_id)
	}).Find(&order).Error
	return
}

type MedicalInsuranceCostCompare struct {
	ID        int64   `gorm:"column:id" json:"id" form:"id"`
	StartTime int64   `gorm:"column:start_time" json:"start_time" form:"start_time"`
	EndTime   int64   `gorm:"column:end_time" json:"end_time" form:"end_time"`
	Insutype  string  `gorm:"column:insutype" json:"insutype" form:"insutype"`
	CheckType int64   `gorm:"column:check_type" json:"check_type" form:"check_type"`
	Num       int64   `gorm:"column:num" json:"num" form:"num"`
	Mtime     int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
	Status    int64   `gorm:"column:status" json:"status" form:"status"`
	UserOrgId int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
	CostTotal float64 `gorm:"column:cost_total" json:"cost_total" form:"cost_total"`
	FuncTotal float64 `gorm:"column:func_total" json:"func_total" form:"func_total"`
	PsnPay    float64 `gorm:"column:psn_pay" json:"psn_pay" form:"psn_pay"`
	Creator   int64   `gorm:"column:creator" json:"creator" form:"creator"`
	Ctime     int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
}

func (MedicalInsuranceCostCompare) TableName() string {
	return "medical_insurance_cost_compare"
}

func GetMedicalInsuranceCostCompareList(orgID, page, limit int64, keywords string, insutype string, start_time int64, end_time int64) (list []*MedicalInsuranceCostCompare, total int, err error) {
	offset := (page - 1) * limit
	db := readDb.Model(&MedicalInsuranceCostCompare{}).Where("medical_insurance_cost_compare.user_org_id = ?", orgID)
	if len(keywords) == 0 {
		db = db.Where("status=1")
		if len(insutype) != 0 {
			db = db.Where("insutype = ?", insutype)
		}
		if start_time != 0 {
			db = db.Where("ctime  >= ? ", start_time)
		}
		if end_time != 0 {
			db = db.Where("ctime  <= ? ", end_time)
		}
		err = db.Count(&total).Offset(offset).Limit(limit).Find(&list).Error
	} else {
		keywords = "%" + keywords + "%"
		db = db.Joins("join sgj_users.sgj_user_admin_role role  on role.admin_user_id = medical_insurance_cost_compare.creator and role.user_name Like ?", keywords)
		db = db.Where("medical_insurance_cost_compare.status=1 ")
		err = db.Count(&total).Offset(offset).Limit(limit).Find(&list).Error
	}
	return
}

type TempPatients 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"`
	Lapseto           int64             `gorm:"column:lapseto" json:"lapseto" form:"lapseto"`
	Name              string            `gorm:"column:name" json:"name" form:"name"`
	IdCardNo          string            `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
	Phone             string            `gorm:"column:phone" json:"phone" form:"phone"`
	HomeTelephone     string            `gorm:"column:home_telephone" json:"home_telephone" form:"home_telephone"`
	HomeAddress       string            `gorm:"column:home_address" json:"home_address" form:"home_address"`
	Status            int64             `gorm:"column:status" json:"status" form:"status"`
	GdybPsnNcdsRecord GdybPsnNcdsRecord `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"record"`
}

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

type GdybPsnNcdsRecord 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"`
	PsnNo         string `gorm:"column:psn_no" json:"psn_no" form:"psn_no"`
	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"`
	IsCancel      int64  `gorm:"column:is_cancel" json:"is_cancel" form:"is_cancel"`
	TrtDclaDetlSn string `gorm:"column:trt_dcla_detl_sn" json:"trt_dcla_detl_sn" form:"trt_dcla_detl_sn"`
	DoctorId      int64  `gorm:"column:doctor_id" json:"doctor_id" form:"doctor_id"`
	DepartmentId  int64  `gorm:"column:department_id" json:"department_id" form:"department_id"`
	Insutype      string `gorm:"column:insutype" json:"insutype" form:"insutype"`
	SickType      int64  `gorm:"column:sick_type" json:"sick_type" form:"sick_type"`
	OrgName       string `gorm:"column:org_name" json:"org_name" form:"org_name"`
}

func (GdybPsnNcdsRecord) TableName() string {
	return "gdyb_psn_ncds_record"
}

func GetGdybPsnNcdsRecordList(orgID, page, limit int64, keywords string, is_cancel int64) (list []*TempPatients, total int64, err error) {
	offset := (page - 1) * limit
	db := readDb.Model(&TempPatients{})
	db = db.Preload("GdybPsnNcdsRecord", func(db *gorm.DB) *gorm.DB {
		return db.Model(&GdybPsnNcdsRecord{}).Where("user_org_id = ?", orgID).Order("id asc")
	})
	fmt.Println(is_cancel)
	if len(keywords) == 0 {
		if is_cancel == 1 {
			db = db.Joins("JOIN gdyb_psn_ncds_record On gdyb_psn_ncds_record.patient_id = xt_patients.id AND gdyb_psn_ncds_record.is_cancel = ?", is_cancel)
			db = db.Where("xt_patients.user_org_id = ? AND xt_patients.status = 1 AND xt_patients.lapseto = 1", orgID)
		} else if is_cancel == 0 {
			db = db.Preload("GdybPsnNcdsRecord", "user_org_id = ?", orgID)
			db = db.Where("xt_patients.user_org_id = ? AND xt_patients.status = 1 AND xt_patients.lapseto = 1", orgID)
		} else if is_cancel == 2 {
			db = db.Joins("LEFT JOIN gdyb_psn_ncds_record On gdyb_psn_ncds_record.patient_id = xt_patients.id AND (gdyb_psn_ncds_record.is_cancel <> 1 OR gdyb_psn_ncds_record.is_cancel is null)")
			db = db.Where("xt_patients.user_org_id = ? AND xt_patients.status = 1 AND xt_patients.lapseto = 1", orgID)
		}
		err = db.Count(&total).Offset(offset).Limit(limit).Find(&list).Error
	} else {
		keywords = "%" + keywords + "%"
		db = db.Where("xt_patients.user_org_id = ? AND xt_patients.status = 1 AND xt_patients.lapseto = 1 AND xt_patients.name LIKE ?", orgID, keywords)
		err = db.Count(&total).Offset(offset).Limit(limit).Find(&list).Error

	}

	return
}

type CustomAccountFormData struct {
	MedfeeSumamt       float64 `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
	PsnName            string  `gorm:"column:psn_name" json:"psn_name" form:"psn_name"`
	IdCardNo           string  `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
	PsnNo              string  `gorm:"column:psn_no" json:"psn_no" form:"psn_no"`
	MdtrtiId           string  `gorm:"column:mdtrt_id" json:"mdtrt_id" form:"mdtrt_id"`
	SettleAccountsDate int64   `gorm:"column:settle_accounts_date" json:"settle_accounts_date" form:"settle_accounts_date"`
	ActPayDedc         float64 `gorm:"column:act_pay_dedc" json:"act_pay_dedc" form:"act_pay_dedc"`
	FundPaySumamt      float64 `gorm:"column:fund_pay_sumamt" json:"fund_pay_sumamt" form:"fund_pay_sumamt"`
	PsnCashPay         float64 `gorm:"column:psn_cash_pay" json:"psn_cash_pay" form:"psn_cash_pay"`
	AcctPay            float64 `gorm:"column:acct_pay" json:"acct_pay" form:"acct_pay"`
	CashPay            float64 `gorm:"column:cash_pay" json:"cash_pay" form:"cash_pay"`
	Sumamt             float64 `gorm:"column:sumamt" json:"sumamt" form:"sumamt"`
	Iinfo              string  `gorm:"column:iinfo" json:"iinfo" form:"iinfo"`
	DiagnosisId        int64   `gorm:"column:diagnosis_id" json:"diagnosis_id" form:"diagnosis_id"`
	DialysisCount      int64   `gorm:"-"`
	PatientId          int64   `gorm:"column:patient_id" json:"dialysis_count" form:"dialysis_count"`
	HifmiPay           float64 `gorm:"column:hifmi_pay" json:"hifmi_pay" form:"hifmi_pay"`
	HifobPay           float64 `gorm:"column:hifob_pay" json:"hifob_pay" form:"hifob_pay"`
	CvlservPay         float64 `gorm:"column:cvlserv_pay" json:"cvlserv_pay" form:"cvlserv_pay"`
	HifesPay           float64 `gorm:"column:hifes_pay" json:"hifes_pay" form:"hifes_pay"`
	MayPay             float64 `gorm:"column:maf_pay" json:"maf_pay" form:"maf_pay"`
	SetlDetail         string  `gorm:"column:setl_detail" json:"setl_detail" form:"setl_detail"`
}

func GetCheckAccountFormData(start_time int64, end_time int64, org_id int64, insutype string) (cus []*CustomAccountFormData, err error) {
	err = readDb.Raw("select o.setl_detail as setl_detail, o.maf_pay as maf_pay,  o.hifmi_pay  as hifmi_pay, o.hifob_pay as hifob_pay, o.cvlserv_pay as cvlserv_pay, o.hifes_pay as hifes_pay, o.patient_id as patient_id, p.diagnosis as diagnosis_id, p.iinfo as iinfo, o.medfee_sumamt as medfee_sumamt ,o.psn_name as psn_name ,p.id_card_no as id_card_no ,o.psn_no as psn_no, o.mdtrt_id as mdtrt_id, o.settle_accounts_date as settle_accounts_date,o.act_pay_dedc as act_pay_dedc,O.fund_pay_sumamt as fund_pay_sumamt,o.psn_cash_pay as psn_cash_pay ,o.acct_pay as acct_pay,o.psn_cash_pay as cash_pay,o.medfee_sumamt as sumamt  from his_order o  Join his_patient p On o.patient_id = p.patient_id AND o.settle_accounts_date = p.record_date where o.user_org_id = ? AND o.status = 1 AND o.order_status = 2  AND o.settle_accounts_date >= ? AND o.settle_accounts_date <= ? AND insutype = ? Group by o.id", org_id, start_time, end_time, insutype).Scan(&cus).Error

	for _, item := range cus {
		var total int64
		readDb.Model(&models.DialysisOrder{}).Where("patient_id = ? AND status = 1 AND stage = 2 AND dialysis_date <= ? AND  dialysis_date >= ?", item.PatientId, end_time, start_time).Count(&total)
		fmt.Println(total)
		item.DialysisCount = total
		fmt.Println(item.DialysisCount)
	}
	return
}

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

func GetNewHisOrder(user_org_id int64, mdtrt_id string, patient_id int64) (order HisOrder, err error) {
	err = readDb.Model(&HisOrder{}).Where("status = 1 AND user_org_id = ? AND patient_id = ? AND mdtrt_id=? ", user_org_id, patient_id, mdtrt_id).
		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").
		Last(&order).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
}

type NewCustomPatients 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"`
	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"`
	RecordDate int64      `gorm:"column:record_date" json:"record_date" form:"record_date"`
	VMHisOrder VMHisOrder `gorm:"ForeignKey:PatientId,MdtrtId;AssociationForeignKey:PatientId,Number" json:"order"`
}

func (NewCustomPatients) TableName() string {
	return "his_patients"
}

type NewSZCustomPatients 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"`
	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"`
	RecordDate int64      `gorm:"column:record_date" json:"record_date" form:"record_date"`
	VMHisOrder VMHisOrder `gorm:"ForeignKey:PatientId,MdtrtId;AssociationForeignKey:PatientId,MzNumber" json:"order"`
}

func (NewSZCustomPatients) TableName() string {
	return "his_patients"
}

//
//func GetNewAllChargeHisPatientList(org_id int64, record_date int64) (patients []*NewSZCustomPatients, err error) {
//	var tempPatients []*NewSZCustomPatients
//	db := readDb.Model(&NewSZCustomPatients{}).Where("his_patients.user_org_id = ? AND his_patients.status = 1", org_id)
//	db = db.Preload("VMHisOrder", "user_org_id = ? AND status = 1 AND settle_accounts_date = ?", org_id, record_date)
//	return tempPatients, err
//}

type NewTempPatients 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"`
	IdCardNo     string `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
	ScheduleType int64  `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`

	Schedule              Schedule              `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"schedule"`
	HisPatient            []*HisPatient         `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"his_patient"`
	HisPrescription       []*HisPrescription    `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"prescription"`
	VMHisPrescriptionInfo VMHisPrescriptionInfo `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"info"`
}

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

//"VMHisOrder", "user_org_id = ? AND status = 1 AND settle_accounts_date = ?", org_id, record_date

func GetNewAllUnChargeHisPatientList(org_id int64, keywords string, record_date int64) (patients []*NewTempPatients, err error) {
	db := readDb.Model(&NewTempPatients{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)
	db = db.Preload("HisPatient", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ? AND record_date = ?", org_id, record_date).Preload("VMHisOrders", "user_org_id = ? AND status = 1 AND settle_accounts_date = ?", org_id, record_date)
	})
	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1 AND order_status <> 2 AND order_status <> 3", org_id, record_date)
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1 AND prescription_status <> 3", org_id, record_date).Find(&patients).Error

	for _, item := range patients {
		for _, sumItem := range item.HisPatient {
			if len(sumItem.VMHisOrders) > 0 {
				sumItem.VMHisOrder.OrderStatus = sumItem.VMHisOrders[len(sumItem.VMHisOrders)-1].OrderStatus
			}
		}

	}

	return
}

func GetNewAllChargeHisPatientList(org_id int64, keywords string, record_date int64) (patients []*NewTempPatients, err error) {
	db := readDb.Model(&NewTempPatients{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)
	db = db.Preload("HisPatient", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ? AND record_date = ?", org_id, record_date).Preload("VMHisOrders", "user_org_id = ? AND status = 1 AND settle_accounts_date = ? ", org_id, record_date)
	})
	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1 AND order_status <>", org_id, record_date)
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1", org_id, record_date).Find(&patients).Error

	for _, item := range patients {
		for _, sumItem := range item.HisPatient {
			if len(sumItem.VMHisOrders) > 0 {
				sumItem.VMHisOrder.OrderStatus = sumItem.VMHisOrders[len(sumItem.VMHisOrders)-1].OrderStatus
			}
		}

	}

	return
}

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

type CustomInComeStatistics struct {
	PsnName            string  `gorm:"column:psn_name" json:"psn_name" form:"psn_name"`
	SetlTime           string  `gorm:"column:setl_time" json:"setl_time" form:"setl_time"`
	SettleAccountsDate string  `gorm:"column:settle_accounts_date" json:"settle_accounts_date" form:"settle_accounts_date"`
	MedfeeSumamt       float64 `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
	FundPaySumamt      float64 `gorm:"column:fund_pay_sumamt" json:"fund_pay_sumamt" form:"fund_pay_sumamt"`
	HifobPay           float64 `gorm:"column:hifob_pay" json:"hifob_pay" form:"hifob_pay"`
	HifmiPay           float64 `gorm:"column:hifmi_pay" json:"hifmi_pay" form:"hifmi_pay"`
	HifesPay           float64 `gorm:"column:hifes_pay" json:"hifes_pay" form:"hifes_pay"`
	MafPay             float64 `gorm:"column:maf_pay" json:"maf_pay" form:"maf_pay"`
	CvlservPay         float64 `gorm:"column:cvlserv_pay" json:"cvlserv_pay" form:"cvlserv_pay"`
	PsnCashPay         float64 `gorm:"column:psn_cash_pay" json:"psn_cash_pay" form:"psn_cash_pay"`
	DiscountPrice      float64 `gorm:"column:discount_price" json:"discount_price" form:"discount_price"`
	PreferentialPrice  float64 `gorm:"column:preferential_price" json:"preferential_price" form:"preferential_price"`
	AcctPay            float64 `gorm:"column:acct_pay" json:"acct_pay" form:"acct_pay"`

	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"`
	IsPre        int64  `gorm:"column:is_pre" json:"is_pre" form:"is_pre"`
	Diagnosis    string `gorm:"column:diagnosis" json:"diagnosis" form:"diagnosis"`
}

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

func GetDayIncomeStatisticsData(org_id int64, keywords string, start_time int64, end_time int64, page int64, limit int64) (order []*CustomInComeStatistics, total int64, err error) {
	offset := (page - 1) * limit
	if len(keywords) != 0 {

		err = readDb.Model(&CustomInComeStatistics{}).Select("sum(medfee_sumamt) as medfee_sumamt,sum(`fund_pay_sumamt`) as fund_pay_sumamt, sum(`hifob_pay`) as hifob_pay, sum(`hifmi_pay`) as hifmi_pay , sum(`hifes_pay`) as hifes_pay, sum(`maf_pay`) as maf_pay,sum(`cvlserv_pay`) as cvlserv_pay, sum(`discount_price`) as discount_price, sum(`preferential_price`) as preferential_price,sum(`acct_pay`)  as acct_pay,FROM_UNIXTIME(settle_accounts_date,'%Y-%m-%d') as settle_accounts_date").Where("user_org_id = ? AND status = 1 AND order_status = 2  ", org_id).Group("settle_accounts_date").Count(&total).Offset(offset).Limit(limit).Order("settle_accounts_date").Find(&order).Error

	} else {

		if start_time != 0 && end_time != 0 {
			err = readDb.Model(&CustomInComeStatistics{}).Select("sum(medfee_sumamt) as medfee_sumamt,sum(`fund_pay_sumamt`) as fund_pay_sumamt, sum(`hifob_pay`) as hifob_pay, sum(`hifmi_pay`) as hifmi_pay , sum(`hifes_pay`) as hifes_pay, sum(`maf_pay`) as maf_pay,sum(`cvlserv_pay`) as cvlserv_pay, sum(`discount_price`) as discount_price, sum(`preferential_price`) as preferential_price,sum(`acct_pay`)  as acct_pay,FROM_UNIXTIME(settle_accounts_date,'%Y-%m-%d') as settle_accounts_date").Where("user_org_id = ? AND status = 1 AND order_status = 2  AND settle_accounts_date >= ? AND settle_accounts_date <= ?", org_id, start_time, end_time).Group("settle_accounts_date").Count(&total).Offset(offset).Limit(limit).Order("settle_accounts_date").Find(&order).Error
		} else {
			err = readDb.Model(&CustomInComeStatistics{}).Select("sum(medfee_sumamt) as medfee_sumamt,sum(`fund_pay_sumamt`) as fund_pay_sumamt, sum(`hifob_pay`) as hifob_pay, sum(`hifmi_pay`) as hifmi_pay , sum(`hifes_pay`) as hifes_pay, sum(`maf_pay`) as maf_pay,sum(`cvlserv_pay`) as cvlserv_pay, sum(`discount_price`) as discount_price, sum(`preferential_price`) as preferential_price,sum(`acct_pay`)  as acct_pay,FROM_UNIXTIME(settle_accounts_date,'%Y-%m-%d') as settle_accounts_date").Where("user_org_id = ? AND status = 1 AND order_status = 2  ", org_id).Group("settle_accounts_date").Count(&total).Offset(offset).Limit(limit).Order("settle_accounts_date").Find(&order).Error

		}

	}

	return
}

func GetDayIncomeDetailStatisticsData(org_id int64, keywords string, start_time int64, end_time int64, page int64, limit int64) (cis []*CustomInComeStatistics, total int64, err error) {
	offset := (page - 1) * limit
	if len(keywords) != 0 {
		err = readDb.Model(&CustomInComeStatistics{}).Select("psn_name,setl_time,medfee_sumamt,fund_pay_sumamt, hifob_pay,  hifmi_pay ,  hifes_pay,  maf_pay, cvlserv_pay, discount_price,preferential_price,acct_pay,FROM_UNIXTIME(settle_accounts_date,'%Y-%m-%d') as settle_accounts_date").Where("user_org_id = ? AND status = 1 AND order_status = 2  ", org_id).Count(&total).Offset(offset).Limit(limit).Order("settle_accounts_date").Find(&cis).Error
	} else {
		if start_time != 0 && end_time != 0 {
			err = readDb.Model(&CustomInComeStatistics{}).Select("psn_name,setl_time,medfee_sumamt,fund_pay_sumamt, hifob_pay,  hifmi_pay ,  hifes_pay,  maf_pay, cvlserv_pay, discount_price,preferential_price,acct_pay,FROM_UNIXTIME(settle_accounts_date,'%Y-%m-%d') as settle_accounts_date").Where("user_org_id = ? AND status = 1 AND order_status = 2 AND  settle_accounts_date >= ? AND settle_accounts_date <= ?  ", org_id, start_time, end_time).Count(&total).Offset(offset).Limit(limit).Order("settle_accounts_date").Find(&cis).Error
		} else {
			err = readDb.Model(&CustomInComeStatistics{}).Select("psn_name,setl_time,medfee_sumamt,fund_pay_sumamt, hifob_pay,  hifmi_pay ,  hifes_pay,  maf_pay, cvlserv_pay, discount_price,preferential_price,acct_pay,FROM_UNIXTIME(settle_accounts_date,'%Y-%m-%d') as settle_accounts_date").Where("user_org_id = ? AND status = 1 AND order_status = 2", org_id).Count(&total).Offset(offset).Limit(limit).Order("settle_accounts_date").Find(&cis).Error
		}
	}
	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 CreateHisPrescriptionTemplate(template *models.HisPrescriptionTemplate) (err error) {
	err = writeDb.Create(&template).Error
	return

}

func CreateHisPrescriptionAdviceTemplate(s *models.HisPrescriptionAdviceTemplate) (err error) {
	err = writeDb.Save(&s).Error
	return
}

func CreateHisPrescriptionInfoTemplate(s *models.HisPrescriptionInfoTemplate) (err error) {
	err = writeDb.Save(&s).Error
	return
}

func CreateHisPrescriptionProjectTemplate(project *models.HisPrescriptionProjectTemplate) (err error) {
	err = writeDb.Save(&project).Error
	return
}

func GetPatientSch(patient_id int64, sch_date int64, org_id int64) (sch models.Schedule, err error) {
	err = readDb.Model(&models.Schedule{}).Where("user_org_id = ? AND patient_id = ? AND schedule_date = ? AND status = 1", org_id, patient_id, sch_date).First(&sch).Error
	return
}

func GetHisPrescriptionBySchMode(mode_id int64, patient_id int64, org_id int64) (prescription models.HisPrescriptionTemplate, err error) {
	err = readDb.Model(&models.HisPrescriptionTemplate{}).Where("user_org_id = ? AND status = 1 AND mode = ? AND patient_id = ?", org_id, mode_id, patient_id).Last(&prescription).Error
	return
}

func GetHisPrescriptionTemplate(template_id int64, org_id int64) (prescription []*models.HisPrescriptionInfoTemplate, err error) {
	err = readDb.Model(&models.HisPrescriptionInfoTemplate{}).
		Preload("HisPrescriptionAdviceTemplate", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("Drug", "status=1")
		}).
		Preload("HisPrescriptionProjectTemplate", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 AND user_org_id = ?", org_id).Preload("XtHisProject").Preload("GoodInfo", "status=1")
		}).
		Where("status = 1 AND p_template_id = ? ", template_id).
		Find(&prescription).Error
	return
}

func FindHisConsumablesByID(orgID int64, patient_id int64, recordDate int64, good_id int64) (consumables models.DialysisBeforePrepare, err error) {
	err = readDb.Model(&models.DialysisBeforePrepare{}).Where("user_org_id = ? AND patient_id = ? AND record_date = ? AND status = 1 AND good_id = ?", orgID, patient_id, recordDate, good_id).First(&consumables).Error
	return
}

func UpdateConsumables(consumables *models.DialysisBeforePrepare) (err error) {
	err = writeDb.Save(&consumables).Error
	return
}

func GetHisPrescriptionProjectsByID(id int64) (projects []*models.HisPrescriptionProject, err error) {
	err = readDb.Model(&models.HisPrescriptionProject{}).Preload("GoodInfo", "status = 1").Where("prescription_id = ? AND status = 1", id).Find(&projects).Error
	return
}

func GetHisPrescriptionProjects(user_org_id int64, patient_id int64, record_time int64) (projects []*models.HisPrescriptionProject, err error) {
	err = readDb.Model(&models.HisPrescriptionProject{}).Preload("HisProject", "status = 1").Preload("GoodInfo", "status = 1").Where("user_org_id = ? AND patient_id = ? AND record_date = ? AND  status = 1", user_org_id, patient_id, record_time).Find(&projects).Error
	return
}

func GetHisPrescriptionProjectByID(id int64) (projects models.HisPrescriptionProject, err error) {
	err = readDb.Model(&models.HisPrescriptionProject{}).Preload("GoodInfo", "status = 1").Where("id = ? AND status = 1", id).First(&projects).Error
	return
}

func GetHisPrescriptionAdviceByID(id int64) (advices []*models.HisDoctorAdviceInfo, err error) {
	err = readDb.Model(&models.HisDoctorAdviceInfo{}).Where("prescription_id = ? AND status = 1", id).Find(&advices).Error
	return
}

func UpdateGoodInfo(good_info *models.GoodInfo) (err error) {
	err = writeDb.Save(&good_info).Error
	return
}

func GetUnChargeMonthHisPrescriptionSix(org_id int64, patient_id int64, start_date int64, end_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ?  AND p_type = ? AND order_status <> 2 ", org_id, start_date, end_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

func GetChargeMonthHisPrescriptionSix(org_id int64, patient_id int64, start_date int64, end_date int64, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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("user_org_id = ? AND status = 1 AND record_date >= ? AND record_date <= ? AND patient_id = ?  AND p_type = ? AND order_status = 2 ", org_id, start_date, end_date, patient_id, p_type).
		Find(&prescription).Error
	return
}

func GetChargeHisPrescriptionSeven(org_id int64, patient_id int64, order_number string, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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")
		}).Preload("TempHisOrder", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ?", org_id)
	}).
		Where("user_org_id = ? AND status = 1  AND patient_id = ? AND order_status = 2 AND batch_number = ? AND p_type = ?", org_id, patient_id, order_number, p_type).
		Find(&prescription).Error
	return
}

//已收费
func GetChargeMonthHisPrescriptionFive(org_id int64, patient_id int64, order_number string, p_type int64) (prescription []*models.HisPrescription, err error) {
	err = readDb.Model(&models.HisPrescription{}).
		Preload("HisAdditionalCharge", func(db *gorm.DB) *gorm.DB {
			return db.Where("status = 1 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("Drug", "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")
		}).Preload("TempHisOrder", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ?", org_id)
	}).
		Where("user_org_id = ? AND status = 1 AND batch_number = ? AND patient_id = ? AND order_status = 2 AND p_type = ?", org_id, order_number, patient_id, p_type).
		Find(&prescription).Error
	return
}

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

}

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

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("Drug", "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")
		}).Preload("TempHisOrder", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ?", org_id)
	}).
		Where("id in (?) AND user_org_id = ? AND status = 1", ids, org_id).
		Find(&prescription).Error

	return
}

func GetNewAllUnChargeHisPatientListTwo(org_id int64, keywords string, record_date int64) (patients []*NewTempPatients, err error) {
	db := readDb.Model(&NewTempPatients{}).Where("xt_patients.user_org_id = ? AND xt_patients.status = 1", org_id)
	db = db.Preload("HisPatient", func(db *gorm.DB) *gorm.DB {
		return db.Where("status = 1 AND user_org_id = ? AND record_date = ?", org_id, record_date).Preload("VMHisOrders", "user_org_id = ? AND status = 1 AND settle_accounts_date = ? AND order_status <> 2", org_id, record_date)
	})
	db = db.Preload("HisPrescription", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1 AND order_status <> 2 AND order_status <> 3", org_id, record_date)
	err = db.Preload("VMHisPrescriptionInfo", "user_org_id = ? AND status = 1 AND record_date = ? AND p_type <> 1 AND prescription_status <> 3", org_id, record_date).Find(&patients).Error

	for _, item := range patients {
		for _, sumItem := range item.HisPatient {
			if len(sumItem.VMHisOrders) > 0 {
				sumItem.VMHisOrder.OrderStatus = sumItem.VMHisOrders[len(sumItem.VMHisOrders)-1].OrderStatus
			}
		}

	}

	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
}
