package statistics_service

import (
	"Xcx_New/models"
	"Xcx_New/service"
	"fmt"
	"github.com/jinzhu/gorm"
	"math"
	"strconv"
	"strings"
)

func GetOrgFirstPatientInfo(user_org_id int64) (patient *models.Patients, err error) {
	db := service.XTReadDB()
	var tempPatient models.Patients
	findErr := db.Model(&models.Patients{}).Where("user_org_id = ? AND status = 1 AND lapseto = 1", user_org_id).Last(&tempPatient).Error
	if findErr == gorm.ErrRecordNotFound {
		return nil, nil
	}
	if findErr != nil {
		return nil, findErr
	}
	return &tempPatient, nil
}

type ProcessIndexDataStruct struct {
	Date  string  `json:"date"`
	Value float64 `json:"value"`
}

//透析过程统计
func GetDialysisProcessIndexChartData(user_org_id int64, patient_id int64, start_time int64, end_time int64, statistics_type int) (datas []*ProcessIndexDataStruct, err error) {
	db := service.XTReadDB()
	switch statistics_type {
	case 1:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, weight_before as value from xt_assessment_before_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ?  AND assessment_date <= ? AND  assessment_date >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break
	case 2:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, weight_after as value from xt_assessment_after_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ?  AND assessment_date <= ? AND  assessment_date >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		break
	case 3:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, systolic_blood_pressure as value from xt_assessment_before_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ? AND  assessment_date <= ? AND  assessment_date >= ? AND systolic_blood_pressure <> 0 ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		break
	case 4:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, diastolic_blood_pressure as value from xt_assessment_before_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ?  AND assessment_date <= ? AND  assessment_date >= ?  AND diastolic_blood_pressure <> 0", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		break
	case 5:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, pulse_frequency as value from xt_assessment_before_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ?  AND assessment_date <= ? AND  assessment_date >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		break
	case 6:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, systolic_blood_pressure as value from xt_assessment_after_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ? AND assessment_date <= ? AND  assessment_date >= ?  AND systolic_blood_pressure <> 0", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break
	case 7:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, diastolic_blood_pressure as value from xt_assessment_after_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ? AND assessment_date <= ? AND  assessment_date >= ? AND diastolic_blood_pressure <> 0 ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		break
	case 8:
		err = db.Raw("select from_unixtime(assessment_date,'%Y-%m-%d') as date, pulse_frequency as value from xt_assessment_after_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ? AND assessment_date <= ? AND  assessment_date >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break

	}
	if err != nil {
		return nil, err
	}
	return datas, nil

}

type otherItemAmount struct {
	Total int64  `json:"total"`
	Name  string `json:"name"`
	Ratio string `json:"ratio"`
}

func GetDialysisProcessIndexOtherChartData(user_org_id int64, patient_id int64, start_time int64, end_time int64, statistics_type int) (item []*otherItemAmount, err error) {
	db := service.XTReadDB()
	var items []*otherItemAmount
	var tempErr error
	var total int64
	switch statistics_type {
	case 9:
		tempErr = db.Table("xt_dialysis_prescription as p").Where("p.user_org_id=? and p.status=1 and  p.record_date >= ? and p.record_date <= ? AND p.patient_id = ? ", user_org_id, start_time, end_time, patient_id).
			Select("CASE WHEN p.mode_id = 1 THEN 'HD'" +
				" WHEN p.mode_id = 2 THEN 'HDF'" +
				" WHEN p.mode_id = 3 THEN 'HD+HP'" +
				" WHEN p.mode_id = 4 THEN 'HP'" +
				" WHEN p.mode_id = 5 THEN 'HF'" +
				" WHEN p.mode_id = 6 THEN 'SCUF'" +
				" WHEN p.mode_id = 7 THEN 'IUF'" +
				" WHEN p.mode_id = 8 THEN 'HFHD'" +
				" WHEN p.mode_id = 9 THEN 'HFHD+HP'" +
				" WHEN p.mode_id = 10 THEN 'PHF'" +
				" WHEN p.mode_id = 11 THEN 'HFR'" +
				" WHEN p.mode_id = 12 THEN 'HDF+HP'" +
				" WHEN p.mode_id = 13 THEN 'CRRT'" +
				" WHEN p.mode_id = 14 THEN '腹水回输'" +
				" WHEN p.mode_id = 19 THEN 'IUF+HD'" +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("p.mode_id").Scan(&items).Error

		break
	case 10:
		tempErr = db.Table("xt_dialysis_prescription as p").Where("p.user_org_id=? and p.status=1 and  p.record_date >= ? and p.record_date <= ? AND p.patient_id = ? ", user_org_id, start_time, end_time, patient_id).
			Select("CASE WHEN p.anticoagulant = 1 THEN '无肝素'" +
				" WHEN p.anticoagulant = 2 THEN '普通肝素'" +
				" WHEN p.anticoagulant = 3 THEN '低分子肝素'" +
				" WHEN p.anticoagulant = 4 THEN '阿加曲班'" +
				" WHEN p.anticoagulant = 5 THEN '枸橼酸钠'" +
				" WHEN p.anticoagulant = 6 THEN '低分子肝素钙'" +
				" WHEN p.anticoagulant = 7 THEN '低分子肝素钠'" +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("p.anticoagulant").Scan(&items).Error

		break
	}

	db.Table("xt_dialysis_prescription as p").Where("p.user_org_id=? AND p.status = 1 AND p.patient_id = ? AND p.record_date >= ? and p.record_date <= ? ", user_org_id, patient_id, start_time, end_time).Count(&total)

	for _, item := range items {
		if math.IsNaN(float64(item.Total) / float64(total)) {
			item.Ratio = "0.0"
		} else {
			float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(total))*100), 64)
			item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
		}
	}
	if tempErr != nil {
		return nil, err
	}
	return items, nil
}

type PatientDialysisRecord struct {
	models.VMSchedule
	DeviceNumber            VMDeviceNumber                 `gorm:"foreignkey:ID;AssociationForeignKey:BedId;" json:"device_number"`
	DialysisPrescription    VMDialysisPrescription         `json:"prescription" gorm:"foreignkey:RecordDate;AssociationForeignKey:ScheduleDate;"`
	PredialysisEvaluation   VMPredialysisEvaluation        `json:"predialysis_evaluation" gorm:"foreignkey:AssessmentDate;AssociationForeignKey:ScheduleDate;"`
	AssessmentAfterDislysis models.AssessmentAfterDislysis `json:"assessment_after_dislysis" gorm:"foreignkey:AssessmentDate;AssociationForeignKey:ScheduleDate;"`
	Patient                 VMPatients                     `json:"patient" gorm:"foreignkey:ID;AssociationForeignKey:PatientID;"`
}

func GetDialysisProcessIndexTableData(orgID, patientID int64, page, limit, start, end int64) ([]*PatientDialysisRecord, int64, error) {
	offset := (page - 1) * limit
	var total int64
	var err error
	var orders []*PatientDialysisRecord
	readDb := service.XTReadDB()
	db := readDb.Table("xt_schedule as sch").
		Preload("DeviceNumber", "org_id=? and status=1", orgID).
		Preload("DialysisPrescription", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
		Preload("PredialysisEvaluation", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
		Preload("AssessmentAfterDislysis", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
		Preload("Patient", "user_org_id=? and status=1", orgID).
		Where("sch.patient_id=? and sch.user_org_id=? and sch.status=1", patientID, orgID).Group("sch.schedule_date")
	if start != 0 {
		db = db.Where("sch.schedule_date>=?", start)
	}
	if end != 0 {
		db = db.Where("sch.schedule_date<=?", end)
	}
	err = db.Count(&total).Offset(offset).Limit(limit).Order("sch.schedule_date desc").Select("sch.patient_id,sch.schedule_date,sch.bed_id,sch.user_org_id").Find(&orders).Error
	return orders, total, err
}
func GetAnticoagulantData(user_org_id int64) (config []*models.Dataconfig, tempErr error) {
	var tempDataConfig []*models.Dataconfig
	var tempConfig models.Dataconfig
	db := service.XTReadDB()
	db.Model(&models.Dataconfig{}).Where("name = '抗凝剂' AND field_name = 'anticoagulant' AND parent_id = 0").First(&tempConfig)
	err := db.Model(&models.Dataconfig{}).Where("(org_id = 0 OR org_id = ?) AND parent_id = ?", user_org_id, tempConfig.ID).Find(&tempDataConfig).Error
	return tempDataConfig, err
}

//透析过程统计

//透析监测统计
func GetDialysisWatchChartData(user_org_id int64, patient_id int64, start_time int64, end_time int64, statistics_type int) (datas []*ProcessIndexDataStruct, err error) {
	db := service.XTReadDB()
	switch statistics_type {
	case 1:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.systolic_blood_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? AND systolic_blood_pressure <> 0 Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.systolic_blood_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND  operate_time <= ? AND  operate_time >= ? AND systolic_blood_pressure <> 0 Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		}
		break
	case 2:

		if patient_id == 0 {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.diastolic_blood_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? AND diastolic_blood_pressure <> 0 Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.diastolic_blood_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND  operate_time <= ? AND  operate_time >= ? AND diastolic_blood_pressure <> 0 Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}

		break
	case 3:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.pulse_frequency as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.pulse_frequency as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}
		break
	case 4:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.breathing_rate as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.breathing_rate as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}
		break
	case 5:
		if patient_id == 0 {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.temperature as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.temperature as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND operate_time <= ? AND  operate_time >= ?Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}
		break
	case 6:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.blood_flow_volume as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND    operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.blood_flow_volume as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}
		break
	case 7:
		if patient_id == 0 {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.venous_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.venous_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}
		break
	case 8:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.arterial_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ?  AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.arterial_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		}
		break
	case 9:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.transmembrane_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.transmembrane_pressure as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ?  AND operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}

		break
	case 10:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.dialysate_temperature as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by  operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.dialysate_temperature as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ?  AND operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}

		break
	case 11:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.ultrafiltration_rate as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.ultrafiltration_rate as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ?  AND operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}

		break
	case 12:
		if patient_id == 0 {
			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.ultrafiltration_volume as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND  operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, end_time, start_time).Scan(&datas).Error

		} else {

			err = db.Raw("select from_unixtime(monitor.operate_time,'%Y-%m-%d') as date, monitor.ultrafiltration_volume as value from xt_monitoring_record as monitor Where status = 1 AND user_org_id = ? AND patient_id = ?  AND operate_time <= ? AND  operate_time >= ? Order by operate_time asc", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error

		}

		break
	}

	if err != nil {
		return nil, err
	}
	return datas, nil

}
func GetDialysisWatchTableData(orgID, patientID int64, page, limit, start, end int64) ([]*VMMonitoringRecord, int64, error) {
	offset := (page - 1) * limit
	var total int64
	var err error
	var orders []*VMMonitoringRecord
	readDb := service.XTReadDB()
	db := readDb.Table("xt_monitoring_record as mo").
		Where("  mo.user_org_id=?  and mo.status=1", orgID)
	if patientID != 0 {
		db = db.Where("mo.patient_id =?", patientID)
	}
	if start != 0 {
		db = db.Where("mo.operate_time>=?", start)
	}
	if end != 0 {
		db = db.Where("mo.operate_time<=?", end)
	}
	err = db.Count(&total).Offset(offset).Limit(limit).Order("mo.operate_time desc").Select("mo.patient_id,mo.operate_time,mo.systolic_blood_pressure, mo.diastolic_blood_pressure, mo.pulse_frequency,mo.breathing_rate,mo.temperature,mo.blood_flow_volume,mo.venous_pressure,mo.arterial_pressure,mo.transmembrane_pressure,mo.dialysate_temperature,mo.ultrafiltration_rate,mo.ultrafiltration_volume").Find(&orders).Error
	return orders, total, err
}

//透析监测统计

//透析体重统计
func GetDialysisWeightChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int) (item []*otherItemAmount, err error) {
	db := service.XTReadDB()
	var items []*otherItemAmount
	var tempErr error
	var Total int64
	switch statistics_type {
	case 1:
		db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).Count(&Total)
		tempErr = db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).
			Select("CASE WHEN dry_weight < 40 THEN '小于40kg'" +
				" WHEN dry_weight >= 40 AND dry_weight < 50 THEN '40~50kg'" +
				" WHEN dry_weight >= 50 AND dry_weight < 60 THEN '50~60kg'" +
				" WHEN dry_weight >= 60 AND dry_weight < 70 THEN '60~70kg'" +
				" WHEN dry_weight >= 70 THEN '大于70kg'" +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("name").Scan(&items).Error

		var isHasConditionOne bool = false
		var isHasConditionTwo bool = false
		var isHasConditionThree bool = false
		var isHasConditionFour bool = false
		var isHasConditionFive bool = false

		for _, item := range items {
			if item.Name == "小于40kg" {
				isHasConditionOne = true
			}
			if item.Name == "40~50kg" {
				isHasConditionTwo = true
			}

			if item.Name == "60~70kg" {
				isHasConditionThree = true
			}

			if item.Name == "大于70kg" {
				isHasConditionFour = true
			}

			if item.Name == "未知" {
				isHasConditionFive = true
			}
		}
		if !isHasConditionOne {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "小于40kg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionTwo {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "40~50kg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}
		if !isHasConditionThree {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "60~70kg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionFour {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "大于70kg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionFive {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "未知",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}

		break
	case 2:
		db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).Count(&Total)

		tempErr = db.Table("xt_assessment_before_dislysis").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).
			Select("CASE WHEN weight_before < 40 THEN '小于40kg'" +
				" WHEN weight_before >= 40 AND weight_before < 50 THEN '40~50kg'" +
				" WHEN weight_before >= 50 AND weight_before < 60 THEN '50~60kg'" +
				" WHEN weight_before >= 60 AND weight_before < 70 THEN '60~70kg'" +
				" WHEN weight_before >= 70 THEN '大于70kg'" +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("name").Scan(&items).Error

		var isHasConditionOne bool = false
		var isHasConditionTwo bool = false
		var isHasConditionThree bool = false
		var isHasConditionFour bool = false
		var isHasConditionFive bool = false

		for _, item := range items {
			if item.Name == "小于40kg" {
				isHasConditionOne = true
			}
			if item.Name == "40~50kg" {
				isHasConditionTwo = true
			}

			if item.Name == "60~70kg" {
				isHasConditionThree = true
			}

			if item.Name == "大于70kg" {
				isHasConditionFour = true
			}

			if item.Name == "未知" {
				isHasConditionFive = true
			}
		}
		if !isHasConditionOne {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "小于40kg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionTwo {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "40~50kg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}
		if !isHasConditionThree {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "60~70kg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionFour {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "大于70kg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionFive {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "未知",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}

		break
	case 3:

		//db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).Count(&Total)

		//db.Raw("Select count(*) from `xt_assessment_before_dislysis`   LEFT JOIN  `xt_assessment_after_dislysis`  On xt_assessment_before_dislysis.`patient_id` = xt_assessment_after_dislysis.`patient_id` AND xt_assessment_before_dislysis.assessment_date = xt_assessment_after_dislysis.assessment_date AND xt_assessment_after_dislysis.weight_after != 0   Where  xt_assessment_before_dislysis.user_org_id = ? AND xt_assessment_before_dislysis.created_time >= ? AND  xt_assessment_before_dislysis.created_time <= ? Order by xt_assessment_before_dislysis.assessment_date desc", user_org_id, start_time, end_time).Count(&Total)

		var newTotal int64
		type weight struct {
			WeightAfter  float64 `json:"weight_after"`
			WeightBefore float64 `json:"weight_before"`
		}
		var weights []*weight
		var weightAdd []float64
		db.Raw("Select xt_assessment_after_dislysis.weight_after as weight_after ,xt_assessment_before_dislysis.weight_before as weight_before from `xt_assessment_before_dislysis`   LEFT JOIN  `xt_assessment_after_dislysis`  On xt_assessment_before_dislysis.`patient_id` = xt_assessment_after_dislysis.`patient_id` AND xt_assessment_before_dislysis.assessment_date = xt_assessment_after_dislysis.assessment_date AND xt_assessment_after_dislysis.weight_after <> 0 AND xt_assessment_after_dislysis.user_org_id = ?  Where  xt_assessment_before_dislysis.user_org_id = ? AND xt_assessment_before_dislysis.created_time >= ? AND  xt_assessment_before_dislysis.created_time <= ? Order by xt_assessment_before_dislysis.assessment_date desc", user_org_id, user_org_id, start_time, end_time).Scan(&weights)
		for index, _ := range weights {
			if index+1 < len(weights) {
				if weights[index+1].WeightAfter == 0 || weights[index].WeightBefore == 0 {
					continue
				}
				weightAdd = append(weightAdd, weights[index].WeightBefore-weights[index+1].WeightAfter)
			}
		}

		var total_one int64
		var total_two int64
		var total_three int64
		var total_four int64
		var total_five int64

		for _, item := range weightAdd {
			if item < 1 {
				total_one++

			}

			if item >= 1 && item < 2 {
				total_two++

			}

			if item >= 2 && item < 3 {
				total_three++

			}

			if item >= 3 && item <= 4 {
				total_four++

			}

			if item > 4 {
				total_five++

			}
		}

		newTotal = total_one + total_two + total_three + total_four + total_five

		newItem := &otherItemAmount{
			Total: total_one,
			Name:  "小于1kg",
			Ratio: "0",
		}
		newItem1 := &otherItemAmount{
			Total: total_two,
			Name:  "1-2kg",
			Ratio: "0",
		}
		newItem2 := &otherItemAmount{
			Total: total_three,
			Name:  "2-3kg",
			Ratio: "0",
		}
		newItem3 := &otherItemAmount{
			Total: total_four,
			Name:  "3-4kg",
			Ratio: "0",
		}
		newItem4 := &otherItemAmount{
			Total: total_five,
			Name:  "大于4kg",
			Ratio: "0",
		}

		items = append(items, newItem)
		items = append(items, newItem1)
		items = append(items, newItem2)
		items = append(items, newItem3)
		items = append(items, newItem4)

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(newTotal)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(newTotal))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}

		break
	case 4:

		db.Table("xt_assessment_after_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).Count(&Total)

		tempErr = db.Table("xt_assessment_after_dislysis").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).
			Select("CASE WHEN weight_after < 40 THEN '小于40kg'" +
				" WHEN weight_after >= 40 AND weight_after < 50 THEN '40~50kg'" +
				" WHEN weight_after >= 50 AND weight_after < 60 THEN '50~60kg'" +
				" WHEN weight_after >= 60 AND weight_after < 70 THEN '60~70kg'" +
				" WHEN weight_after >= 70 THEN '大于70kg'" +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("name").Scan(&items).Error

		var isHasConditionOne bool = false
		var isHasConditionTwo bool = false
		var isHasConditionThree bool = false
		var isHasConditionFour bool = false
		var isHasConditionFive bool = false

		for _, item := range items {
			if item.Name == "小于40kg" {
				isHasConditionOne = true
			}
			if item.Name == "40~50kg" {
				isHasConditionTwo = true
			}

			if item.Name == "60~70kg" {
				isHasConditionThree = true
			}

			if item.Name == "大于70kg" {
				isHasConditionFour = true
			}

			if item.Name == "未知" {
				isHasConditionFive = true
			}
		}
		if !isHasConditionOne {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "小于40kg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionTwo {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "40~50kg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}
		if !isHasConditionThree {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "60~70kg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionFour {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "大于70kg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionFive {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "未知",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}

		break
	}
	if tempErr != nil {
		return nil, err
	}

	fmt.Println(items)
	return items, nil
}
func GetDialysisWeightTableData(orgID, patientID int64, page, limit, start, end int64) ([]*VMPredialysisEvaluation, int64, error) {
	offset := (page - 1) * limit
	var total int64
	var err error
	var orders []*VMPredialysisEvaluation
	readDb := service.XTReadDB()
	db := readDb.Table("xt_assessment_before_dislysis")
	db = db.Where(" user_org_id=?  and status=1", orgID)
	if patientID > 0 {
		db = db.Where("patient_id=?", patientID)
	}

	if start != 0 {
		db = db.Where("assessment_date>=?", start)
	}
	if end != 0 {
		db = db.Where("assessment_date<=?", end)
	}
	db = db.Preload("VMAssessmentAfterDislysis", "status = 1 AND user_org_id = ?", orgID).Preload("VMPatients", "status = 1 AND user_org_id = ?", orgID)
	err = db.Count(&total).Offset(offset).Limit(limit).Order("assessment_date desc").Select("dry_weight, weight_before, patient_id, assessment_date").Find(&orders).Error

	for _, item := range orders {
		after, _ := GetLastAfterWeight(orgID, item.AssessmentDate, item.PatientId)
		if after.ID > 0 {
			fmt.Println(after.WeightAfter)
			item.LastAfterWeight = after.WeightAfter
		}
	}
	return orders, total, err
}

type LastAfter struct {
	ID          int64   `json:"id"`
	WeightAfter float64 `json:"weight_after"`
}

func GetLastAfterWeight(user_org_id int64, before_assessment_date int64, patient_id int64) (after LastAfter, err error) {
	readDb := service.XTReadDB()
	err = readDb.Raw("SELECT weight_after as weight_after,id as id from xt_assessment_after_dislysis   WHERE (user_org_id = ? AND patient_id = ? AND assessment_date < ?) ORDER BY id desc,`xt_assessment_after_dislysis`.`id` ASC LIMIT 1 ", user_org_id, patient_id, before_assessment_date).Scan(&after).Error
	return
}

func GetPatientDialysisWeightChartData(user_org_id int64, patient_id int64, start_time int64, end_time int64, statistics_type int) (datas []*ProcessIndexDataStruct, err error) {
	db := service.XTReadDB()
	switch statistics_type {
	case 1:
		err = db.Raw("select from_unixtime(assessment_date, '%Y-%m-%d') as date, dry_weight as value from xt_assessment_before_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ? AND created_time <= ? AND  created_time >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break
	case 2:
		err = db.Raw("select from_unixtime(assessment_date, '%Y-%m-%d') as date, weight_before as value from xt_assessment_before_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ? AND  created_time <= ? AND  created_time >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break
	case 3:

		type weight struct {
			WeightAfter  float64 `json:"weight_after"`
			WeightBefore float64 `json:"weight_before"`
			Date         string  `json:"date"`
		}

		var weights []*weight
		db.Raw("Select xt_assessment_after_dislysis.weight_after as weight_after ,xt_assessment_before_dislysis.weight_before as weight_before,from_unixtime(xt_assessment_before_dislysis.assessment_date,'%Y-%m-%d') as date from `xt_assessment_before_dislysis`   LEFT JOIN  `xt_assessment_after_dislysis`  On xt_assessment_before_dislysis.`patient_id` = xt_assessment_after_dislysis.`patient_id` AND xt_assessment_before_dislysis.assessment_date = xt_assessment_after_dislysis.assessment_date AND xt_assessment_after_dislysis.weight_after <> 0   Where  xt_assessment_before_dislysis.user_org_id = ? AND xt_assessment_before_dislysis.created_time >= ? AND  xt_assessment_before_dislysis.created_time <= ? AND xt_assessment_before_dislysis.patient_id = ? Order by date desc", user_org_id, start_time, end_time, patient_id).Scan(&weights)
		fmt.Println(len(weights))
		for index, _ := range weights {

			if index+1 < len(weights) {
				var weight_add ProcessIndexDataStruct
				fmt.Println(weights[index+1].WeightAfter)
				fmt.Println(weights[index].WeightBefore)

				if weights[index+1].WeightAfter == 0 || weights[index].WeightBefore == 0 {
					continue
				}
				add := weights[index].WeightBefore - weights[index+1].WeightAfter
				weight_add.Value = add
				weight_add.Date = weights[index].Date
				datas = append(datas, &weight_add)

			}
		}

		break
	case 4:
		err = db.Raw("select from_unixtime(assessment_date, '%Y-%m-%d') as date, weight_after as value from xt_assessment_after_dislysis Where status = 1 AND user_org_id = ? AND patient_id = ? AND  created_time <= ? AND  created_time >= ? ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break

	}
	if err != nil {
		return nil, err
	}
	return datas, nil

}

//透析体重统计

//透析血压统计
func GetBloodPressureChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int, patient_id int64) (item []*otherItemAmount, err error) {
	db := service.XTReadDB()
	var items []*otherItemAmount
	var tempErr error
	var TotalOne int64
	var TotalTwo int64
	var Total int64

	switch statistics_type {
	case 1:
		type bp struct {
			SystolicBloodPressure  float64 `json:"systolic_blood_pressure"`
			DiastolicBloodPressure float64 `json:"diastolic_blood_pressure"`
		}
		var bps []*bp

		if patient_id == 0 {
			db.Raw("SELECT systolic_blood_pressure,diastolic_blood_pressure FROM xt_assessment_before_dislysis Where user_org_id = ? AND  created_time >= ? AND created_time <= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0   UNION ALL SELECT systolic_blood_pressure,diastolic_blood_pressure  FROM xt_assessment_after_dislysis Where user_org_id = ? AND created_time >= ? AND created_time <= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time, user_org_id, start_time, end_time).Scan(&bps)
			db.Raw("SELECT count(id) FROM xt_assessment_before_dislysis Where user_org_id = ? AND  created_time >= ? AND created_time <= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time).Count(&TotalOne)
			db.Raw("SELECT count(id) FROM xt_assessment_after_dislysis Where user_org_id = ? AND  created_time >= ? AND created_time <= ?  AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time).Count(&TotalTwo)
			Total = TotalOne + TotalTwo
			fmt.Println("----Total-----")
			fmt.Println(TotalOne)
			fmt.Println(TotalTwo)
			fmt.Println(Total)

		} else {
			db.Raw("SELECT systolic_blood_pressure,diastolic_blood_pressure FROM xt_assessment_before_dislysis Where user_org_id = ? AND  created_time >= ? AND created_time <= ? AND patient_id = ? AND AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0   UNION ALL SELECT systolic_blood_pressure,diastolic_blood_pressure  FROM xt_assessment_after_dislysis Where user_org_id = ? AND created_time >= ? AND created_time <= ? AND patient_id = ? AND AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0   ", user_org_id, start_time, end_time, patient_id, user_org_id, start_time, end_time, patient_id).Scan(&bps)
			db.Raw("SELECT count(id) FROM xt_assessment_before_dislysis Where user_org_id = ? AND  created_time >= ? AND created_time <= ? AND patient_id = ? AND  systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time, patient_id).Count(&TotalOne)
			db.Raw("SELECT count(id) FROM xt_assessment_after_dislysis Where user_org_id = ? AND  created_time >= ? AND created_time <= ? AND patient_id = ?  AND  systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time, patient_id).Count(&TotalTwo)
			Total = TotalOne + TotalTwo
			fmt.Println(TotalOne)
			fmt.Println(TotalTwo)
			fmt.Println(Total)

		}

		var total_one int64
		var total_two int64
		var total_three int64
		var total_four int64

		for _, item := range bps {
			if item.SystolicBloodPressure > 160 && item.DiastolicBloodPressure > 100 {
				total_one++
			} else if item.SystolicBloodPressure < 140 && item.DiastolicBloodPressure < 90 {
				total_two++

			} else if item.SystolicBloodPressure >= 140 && item.SystolicBloodPressure <= 160 && item.DiastolicBloodPressure >= 90 && item.DiastolicBloodPressure <= 100 {
				total_three++
			} else {

				total_four++
			}
		}

		newItem := &otherItemAmount{
			Total: total_one,
			Name:  "大于160/100mmHg",
			Ratio: "0",
		}
		newItem1 := &otherItemAmount{
			Total: total_two,
			Name:  "小于140/90mmHg",
			Ratio: "0",
		}
		newItem2 := &otherItemAmount{
			Total: total_three,
			Name:  "140-160mmHg/90-100mmHg",
			Ratio: "0",
		}
		newItem3 := &otherItemAmount{
			Total: total_four,
			Name:  "其他",
			Ratio: "0",
		}

		items = append(items, newItem)
		items = append(items, newItem1)
		items = append(items, newItem2)
		items = append(items, newItem3)

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}
		break
	case 2:
		if patient_id == 0 {
			tempErr = db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0  ", user_org_id, start_time, end_time).
				Select("CASE WHEN systolic_blood_pressure > 160 AND  diastolic_blood_pressure > 100 THEN '大于160/100mmHg'" +
					" WHEN systolic_blood_pressure < 140 AND  diastolic_blood_pressure < 90 THEN '小于140/90mmHg'" +
					" WHEN systolic_blood_pressure >= 140 AND  systolic_blood_pressure <= 160   AND  diastolic_blood_pressure >= 90 AND  diastolic_blood_pressure <= 100 THEN '140-160mmHg/90-100mmHg'" +
					" ELSE '其他' END AS name, COUNT(*) AS total",
				).Group("name").Scan(&items).Error
			db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? AND status = 1  AND created_time >= ? AND created_time <= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time).Count(&Total)

		} else {

			tempErr = db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ?  and patient_id = ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time, patient_id).
				Select("CASE WHEN systolic_blood_pressure > 160 AND  diastolic_blood_pressure > 100 THEN '大于160/100mmHg'" +
					" WHEN systolic_blood_pressure < 140 AND  diastolic_blood_pressure < 90 THEN '小于140/90mmHg'" +
					" WHEN systolic_blood_pressure >= 140 AND  systolic_blood_pressure <= 160   AND  diastolic_blood_pressure >= 90 AND  diastolic_blood_pressure <= 100 THEN '140-160mmHg/90-100mmHg'" +
					" ELSE '其他' END AS name, COUNT(*) AS total",
				).Group("name").Scan(&items).Error

			db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? AND status = 1  AND created_time >= ? AND created_time <= ? AND patient_id = ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0", user_org_id, start_time, end_time, patient_id).Count(&Total)

		}

		var isHasConditionOne bool = false
		var isHasConditionTwo bool = false
		var isHasConditionThree bool = false
		var isHasConditionFour bool = false

		for _, item := range items {
			if item.Name == "大于160/100mmHg" {
				isHasConditionOne = true
			}
			if item.Name == "小于140/90mmHg" {
				isHasConditionTwo = true
			}

			if item.Name == "140-160mmHg/90-100mmHg" {
				isHasConditionThree = true
			}
			if item.Name == "其他" {
				isHasConditionFour = true
			}
		}
		if !isHasConditionOne {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "大于160/100mmHg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionTwo {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "小于140/90mmHg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionThree {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "140-160mmHg/90-100mmHg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionFour {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "其他",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}
		break
	case 3:
		if patient_id == 0 {
			tempErr = db.Table("xt_assessment_after_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time).
				Select("CASE WHEN systolic_blood_pressure > 160 AND  diastolic_blood_pressure > 100 THEN '大于160/100mmHg'" +
					" WHEN systolic_blood_pressure < 140 AND  diastolic_blood_pressure < 90 THEN '小于140/90mmHg'" +
					" WHEN systolic_blood_pressure >= 140 AND  systolic_blood_pressure <= 160   AND  diastolic_blood_pressure >= 90 AND  diastolic_blood_pressure <= 100 THEN '140-160mmHg/90-100mmHg'" +
					" ELSE '其他' END AS name, COUNT(*) AS total",
				).Group("name").Scan(&items).Error
			db.Table("xt_assessment_after_dislysis").Where("user_org_id=? AND status = 1  AND created_time >= ? AND created_time <= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time).Count(&Total)

		} else {
			tempErr = db.Table("xt_assessment_after_dislysis ").Where("user_org_id=? and status=1 and  created_time >= ? and created_time <= ? and patient_id = ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0", user_org_id, start_time, end_time, patient_id).
				Select("CASE WHEN systolic_blood_pressure > 160 AND  diastolic_blood_pressure > 100 THEN '大于160/100mmHg'" +
					" WHEN systolic_blood_pressure < 140 AND  diastolic_blood_pressure < 90 THEN '小于140/90mmHg'" +
					" WHEN systolic_blood_pressure >= 140 AND  systolic_blood_pressure <= 160   AND  diastolic_blood_pressure >= 90 AND  diastolic_blood_pressure <= 100 THEN '140-160mmHg/90-100mmHg'" +
					" ELSE '其他' END AS name, COUNT(*) AS total",
				).Group("name").Scan(&items).Error

			db.Table("xt_assessment_after_dislysis ").Where("user_org_id=? AND status = 1  AND created_time >= ? AND created_time <= ? AND patient_id = ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, start_time, end_time, patient_id).Count(&Total)

		}

		var isHasConditionOne bool = false
		var isHasConditionTwo bool = false
		var isHasConditionThree bool = false
		var isHasConditionFour bool = false

		for _, item := range items {
			if item.Name == "大于160/100mmHg" {
				isHasConditionOne = true
			}
			if item.Name == "小于140/90mmHg" {
				isHasConditionTwo = true
			}

			if item.Name == "140-160mmHg/90-100mmHg" {
				isHasConditionThree = true
			}
			if item.Name == "其他" {
				isHasConditionFour = true
			}
		}
		if !isHasConditionOne {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "大于160/100mmHg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionTwo {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "小于140/90mmHg",
				Ratio: "0",
			}
			items = append(items, newItem)
		}
		if !isHasConditionThree {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "140-160mmHg/90-100mmHg",
				Ratio: "0",
			}
			items = append(items, newItem)

		}

		if !isHasConditionFour {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "其他",
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}
		break
	}
	if tempErr != nil {
		return nil, err
	}
	return items, nil
}
func GetBloodPressureTableData(orgID, patientID int64, page, limit, start, end int64) ([]*VMSchedule, int64, error) {
	offset := (page - 1) * limit
	var total int64
	var err error
	var orders []*VMSchedule
	readDb := service.XTReadDB()
	db := readDb.Table("xt_schedule as sch")
	db = db.Where(" sch.user_org_id=?  and sch.status=1", orgID)
	if patientID > 0 {
		db = db.Where("sch.patient_id=?", patientID)
	}
	if start != 0 {
		db = db.Where("sch.schedule_date>=?", start)
	}
	if end != 0 {
		db = db.Where("sch.schedule_date<=?", end)
	}
	db = db.Preload("VMPredialysisEvaluation", "status = 1 AND user_org_id = ?", orgID).
		Preload("VMAssessmentAfterDislysis", "status = 1 AND user_org_id = ?", orgID).
		Preload("VMMinMonitoringRecord", func(db *gorm.DB) *gorm.DB {
			return db.Where("user_org_id = ? AND status = 1", orgID).Order("diastolic_blood_pressure ASC")
		}).
		Preload("VMMaxMonitoringRecord", func(db *gorm.DB) *gorm.DB {
			return db.Where("user_org_id = ? AND status = 1 ", orgID).Order("systolic_blood_pressure DESC")
		}).
		Preload("VMPatients", "status = 1 AND user_org_id = ?", orgID)
	err = db.Count(&total).Offset(offset).Limit(limit).Order("sch.schedule_date desc").Select(" sch.schedule_date,sch.patient_id,sch.user_org_id").Find(&orders).Error
	return orders, total, err

}

type BPDataStruct struct {
	Date                   string  `json:"date"`
	SystolicBloodPressure  float64 `json:"systolic_blood_pressure"`
	DiastolicBloodPressure float64 `json:"diastolic_blood_pressure"`
}

func GetPatientBloodPressureChartData(user_org_id int64, patient_id int64, start_time int64, end_time int64, statistics_type int) (datas []*BPDataStruct, err error) {
	db := service.XTReadDB()
	switch statistics_type {
	case 1:
		err = db.Raw("select from_unixtime(assessment_date, '%Y-%m-%d') as date, systolic_blood_pressure as systolic_blood_pressure, diastolic_blood_pressure as diastolic_blood_pressure from xt_assessment_before_dislysis  Where status = 1 AND user_org_id = ? AND patient_id = ? AND   created_time <= ? AND  created_time >= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break
	case 2:
		err = db.Raw("select from_unixtime(assessment_date, '%Y-%m-%d') as date, systolic_blood_pressure as systolic_blood_pressure, diastolic_blood_pressure as diastolic_blood_pressure from xt_assessment_after_dislysis Where status = 1 AND user_org_id = ? AND patient_id = ? AND  created_time <= ? AND  created_time >= ? AND systolic_blood_pressure <> 0 AND diastolic_blood_pressure <> 0 ", user_org_id, patient_id, end_time, start_time).Scan(&datas).Error
		break

	}
	if err != nil {
		return nil, err
	}
	return datas, nil

}

//透析血压统计

//工作量统计
func GetDoctorWorkloadChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int, admin_user_id int64) (datas []*VMUserAdminRole, err error) {
	userDb := service.UserReadDB()
	db := service.XTReadDB()
	if admin_user_id == 0 {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 2 ", user_org_id).Scan(&datas)
	} else {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 2  AND admin_user_id = ?", user_org_id, admin_user_id).Scan(&datas)
	}

	switch statistics_type {
	case 1:
		var Total int64
		db.Table("xt_dialysis_prescription as p").Joins("join xt_schedule sch On sch.schedule_date = p.record_date AND sch.patient_id = p.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("p.user_org_id = ? AND p.status = 1  AND p.record_date >= ? AND  p.record_date <= ? AND p.creater <> 0 ", user_org_id, start_time, end_time).Count(&Total)

		for _, item := range datas {
			var total int64
			db.Table("xt_dialysis_prescription as p").Joins("join xt_schedule sch On sch.schedule_date = p.record_date AND sch.patient_id = p.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("p.user_org_id = ? AND p.status = 1 AND p.creater = ? AND p.record_date >= ? AND  p.record_date <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&total)
			item.PCount = total

			if math.IsNaN(float64(item.PCount) / float64(Total)) {
				item.PRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.PCount)/float64(Total))*100), 64)
				item.PRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}
		break
	case 2:
		var Total int64
		db.Table("xt_patient_course_of_disease as course").Where("org_id = ? AND status = 1 AND record_time >= ? AND record_time <= ?", user_org_id, start_time, end_time).Count(&Total)

		for _, item := range datas {
			var total int64
			db.Table("xt_patient_course_of_disease as course").Where("org_id = ? AND status = 1 AND recorder = ? AND record_time >= ? AND record_time <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&total)
			item.CourseCount = total

			if math.IsNaN(float64(item.CourseCount) / float64(Total)) {
				item.CourseRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.CourseCount)/float64(Total))*100), 64)
				item.CourseRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}

		break
	case 3:
		var Total int64

		db.Table("xt_patient_rescue_record as rescue").Where("org_id = ? AND status = 1  AND record_time >= ? AND record_time <= ?", user_org_id, start_time, end_time).Count(&Total)

		for _, item := range datas {
			var total int64
			db.Table("xt_patient_rescue_record as rescue").Where("org_id = ? AND status = 1 AND recorder = ?  AND record_time >= ? AND record_time <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&total)
			item.RescueCount = total

			if math.IsNaN(float64(item.RescueCount) / float64(Total)) {
				item.RescueRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.RescueCount)/float64(Total))*100), 64)
				item.RescueRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}
		break
	}
	if err != nil {
		return nil, err
	}

	fmt.Println(datas)
	return datas, nil

}
func GetDoctorWorkloadTableData(user_org_id int64, start_time int64, end_time int64, admin_user_id int64) (datas []*VMUserAdminRole, err error) {
	userDb := service.UserReadDB()
	db := service.XTReadDB()
	if admin_user_id == 0 {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 2 ", user_org_id).Scan(&datas)
	} else {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 2  AND admin_user_id = ?", user_org_id, admin_user_id).Scan(&datas)
	}
	for _, item := range datas {
		var Total int64
		var TotalOne int64
		var TotalTwo int64
		db.Table("xt_dialysis_prescription as p").Joins("join xt_schedule sch On sch.schedule_date = p.record_date AND sch.patient_id = p.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("p.user_org_id = ? AND p.status = 1 AND p.creater = ?  AND p.record_date >= ? AND  p.record_date <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&Total)
		db.Table("xt_patient_course_of_disease as course").Where("org_id = ? AND status = 1 AND recorder = ? AND record_time >= ? AND record_time <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&TotalOne)
		db.Table("xt_patient_rescue_record as rescue").Where("org_id = ? AND status = 1 AND recorder = ? AND record_time >= ? AND record_time <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&TotalTwo)
		item.PCount = Total
		item.CourseCount = TotalOne
		item.RescueCount = TotalTwo
	}
	if err != nil {
		return nil, err
	}
	return datas, nil

}
func GetNurseWorkloadChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int, admin_user_id int64) (datas []*VMUserAdminRole, err error) {
	userDb := service.UserReadDB()
	db := service.XTReadDB()

	if admin_user_id == 0 {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 3 ", user_org_id).Scan(&datas)
	} else {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 3  AND admin_user_id = ?", user_org_id, admin_user_id).Scan(&datas)
	}

	var NewTotalOne int64
	var NewTotalThree int64
	var NewTotalFour int64

	var NewTotalFive int64
	var NewTotalSix int64
	var NewTotalSeven int64
	var NewTotalEight int64

	db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ?", user_org_id, start_time, end_time).Count(&NewTotalOne)
	db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ?", user_org_id, start_time, end_time).Count(&NewTotalFive)
	db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ?", user_org_id, start_time, end_time).Count(&NewTotalSix)
	db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ?", user_org_id, start_time, end_time).Count(&NewTotalSeven)
	db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ?", user_org_id, start_time, end_time).Count(&NewTotalEight)
	db.Table("xt_monitoring_record as monitor ").Joins("join xt_schedule sch On sch.schedule_date = monitor.monitoring_date AND sch.patient_id = monitor.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("monitor.user_org_id = ? AND monitor.status = 1  AND monitor.monitoring_date >= ? AND monitor.monitoring_date <= ?", user_org_id, start_time, end_time).Count(&NewTotalThree)
	db.Table("xt_treatment_summary as summary").Joins("join xt_schedule sch On sch.schedule_date = summary.assessment_date AND sch.patient_id = summary.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("summary.user_org_id = ? AND summary.status = 1  AND summary.assessment_date >= ? AND summary.assessment_date <= ?", user_org_id, start_time, end_time).Count(&NewTotalFour)

	switch statistics_type {
	case 2:
		for _, item := range datas {
			var Total int64
			db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.puncture_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&Total)
			item.PunctureCount = Total
			if math.IsNaN(float64(item.PunctureCount) / float64(NewTotalOne)) {
				item.PunctureRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.PunctureCount)/float64(NewTotalOne))*100), 64)
				item.PunctureRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}
		break
	case 1:
		for _, item := range datas {
			var Total int64
			db.Table("xt_monitoring_record as monitor").Joins("join xt_schedule sch On sch.schedule_date = monitor.monitoring_date AND sch.patient_id = monitor.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("monitor.user_org_id = ? AND monitor.status = 1 AND monitor.monitoring_nurse = ?  AND monitor.monitoring_date >= ? AND monitor.monitoring_date <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&Total)
			item.CureCount = Total
			if math.IsNaN(float64(item.CureCount) / float64(NewTotalThree)) {
				item.CureRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.CureCount)/float64(NewTotalThree))*100), 64)
				item.CureRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}
		break

	case 3:
		for _, item := range datas {
			var Total int64
			db.Table("xt_treatment_summary as summary ").Joins("join xt_schedule sch On sch.schedule_date = summary.assessment_date AND sch.patient_id = summary.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("summary.user_org_id = ? AND summary.status = 1 AND summary.creater = ?  AND summary.assessment_date >= ? AND summary.assessment_date <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&Total)
			item.MissionCount = Total
			if math.IsNaN(float64(item.MissionCount) / float64(NewTotalFour)) {
				item.MissionRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.MissionCount)/float64(NewTotalFour))*100), 64)
				item.MissionRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}
		break

	case 4:
		for _, item := range datas {
			var Total int64
			db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.change_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&Total)
			item.ChangeNuserCount = Total
			if math.IsNaN(float64(item.ChangeNuserCount) / float64(NewTotalFive)) {
				item.ChangeRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.ChangeNuserCount)/float64(NewTotalFive))*100), 64)
				item.ChangeRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}

		break

	case 5:
		for _, item := range datas {
			var Total int64
			db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.difficult_puncture_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&Total)
			item.DiffiCultPuntureNuserCount = Total
			if math.IsNaN(float64(item.DiffiCultPuntureNuserCount) / float64(NewTotalSix)) {
				item.DiffiCultNuserRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.DiffiCultPuntureNuserCount)/float64(NewTotalSix))*100), 64)
				item.DiffiCultNuserRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}
		break

	case 6:
		for _, item := range datas {
			var Total int64
			db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.new_fistula_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&Total)
			item.NewNuserCount = Total
			if math.IsNaN(float64(item.NewNuserCount) / float64(NewTotalSeven)) {
				item.NewNuserRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.NewNuserCount)/float64(NewTotalSeven))*100), 64)
				item.NewNuserRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}
		break

	case 7:
		for _, item := range datas {
			var Total int64
			db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.start_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&Total)
			item.StartNuserCount = Total
			if math.IsNaN(float64(item.StartNuserCount) / float64(NewTotalEight)) {
				item.StartNuserRatio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.StartNuserCount)/float64(NewTotalEight))*100), 64)
				item.StartNuserRatio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}

		}
		break

	}

	if err != nil {
		return nil, err
	}
	return datas, nil

}
func GetNurseWorkloadTableData(user_org_id int64, start_time int64, end_time int64, admin_user_id int64, page int64, limit int64) (datas []*VMUserAdminRole, AdminTotal int64, err error) {
	userDb := service.UserReadDB()
	db := service.XTReadDB()
	//var tempConfig models.Dataconfig
	offset := (page - 1) * limit

	//db.Model(&models.Dataconfig{}).Where("name = '血管通路' AND module = 'hemodialysis' AND field_name = 'vascular_access_desc' AND parent_id = 0").First(&tempConfig)

	if admin_user_id == 0 {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 3 ", user_org_id).Offset(offset).Limit(limit).Scan(&datas)
	} else {
		userDb.Raw("select admin_user_id, user_name,org_id  from sgj_user_admin_role  Where status = 1 AND org_id = ?  AND user_type = 3  AND admin_user_id = ?", user_org_id, admin_user_id).Scan(&datas)
	}

	for _, item := range datas {
		var Total int64
		var TotalTwo int64
		var TotalThree int64
		var TotalFour int64
		var TotalFive int64
		var TotalSix int64
		var TotalSeven int64
		//db.Raw("select count(*) as total from  (select d.patient_id as patient, d.id, d.`assessment_date` as date,config.name as name from  xt_assessment_before_dislysis as d  JOIN `xt_data_config` config on  d.`blood_access_part_opera_id` = config.value AND config.org_id = ? AND config.parent_id = ? AND FIND_IN_SET('内瘘',config.name) > 0 Where d.user_org_id = ? AND d.assessment_date >=? AND d.assessment_date <= ?  Group by d.id)  b JOIN `xt_dialysis_order`  on xt_dialysis_order.`dialysis_date` = b.date AND xt_dialysis_order.user_org_id = ? AND xt_dialysis_order.status = 1  AND xt_dialysis_order.start_nurse = ? AND xt_dialysis_order.dialysis_date >= ? AND xt_dialysis_order.dialysis_date <= ? ", user_org_id, tempConfig.ID, user_org_id, start_time, end_time, user_org_id, item.AdminUserId, start_time, end_time).Count(&Total)
		//db.Raw("select count(*) as total_one from  (select d.patient_id as patient, d.id, d.`assessment_date` as date,config.name as name from  xt_assessment_before_dislysis as d  JOIN `xt_data_config` config on  d.`blood_access_part_opera_id` = config.value AND config.org_id = ? AND config.parent_id = ? AND FIND_IN_SET('导管',config.name) > 0 Where  d.user_org_id = ?  AND d.assessment_date >=? AND d.assessment_date <= ?  Group by d.id)  b JOIN `xt_dialysis_order`  on xt_dialysis_order.`dialysis_date` = b.date AND xt_dialysis_order.user_org_id = ? AND xt_dialysis_order.status = 1  AND xt_dialysis_order.start_nurse = ? AND xt_dialysis_order.dialysis_date >= ? AND xt_dialysis_order.dialysis_date <= ? ", user_org_id, tempConfig.ID, user_org_id, start_time, end_time, user_org_id, item.AdminUserId, start_time, end_time).Count(&TotalOne)
		db.Table("xt_monitoring_record as monitor ").Joins("join xt_schedule sch On sch.schedule_date = monitor.monitoring_date AND sch.patient_id = monitor.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("monitor.user_org_id = ? AND monitor.status = 1 AND monitor.monitoring_nurse = ? AND monitor.monitoring_date >= ? AND monitor.monitoring_date <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&TotalTwo)
		db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.puncture_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&Total)
		db.Table("xt_treatment_summary as summary").Joins("join xt_schedule sch On sch.schedule_date = summary.assessment_date AND sch.patient_id = summary.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("summary.user_org_id = ? AND summary.status = 1 AND summary.creater = ? AND summary.assessment_date >= ? AND summary.assessment_date <= ?", user_org_id, item.AdminUserId, start_time, end_time).Count(&TotalThree)

		db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.change_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&TotalFour)
		db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.difficult_puncture_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&TotalFive)
		db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.new_fistula_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&TotalSix)
		db.Table("xt_dialysis_order as o").Joins("join xt_schedule sch On sch.schedule_date = o.dialysis_date AND sch.patient_id = o.patient_id AND sch.user_org_id = ? AND sch.status = 1", user_org_id).Where("o.user_org_id = ? AND o.status = 1  AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND o.start_nurse = ?", user_org_id, start_time, end_time, item.AdminUserId).Count(&TotalSeven)

		item.PunctureCount = Total
		item.CureCount = TotalTwo
		item.MissionCount = TotalThree
		item.ChangeNuserCount = TotalFour
		item.DiffiCultPuntureNuserCount = TotalFive
		item.NewNuserCount = TotalSix
		item.StartNuserCount = TotalSeven
	}

	if err != nil {
		return nil, AdminTotal, err
	}
	return datas, AdminTotal, nil

}

//工作量统计
type AdminUser struct {
	ID          int64  `gorm:"column:id" json:"id" form:"id"`
	AdminUserId int64  `gorm:"column:admin_user_id" json:"admin_user_id" form:"admin_user_id"`
	OrgId       int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
	UserName    string `gorm:"column:user_name" json:"user_name" form:"user_name"`
	UserType    int64  `gorm:"column:user_type" json:"user_type" form:"user_type"`
}

func GetAllAdminUser(user_org_id int64) (datas []*AdminUser, err error) {
	userDb := service.UserReadDB()
	userDb.Raw("select id, admin_user_id, user_name,org_id, user_type  from sgj_user_admin_role  Where status = 1 AND org_id = ?", user_org_id).Scan(&datas)
	return datas, nil

}

//func FindOrgInspectionCount(user_org_id int64) (count int64, err error) {
//	db := service.XTReadDB()
//	err = db.Model(&models.QualityControlStandard{}).Where("status = 1 AND org_id = ? ", user_org_id).Count(&count).Error
//	return
//}

type InspectionReference struct {
	ID          int64  `gorm:"column:id" json:"id" form:"id"`
	OrgId       int64  `gorm:"column:org_id" json:"org_id" form:"org_id"`
	ProjectName string `gorm:"column:project_name" json:"project_name" form:"project_name"`
	Project     string `gorm:"column:project" json:"project" form:"project"`
	ProjectId   int64  `gorm:"column:project_id" json:"project_id" form:"project_id"`
	ItemName    string `gorm:"column:item_name" json:"item_name" form:"item_name"`
	RangeType   int64  `gorm:"column:range_type" json:"range_type" form:"range_type"`
	RangeMin    string `gorm:"column:range_min" json:"range_min" form:"range_min"`
	RangeMax    string `gorm:"column:range_max" json:"range_max" form:"range_max"`
	RangeValue  string `gorm:"column:range_value" json:"range_value" form:"range_value"`
	Unit        string `gorm:"column:unit" json:"unit" form:"unit"`
	Status      int64  `gorm:"column:status" json:"status" form:"status"`
}

func FindOrgQualityControlStandardInspectionReference(user_org_id int64) (references []*InspectionReference, err error) {
	db := service.XTReadDB()
	err = db.Raw("SELECT reference.project_name AS project_name,qcs.inspection_major AS project_id, qcs.inspection_minor AS id,reference.item_name AS item_name,qcs.range_type AS range_type,reference.range_min AS range_min,reference.range_max AS range_max,reference.unit AS  unit,qcs.range_value AS range_value  FROM xt_quality_control_standard qcs LEFT JOIN xt_inspection_reference reference ON  qcs.inspection_major = reference.project_id AND  ( qcs.inspection_minor = reference.item_id  AND reference.org_id = ?)  OR (org_id = 0 AND qcs.inspection_minor = reference.id )  WHERE qcs.user_org_id = ? AND qcs.status = 1 AND reference.status = 1", user_org_id, user_org_id).Scan(&references).Error
	return
}

func FindOrgInspectionReference(user_org_id int64, range_type int) (references []*models.InspectionReference, err error) {
	db := service.XTReadDB()
	if range_type == 1 {

		err = db.Model(&models.InspectionReference{}).Where("status = 1 AND org_id = ? AND range_type = 1 AND  (range_min REGEXP '[^0-9.]') = 0  AND  (range_max REGEXP '[^0-9.]') = 0 ", user_org_id).Find(&references).Error

	} else {
		err = db.Model(&models.InspectionReference{}).Where("status = 1 AND org_id = ? AND range_type = 2", user_org_id).Find(&references).Error

	}
	return
}

func FindProcjectInspectionReference(user_org_id int64, project_id int64, item_id int64) (references models.InspectionReference, err error) {
	db := service.XTReadDB()
	err = db.Model(&models.InspectionReference{}).Where("status = 1 AND org_id = ? AND project_id = ? AND id = ?", user_org_id, project_id, item_id).First(&references).Error
	return
}

func FindOrgInspectionReferenceRangeTypeValue(user_org_id int64, project_id int64, item_id int64) (inspection []*models.Inspection, err error) {
	db := service.XTReadDB()
	err = db.Model(&models.Inspection{}).Where("status = 1 AND org_id = ? AND project_id = ? AND item_id = ? ", user_org_id, project_id, item_id).Group("inspect_value").Find(&inspection).Error
	return
}

func FindOrgConfigRangeTypeValue(user_org_id int64, project_id int64, item_id int64) (qcs models.InspectionReference, err error) {
	db := service.XTReadDB()
	err = db.Model(&models.InspectionReference{}).Where("status = 1 AND org_id = ? AND project_id = ? AND id = ?", user_org_id, project_id, item_id).First(&qcs).Error
	return
}

func GetInspectionChartData(user_org_id int64, start_time int64, end_time int64, project_id int64, item_id int64, range_type int, range_value string) (item []*otherItemAmount, err error) {
	db := service.XTReadDB()
	var items []*otherItemAmount
	var tempErr error
	var Total int64
	selectContent := "CASE"
	range_value_arr := strings.Split(range_value, ",")

	db.Table("xt_inspection").Where("org_id=? and status=1 and  inspect_date >= ? and inspect_date <= ? AND project_id = ? AND item_id = ? AND inspect_value <> '' ", user_org_id, start_time, end_time, project_id, item_id).Count(&Total)

	if range_type == 1 {

		tempErr = db.Table("xt_inspection").Where("org_id=? and status=1 and  inspect_date >= ? and inspect_date <= ? AND project_id = ? AND item_id = ? AND inspect_value <> ''", user_org_id, start_time, end_time, project_id, item_id).
			Select("CASE WHEN inspect_value < " + range_value_arr[0] + " THEN " + "'" + "小于" + range_value_arr[0] + "'" +
				" WHEN inspect_value >= " + range_value_arr[0] + " AND  inspect_value <= " + range_value_arr[1] + " THEN " + "'" + range_value_arr[0] + "~" + range_value_arr[1] + "'" +
				" WHEN inspect_value > " + range_value_arr[1] + " THEN " + "'" + "大于" + range_value_arr[1] + "'" +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("name").Scan(&items).Error

		var isHasConditionOne bool = false
		var isHasConditionTwo bool = false
		var isHasConditionThree bool = false

		for _, item := range items {
			if item.Name == "大于"+range_value_arr[1] {
				isHasConditionOne = true
			}
			if item.Name == "小于"+range_value_arr[0] {
				isHasConditionTwo = true
			}
			if item.Name == range_value_arr[0]+"~"+range_value_arr[1] {
				isHasConditionThree = true
			}
		}
		if !isHasConditionOne {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "大于" + range_value_arr[1],
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionTwo {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "小于" + range_value_arr[0],
				Ratio: "0",
			}
			items = append(items, newItem)
		}
		if !isHasConditionThree {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  range_value_arr[0] + "～" + range_value_arr[1],
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}
		return items, tempErr

	} else {
		for _, item := range range_value_arr {
			//selectContent = selectContent + " WHEN inspect_value =" + item + " THEN " + "'" + item + "'"
			selectContent = selectContent + " WHEN inspect_value =" + "'" + item + "'" + " THEN " + "'" + item + "'"

		}
		tempErr = db.Table("xt_inspection").Where("org_id=? and status=1 and  inspect_date >= ? and inspect_date <= ? AND project_id = ? AND item_id = ? AND inspect_value <> '' ", user_org_id, start_time, end_time, project_id, item_id).
			Select(selectContent +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("name").Scan(&items).Error

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}

		return items, tempErr
	}

}

type Inspection struct {
	ID           int64           `gorm:"column:id" json:"id" form:"id"`
	PatientId    int64           `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
	OrgId        int64           `gorm:"column:org_id" json:"org_id" form:"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"`
	ItemName     string          `gorm:"column:item_name" json:"item_name" form:"item_name"`
	ProjectName  string          `gorm:"column:project_name" json:"project_name" form:"project_name"`
	InspectType  int64           `gorm:"column:inspect_type" json:"inspect_type" form:"inspect_type"`
	InspectValue string          `gorm:"column:inspect_value" json:"inspect_value" form:"inspect_value"`
	InspectDate  int64           `gorm:"column:inspect_date" json:"inspect_date" form:"inspect_date"`
	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"`
	Patient      models.Patients `gorm:"ForeignKey:ID;AssociationForeignKey:PatientId" json:"patient"`
}

func (Inspection) TableName() string {
	return "xt_inspection"
}

func GetInspectionChartTableData(user_org_id int64, start_time int64, end_time int64, project_id int64, item_id int64, patient_id int64, page, limit int64, range_type int, range_value string) (datas []*Inspection, total int64, err error) {

	if range_type == 1 {

		index := strings.Index(range_value, "小于")
		indexTwo := strings.Index(range_value, "大于")
		indexThree := strings.Index(range_value, "~")

		if index != -1 {
			value, _ := strconv.ParseFloat(strings.Replace(range_value, "小于", "", 1), 64)
			db := service.XTReadDB()
			offset := (page - 1) * limit
			err = db.Model(&Inspection{}).Where("org_id = ? AND status = 1 AND inspect_date >= ? AND inspect_date <= ?  AND project_id = ? AND item_id = ? AND status = 1  AND inspect_value < ?", user_org_id, start_time, end_time, project_id, item_id, value).Preload("Patient", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", user_org_id)
			}).Count(&total).Offset(offset).Limit(limit).Find(&datas).Error
			return datas, total, err
		} else if indexTwo != -1 {
			value, _ := strconv.ParseFloat(strings.Replace(range_value, "大于", "", 1), 64)

			db := service.XTReadDB()
			offset := (page - 1) * limit
			err = db.Model(&Inspection{}).Where("org_id = ? AND status = 1 AND inspect_date >= ? AND inspect_date <= ?  AND project_id = ? AND item_id = ? AND status = 1  AND inspect_value > ?", user_org_id, start_time, end_time, project_id, item_id, value).Preload("Patient", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", user_org_id)
			}).Count(&total).Offset(offset).Limit(limit).Find(&datas).Error
			return datas, total, err
		} else if indexThree != -1 {
			range_value_arr := strings.Split(range_value, "~")
			fmt.Println(range_value_arr)

			float1, err := strconv.ParseFloat(range_value_arr[0], 64)
			float2, err := strconv.ParseFloat(range_value_arr[1], 64)
			fmt.Println(err)
			fmt.Println(float1)

			fmt.Println(float2)

			db := service.XTReadDB()
			offset := (page - 1) * limit
			err = db.Model(&Inspection{}).Where("org_id = ? AND status = 1 AND inspect_date >= ? AND inspect_date <= ?  AND project_id = ? AND item_id = ? AND status = 1  AND inspect_value >= ? AND inspect_value <= ?", user_org_id, start_time, end_time, project_id, item_id, float1, float2).Preload("Patient", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", user_org_id)
			}).Count(&total).Offset(offset).Limit(limit).Find(&datas).Error
			return datas, total, err
		} else {
			db := service.XTReadDB()
			offset := (page - 1) * limit
			err = db.Model(&Inspection{}).Where("org_id = ? AND status = 1 AND inspect_date >= ? AND inspect_date <= ?  AND project_id = ? AND item_id = ? AND status = 1 ", user_org_id, start_time, end_time, project_id, item_id).Preload("Patient", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", user_org_id)
			}).Count(&total).Offset(offset).Limit(limit).Find(&datas).Error
			return datas, total, err
		}

	} else {

		if range_value == "全部" {
			db := service.XTReadDB()
			offset := (page - 1) * limit
			err = db.Model(&Inspection{}).Where("org_id = ? AND status = 1 AND inspect_date >= ? AND inspect_date <= ?  AND project_id = ? AND item_id = ? AND status = 1   ", user_org_id, start_time, end_time, project_id, item_id).Preload("Patient", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", user_org_id)
			}).Count(&total).Offset(offset).Limit(limit).Find(&datas).Error
			return datas, total, err

		} else {

			db := service.XTReadDB()
			offset := (page - 1) * limit
			err = db.Model(&Inspection{}).Where("org_id = ? AND status = 1 AND inspect_date >= ? AND inspect_date <= ?  AND project_id = ? AND item_id = ? AND status = 1  AND inspect_value = ?", user_org_id, start_time, end_time, project_id, item_id, range_value).Preload("Patient", func(db *gorm.DB) *gorm.DB {
				return db.Where("status = 1 AND user_org_id = ?", user_org_id)
			}).Count(&total).Offset(offset).Limit(limit).Find(&datas).Error
			return datas, total, err

		}

	}

}

type NewIndexDataStruct struct {
	Date  string `json:"date"`
	Value string `json:"value"`
}

func GetPatientInspectionChartData(user_org_id int64, start_time int64, end_time int64, project_id int64, item_id int64, patient_id int64) (datas []*NewIndexDataStruct, err error) {
	db := service.XTReadDB()
	err = db.Raw("select from_unixtime(inspect_date, '%Y-%m-%d') as date, inspect_value as value from xt_inspection  Where status = 1 AND org_id = ? AND patient_id = ? AND project_id = ? AND item_id = ? AND inspect_date <= ? AND  inspect_date >= ? Order by inspect_date asc ", user_org_id, patient_id, project_id, item_id, end_time, start_time).Scan(&datas).Error
	if err != nil {
		return nil, err
	}
	return datas, nil

}

func GetPatientInspectionBarChartData(user_org_id int64, start_time int64, end_time int64, project_id int64, item_id int64, range_type int, range_value string, patient_id int64) (item []*otherItemAmount, err error) {
	db := service.XTReadDB()
	var items []*otherItemAmount
	var tempErr error
	selectContent := "CASE"
	range_value_arr := strings.Split(range_value, ",")
	var Total int64

	db.Table("xt_inspection").Where("org_id=? and status=1 and  inspect_date >= ? and inspect_date <= ? AND project_id = ? AND item_id = ? AND patient_id = ?  AND inspect_value <> ''", user_org_id, start_time, end_time, project_id, item_id, patient_id).Count(&Total)

	if range_type == 1 {
		tempErr = db.Table("xt_inspection").Where("org_id=? and status=1 and  inspect_date >= ? and inspect_date <= ? AND project_id = ? AND item_id = ? AND patient_id = ? AND inspect_value <> ''", user_org_id, start_time, end_time, project_id, item_id, patient_id).
			Select("CASE WHEN inspect_value < " + range_value_arr[0] + " THEN " + "'" + "小于" + range_value_arr[0] + "'" +
				" WHEN inspect_value >= " + range_value_arr[0] + " AND  inspect_value <= " + range_value_arr[1] + " THEN " + "'" + range_value_arr[0] + "~" + range_value_arr[1] + "'" +
				" WHEN inspect_value > " + range_value_arr[1] + " THEN " + "'" + "大于" + range_value_arr[1] + "'" +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("name").Scan(&items).Error

		var isHasConditionOne bool = false
		var isHasConditionTwo bool = false
		var isHasConditionThree bool = false

		for _, item := range items {

			if item.Name == "大于"+range_value_arr[1] {
				isHasConditionOne = true
			}

			if item.Name == "小于"+range_value_arr[0] {
				isHasConditionTwo = true
			}

			if item.Name == range_value_arr[0]+"~"+range_value_arr[1] {
				isHasConditionThree = true
			}
		}
		if !isHasConditionOne {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "大于" + range_value_arr[1],
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		if !isHasConditionTwo {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  "小于" + range_value_arr[0],
				Ratio: "0",
			}
			items = append(items, newItem)
		}
		if !isHasConditionThree {
			newItem := &otherItemAmount{
				Total: 0,
				Name:  range_value_arr[0] + "～" + range_value_arr[1],
				Ratio: "0",
			}
			items = append(items, newItem)
		}

		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}

		return items, tempErr

	} else {

		for _, item := range range_value_arr {
			selectContent = selectContent + " WHEN inspect_value =" + "'" + item + "'" + " THEN " + "'" + item + "'"
		}
		tempErr = db.Table("xt_inspection").Where("org_id=? and status=1 and  inspect_date >= ? and inspect_date <= ? AND patient_id  = ? AND inspect_value <> '' AND project_id = ? AND item_id = ?", user_org_id, start_time, end_time, patient_id, project_id, item_id).
			Select(selectContent +
				" ELSE '未知' END AS name, COUNT(*) AS total",
			).Group("name").Scan(&items).Error
		for _, item := range items {
			if math.IsNaN(float64(item.Total) / float64(Total)) {
				item.Ratio = "0.0"
			} else {
				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
			}
		}
		return items, tempErr
	}

}

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

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

func GetOrgPatients(user_org_id int64) (patient *[]VMPatient, err error) {
	db := service.XTReadDB()
	var tempPatient []VMPatient
	findErr := db.Model(&models.Patients{}).Where("user_org_id = ? AND status = 1 AND lapseto = 1", user_org_id).Find(&tempPatient).Error
	if findErr == gorm.ErrRecordNotFound {
		return nil, nil
	}
	if findErr != nil {
		return nil, findErr
	}
	return &tempPatient, nil
}

func FindOrgQualityControlStandardInspectionReferenceById(user_org_id int64, project_id int64, item_id int64) (references InspectionReference, err error) {
	db := service.XTReadDB()
	err = db.Raw("Select reference.project_name as project_name,qcs.inspection_major as project_id, qcs.inspection_minor as id,reference.item_name as item_name,qcs.range_type as range_type,reference.range_min as range_min, reference.range_max as range_max,reference.unit as  unit,qcs.range_value as range_value   from xt_quality_control_standard qcs Left JOIN xt_inspection_reference reference ON  qcs.inspection_major = reference.project_id and qcs.inspection_minor = reference.id and  (reference.org_id = ? OR org_id = 0)  Where qcs.user_org_id = ?  AND qcs.status = 1 AND qcs.inspection_major = ? AND qcs.inspection_minor = ?", user_org_id, user_org_id, project_id, item_id).Scan(&references).Error
	return
}

func FindOrgInspectionCount(user_org_id int64) (count int64, err error) {
	db := service.XTReadDB()
	err = db.Model(&models.InspectionReference{}).Where("status = 1 AND org_id = ?", user_org_id).Count(&count).Error
	return
}

func GetOrderDialysisCount(orgid int64, startime int64, endtime int64) (order []*models.BloodDialysisOrderOne, err error) {
	db := service.XTReadDB()
	table := db.Table("xt_schedule as s")
	fmt.Println(table)
	d := db.Table("xt_patients as p")
	fmt.Println(d)
	db = db.Table("xt_dialysis_order as o").Where("o.status = 1")
	if orgid > 0 {
		db = db.Where("o.user_org_id = ?", orgid)
	}
	if startime > 0 {
		db = db.Where("o.dialysis_date>=?", startime)
	}
	if endtime > 0 {
		db = db.Where("o.dialysis_date<=?", endtime)
	}
	err = db.Group("o.start_nurse,s.mode_id").Select("s.mode_id,s.patient_id,count(s.mode_id) as count,o.start_nurse").Joins("left join xt_schedule as s on s.patient_id = o.patient_id").Joins("left join xt_patients as p on p.id = o.patient_id ").Where("s.schedule_date = o.dialysis_date and s.status = 1 and o.user_org_id = ?", orgid).Scan(&order).Error
	return order, err
}
