Browse Source

Merge branch '20230223_xt_api_new_branch' of http://git.shengws.com/csx/XT_New into 20230223_xt_api_new_branch

28169 9 months ago
parent
commit
e0bbb7fafd

+ 1 - 1
controllers/mobile_api_controllers/dialysis_api_controller.go View File

@@ -8989,7 +8989,7 @@ func RemoveRepeatedCheckRecod(arr []*models.HisPrescriptionProject) (newArr []*m
8989 8989
 	for i := 0; i < len(arr); i++ {
8990 8990
 		repeat := false
8991 8991
 		for j := i + 1; j < len(arr); j++ {
8992
-			if arr[i].TeamId == arr[j].TeamId {
8992
+			if arr[i].TeamId == arr[j].TeamId && arr[i].PrescriptionId == arr[j].PrescriptionId {
8993 8993
 				repeat = true
8994 8994
 				break
8995 8995
 			}

File diff suppressed because it is too large
+ 1494 - 23
controllers/statistics_api_controller.go


+ 1 - 0
models/dialysis.go View File

@@ -992,6 +992,7 @@ type TreatmentMode struct {
992 992
 	Status              int64  `gorm:"column:status" json:"status" form:"status"`
993 993
 	CreatedTime         int64  `gorm:"column:created_time" json:"created_time" form:"created_time"`
994 994
 	UpdatedTime         int64  `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
995
+	ModeID              int64  `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
995 996
 }
996 997
 
997 998
 func (TreatmentMode) TableName() string {

+ 1 - 0
models/patient_models.go View File

@@ -334,6 +334,7 @@ type DialysisPrescription struct {
334 334
 	TubingHemodialysis         int64         `gorm:"column:tubing_hemodialysis" json:"tubing_hemodialysis"`
335 335
 	Package                    int64         `gorm:"column:package" json:"package"`
336 336
 	ALiquid                    int64         `gorm:"column:a_liquid" json:"a_liquid"`
337
+	QCPatients                 QCPatients    `json:"patient" gorm:"foreignkey:ID;AssociationForeignKey:PatientID;"`
337 338
 	UserAdminRole              UserAdminRole `json:"role" gorm:"foreignkey:AdminUserId;AssociationForeignKey:Creater;"`
338 339
 	PreImpulse                 float64       `gorm:"column:pre_impulse" json:"pre_impulse" form:"pre_impulse"`
339 340
 	AnticoagulantStopTimeMin   int64         `gorm:"column:anticoagulant_stop_time_min" json:"anticoagulant_stop_time_min" form:"anticoagulant_stop_time_min"`

+ 116 - 0
models/qc.go View File

@@ -5,3 +5,119 @@ type CustomDialysisData struct {
5 5
 	Count int64  `json:"count"`
6 6
 	Total int64  `json:"total"`
7 7
 }
8
+
9
+type QCPrescription struct {
10
+	ID                        int64                     `gorm:"column:id" json:"id"`
11
+	UserOrgId                 int64                     `gorm:"column:user_org_id" json:"user_org_id"`
12
+	PatientId                 int64                     `gorm:"column:patient_id" json:"patient_id"`
13
+	ModeId                    int64                     `gorm:"column:mode_id" json:"mode_id"`
14
+	Status                    int64                     `gorm:"column:status" json:"status"`
15
+	CreatedTime               int64                     `gorm:"column:created_time" json:"created_time"`
16
+	UpdatedTime               int64                     `gorm:"column:updated_time" json:"updated_time"`
17
+	RecordDate                int64                     `gorm:"column:record_date" json:"record_date"`
18
+	RecordId                  int64                     `gorm:"column:record_id" json:"record_id"`
19
+	UserAdminRole             UserAdminRole             `json:"role" gorm:"foreignkey:AdminUserId;AssociationForeignKey:Creater;"`
20
+	Creater                   int64                     `gorm:"column:creater" json:"creater"`
21
+	Modifier                  int64                     `gorm:"column:modifier" json:"modifier"`
22
+	QCPatients                QCPatients                `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"patient"`
23
+	QCDialysisOrder           QCDialysisOrder           `gorm:"ForeignKey:PatientId,DialysisDate;AssociationForeignKey:PatientId,RecordDate" json:"order"`
24
+	QCAssessmentAfterDislysis QCAssessmentAfterDislysis `gorm:"ForeignKey:PatientId,AssessmentDate;AssociationForeignKey:PatientId,RecordDate" json:"ad"`
25
+}
26
+
27
+func (QCPrescription) TableName() string {
28
+	return "xt_dialysis_prescription"
29
+}
30
+
31
+type QCPatients struct {
32
+	ID         int64  `gorm:"column:id" json:"id" form:"id"`
33
+	UserOrgId  int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
34
+	Gender     int64  `gorm:"column:gender" json:"gender" form:"gender"`
35
+	DialysisNo string `gorm:"column:dialysis_no" json:"dialysis_no" form:"dialysis_no"`
36
+	Name       string `gorm:"column:name" json:"name" form:"name"`
37
+	IdCardNo   string `gorm:"column:id_card_no" json:"id_card_no" form:"id_card_no"`
38
+	Status     int64  `gorm:"column:status" json:"status" form:"status"`
39
+}
40
+
41
+func (QCPatients) TableName() string {
42
+	return "xt_patients"
43
+}
44
+
45
+type QCDialysisOrder struct {
46
+	ID             int64         `gorm:"column:id" json:"id"`
47
+	DialysisDate   int64         `gorm:"column:dialysis_date" json:"dialysis_date"`
48
+	UserOrgId      int64         `gorm:"column:user_org_id" json:"user_org_id"`
49
+	PatientId      int64         `gorm:"column:patient_id" json:"patient_id"`
50
+	Stage          int64         `gorm:"column:stage" json:"stage"`
51
+	Remark         string        `gorm:"column:remark" json:"remark"`
52
+	BedID          int64         `gorm:"column:bed_id" json:"bed_id"`
53
+	StartNurse     int64         `gorm:"column:start_nurse" json:"start_nurse"`
54
+	FinishNurse    int64         `gorm:"column:finish_nurse" json:"finish_nurse"`
55
+	Status         int64         `gorm:"column:status" json:"status"`
56
+	DeviceNumber   DeviceNumber  `gorm:"ForeignKey:BedID"`
57
+	StartTime      int64         `gorm:"column:start_time" json:"start_time"`
58
+	EndTime        int64         `gorm:"column:end_time" json:"end_time"`
59
+	FinishCreator  int64         `gorm:"column:finish_creator" json:"finish_creator"`
60
+	FinishModifier int64         `gorm:"column:finish_modifier" json:"finish_modifier"`
61
+	SchedualType   int64         `gorm:"column:schedual_type" json:"schedual_type"`
62
+	UserAdminRole  UserAdminRole `json:"role" gorm:"foreignkey:AdminUserId;AssociationForeignKey:StartNurse;"`
63
+	ZoneId         int64         `gorm:"column:zone_id" json:"zone_id" form:"zone_id"`
64
+}
65
+
66
+func (QCDialysisOrder) TableName() string {
67
+	return "xt_dialysis_order"
68
+}
69
+
70
+type QCAssessmentAfterDislysis struct {
71
+	ID                    int64 `gorm:"column:id" json:"id" form:"id"`
72
+	UserOrgId             int64 `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
73
+	PatientId             int64 `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
74
+	AssessmentDate        int64 `gorm:"column:assessment_date" json:"assessment_date" form:"assessment_date"`
75
+	ActualTreatmentHour   int64 `gorm:"column:actual_treatment_hour" json:"actual_treatment_hour" form:"actual_treatment_hour"`
76
+	ActualTreatmentMinute int64 `gorm:"column:actual_treatment_minute" json:"actual_treatment_minute" form:"actual_treatment_minute"`
77
+}
78
+
79
+func (QCAssessmentAfterDislysis) TableName() string {
80
+
81
+	return "xt_assessment_after_dislysis"
82
+}
83
+
84
+type QCSchedule struct {
85
+	ID                        int64                     `gorm:"column:id" json:"id" form:"id"`
86
+	UserOrgId                 int64                     `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
87
+	PatientId                 int64                     `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
88
+	ScheduleDate              int64                     `gorm:"column:schedule_date" json:"schedule_date" form:"schedule_date"`
89
+	ScheduleType              int64                     `gorm:"column:schedule_type" json:"schedule_type" form:"schedule_type"`
90
+	ScheduleWeek              int64                     `gorm:"column:schedule_week" json:"schedule_week" form:"schedule_week"`
91
+	ModeId                    int64                     `gorm:"column:mode_id" json:"mode_id" form:"mode_id"`
92
+	Status                    int64                     `gorm:"column:status" json:"status" form:"status"`
93
+	CreatedTime               int64                     `gorm:"column:created_time" json:"created_time" form:"created_time"`
94
+	UpdatedTime               int64                     `gorm:"column:updated_time" json:"updated_time" form:"updated_time"`
95
+	QCSPrescription           QCSPrescription           `gorm:"ForeignKey:RecordDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"prescription"`
96
+	QCPatients                QCPatients                `gorm:"ForeignKey:ID;AssociationForeignKey:PatientId" json:"patient"`
97
+	QCDialysisOrder           QCDialysisOrder           `gorm:"ForeignKey:PatientId,DialysisDate;AssociationForeignKey:PatientId,ScheduleDate" json:"order"`
98
+	QCAssessmentAfterDislysis QCAssessmentAfterDislysis `gorm:"ForeignKey:PatientId,AssessmentDate;AssociationForeignKey:PatientId,ScheduleDate" json:"ad"`
99
+}
100
+
101
+// `gorm:"ForeignKey:DialysisDate,PatientId;AssociationForeignKey:ScheduleDate,PatientId" json:"dialysis_order"`
102
+func (QCSchedule) TableName() string {
103
+	return "xt_schedule"
104
+}
105
+
106
+type QCSPrescription struct {
107
+	ID            int64         `gorm:"column:id" json:"id"`
108
+	UserOrgId     int64         `gorm:"column:user_org_id" json:"user_org_id"`
109
+	PatientId     int64         `gorm:"column:patient_id" json:"patient_id"`
110
+	ModeId        int64         `gorm:"column:mode_id" json:"mode_id"`
111
+	Status        int64         `gorm:"column:status" json:"status"`
112
+	CreatedTime   int64         `gorm:"column:created_time" json:"created_time"`
113
+	UpdatedTime   int64         `gorm:"column:updated_time" json:"updated_time"`
114
+	RecordDate    int64         `gorm:"column:record_date" json:"record_date"`
115
+	RecordId      int64         `gorm:"column:record_id" json:"record_id"`
116
+	UserAdminRole UserAdminRole `json:"role" gorm:"foreignkey:AdminUserId;AssociationForeignKey:Creater;"`
117
+	Creater       int64         `gorm:"column:creater" json:"creater"`
118
+	Modifier      int64         `gorm:"column:modifier" json:"modifier"`
119
+}
120
+
121
+func (QCSPrescription) TableName() string {
122
+	return "xt_dialysis_prescription"
123
+}

+ 1 - 0
service/his_service.go View File

@@ -974,6 +974,7 @@ func CreateNewHisProjectTwo(project *models.HisPrescriptionProject, tx *gorm.DB)
974 974
 	}
975 975
 	return
976 976
 }
977
+
977 978
 func CreateHisProjectTwo(project *models.HisPrescriptionProject) (err error) {
978 979
 
979 980
 	err = writeDb.Model(&models.HisPrescriptionProject{}).Save(project).Error

+ 554 - 199
service/statistis_qc_service.go View File

@@ -2,8 +2,12 @@ package service
2 2
 
3 3
 import (
4 4
 	"XT_New/models"
5
+	"database/sql"
5 6
 	"fmt"
7
+	"github.com/jinzhu/gorm"
8
+	"reflect"
6 9
 	"strings"
10
+	"time"
7 11
 )
8 12
 
9 13
 func GetDialysisTotalDatas() {
@@ -14,20 +18,20 @@ func GetNewDialysiTotal(startime int64, endtime int64, orgid int64, origin int64
14 18
 	counts := models.PatientPrescriptionCountStruct{}
15 19
 	var err error
16 20
 	if origin == 1 { //透析记录,上机为准
17
-		db := XTReadDB().Table("xt_dialysis_order as x")
21
+		db := XTReadDB().Table("xt_dialysis_order as x").Joins("join xt_dialysis_prescription p on p.patient_id = x.patient_id and p.record_date = x.dialysis_date")
18 22
 		err = db.Select("count(x.id) as count").Where("x.dialysis_date >= ? and x.dialysis_date<=? and x.user_org_id = ? AND x.status = 1", startime, endtime, orgid).Scan(&counts).Error
19 23
 		return counts.Count, err
20 24
 
21 25
 	} else {
22
-		db := XTReadDB().Table("xt_schedule as sch")
23
-		//err = db.Select("COUNT(DISTINCT patient_id) AS total_employees").Where("x.dialysis_date >= ? and x.dialysis_date<=? and x.user_org_id = ? AND x.status = 1", startime, endtime, orgid).Scan(&counts).Error
24 26
 		var count int64
25
-		err := db.Model(&Schedule{}).
26
-			Select("patient_id, schedule_date").
27
+		var schs []models.Schedule
28
+		db := XTReadDB().Model(&models.Schedule{})
29
+		err := db.
27 30
 			Group("patient_id, schedule_date").
28
-			Where("schedule_date >= ? AND schedule_date  <= ?", startime, endtime).
29
-			Count(&count).
31
+			Where("schedule_date >= ? AND schedule_date  <= ? and user_org_id = ? and status = 1", startime, endtime, orgid).
32
+			Find(&schs).
30 33
 			Error
34
+		count = int64(len(schs))
31 35
 		return count, err
32 36
 
33 37
 	}
@@ -45,23 +49,37 @@ type DialysisStat struct {
45 49
 	Total  int            `json:"合计"`
46 50
 }
47 51
 
48
-func getTreatmentModes() ([]TreatmentMode, error) {
49
-	var modes []TreatmentMode
50
-	if err := XTReadDB().Find(&modes).Error; err != nil {
52
+func GetTreatmentModes() ([]models.TreatmentMode, error) {
53
+	var modes []models.TreatmentMode
54
+	if err := XTReadDB().Model(&models.TreatmentMode{}).Find(&modes).Error; err != nil {
51 55
 		return nil, err
52 56
 	}
53 57
 	return modes, nil
54 58
 }
55 59
 
56
-func GetDialysisStats(startDate int64, endDate int64, groupBy int64, mode int64) ([]DialysisStat, error) {
57
-	var stats []DialysisStat
58
-	var modes []TreatmentMode
59
-	if mode > 0 {
60
-		modes, _ = getTreatmentModes()
60
+func GetDialysisStats(start int64, end int64, mode int64, org_id int64, time_way int64) ([]map[string]interface{}, error) {
61
+	// 将时间戳转换为time.Time类型
62
+	t := time.Unix(start, 0)
63
+	// 使用布局定义格式化时间
64
+	layout := "2006-01-02"
65
+	// 将时间格式化为字符串
66
+	startDate := t.Format(layout) + " 00:00:00"
67
+
68
+	t2 := time.Unix(end, 0)
69
+	// 使用布局定义格式化时间
70
+	//layout := "2006-01-02"
71
+	// 将时间格式化为字符串
72
+	endDate := t2.Format(layout) + " 00:00:00"
73
+	//var stats []DialysisStat
74
+	var modes []models.TreatmentMode
75
+	fmt.Println(mode)
76
+	if mode == 0 {
77
+		modes, _ = GetTreatmentModes()
78
+
61 79
 	} else {
62
-		modes_two, _ := getTreatmentModes()
80
+		modes_two, _ := GetTreatmentModes()
63 81
 		for _, item := range modes_two {
64
-			if item.ModeID == int(mode) {
82
+			if item.ModeID == mode {
65 83
 				modes = append(modes, item)
66 84
 			}
67 85
 		}
@@ -71,28 +89,34 @@ func GetDialysisStats(startDate int64, endDate int64, groupBy int64, mode int64)
71 89
 		return nil, err
72 90
 	}
73 91
 
74
-	// 构建日期格式
75
-	dateFormat := "%Y-%m-%d"
76
-	switch groupBy {
77
-	case 2:
78
-		dateFormat = "%Y-%m-%d"
79
-	case 1:
80
-		dateFormat = "%Y-%u"
81
-	case 3:
82
-		dateFormat = "%Y-%m"
83
-	case 4:
84
-		dateFormat = "%Y"
85
-	default:
86
-		return nil, fmt.Errorf("invalid group by option")
87
-	}
92
+	var selectClauses []string
88 93
 	// 构建动态查询语句
89
-	selectClauses := []string{fmt.Sprintf("DATE_FORMAT(p.record_date, '%s') AS `日期`", dateFormat)}
94
+	if time_way == 1 {
95
+		//selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0])}
96
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
97
+
98
+	} else if time_way == 3 {
99
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
100
+
101
+		//selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0]+"-"+strings.Split(strings.Split(startDate, " ")[0], "-")[1])}
102
+	} else if time_way == 4 {
103
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
104
+
105
+		//selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0])}
106
+	} else {
107
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
108
+	}
90 109
 	for _, mode := range modes {
91
-		selectClauses = append(selectClauses, fmt.Sprintf("SUM(CASE WHEN t.mode_name = '%s' THEN 1 ELSE 0 END) AS `%s`", mode.ModeName, mode.ModeName))
110
+		fmt.Println(mode)
111
+
112
+		selectClauses = append(selectClauses, fmt.Sprintf("COALESCE(SUM(CASE WHEN t.name = '%s' THEN 1 ELSE 0 END), 0) AS `%s`", mode.Name, mode.Name))
92 113
 	}
93 114
 	selectClauses = append(selectClauses, "COUNT(*) AS `合计`")
94 115
 
95
-	query := fmt.Sprintf(`
116
+	var rows *sql.Rows
117
+	var query string
118
+	if mode > 0 {
119
+		query = fmt.Sprintf(`
96 120
         SELECT
97 121
             %s
98 122
         FROM
@@ -100,48 +124,108 @@ func GetDialysisStats(startDate int64, endDate int64, groupBy int64, mode int64)
100 124
         JOIN
101 125
             xt_treatment_mode t ON p.mode_id = t.mode_id
102 126
         WHERE
103
-            p.record_date >= ? AND p.record_date <= ?
127
+            FROM_UNIXTIME(p.record_date) >= ? AND FROM_UNIXTIME(p.record_date) <= ? AND p.user_org_id = ? and p.mode_id = ?
104 128
         GROUP BY
105
-            DATE_FORMAT(p.record_date, '%s')
106
-    `, dateFormat, dateFormat, selectClauses)
129
+           日期
130
+    `, strings.Join(selectClauses, ", "))
131
+		rows, _ = readDb.Raw(query, startDate, endDate, org_id, mode).Rows()
132
+
133
+	} else {
134
+		query = fmt.Sprintf(`
135
+        SELECT
136
+            %s
137
+        FROM
138
+            xt_dialysis_prescription p
139
+        JOIN
140
+            xt_treatment_mode t ON p.mode_id = t.mode_id
141
+        WHERE
142
+            FROM_UNIXTIME(p.record_date) >= ? AND FROM_UNIXTIME(p.record_date) <= ? AND p.user_org_id = ? 
143
+        GROUP BY
144
+           日期
145
+    `, strings.Join(selectClauses, ", "))
146
+		rows, _ = readDb.Raw(query, startDate, endDate, org_id).Rows()
147
+	}
107 148
 
108
-	rows, err := readDb.Raw(query, startDate, endDate).Rows()
109 149
 	if err != nil {
110 150
 		return nil, err
111 151
 	}
112 152
 	defer rows.Close()
113 153
 
114
-	// 解析查询结果
154
+	columns, err := rows.Columns()
155
+	if err != nil {
156
+		return nil, err
157
+	}
158
+
159
+	var results []map[string]interface{}
160
+
115 161
 	for rows.Next() {
116
-		var stat DialysisStat
117
-		stat.Counts = make(map[string]int)
118
-		cols := []interface{}{&stat.Date}
119
-		for _, mode := range modes {
120
-			var count int
121
-			cols = append(cols, &count)
122
-			stat.Counts[mode.ModeName] = count
162
+		// 创建一个长度为列数的切片,用于存储每一行的值
163
+		columnValues := make([]interface{}, len(columns))
164
+		columnPointers := make([]interface{}, len(columns))
165
+		for i := range columnValues {
166
+			columnPointers[i] = &columnValues[i]
123 167
 		}
124
-		var total int
125
-		cols = append(cols, &total)
126
-		stat.Total = total
127
-		if err := rows.Scan(cols...); err != nil {
168
+
169
+		// 扫描当前行的值
170
+		if err := rows.Scan(columnPointers...); err != nil {
128 171
 			return nil, err
129 172
 		}
130
-		stats = append(stats, stat)
173
+
174
+		// 将扫描到的值放入结果 map 中
175
+		result := make(map[string]interface{})
176
+		for i, colName := range columns {
177
+			val := columnPointers[i].(*interface{})
178
+			result[colName] = *val
179
+		}
180
+
181
+		results = append(results, result)
131 182
 	}
132 183
 
133
-	return stats, nil
184
+	//// 解析查询结果
185
+	//for rows.Next() {
186
+	//	var stat DialysisStat
187
+	//	stat.Counts = make(map[string]int)
188
+	//	cols := []interface{}{&stat.Date}
189
+	//	for _, mode := range modes {
190
+	//		var count int
191
+	//		cols = append(cols, &count)
192
+	//		stat.Counts[mode.Name] = count
193
+	//	}
194
+	//	var total int
195
+	//	cols = append(cols, &total)
196
+	//	stat.Total = total
197
+	//	if err := rows.Scan(cols...); err != nil {
198
+	//		return nil, err
199
+	//	}
200
+	//	stats = append(stats, stat)
201
+	//}
202
+
203
+	return results, nil
134 204
 }
135 205
 
136
-func GetScheduleStats(startDate int64, endDate int64, groupBy int64, mode int64) ([]DialysisStat, error) {
137
-	var stats []DialysisStat
138
-	var modes []TreatmentMode
139
-	if mode > 0 {
140
-		modes, _ = getTreatmentModes()
206
+func GetScheduleStats(start int64, end int64, mode int64, org_id int64, time_way int64) ([]map[string]interface{}, error) {
207
+	// 将时间戳转换为time.Time类型
208
+	t := time.Unix(start, 0)
209
+	// 使用布局定义格式化时间
210
+	layout := "2006-01-02"
211
+	// 将时间格式化为字符串
212
+	startDate := t.Format(layout) + " 00:00:00"
213
+
214
+	t2 := time.Unix(end, 0)
215
+	// 使用布局定义格式化时间
216
+	//layout := "2006-01-02"
217
+	// 将时间格式化为字符串
218
+	endDate := t2.Format(layout) + " 00:00:00"
219
+	//var stats []DialysisStat
220
+	var modes []models.TreatmentMode
221
+	fmt.Println(mode)
222
+	if mode == 0 {
223
+		modes, _ = GetTreatmentModes()
224
+
141 225
 	} else {
142
-		modes_two, _ := getTreatmentModes()
226
+		modes_two, _ := GetTreatmentModes()
143 227
 		for _, item := range modes_two {
144
-			if item.ModeID == int(mode) {
228
+			if item.ModeID == mode {
145 229
 				modes = append(modes, item)
146 230
 			}
147 231
 		}
@@ -151,28 +235,28 @@ func GetScheduleStats(startDate int64, endDate int64, groupBy int64, mode int64)
151 235
 		return nil, err
152 236
 	}
153 237
 
154
-	// 构建日期格式
155
-	dateFormat := "%Y-%m-%d"
156
-	switch groupBy {
157
-	case 2:
158
-		dateFormat = "%Y-%m-%d"
159
-	case 1:
160
-		dateFormat = "%Y-%u"
161
-	case 3:
162
-		dateFormat = "%Y-%m"
163
-	case 4:
164
-		dateFormat = "%Y"
165
-	default:
166
-		return nil, fmt.Errorf("invalid group by option")
167
-	}
238
+	var selectClauses []string
168 239
 	// 构建动态查询语句
169
-	selectClauses := []string{fmt.Sprintf("DATE_FORMAT(p.schudle_date, '%s') AS `日期`", dateFormat)}
240
+	if time_way == 1 {
241
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0])}
242
+	} else if time_way == 3 {
243
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0]+strings.Split(strings.Split(startDate, " ")[0], "-")[1])}
244
+	} else if time_way == 4 {
245
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0])}
246
+	} else {
247
+		selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
248
+	}
170 249
 	for _, mode := range modes {
171
-		selectClauses = append(selectClauses, fmt.Sprintf("SUM(CASE WHEN t.mode_name = '%s' THEN 1 ELSE 0 END) AS `%s`", mode.ModeName, mode.ModeName))
250
+		fmt.Println(mode)
251
+
252
+		selectClauses = append(selectClauses, fmt.Sprintf("COALESCE(SUM(CASE WHEN t.name = '%s' THEN 1 ELSE 0 END), 0) AS `%s`", mode.Name, mode.Name))
172 253
 	}
173 254
 	selectClauses = append(selectClauses, "COUNT(*) AS `合计`")
174 255
 
175
-	query := fmt.Sprintf(`
256
+	var rows *sql.Rows
257
+	var query string
258
+	if mode > 0 {
259
+		query = fmt.Sprintf(`
176 260
         SELECT
177 261
             %s
178 262
         FROM
@@ -180,39 +264,165 @@ func GetScheduleStats(startDate int64, endDate int64, groupBy int64, mode int64)
180 264
         JOIN
181 265
             xt_treatment_mode t ON p.mode_id = t.mode_id
182 266
         WHERE
183
-            p.schedule_date >= ? AND p.schedule_date <= ?
267
+            FROM_UNIXTIME(p.schedule_date) >= ? AND FROM_UNIXTIME(p.schedule_date) <= ? AND p.user_org_id = ? and p.mode_id = ?
184 268
         GROUP BY
185
-            DATE_FORMAT(p.schedule_date, '%s')
186
-    `, dateFormat, dateFormat, selectClauses)
269
+           日期
270
+    `, strings.Join(selectClauses, ", "))
271
+		rows, _ = readDb.Raw(query, startDate, endDate, org_id, mode).Rows()
272
+
273
+	} else {
274
+		query = fmt.Sprintf(`
275
+        SELECT
276
+            %s
277
+        FROM
278
+            xt_schedule p
279
+        JOIN
280
+            xt_treatment_mode t ON p.mode_id = t.mode_id
281
+        WHERE
282
+            FROM_UNIXTIME(p.schedule_date) >= ? AND FROM_UNIXTIME(p.schedule_date) <= ? AND p.user_org_id = ? 
283
+        GROUP BY
284
+           日期
285
+    `, strings.Join(selectClauses, ", "))
286
+		rows, _ = readDb.Raw(query, startDate, endDate, org_id).Rows()
287
+	}
187 288
 
188
-	rows, err := readDb.Raw(query, startDate, endDate).Rows()
189 289
 	if err != nil {
190 290
 		return nil, err
191 291
 	}
192 292
 	defer rows.Close()
193 293
 
194
-	// 解析查询结果
294
+	columns, err := rows.Columns()
295
+	if err != nil {
296
+		return nil, err
297
+	}
298
+
299
+	var results []map[string]interface{}
300
+
195 301
 	for rows.Next() {
196
-		var stat DialysisStat
197
-		stat.Counts = make(map[string]int)
198
-		cols := []interface{}{&stat.Date}
199
-		for _, mode := range modes {
200
-			var count int
201
-			cols = append(cols, &count)
202
-			stat.Counts[mode.ModeName] = count
302
+		// 创建一个长度为列数的切片,用于存储每一行的值
303
+		columnValues := make([]interface{}, len(columns))
304
+		columnPointers := make([]interface{}, len(columns))
305
+		for i := range columnValues {
306
+			columnPointers[i] = &columnValues[i]
203 307
 		}
204
-		var total int
205
-		cols = append(cols, &total)
206
-		stat.Total = total
207
-		if err := rows.Scan(cols...); err != nil {
308
+
309
+		// 扫描当前行的值
310
+		if err := rows.Scan(columnPointers...); err != nil {
208 311
 			return nil, err
209 312
 		}
210
-		stats = append(stats, stat)
313
+
314
+		// 将扫描到的值放入结果 map 中
315
+		result := make(map[string]interface{})
316
+		for i, colName := range columns {
317
+			val := columnPointers[i].(*interface{})
318
+			result[colName] = *val
319
+		}
320
+
321
+		results = append(results, result)
211 322
 	}
212 323
 
213
-	return stats, nil
324
+	//// 解析查询结果
325
+	//for rows.Next() {
326
+	//	var stat DialysisStat
327
+	//	stat.Counts = make(map[string]int)
328
+	//	cols := []interface{}{&stat.Date}
329
+	//	for _, mode := range modes {
330
+	//		var count int
331
+	//		cols = append(cols, &count)
332
+	//		stat.Counts[mode.Name] = count
333
+	//	}
334
+	//	var total int
335
+	//	cols = append(cols, &total)
336
+	//	stat.Total = total
337
+	//	if err := rows.Scan(cols...); err != nil {
338
+	//		return nil, err
339
+	//	}
340
+	//	stats = append(stats, stat)
341
+	//}
342
+
343
+	return results, nil
214 344
 }
215 345
 
346
+//func GetScheduleStats(startDate int64, endDate int64, groupBy int64, mode int64, org_id int64) ([]DialysisStat, error) {
347
+//	var stats []DialysisStat
348
+//	var modes []models.TreatmentMode
349
+//	if mode > 0 {
350
+//		modes, _ = GetTreatmentModes()
351
+//	} else {
352
+//		modes_two, _ := GetTreatmentModes()
353
+//		for _, item := range modes_two {
354
+//			if item.ModeID == mode {
355
+//				modes = append(modes, item)
356
+//			}
357
+//		}
358
+//	}
359
+//	// 获取透析模式
360
+//	if err != nil {
361
+//		return nil, err
362
+//	}
363
+//
364
+//	// 构建日期格式
365
+//	dateFormat := "%Y-%m-%d"
366
+//	switch groupBy {
367
+//	case 2:
368
+//		dateFormat = "%Y-%m-%d"
369
+//	case 1:
370
+//		dateFormat = "%Y-%u"
371
+//	case 3:
372
+//		dateFormat = "%Y-%m"
373
+//	case 4:
374
+//		dateFormat = "%Y"
375
+//	default:
376
+//		return nil, fmt.Errorf("invalid group by option")
377
+//	}
378
+//	// 构建动态查询语句
379
+//	selectClauses := []string{fmt.Sprintf("DATE_FORMAT(p.schudle_date, '%s') AS `日期`", dateFormat)}
380
+//	for _, mode := range modes {
381
+//		selectClauses = append(selectClauses, fmt.Sprintf("SUM(CASE WHEN t.mode_name = '%s' THEN 1 ELSE 0 END) AS `%s`", mode.Name, mode.Name))
382
+//	}
383
+//	selectClauses = append(selectClauses, "COUNT(*) AS `合计`")
384
+//
385
+//	query := fmt.Sprintf(`
386
+//        SELECT
387
+//            %s
388
+//        FROM
389
+//            xt_schedule p
390
+//        JOIN
391
+//            xt_treatment_mode t ON p.mode_id = t.mode_id
392
+//        WHERE
393
+//            p.schedule_date >= ? AND p.schedule_date <= ?
394
+//        GROUP BY
395
+//            DATE_FORMAT(p.schedule_date, '%s')
396
+//    `, dateFormat, dateFormat, selectClauses)
397
+//
398
+//	rows, err := readDb.Raw(query, startDate, endDate).Rows()
399
+//	if err != nil {
400
+//		return nil, err
401
+//	}
402
+//	defer rows.Close()
403
+//
404
+//	// 解析查询结果
405
+//	for rows.Next() {
406
+//		var stat DialysisStat
407
+//		stat.Counts = make(map[string]int)
408
+//		cols := []interface{}{&stat.Date}
409
+//		for _, mode := range modes {
410
+//			var count int
411
+//			cols = append(cols, &count)
412
+//			stat.Counts[mode.Name] = count
413
+//		}
414
+//		var total int
415
+//		cols = append(cols, &total)
416
+//		stat.Total = total
417
+//		if err := rows.Scan(cols...); err != nil {
418
+//			return nil, err
419
+//		}
420
+//		stats = append(stats, stat)
421
+//	}
422
+//
423
+//	return stats, nil
424
+//}
425
+
216 426
 func GetNewDialysisCountMode(starttime int64, endtime int64, orgid int64, origin int64, mode_id int64) (counts []*models.PatientPrescriptionCountStruct, err error) {
217 427
 	if origin == 1 {
218 428
 
@@ -237,17 +447,7 @@ func GetNewDialysisCountMode(starttime int64, endtime int64, orgid int64, origin
237 447
 		return counts, err
238 448
 
239 449
 	} else {
240
-		db := readDb.Table("xt_schedule as o").Where("o.status = 1").Select("patient_id, schedule_date").Group("patient_id, schedule_date,mode_id")
241
-		if starttime > 0 {
242
-			db = db.Where("o.schedule_date >= ?", starttime)
243
-		}
244
-		if endtime > 0 {
245
-			db = db.Where("o.schedule_date <= ?", endtime)
246
-		}
247
-		if orgid > 0 {
248
-			db = db.Where("o.user_org_id = ?", orgid)
249
-		}
250
-		err = db.Select("o.mode_id,count(o.mode_id) as count").Scan(&counts).Error
450
+		err = readDb.Raw("select mode_id, count(aa.`mode_id`) as count from xt_schedule aa join (SELECT DISTINCT o.patient_id, o.`schedule_date` FROM xt_schedule AS o WHERE o.status = 1 AND o.schedule_date >= ?   AND o.schedule_date <= ?   AND o.user_org_id = ?) as b on  aa.`patient_id` = b.`patient_id` and aa.`schedule_date` = b.`schedule_date` where aa.`status` = 1 and    aa.schedule_date >= ?    AND aa.schedule_date <= ?   AND aa.user_org_id = ? Group by aa.`mode_id`", starttime, endtime, orgid, starttime, endtime, orgid).Find(&counts).Error
251 451
 		return counts, err
252 452
 
253 453
 	}
@@ -255,28 +455,52 @@ func GetNewDialysisCountMode(starttime int64, endtime int64, orgid int64, origin
255 455
 }
256 456
 
257 457
 func GetNewDialysisCountModeTwo(starttime int64, endtime int64, orgid int64, origin int64, mode_id int64) (counts models.CustomDialysisData, err error) {
458
+
459
+	// 将时间戳转换为time.Time类型
460
+	t := time.Unix(starttime, 0)
461
+
462
+	// 使用布局定义格式化时间
463
+	layout := "2006-01-02"
464
+
465
+	// 将时间格式化为字符串
466
+	startDate := t.Format(layout) + " 00:00:00"
467
+
468
+	t2 := time.Unix(endtime, 0)
469
+
470
+	// 使用布局定义格式化时间
471
+	//layout := "2006-01-02"
472
+
473
+	// 将时间格式化为字符串
474
+	endDate := t2.Format(layout) + " 00:00:00"
475
+	//fmt.Println(formattedDate)
476
+
477
+	// 将日期字符串解析为time.Time类型
478
+	//start, _ := time.Parse("2006-01-02 15:04:05", formattedDate)
479
+	//starttime = start.Unix()
480
+	//fmt.Println(starttime)
481
+
258 482
 	if origin == 1 {
259 483
 		db := readDb.Table("xt_dialysis_order as o").Where("o.status = 1")
260 484
 		if starttime > 0 {
261
-			db = db.Where("o.dialysis_date >=?", starttime)
485
+			db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.dialysis_date), '%Y-%m-%d %H:%i:%s') >= ?", startDate)
262 486
 		}
263 487
 		if endtime > 0 {
264
-			db = db.Where("o.dialysis_date<=?", endtime)
488
+			db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.dialysis_date), '%Y-%m-%d %H:%i:%s') <= ?", endDate)
265 489
 		}
266 490
 		if orgid > 0 {
267 491
 			db = db.Where("o.user_org_id = ?", orgid)
268 492
 		}
269 493
 
270
-		err = db.Select("s.mode_id,count(s.mode_id) as count").Joins("join xt_dialysis_prescription as s on s.patient_id = o.patient_id and s.record_date = o.dialysis_date and s.status= 1 AND s.record_date >= ? AND s.record_date <= ? AND  s.mode_id = ? ", starttime, endtime, mode_id).Group("s.mode_id").Scan(&counts).Error
494
+		err = db.Select("s.mode_id,count(s.mode_id) as count").Joins("join xt_dialysis_prescription as s on s.patient_id = o.patient_id and s.record_date = o.dialysis_date and s.status= 1 AND DATE_FORMAT(FROM_UNIXTIME(s.record_date), '%Y-%m-%d %H:%i:%s') >= ?  AND DATE_FORMAT(FROM_UNIXTIME(s.record_date), '%Y-%m-%d %H:%i:%s') <= ? AND  s.mode_id = ? ", startDate, endDate, mode_id).Group("s.mode_id").Scan(&counts).Error
271 495
 		return counts, err
272 496
 
273 497
 	} else {
274
-		db := readDb.Table("xt_schedule as o").Where("o.status = 1").Select("patient_id, schedule_date").Group("patient_id, schedule_date,mode_id")
498
+		db := readDb.Table("xt_schedule as o").Where("o.status = 1").Select("patient_id, schedule_date").Group("mode_id")
275 499
 		if starttime > 0 {
276
-			db = db.Where("o.schedule_date >= ?", starttime)
500
+			db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.schedule_date),'%Y-%m-%d %H:%i:%s') >= ?", startDate)
277 501
 		}
278 502
 		if endtime > 0 {
279
-			db = db.Where("o.schedule_date <= ?", endtime)
503
+			db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.schedule_date),'%Y-%m-%d %H:%i:%s') <= ?", endDate)
280 504
 		}
281 505
 		if orgid > 0 {
282 506
 			db = db.Where("o.user_org_id = ?", orgid)
@@ -357,6 +581,19 @@ func GetDialyzerSummary(org_id int64) ([]string, error) {
357 581
 	return Dialyzer, nil
358 582
 }
359 583
 
584
+func GetIrrigationSummary(org_id int64) ([]string, error) {
585
+	var Irrigation []string
586
+	err := XTReadDB().Model(&models.DialysisPrescription{}).
587
+		Select("dialysis_irrigation").
588
+		Where(" user_org_id = ? and status = 1", org_id).
589
+		Group("dialysis_irrigation").
590
+		Scan(&Irrigation).Error
591
+	if err != nil {
592
+		return nil, err
593
+	}
594
+	return Irrigation, nil
595
+}
596
+
360 597
 type DialyzerResult struct {
361 598
 	Dialyzer string
362 599
 	Count    int
@@ -371,6 +608,15 @@ func GetDialyzerData(start_time int64, end_time int64, org_id int64) (dr []Dialy
371 608
 	return
372 609
 }
373 610
 
611
+func GetIrrigationData(start_time int64, end_time int64, org_id int64) (dr []DialyzerResult, err error) {
612
+	err = XTReadDB().Model(&models.DialysisPrescription{}).
613
+		Select("dialysis_irrigation as dialyzer, COUNT(*) as count").
614
+		Where("record_date >= ? and record_date <= ? and user_org_id = ? and status = 1", start_time, end_time, org_id).
615
+		Group("dialysis_irrigation").
616
+		Scan(&dr).Error
617
+	return
618
+}
619
+
374 620
 func GetDialyzerTotal(start_time int64, end_time int64, org_id int64) (total int64, err error) {
375 621
 	err = XTReadDB().Model(&models.DialysisPrescription{}).
376 622
 		Where("status = 1 and record_date >= ? and record_date <= ? and user_org_id = ? and dialysis_dialyszers <> ''", start_time, end_time, org_id).
@@ -380,7 +626,7 @@ func GetDialyzerTotal(start_time int64, end_time int64, org_id int64) (total int
380 626
 
381 627
 func GetPrescriptionByAnticoagulant(page int64, limit int64, orgid int64, anticoagulant int64, start_time int64, end_time int64) (solution []*models.DialysisPrescription, total int64, err error) {
382 628
 
383
-	db := XTReadDB().Model(&models.DialysisPrescription{}).Where("status = 1")
629
+	db := XTReadDB().Model(&models.DialysisPrescription{}).Preload("QCPatients", "status = 1 and user_org_id = ?", orgid).Where("status = 1")
384 630
 	if anticoagulant > 0 {
385 631
 		db = db.Where("anticoagulant = ?", anticoagulant)
386 632
 	}
@@ -471,116 +717,185 @@ func GetDialysisCompletionTotal(org_id int64, start_time int64, end_time int64)
471 717
             xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
472 718
         WHERE
473 719
             o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?
474
-        GROUP BY
475
-            dialysis_status;
476 720
     `
477
-	if err := readDb.Raw(query, org_id, org_id, org_id, start_time, end_time).Scan(&Count).Error; err != nil {
721
+	if err := readDb.Raw(query, org_id, org_id, org_id, start_time, end_time).Count(&Count).Error; err != nil {
478 722
 		return 0, err
479 723
 	}
480 724
 
481 725
 	return Count, nil
482 726
 }
483
-func GetDialysisCompletionDetail(org_id int64, start_time int64, end_time int64, mode int64, limit int64, page int64) (date []*CustomData, total int64, err error) {
727
+func GetDialysisCompletionDetail(org_id int64, start_time int64, end_time int64, mode int64, limit int64, page int64) (results []interface{}, total int64, err error) {
484 728
 	var query string
485 729
 	if mode == 0 {
486 730
 		query = `
487
-        SELECT
488
-           p.dialysis_no as dialysis_no,
489
-           p.name as patient_name,
490
-           FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
491
-           CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
492
-           CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
493
-           ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
494
-           p.prescription_doctor as doctor,
495
-           p.finish_nurse as nurse
496
-        FROM
497
-            xt_dialysis_order o
498
-    	JOIN           
499
-            xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
500
-        JOIN
501
-            xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
502
-        JOIN
503
-            xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
504
-        WHERE
505
-            o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?
506
-    `
731
+	   SELECT
732
+	      p.dialysis_no as dialysis_no,
733
+	      p.name as patient_name,
734
+	      FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
735
+	      CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
736
+	      CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
737
+	      ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
738
+	      p.prescription_doctor as doctor,
739
+	      o.finish_nurse as nurse
740
+	   FROM
741
+	       xt_dialysis_order o
742
+		JOIN
743
+	       xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
744
+	   JOIN
745
+	       xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
746
+	   JOIN
747
+	       xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
748
+	   WHERE
749
+	       o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?
750
+	`
751
+
752
+		readDb.Table("xt_dialysis_order o").
753
+			Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
754
+			Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
755
+			Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
756
+			Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?", org_id, start_time, end_time).Count(&total)
507 757
 
508 758
 	} else if mode == 1 {
509 759
 		query = `
510
-        SELECT
511
-           p.dialysis_no as dialysis_no,
512
-           p.name as patient_name,
513
-           FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
514
-           CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
515
-           CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
516
-           ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
517
-           p.prescription_doctor as doctor,
518
-           p.finish_nurse as nurse
519
-        FROM
520
-            xt_dialysis_order o
521
-    	JOIN           
522
-            xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
523
-        JOIN
524
-            xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
525
-        JOIN
526
-            xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
527
-        WHERE
528
-            o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) <= 15
529
-    `
760
+	   SELECT
761
+	      pp.dialysis_no as dialysis_no,
762
+	      pp.name as patient_name,
763
+	      FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
764
+	      CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
765
+	      CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
766
+	      ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
767
+	      p.prescription_doctor as doctor,
768
+	      o.finish_nurse as nurse
769
+	   FROM
770
+	       xt_dialysis_order o
771
+		JOIN
772
+	       xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
773
+	   JOIN
774
+	       xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
775
+	   JOIN
776
+	       xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
777
+	   WHERE
778
+	       o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) <= 15
779
+	`
780
+		readDb.Table("xt_dialysis_order o").
781
+			Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
782
+			Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
783
+			Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
784
+			Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? and ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) <= 15", org_id, start_time, end_time).Count(&total)
530 785
 
531 786
 	} else if mode == 2 {
532 787
 		query = `
533
-        SELECT
534
-           p.dialysis_no as dialysis_no,
535
-           p.name as patient_name,
536
-           FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
537
-           CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
538
-           CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
539
-           ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
540
-           p.prescription_doctor as doctor,
541
-           p.finish_nurse as nurse
542
-        FROM
543
-            xt_dialysis_order o
544
-    	JOIN           
545
-            xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
546
-        JOIN
547
-            xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
548
-        JOIN
549
-            xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
550
-        WHERE
551
-            o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) < 0
552
-    `
788
+	   SELECT
789
+	      pp.dialysis_no as dialysis_no,
790
+	      pp.name as patient_name,
791
+	      FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
792
+	      CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
793
+	      CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
794
+	      ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
795
+	      p.prescription_doctor as doctor,
796
+	      o.finish_nurse as nurse
797
+	   FROM
798
+	       xt_dialysis_order o
799
+		JOIN
800
+	       xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
801
+	   JOIN
802
+	       xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
803
+	   JOIN
804
+	       xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
805
+	   WHERE
806
+	       o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) < 0
807
+	`
808
+		readDb.Table("xt_dialysis_order o").
809
+			Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
810
+			Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
811
+			Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
812
+			Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? and TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) < 0", org_id, start_time, end_time).Count(&total)
553 813
 
554 814
 	} else if mode == 3 {
555 815
 		query = `
556
-        SELECT
557
-           p.dialysis_no as dialysis_no,
558
-           p.name as patient_name,
559
-           FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
560
-           CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
561
-           CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
562
-           ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
563
-           p.prescription_doctor as doctor,
564
-           p.finish_nurse as nurse
565
-        FROM
566
-            xt_dialysis_order o
567
-    	JOIN           
568
-            xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
569
-        JOIN
570
-            xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
571
-        JOIN
572
-            xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
573
-        WHERE
574
-            o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) > 15
575
-    `
816
+	   SELECT
817
+	      pp.dialysis_no as dialysis_no,
818
+	      pp.name as patient_name,
819
+	      FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
820
+	      CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
821
+	      CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
822
+	      ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
823
+	      p.prescription_doctor as doctor,
824
+	      o.finish_nurse as nurse
825
+	   FROM
826
+	       xt_dialysis_order o
827
+		JOIN
828
+	       xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
829
+	   JOIN
830
+	       xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
831
+	   JOIN
832
+	       xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
833
+	   WHERE
834
+	       o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) > 15
835
+	`
836
+		readDb.Table("xt_dialysis_order o").
837
+			Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
838
+			Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
839
+			Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
840
+			Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? and TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) > 15", org_id, start_time, end_time).Count(&total)
841
+
576 842
 	}
843
+
577 844
 	offset := (page - 1) * limit
578 845
 
579
-	if err := readDb.Raw(query, org_id, org_id, org_id, org_id, start_time, end_time).Count(&total).Offset(offset).Limit(limit).Scan(&date).Error; err != nil {
580
-		return nil, 0, err
846
+	rows, err := readDb.Raw(query, org_id, org_id, org_id, org_id, start_time, end_time).Offset(offset).Limit(limit).Rows()
847
+	if err != nil {
848
+		fmt.Println(err)
581 849
 	}
850
+	defer rows.Close()
582 851
 
583
-	return
852
+	// Define a map to hold the dynamic fields
853
+	fields := map[string]interface{}{
854
+		"dialysis_no":       "",
855
+		"patient_name":      "",
856
+		"dialysis_date":     "",
857
+		"dialysis_duration": "",
858
+		"actual_duration":   "",
859
+		"diff":              0,
860
+		"doctor":            "",
861
+		"nurse":             "",
862
+	}
863
+
864
+	// Create the dynamic struct type
865
+	dynamicStructType := createDynamicStruct(fields)
866
+
867
+	// Slice to hold the results
868
+	//var results []interface{}
869
+
870
+	// Iterate over the rows and scan into the dynamic struct
871
+	for rows.Next() {
872
+		// Create a new instance of the dynamic struct
873
+		result := reflect.New(dynamicStructType).Interface()
874
+
875
+		// Create a slice of pointers to the fields in the struct
876
+		fieldPtrs := []interface{}{
877
+			reflect.ValueOf(result).Elem().FieldByName("Dialysis_no").Addr().Interface(),
878
+			reflect.ValueOf(result).Elem().FieldByName("Patient_name").Addr().Interface(),
879
+			reflect.ValueOf(result).Elem().FieldByName("Dialysis_date").Addr().Interface(),
880
+			reflect.ValueOf(result).Elem().FieldByName("Dialysis_duration").Addr().Interface(),
881
+			reflect.ValueOf(result).Elem().FieldByName("Actual_duration").Addr().Interface(),
882
+			reflect.ValueOf(result).Elem().FieldByName("Diff").Addr().Interface(),
883
+			reflect.ValueOf(result).Elem().FieldByName("Doctor").Addr().Interface(),
884
+			reflect.ValueOf(result).Elem().FieldByName("Nurse").Addr().Interface(),
885
+		}
886
+
887
+		// Scan the row into the struct
888
+		if err := rows.Scan(fieldPtrs...); err != nil {
889
+			//log.Fatalf("failed to scan row: %v", err)
890
+			fmt.Println(err)
891
+
892
+		}
893
+
894
+		// Append the result to the slice
895
+		results = append(results, result)
896
+	}
897
+
898
+	return results, total, err
584 899
 }
585 900
 
586 901
 type QualityControlStandard struct {
@@ -665,3 +980,43 @@ func GetLatestInspectionValues(org_id int64, yearMonth string) ([]map[string]int
665 980
 
666 981
 	return results, nil
667 982
 }
983
+
984
+func createDynamicStruct(fields map[string]interface{}) reflect.Type {
985
+	var structFields []reflect.StructField
986
+	for name, value := range fields {
987
+		structFields = append(structFields, reflect.StructField{
988
+			Name: strings.Title(name),
989
+			Type: reflect.TypeOf(value),
990
+			Tag:  reflect.StructTag(fmt.Sprintf(`json:"%s"`, name)),
991
+		})
992
+	}
993
+	return reflect.StructOf(structFields)
994
+}
995
+
996
+func GetDialysisPrescriptionInfo(start_date string, end_date string, mode int64, org_id int64, page int64, limit int64) (qcp []models.QCPrescription, total int64, err error) {
997
+	offset := (page - 1) * limit
998
+
999
+	err = readDb.Model(&models.QCPrescription{}).Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
1000
+		return readUserDb.Where("status = 1 and org_id=?", org_id)
1001
+	}).Preload("QCPatients", "status = 1 and user_org_id = ?", org_id).Preload("QCDialysisOrder", func(db *gorm.DB) *gorm.DB {
1002
+		return db.Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
1003
+			return readUserDb.Where("status = 1 and org_id=?", org_id)
1004
+		}).Preload("DeviceNumber", "status = 1 and org_id = ?", org_id).Where("status = 1 AND user_org_id = ?", org_id)
1005
+	}).Preload("QCAssessmentAfterDislysis", "status = 1 and user_org_id = ?", org_id).Where("FROM_UNIXTIME(record_date, '%Y-%m-%d') >= ? and FROM_UNIXTIME(record_date, '%Y-%m-%d') <= ? and user_org_id = ? and mode_id = ?  and status = 1", start_date, end_date, org_id, mode).Count(&total).Offset(offset).Limit(limit).Find(&qcp).Error
1006
+	return
1007
+}
1008
+
1009
+func GetScheduleInfo(start_date string, end_date string, mode int64, org_id int64, page int64, limit int64) (qcp []models.QCSchedule, total int64, err error) {
1010
+	offset := (page - 1) * limit
1011
+
1012
+	err = readDb.Model(&models.QCSchedule{}).Preload("QCPatients", "status = 1 and user_org_id =?", org_id).Preload("QCSPrescription", func(db *gorm.DB) *gorm.DB {
1013
+		return db.Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
1014
+			return readUserDb.Where("status = 1 and org_id=?", org_id)
1015
+		}).Where("status = 1 AND user_org_id = ?", org_id)
1016
+	}).Preload("QCAssessmentAfterDislysis", "status = 1 and user_org_id = ?", org_id).Preload("QCDialysisOrder", func(db *gorm.DB) *gorm.DB {
1017
+		return db.Preload("DeviceNumber", "status = 1").Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
1018
+			return readUserDb.Where("status = 1 and org_id=?", org_id)
1019
+		}).Where("status = 1 AND user_org_id = ?", org_id)
1020
+	}).Where("FROM_UNIXTIME(schedule_date, '%Y-%m-%d') >= ? and FROM_UNIXTIME(schedule_date, '%Y-%m-%d') <= ? and user_org_id = ? and mode_id = ? and status = 1", start_date, end_date, org_id, mode).Count(&total).Offset(offset).Limit(limit).Find(&qcp).Error
1021
+	return
1022
+}