Browse Source

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

28169 2 months ago
parent
commit
4a12877beb

+ 218 - 0
controllers/fapiao_controller.go View File

@@ -0,0 +1,218 @@
1
+package controllers
2
+
3
+import (
4
+	"XT_New/enums"
5
+	"XT_New/models"
6
+	"XT_New/service"
7
+	"XT_New/service/fapiao"
8
+	"XT_New/utils"
9
+	"fmt"
10
+	"github.com/astaxie/beego"
11
+	"github.com/gaodengyun/goldencloud-sdk-go/goldencloud/common"
12
+	"github.com/gaodengyun/goldencloud-sdk-go/goldencloud/invoice"
13
+	"time"
14
+)
15
+
16
+type FapiaoApiController struct {
17
+	BaseAuthAPIController
18
+}
19
+
20
+func FaPiaoApiRegistRouters() {
21
+	beego.Router("/api/fapiao/sms/code", &FapiaoApiController{}, "get:GetLoginUploadCode")
22
+	beego.Router("/api/fapiao/sms/login", &FapiaoApiController{}, "get:Login")
23
+	beego.Router("/api/fapiao/qrcode/get", &FapiaoApiController{}, "get:GetQRCode")
24
+	beego.Router("/api/fapiao/stock/get", &FapiaoApiController{}, "get:GetFaPiaoStock")
25
+	beego.Router("/api/fapiao/blue", &FapiaoApiController{}, "get:OpenFaPiao")
26
+	beego.Router("/api/fapiao/red", &FapiaoApiController{}, "get:RedFaPiao")
27
+
28
+	beego.Router("/api/order/fapiao/list", &FapiaoApiController{}, "get:GetOrderFaPiaoList")
29
+	beego.Router("/api/fapiao/list", &FapiaoApiController{}, "get:GetFaPiaoList")
30
+
31
+}
32
+func (c *FapiaoApiController) GetFaPiaoList() {
33
+	page, _ := c.GetInt64("page", -1)
34
+	limit, _ := c.GetInt64("limit", -1)
35
+	start_time := c.GetString("start_time")
36
+	end_time := c.GetString("end_time")
37
+	timeLayout := "2006-01-02"
38
+	loc, _ := time.LoadLocation("Local")
39
+	var startTime int64
40
+	if len(start_time) > 0 {
41
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
42
+		if err != nil {
43
+			//fmt.Println(err)
44
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
45
+			return
46
+		}
47
+		startTime = theTime.Unix()
48
+	}
49
+	var endTime int64
50
+	if len(end_time) > 0 {
51
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
52
+		if err != nil {
53
+			utils.ErrorLog(err.Error())
54
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
55
+			return
56
+		}
57
+		endTime = theTime.Unix()
58
+	}
59
+
60
+	adminUser := c.GetAdminUserInfo()
61
+	org_id := adminUser.CurrentOrgId
62
+	order, err, total := service.GetFaPiaoList(org_id, page, limit, startTime, endTime)
63
+	if err == nil {
64
+		c.ServeSuccessJSON(map[string]interface{}{
65
+			"order": order,
66
+			"total": total,
67
+		})
68
+
69
+	} else {
70
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
71
+		return
72
+	}
73
+
74
+}
75
+func (c *FapiaoApiController) GetOrderFaPiaoList() {
76
+	page, _ := c.GetInt64("page", -1)
77
+	limit, _ := c.GetInt64("limit", -1)
78
+	start_time := c.GetString("start_time")
79
+	end_time := c.GetString("end_time")
80
+	is_open_fapiao, _ := c.GetInt64("is_open_fapiao", 0)
81
+	sort_type, _ := c.GetInt64("sort_type", 0)
82
+
83
+	patient_id, _ := c.GetInt64("patient_id", 0)
84
+
85
+	timeLayout := "2006-01-02"
86
+	loc, _ := time.LoadLocation("Local")
87
+	var startTime int64
88
+	if len(start_time) > 0 {
89
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
90
+		if err != nil {
91
+			//fmt.Println(err)
92
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
93
+			return
94
+		}
95
+		startTime = theTime.Unix()
96
+	}
97
+	var endTime int64
98
+	if len(end_time) > 0 {
99
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
100
+		if err != nil {
101
+			utils.ErrorLog(err.Error())
102
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
103
+			return
104
+		}
105
+		endTime = theTime.Unix()
106
+	}
107
+	adminUser := c.GetAdminUserInfo()
108
+	org_id := adminUser.CurrentOrgId
109
+	order, err, total := service.GetFaPiaoSettleList(org_id, page, limit, startTime, endTime, sort_type, start_time, end_time, is_open_fapiao, patient_id)
110
+	if err == nil {
111
+		c.ServeSuccessJSON(map[string]interface{}{
112
+			"order": order,
113
+			"total": total,
114
+		})
115
+
116
+	} else {
117
+		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
118
+		return
119
+	}
120
+}
121
+
122
+func (c *FapiaoApiController) GetLoginUploadCode() {
123
+	sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
124
+	var config models.FapiaoConfig
125
+	config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
126
+	routerAddress, postData := fapiao.GetSMSCode(config) //发票开具
127
+	r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
128
+	if err != nil {
129
+		fmt.Println(err)
130
+	} else {
131
+		fmt.Println(string(r))
132
+	}
133
+}
134
+
135
+func (c *FapiaoApiController) Login() {
136
+	GetQRStatus(c.GetAdminUserInfo().CurrentOrgId)
137
+	code := c.GetString("code")
138
+	var config models.FapiaoConfig
139
+	config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
140
+	sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
141
+	routerAddress, postData := fapiao.Login(code, config) //发票开具
142
+	r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
143
+	if err != nil {
144
+		fmt.Println(err)
145
+	} else {
146
+		fmt.Println(string(r))
147
+	}
148
+}
149
+
150
+func (c *FapiaoApiController) GetQRCode() {
151
+	sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
152
+	var config models.FapiaoConfig
153
+	config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
154
+	routerAddress, postData := fapiao.GetQRCode(config) //发票开具
155
+	r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
156
+	if err != nil {
157
+		fmt.Println(err)
158
+	} else {
159
+		fmt.Println(string(r))
160
+	}
161
+}
162
+
163
+func (c *FapiaoApiController) GetFaPiaoStock() {
164
+	sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
165
+	var config models.FapiaoConfig
166
+	config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
167
+	routerAddress, postData := fapiao.QueryStock(config) //发票开具
168
+	r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
169
+	if err != nil {
170
+		fmt.Println(err)
171
+	} else {
172
+		fmt.Println(string(r))
173
+	}
174
+
175
+}
176
+
177
+func (c *FapiaoApiController) OpenFaPiao() {
178
+	GetQRStatus(c.GetAdminUserInfo().CurrentOrgId)
179
+	sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
180
+	var config models.FapiaoConfig
181
+	config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
182
+	routerAddress, postData := fapiao.Blue(config) //发票开具
183
+	r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
184
+	if err != nil {
185
+		fmt.Println(err)
186
+	} else {
187
+		fmt.Println(string(r))
188
+	}
189
+}
190
+
191
+func (c *FapiaoApiController) RedFaPiao() {
192
+	GetQRStatus(c.GetAdminUserInfo().CurrentOrgId)
193
+	sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
194
+	//var config models.FapiaoConfig
195
+	//config, _ = service.FindFaPiaoConfigInfo(c.GetAdminUserInfo().CurrentOrgId)
196
+	routerAddress, postData := fapiao.Red() //发票开具
197
+	r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
198
+	if err != nil {
199
+		fmt.Println(err)
200
+	} else {
201
+		fmt.Println(string(r))
202
+	}
203
+}
204
+
205
+func GetQRStatus(org_id int64) {
206
+	redis := service.RedisClient()
207
+	defer redis.Close()
208
+	sdk := invoice.NewSdk(common.HMAC_SHA256, "8ca4ee7b152c0abceff9", "17402aff152dbeedf7a7b30be553f4c4", "", "test")
209
+	var config models.FapiaoConfig
210
+	config, _ = service.FindFaPiaoConfigInfo(org_id)
211
+	routerAddress, postData := fapiao.GetQRStatus("", config) //发票开具
212
+	r, err := sdk.HttpPost("https://apigw-test.goldentec.com", routerAddress, postData)
213
+	if err != nil {
214
+		fmt.Println(err)
215
+	} else {
216
+		fmt.Println(string(r))
217
+	}
218
+}

+ 142 - 2
controllers/statistics_api_controller.go View File

@@ -44,6 +44,148 @@ func StatisticsApiRegistRouters() {
44 44
 	beego.Router("/api/commonqc/dialysistreat/finish", &StatisticsApiController{}, "get:GetDialysisTreatFinsh")
45 45
 	beego.Router("/api/commonqc/dialysistreat/detail", &StatisticsApiController{}, "get:GetDialysisTreatDetail")
46 46
 
47
+	beego.Router("/api/commonqc/patinet/weight", &StatisticsApiController{}, "get:GetPatientWeight")
48
+	beego.Router("/api/commonqc/weight/detail", &StatisticsApiController{}, "get:GetPatientWeightDetail")
49
+	beego.Router("/api/commonqc/patinet/bp", &StatisticsApiController{}, "get:GetPatientBP")
50
+	beego.Router("/api/commonqc/bp/detail", &StatisticsApiController{}, "get:GetPatientBPDetail")
51
+
52
+}
53
+func (c *StatisticsApiController) GetPatientWeight() {
54
+	start_time := c.GetString("start_time")
55
+	end_time := c.GetString("end_time")
56
+	statistics_type, _ := c.GetInt("statistics_type")
57
+
58
+	timeLayout := "2006-01-02"
59
+	loc, _ := time.LoadLocation("Local")
60
+	var startTime int64
61
+	if len(start_time) > 0 {
62
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
63
+		fmt.Println("err-----------", err)
64
+		if err != nil {
65
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
66
+			return
67
+		}
68
+		startTime = theTime.Unix()
69
+	}
70
+	var endTime int64
71
+	if len(end_time) > 0 {
72
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
73
+		if err != nil {
74
+			utils.ErrorLog(err.Error())
75
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
76
+			return
77
+		}
78
+		endTime = theTime.Unix()
79
+	}
80
+	item, _ := service.GetNewDialysisWeightChartData(c.GetAdminUserInfo().CurrentOrgId, startTime, endTime, statistics_type)
81
+	c.ServeSuccessJSON(map[string]interface{}{
82
+		"list": item,
83
+	})
84
+}
85
+func (c *StatisticsApiController) GetPatientWeightDetail() {
86
+	start_time := c.GetString("start_time")
87
+	end_time := c.GetString("end_time")
88
+	add_type, _ := c.GetInt64("add_type")
89
+	dry_type, _ := c.GetInt64("dry_type")
90
+	after_type, _ := c.GetInt64("after_type")
91
+	page, _ := c.GetInt64("page")
92
+	limit, _ := c.GetInt64("limit")
93
+
94
+	timeLayout := "2006-01-02"
95
+	loc, _ := time.LoadLocation("Local")
96
+	var startTime int64
97
+	if len(start_time) > 0 {
98
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
99
+		fmt.Println("err-----------", err)
100
+		if err != nil {
101
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
102
+			return
103
+		}
104
+		startTime = theTime.Unix()
105
+	}
106
+	var endTime int64
107
+	if len(end_time) > 0 {
108
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
109
+		if err != nil {
110
+			utils.ErrorLog(err.Error())
111
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
112
+			return
113
+		}
114
+		endTime = theTime.Unix()
115
+	}
116
+	data, total, _ := service.GetNewDialysisWeightDetailTableTen(c.GetAdminUserInfo().CurrentOrgId, startTime, endTime, add_type, dry_type, after_type, page, limit)
117
+	c.ServeSuccessJSON(map[string]interface{}{
118
+		"list":  data,
119
+		"total": total,
120
+	})
121
+}
122
+func (c *StatisticsApiController) GetPatientBP() {
123
+	start_time := c.GetString("start_time")
124
+	end_time := c.GetString("end_time")
125
+	statistics_type, _ := c.GetInt("statistics_type")
126
+
127
+	timeLayout := "2006-01-02"
128
+	loc, _ := time.LoadLocation("Local")
129
+	var startTime int64
130
+	if len(start_time) > 0 {
131
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
132
+		fmt.Println("err-----------", err)
133
+		if err != nil {
134
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
135
+			return
136
+		}
137
+		startTime = theTime.Unix()
138
+	}
139
+	var endTime int64
140
+	if len(end_time) > 0 {
141
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
142
+		if err != nil {
143
+			utils.ErrorLog(err.Error())
144
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
145
+			return
146
+		}
147
+		endTime = theTime.Unix()
148
+	}
149
+	item, _ := service.GetNewDialysisBloodChartData(c.GetAdminUserInfo().CurrentOrgId, startTime, endTime, statistics_type)
150
+	c.ServeSuccessJSON(map[string]interface{}{
151
+		"list": item,
152
+	})
153
+}
154
+func (c *StatisticsApiController) GetPatientBPDetail() {
155
+	start_time := c.GetString("start_time")
156
+	end_time := c.GetString("end_time")
157
+	add_type, _ := c.GetInt64("status_type")
158
+	page, _ := c.GetInt64("page")
159
+	limit, _ := c.GetInt64("limit")
160
+
161
+	timeLayout := "2006-01-02"
162
+	loc, _ := time.LoadLocation("Local")
163
+	var startTime int64
164
+	if len(start_time) > 0 {
165
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
166
+		fmt.Println("err-----------", err)
167
+		if err != nil {
168
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
169
+			return
170
+		}
171
+		startTime = theTime.Unix()
172
+	}
173
+	var endTime int64
174
+	if len(end_time) > 0 {
175
+		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
176
+		if err != nil {
177
+			utils.ErrorLog(err.Error())
178
+			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
179
+			return
180
+		}
181
+		endTime = theTime.Unix()
182
+	}
183
+	data, total, _ := service.GetNewDialysisBPDetailTableTen(c.GetAdminUserInfo().CurrentOrgId, startTime, endTime, add_type, page, limit)
184
+	c.ServeSuccessJSON(map[string]interface{}{
185
+		"list":  data,
186
+		"total": total,
187
+	})
188
+
47 189
 }
48 190
 
49 191
 func (c *StatisticsApiController) GetDialysisTreatFinsh() {
@@ -118,7 +260,6 @@ func (c *StatisticsApiController) GetDialysisTreatDetail() {
118 260
 		"total": total,
119 261
 	})
120 262
 }
121
-
122 263
 func (c *StatisticsApiController) GetDialysisTotal() {
123 264
 	start_date := c.GetString("start_date")
124 265
 	end_date := c.GetString("end_date")
@@ -1204,7 +1345,6 @@ func (c *StatisticsApiController) GetDialysisTotalDetailInfo() {
1204 1345
 	}
1205 1346
 
1206 1347
 }
1207
-
1208 1348
 func (c *StatisticsApiController) GetAnticoagulant() {
1209 1349
 	start_date := c.GetString("start_date")
1210 1350
 	end_date := c.GetString("end_date")

+ 91 - 0
models/fapiao.go View File

@@ -0,0 +1,91 @@
1
+package models
2
+
3
+type FapiaoConfig struct {
4
+	ID                int64  `gorm:"column:id" json:"id" form:"id"`
5
+	UserOrgId         int64  `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
6
+	IsUse             int64  `gorm:"column:is_use" json:"is_use" form:"is_use"`
7
+	TaxpayerId        string `gorm:"column:taxpayer_id" json:"taxpayer_id" form:"taxpayer_id"`
8
+	TerminalCode      string `gorm:"column:terminal_code" json:"terminal_code" form:"terminal_code"`
9
+	SellerTaxpayerNum string `gorm:"column:seller_taxpayer_num" json:"seller_taxpayer_num" form:"seller_taxpayer_num"`
10
+	SellerAddress     string `gorm:"column:seller_address" json:"seller_address" form:"seller_address"`
11
+	SellerTel         string `gorm:"column:seller_tel" json:"seller_tel" form:"seller_tel"`
12
+	SellerBankName    string `gorm:"column:seller_bank_name" json:"seller_bank_name" form:"seller_bank_name"`
13
+	SellerBankAccount string `gorm:"column:seller_bank_account" json:"seller_bank_account" form:"seller_bank_account"`
14
+	TitleType         string `gorm:"column:title_type" json:"title_type" form:"title_type"`
15
+	BuyerTitle        string `gorm:"column:buyer_title" json:"buyer_title" form:"buyer_title"`
16
+	CallbackUrl       string `gorm:"column:callback_url" json:"callback_url" form:"callback_url"`
17
+	UserOpenid        string `gorm:"column:user_openid" json:"user_openid" form:"user_openid"`
18
+}
19
+
20
+func (FapiaoConfig) TableName() string {
21
+	return "fapiao_config"
22
+}
23
+
24
+type HisOrderByFaPiao struct {
25
+	ID                 int64          `gorm:"column:id" json:"id" form:"id"`
26
+	UserOrgId          int64          `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
27
+	HisPatientId       int64          `gorm:"column:his_patient_id" json:"his_patient_id" form:"his_patient_id"`
28
+	SettleAccountsDate int64          `gorm:"column:settle_accounts_date" json:"settle_accounts_date" form:"settle_accounts_date"`
29
+	Ctime              int64          `gorm:"column:ctime" json:"ctime" form:"ctime"`
30
+	Mtime              int64          `gorm:"column:mtime" json:"mtime" form:"mtime"`
31
+	Status             int64          `gorm:"column:status" json:"status" form:"status"`
32
+	Number             string         `gorm:"column:number" json:"number" form:"number"`
33
+	PatientId          int64          `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
34
+	Infcode            int64          `gorm:"column:infcode" json:"infcode" form:"infcode"`
35
+	WarnMsg            string         `gorm:"column:warn_msg" json:"warn_msg" form:"warn_msg"`
36
+	Cainfo             string         `gorm:"column:cainfo" json:"cainfo" form:"cainfo"`
37
+	ErrMsg             string         `gorm:"column:err_msg" json:"err_msg" form:"err_msg"`
38
+	RespondTime        string         `gorm:"column:respond_time" json:"respond_time" form:"respond_time"`
39
+	InfRefmsgid        string         `gorm:"column:inf_refmsgid" json:"inf_refmsgid" form:"inf_refmsgid"`
40
+	OrderStatus        int64          `gorm:"column:order_status" json:"order_status" form:"order_status"`
41
+	MdtrtId            string         `gorm:"column:mdtrt_id" json:"mdtrt_id" form:"mdtrt_id"`
42
+	SetlId             string         `gorm:"column:setl_id" json:"setl_id" form:"setl_id"`
43
+	PsnNo              string         `gorm:"column:psn_no" json:"psn_no" form:"psn_no"`
44
+	PsnName            string         `gorm:"column:psn_name" json:"psn_name" form:"psn_name"`
45
+	PsnCertType        string         `gorm:"column:psn_cert_type" json:"psn_cert_type" form:"psn_cert_type"`
46
+	Certno             string         `gorm:"column:certno" json:"certno" form:"certno"`
47
+	Gend               string         `gorm:"column:gend" json:"gend" form:"gend"`
48
+	Insutype           string         `gorm:"column:insutype" json:"insutype" form:"insutype"`
49
+	SetlTime           string         `gorm:"column:setl_time" json:"setl_time" form:"setl_time"`
50
+	MedType            string         `gorm:"column:med_type" json:"med_type" form:"med_type"`
51
+	MedfeeSumamt       float64        `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
52
+	FaPiaoCode         string         `gorm:"column:fa_piao_code" json:"fa_piao_code" form:"fa_piao_code"`
53
+	FaPiaoNumber       string         `gorm:"column:fa_piao_number" json:"fa_piao_number" form:"fa_piao_number"`
54
+	Patients           Patients       `gorm:"ForeignKey:PatientId;AssociationForeignKey:ID" json:"patient"`
55
+	HisPatient         HisPatient     `gorm:"ForeignKey:MdtrtId;AssociationForeignKey:Number" json:"his_patient"`
56
+	HisFaPiaoOrder     HisFaPiaoOrder `gorm:"ForeignKey:FaPiaoNumber;AssociationForeignKey:TicketSn" json:"result"`
57
+}
58
+
59
+func (HisOrderByFaPiao) TableName() string {
60
+	return "his_order"
61
+}
62
+
63
+type HisFaPiaoOrder struct {
64
+	ID               int64   `gorm:"column:id" json:"id" form:"id"`
65
+	InvoiceId        string  `gorm:"column:invoice_id" json:"invoice_id" form:"invoice_id"`
66
+	OrderSn          string  `gorm:"column:order_sn" json:"order_sn" form:"order_sn"`
67
+	TicketSn         string  `gorm:"column:ticket_sn" json:"ticket_sn" form:"ticket_sn"`
68
+	TicketDate       string  `gorm:"column:ticket_date" json:"ticket_date" form:"ticket_date"`
69
+	AmountWithTax    string  `gorm:"column:amount_with_tax" json:"amount_with_tax" form:"amount_with_tax"`
70
+	AmountWithoutTax string  `gorm:"column:amount_without_tax" json:"amount_without_tax" form:"amount_without_tax"`
71
+	TaxAmount        string  `gorm:"column:tax_amount" json:"tax_amount" form:"tax_amount"`
72
+	IsRedWashed      string  `gorm:"column:is_red_washed" json:"is_red_washed" form:"is_red_washed"`
73
+	PdfUrl           string  `gorm:"column:pdf_url" json:"pdf_url" form:"pdf_url"`
74
+	OfdUrl           string  `gorm:"column:ofd_url" json:"ofd_url" form:"ofd_url"`
75
+	XmlUrl           string  `gorm:"column:xml_url" json:"xml_url" form:"xml_url"`
76
+	FapiaoStatus     string  `gorm:"column:fapiao_status" json:"fapiao_status" form:"fapiao_status"`
77
+	OrderIds         string  `gorm:"column:order_ids" json:"order_ids" form:"order_ids"`
78
+	UserOrgId        int64   `gorm:"column:user_org_id" json:"user_org_id" form:"user_org_id"`
79
+	Status           int64   `gorm:"column:status" json:"status" form:"status"`
80
+	PatientId        int64   `gorm:"column:patient_id" json:"patient_id" form:"patient_id"`
81
+	Ctime            int64   `gorm:"column:ctime" json:"ctime" form:"ctime"`
82
+	Mtime            int64   `gorm:"column:mtime" json:"mtime" form:"mtime"`
83
+	Creator          string  `gorm:"column:creator" json:"creator" form:"creator"`
84
+	MedfeeSumamt     float64 `gorm:"column:medfee_sumamt" json:"medfee_sumamt" form:"medfee_sumamt"`
85
+	PsnCashPay       float64 `gorm:"column:psn_cash_pay" json:"psn_cash_pay" form:"psn_cash_pay"`
86
+	FundPaySumamt    float64 `gorm:"column:fund_pay_sumamt" json:"fund_pay_sumamt" form:"fund_pay_sumamt"`
87
+}
88
+
89
+func (HisFaPiaoOrder) TableName() string {
90
+	return "his_fapiao_order"
91
+}

+ 1 - 0
routers/router.go View File

@@ -88,4 +88,5 @@ func init() {
88 88
 	controllers.ZuobiaoApiRegistRouters()
89 89
 	controllers.HisExportDataApiRegistRouters()
90 90
 	controllers.NewStockApiRegistRouters()
91
+	controllers.FaPiaoApiRegistRouters()
91 92
 }

+ 63 - 0
service/fapiao/bule.go View File

@@ -0,0 +1,63 @@
1
+package fapiao
2
+
3
+import "XT_New/models"
4
+
5
+func Blue(config models.FapiaoConfig) (routerAddress string, postData map[string]interface{}) {
6
+
7
+	routerAddress = "/tax-api/invoice/blue/v1"
8
+
9
+	postData = map[string]interface{}{
10
+		"seller_name":          "wkbb invoice blue test",
11
+		"seller_taxpayer_num":  "your seller_taxpayer_num",
12
+		"seller_address":       "",
13
+		"seller_tel":           "",
14
+		"seller_bank_name":     "",
15
+		"seller_bank_account":  "",
16
+		"title_type":           1,
17
+		"buyer_title":          "海南高灯科技",
18
+		"buyer_taxpayer_num":   "",
19
+		"buyer_address":        "",
20
+		"buyer_bank_name":      "",
21
+		"buyer_bank_account":   "",
22
+		"buyer_phone":          "",
23
+		"buyer_email":          "",
24
+		"taker_phone":          "",
25
+		"order_id":             "fc5fec2d1b6942658c009a151d4cffa5",
26
+		"invoice_type_code":    "032",
27
+		"callback_url":         "http://www.test.com",
28
+		"drawer":               "TEST",
29
+		"payee":                "TEST",
30
+		"checker":              "TEST",
31
+		"terminal_code":        "661234567789",
32
+		"user_openid":          "ba9ea0bdfa1f460993c990564caab18f",
33
+		"special_invoice_kind": "",
34
+		"zsfs":                 "",
35
+		"deduction":            "",
36
+		"amount_has_tax":       "66.66",
37
+		"tax_amount":           "66.66",
38
+		"amount_without_tax":   "66.66",
39
+		"remark":               "readme",
40
+	}
41
+
42
+	//项目商品明细
43
+	items := make([]map[string]interface{}, 1)
44
+	item := make(map[string]interface{})
45
+	item["name"] = "海鲜真划算"
46
+	item["tax_code"] = "your tax_code"
47
+	item["models"] = "zyx"
48
+	item["unit"] = "个"
49
+	item["total_price"] = "66.66"
50
+	item["total"] = "5"
51
+	item["price"] = "17.22"
52
+	item["tax_rate"] = "66.66"
53
+	item["tax_amount"] = "66.66"
54
+	item["discount"] = "66.66"
55
+	item["preferential_policy_flag"] = "0"
56
+	item["zero_tax_flag"] = "0"
57
+	item["vat_special_management"] = ""
58
+	items[0] = item
59
+
60
+	postData["items"] = items
61
+
62
+	return routerAddress, postData
63
+}

+ 16 - 0
service/fapiao/invalid.go View File

@@ -0,0 +1,16 @@
1
+package fapiao
2
+
3
+func Invalid() (routerAddress string, postData map[string]interface{}) {
4
+
5
+	routerAddress = "/tax-api/invoice/invalid/v1"
6
+
7
+	postData = map[string]interface{}{
8
+		"seller_taxpayer_num": "500102010004038",
9
+		"order_sn":            "",
10
+		"order_id":            "gp_20190828115454_742_11296_31131",
11
+		"name":                "fff",
12
+		"is_red":              0,
13
+	}
14
+
15
+	return routerAddress, postData
16
+}

+ 13 - 0
service/fapiao/login.go View File

@@ -0,0 +1,13 @@
1
+package fapiao
2
+
3
+import "XT_New/models"
4
+
5
+func Login(code string, config models.FapiaoConfig) (routerAddress string, postData map[string]interface{}) {
6
+	routerAddress = "/tax-api/invoice/sms/upload/v1"
7
+	postData = map[string]interface{}{
8
+		"taxpayer_id":   config.TaxpayerId,
9
+		"terminal_code": config.TerminalCode,
10
+		"sms_code":      code,
11
+	}
12
+	return routerAddress, postData
13
+}

+ 18 - 0
service/fapiao/print.go View File

@@ -0,0 +1,18 @@
1
+package fapiao
2
+
3
+func Print() (routerAddress string, postData map[string]interface{}) {
4
+
5
+	routerAddress = "/tax-api/invoice/print/v1"
6
+
7
+	postData = map[string]interface{}{
8
+		"seller_taxpayer_num": "500102010004038",
9
+		"order_sn":            "",
10
+		"order_id":            "gp_20190828115454_742_11296_31131",
11
+		"print_type":          "",
12
+		"print_flag":          "",
13
+		"print_mode":          "",
14
+		"is_red":              0,
15
+	}
16
+
17
+	return routerAddress, postData
18
+}

+ 26 - 0
service/fapiao/qrcode.go View File

@@ -0,0 +1,26 @@
1
+package fapiao
2
+
3
+import "XT_New/models"
4
+
5
+func GetQRCode(config models.FapiaoConfig) (routerAddress string, postData map[string]interface{}) {
6
+
7
+	routerAddress = "/tax-api/invoice/auth/get-qrcode/v1"
8
+	postData = map[string]interface{}{
9
+		"taxpayer_id":   config.TaxpayerId,
10
+		"terminal_code": config.TerminalCode,
11
+	}
12
+
13
+	return routerAddress, postData
14
+}
15
+
16
+func GetQRStatus(auth_id string, config models.FapiaoConfig) (routerAddress string, postData map[string]interface{}) {
17
+
18
+	routerAddress = "tax-api/invoice/auth/query-qrcode-status/v1"
19
+	postData = map[string]interface{}{
20
+		"taxpayer_id":   config.TaxpayerId,
21
+		"terminal_code": config.TerminalCode,
22
+		"auth_id":       auth_id,
23
+	}
24
+
25
+	return routerAddress, postData
26
+}

+ 27 - 0
service/fapiao/query.go View File

@@ -0,0 +1,27 @@
1
+package fapiao
2
+
3
+import "XT_New/models"
4
+
5
+func Query() (routerAddress string, postData map[string]interface{}) {
6
+
7
+	routerAddress = "/tax-api/invoice/query/v1"
8
+
9
+	postData = map[string]interface{}{
10
+		"seller_taxpayer_num": "500102010004038",
11
+		"order_sn":            "",
12
+		"order_id":            "gp_20190828115454_742_11296_31131",
13
+		"is_red":              0,
14
+	}
15
+
16
+	return routerAddress, postData
17
+}
18
+
19
+func QueryStock(config models.FapiaoConfig) (routerAddress string, postData map[string]interface{}) {
20
+	routerAddress = "/tax-api/invoice/query-stock/v1"
21
+	postData = map[string]interface{}{
22
+		"taxpayer_id":       config.TaxpayerId,
23
+		"terminal_code":     config.TerminalCode,
24
+		"invoice_type_code": "007",
25
+	}
26
+	return routerAddress, postData
27
+}

+ 21 - 0
service/fapiao/red.go View File

@@ -0,0 +1,21 @@
1
+package fapiao
2
+
3
+func Red() (routerAddress string, postData map[string]interface{}) {
4
+
5
+	routerAddress = "/tax-api/invoice/red/v1"
6
+
7
+	invoices := make([]map[string]interface{}, 1)
8
+
9
+	invoice := make(map[string]interface{})
10
+	invoice["seller_taxpayer_num"] = "111112222233333"
11
+	invoice["callback_url"] = "http://test.feehi.com/sign/mock/invoice-callback.php"
12
+	invoice["order_sn"] = "6555407740980870214"
13
+
14
+	invoices[0] = invoice
15
+
16
+	postData = map[string]interface{}{
17
+		"invoices": invoices,
18
+	}
19
+
20
+	return routerAddress, postData
21
+}

+ 14 - 0
service/fapiao/sms.go View File

@@ -0,0 +1,14 @@
1
+package fapiao
2
+
3
+import "XT_New/models"
4
+
5
+func GetSMSCode(config models.FapiaoConfig) (routerAddress string, postData map[string]interface{}) {
6
+
7
+	routerAddress = "/tax-api/invoice/login/check/v1"
8
+	postData = map[string]interface{}{
9
+		"taxpayer_id":   config.TaxpayerId,
10
+		"terminal_code": config.TerminalCode,
11
+	}
12
+
13
+	return routerAddress, postData
14
+}

+ 14 - 0
service/fapiao/waitopen.go View File

@@ -0,0 +1,14 @@
1
+package fapiao
2
+
3
+func WaitOpen() (routerAddress string, postData map[string]interface{}) {
4
+
5
+	routerAddress = "/tax-api/invoice/wait-open/v1"
6
+
7
+	postData = map[string]interface{}{
8
+		"taxpayer_num":      "20181010000000865115391398242493",
9
+		"machine_no":        "125523523523",
10
+		"invoice_type_code": "026",
11
+	}
12
+
13
+	return routerAddress, postData
14
+}

+ 85 - 0
service/fapiao_service.go View File

@@ -0,0 +1,85 @@
1
+package service
2
+
3
+import "XT_New/models"
4
+
5
+func FindFaPiaoConfigInfo(org_id int64) (config models.FapiaoConfig, err error) {
6
+	err = readDb.Model(&models.FapiaoConfig{}).Where("status = 1 AND user_org_id = ?", org_id).First(&config).Error
7
+	return
8
+}
9
+
10
+func GetFaPiaoSettleList(user_org_id int64, page int64, limit int64, start_time_timestamp int64, end_time_timestamp int64, sort_type int64, start_time string, end_time string, is_open_fapiao int64, patient_id int64) (order []*models.HisOrderByFaPiao, err error, total int64) {
11
+	offset := (page - 1) * limit
12
+	db := readDb.Model(&models.HisOrderByFaPiao{})
13
+
14
+	// Join the patients table based on user_org_id
15
+	db = db.Joins("join xt_patients as patient on patient.id = his_order.patient_id and patient.user_org_id = ?", user_org_id)
16
+
17
+	// Handle the is_open_fapiao logic
18
+	if is_open_fapiao == 1 {
19
+		// is_open_fapiao == 1: Look for orders with a corresponding fa_piao_number
20
+		db = db.Joins("left join his_fapiao_order as fo on fo.ticket_sn = his_order.fa_piao_number and fo.user_org_id = ?", user_org_id).
21
+			Where("fo.id IS NOT NULL") // Ensure fa_piao_number exists
22
+	} else if is_open_fapiao == 2 {
23
+		// is_open_fapiao == 2: Look for orders without a corresponding fa_piao_number
24
+		db = db.Joins("left join his_fapiao_order as fo on fo.ticket_sn = his_order.fa_piao_number and fo.user_org_id = ?", user_org_id).
25
+			Where("fo.id IS NULL") // Ensure fa_piao_number does not exist
26
+	}
27
+
28
+	// Handle sorting logic
29
+	if sort_type == 1 {
30
+		if start_time_timestamp != 0 {
31
+			db = db.Where("his_order.settle_accounts_date >= ?", start_time_timestamp)
32
+		}
33
+		if end_time_timestamp != 0 {
34
+			db = db.Where("his_order.settle_accounts_date <= ?", end_time_timestamp)
35
+		}
36
+	} else {
37
+		if len(start_time) != 0 {
38
+			db = db.Where("his_order.setl_time >= ?", start_time+" 00:00:00")
39
+		}
40
+		if len(end_time) != 0 {
41
+			db = db.Where("his_order.setl_time <= ?", end_time+" 23:59:59")
42
+		}
43
+	}
44
+	if patient_id > 0 {
45
+		db = db.Where("his_order.patient_id = ?", patient_id)
46
+
47
+	}
48
+
49
+	// Preload related data
50
+	db = db.Preload("Patients", "status = 1 AND user_org_id = ?", user_org_id).
51
+		Preload("HisPatient", "status = 1 AND user_org_id = ?", user_org_id).
52
+		Preload("HisFaPiaoOrder", "status = 1")
53
+
54
+	// Count the total number of records
55
+	db = db.Count(&total)
56
+
57
+	// Apply pagination
58
+	db = db.Limit(limit).Offset(offset)
59
+
60
+	// Execute query and return results
61
+	err = db.Find(&order).Error
62
+	//
63
+	//for _, item := range order {
64
+	//	var hfpo models.HisFaPiaoOrder
65
+	//	readDb.Model(&models.HisFaPiaoOrder{}).Where("ticket_sn = ?", item.FaPiaoNumber).First(&hfpo)
66
+	//	item.HisFaPiaoOrder =
67
+	//}
68
+
69
+	return
70
+}
71
+
72
+func GetFaPiaoList(user_org_id int64, page int64, limit int64, start_time_timestamp int64, end_time_timestamp int64) (order []*models.HisOrder, err error, total int64) {
73
+	offset := (page - 1) * limit
74
+	db := readDb.Model(&models.HisFaPiaoOrder{})
75
+	db = db.Preload("Patients", "status = 1 AND user_org_id = ?", user_org_id).
76
+		Preload("HisFaPiaoOrder", "status = 1")
77
+	db = db.Where("ctime >= ? and ctime <= ? and user_org_id = ?", start_time_timestamp, end_time_timestamp, user_org_id)
78
+	// Count the total number of records
79
+	db = db.Count(&total)
80
+	// Apply pagination
81
+	db = db.Limit(limit).Offset(offset)
82
+	// Execute query and return results
83
+	err = db.Find(&order).Error
84
+	return
85
+}

+ 1 - 4
service/statistics_service/index_evaluation_service.go View File

@@ -365,16 +365,13 @@ func GetDialysisWeightChartData(user_org_id int64, start_time int64, end_time in
365 365
 			if item.Name == "40~50kg" {
366 366
 				isHasConditionTwo = true
367 367
 			}
368
-
369 368
 			if item.Name == "60~70kg" {
370 369
 				isHasConditionThree = true
371 370
 			}
372
-
373 371
 			if item.Name == "大于70kg" {
374 372
 				isHasConditionFour = true
375 373
 			}
376
-
377
-			if item.Name == "未知" {
374
+			if item.Name == "待定/卧床" {
378 375
 				isHasConditionFive = true
379 376
 			}
380 377
 		}

+ 826 - 0
service/statistis_qc_service.go View File

@@ -3,7 +3,10 @@ package service
3 3
 import (
4 4
 	"database/sql"
5 5
 	"fmt"
6
+	"log"
7
+	"math"
6 8
 	"reflect"
9
+	"strconv"
7 10
 	"strings"
8 11
 	"time"
9 12
 
@@ -1232,3 +1235,826 @@ func GetScheduleInfo(start_date string, end_date string, mode int64, org_id int6
1232 1235
 	}).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
1233 1236
 	return
1234 1237
 }
1238
+
1239
+type otherItemAmount struct {
1240
+	Total int64  `json:"total"`
1241
+	Name  string `json:"name"`
1242
+	Ratio string `json:"ratio"`
1243
+}
1244
+
1245
+// xt_patients model
1246
+type Patient struct {
1247
+	ID       uint   `gorm:"primaryKey"`
1248
+	IDCardNo string `gorm:"column:id_card_no"`
1249
+}
1250
+
1251
+// xt_assessment_before_dislysis model
1252
+type Assessment struct {
1253
+	ID             uint      `gorm:"id"`
1254
+	PatientID      uint      `gorm:"column:patient_id"`
1255
+	SystolicBP     int       `gorm:"column:systolic_blood_pressure"`
1256
+	DiastolicBP    int       `gorm:"column:diastolic_blood_pressure"`
1257
+	AssessmentDate time.Time `gorm:"column:assessment_date"`
1258
+	UserOrgID      int       `gorm:"column:user_org_id"`
1259
+}
1260
+
1261
+func (Assessment) TableName() string {
1262
+	return "xt_assessment_before_dislysis"
1263
+}
1264
+
1265
+// xt_assessment_before_dislysis model
1266
+type AssessmentAfter struct {
1267
+	ID             uint      `gorm:"id"`
1268
+	PatientID      uint      `gorm:"column:patient_id"`
1269
+	SystolicBP     int       `gorm:"column:systolic_blood_pressure"`
1270
+	DiastolicBP    int       `gorm:"column:diastolic_blood_pressure"`
1271
+	AssessmentDate time.Time `gorm:"column:assessment_date"`
1272
+	UserOrgID      int       `gorm:"column:user_org_id"`
1273
+}
1274
+
1275
+func (AssessmentAfter) TableName() string {
1276
+	return "xt_assessment_before_dislysis"
1277
+}
1278
+
1279
+type WeightDetail struct {
1280
+	DialysisNo      string
1281
+	PatientName     string
1282
+	Gender          int64
1283
+	IDCardNo        string
1284
+	DialysisDate    string
1285
+	DryWeight       float64
1286
+	LastWeightAfter float64
1287
+	WeightBefore    float64
1288
+}
1289
+
1290
+func GetNewDialysisWeightChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int) (item []*otherItemAmount, err error) {
1291
+	db := XTReadDB()
1292
+	var items []*otherItemAmount
1293
+	var tempErr error
1294
+	var Total int64
1295
+	switch statistics_type {
1296
+	case 1:
1297
+		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)
1298
+		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).
1299
+			Select("CASE WHEN dry_weight < 40 THEN '小于40kg'" +
1300
+				" WHEN dry_weight >= 40 AND dry_weight < 50 THEN '40~50kg'" +
1301
+				" WHEN dry_weight >= 50 AND dry_weight < 60 THEN '50~60kg'" +
1302
+				" WHEN dry_weight >= 60 AND dry_weight < 70 THEN '60~70kg'" +
1303
+				" WHEN dry_weight >= 70 THEN '大于70kg'" +
1304
+				" ELSE '未知' END AS name, COUNT(*) AS total",
1305
+			).Group("name").Scan(&items).Error
1306
+
1307
+		var isHasConditionOne bool = false
1308
+		var isHasConditionTwo bool = false
1309
+		var isHasConditionThree bool = false
1310
+		var isHasConditionFour bool = false
1311
+		var isHasConditionFive bool = false
1312
+
1313
+		for _, item := range items {
1314
+			if item.Name == "小于40kg" {
1315
+				isHasConditionOne = true
1316
+			}
1317
+			if item.Name == "40~50kg" {
1318
+				isHasConditionTwo = true
1319
+			}
1320
+			if item.Name == "60~70kg" {
1321
+				isHasConditionThree = true
1322
+			}
1323
+			if item.Name == "大于70kg" {
1324
+				isHasConditionFour = true
1325
+			}
1326
+			if item.Name == "待定/卧床" {
1327
+				isHasConditionFive = true
1328
+			}
1329
+		}
1330
+		if !isHasConditionOne {
1331
+			newItem := &otherItemAmount{
1332
+				Total: 0,
1333
+				Name:  "小于40kg",
1334
+				Ratio: "0",
1335
+			}
1336
+			items = append(items, newItem)
1337
+		}
1338
+
1339
+		if !isHasConditionTwo {
1340
+			newItem := &otherItemAmount{
1341
+				Total: 0,
1342
+				Name:  "40~50kg",
1343
+				Ratio: "0",
1344
+			}
1345
+			items = append(items, newItem)
1346
+		}
1347
+		if !isHasConditionThree {
1348
+			newItem := &otherItemAmount{
1349
+				Total: 0,
1350
+				Name:  "60~70kg",
1351
+				Ratio: "0",
1352
+			}
1353
+			items = append(items, newItem)
1354
+
1355
+		}
1356
+
1357
+		if !isHasConditionFour {
1358
+			newItem := &otherItemAmount{
1359
+				Total: 0,
1360
+				Name:  "大于70kg",
1361
+				Ratio: "0",
1362
+			}
1363
+			items = append(items, newItem)
1364
+
1365
+		}
1366
+
1367
+		if !isHasConditionFive {
1368
+			newItem := &otherItemAmount{
1369
+				Total: 0,
1370
+				Name:  "未知",
1371
+				Ratio: "0",
1372
+			}
1373
+			items = append(items, newItem)
1374
+		}
1375
+
1376
+		for _, item := range items {
1377
+			if math.IsNaN(float64(item.Total) / float64(Total)) {
1378
+				item.Ratio = "0.0"
1379
+			} else {
1380
+				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
1381
+				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
1382
+			}
1383
+		}
1384
+
1385
+		break
1386
+	case 2:
1387
+
1388
+		//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)
1389
+
1390
+		//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)
1391
+
1392
+		var newTotal int64
1393
+		type weight struct {
1394
+			WeightAfter  float64 `json:"weight_after"`
1395
+			WeightBefore float64 `json:"weight_before"`
1396
+		}
1397
+		var weights []*weight
1398
+		var weightAdd []float64
1399
+		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)
1400
+		for index, _ := range weights {
1401
+			if index+1 < len(weights) {
1402
+				if weights[index+1].WeightAfter == 0 || weights[index].WeightBefore == 0 {
1403
+					continue
1404
+				}
1405
+				weightAdd = append(weightAdd, ((weights[index].WeightBefore - weights[index+1].WeightAfter) / weights[index+1].WeightAfter))
1406
+			}
1407
+		}
1408
+
1409
+		var total_one int64
1410
+		var total_two int64
1411
+		var total_three int64
1412
+		for _, item := range weightAdd {
1413
+			if item <= 0.03 {
1414
+				total_one++
1415
+
1416
+			}
1417
+
1418
+			if item > 0.03 && item < 0.05 {
1419
+				total_two++
1420
+
1421
+			}
1422
+
1423
+			if item >= 0.05 {
1424
+				total_three++
1425
+
1426
+			}
1427
+
1428
+		}
1429
+
1430
+		newTotal = total_one + total_two + total_three
1431
+
1432
+		newItem := &otherItemAmount{
1433
+			Total: total_one,
1434
+			Name:  "体重增长<=3%",
1435
+			Ratio: "0",
1436
+		}
1437
+		newItem1 := &otherItemAmount{
1438
+			Total: total_two,
1439
+			Name:  "3%<体重增长<5%",
1440
+			Ratio: "0",
1441
+		}
1442
+		newItem2 := &otherItemAmount{
1443
+			Total: total_three,
1444
+			Name:  "体重增长>=5%",
1445
+			Ratio: "0",
1446
+		}
1447
+
1448
+		items = append(items, newItem)
1449
+		items = append(items, newItem1)
1450
+		items = append(items, newItem2)
1451
+		for _, item := range items {
1452
+			if math.IsNaN(float64(item.Total) / float64(newTotal)) {
1453
+				item.Ratio = "0.0"
1454
+			} else {
1455
+				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(newTotal))*100), 64)
1456
+				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
1457
+			}
1458
+		}
1459
+
1460
+		break
1461
+	case 3:
1462
+
1463
+		//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)
1464
+
1465
+		//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)
1466
+
1467
+		var newTotal int64
1468
+		type weight struct {
1469
+			DryWeight    float64 `json:"dry_weight"`
1470
+			WeightBefore float64 `json:"weight_before"`
1471
+		}
1472
+		var weights []*weight
1473
+		var weightAdd []float64
1474
+		db.Raw("Select xt_assessment_before_dislysis.dry_weight as dry_weight ,xt_assessment_before_dislysis.weight_before as weight_before from `xt_assessment_before_dislysis`  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)
1475
+		for index, _ := range weights {
1476
+			weightAdd = append(weightAdd, ((weights[index].WeightBefore - weights[index].DryWeight) / weights[index].DryWeight))
1477
+		}
1478
+
1479
+		var total_one int64
1480
+		var total_two int64
1481
+		var total_three int64
1482
+		for _, item := range weightAdd {
1483
+			if item <= 0.03 {
1484
+				total_one++
1485
+
1486
+			}
1487
+
1488
+			if item > 0.03 && item < 0.05 {
1489
+				total_two++
1490
+
1491
+			}
1492
+
1493
+			if item >= 0.05 {
1494
+				total_three++
1495
+
1496
+			}
1497
+
1498
+		}
1499
+
1500
+		newTotal = total_one + total_two + total_three
1501
+
1502
+		newItem := &otherItemAmount{
1503
+			Total: total_one,
1504
+			Name:  "体重增长<=3%",
1505
+			Ratio: "0",
1506
+		}
1507
+		newItem1 := &otherItemAmount{
1508
+			Total: total_two,
1509
+			Name:  "3%<体重增长<5%",
1510
+			Ratio: "0",
1511
+		}
1512
+		newItem2 := &otherItemAmount{
1513
+			Total: total_three,
1514
+			Name:  "体重增长>=5%",
1515
+			Ratio: "0",
1516
+		}
1517
+
1518
+		items = append(items, newItem)
1519
+		items = append(items, newItem1)
1520
+		items = append(items, newItem2)
1521
+		for _, item := range items {
1522
+			if math.IsNaN(float64(item.Total) / float64(newTotal)) {
1523
+				item.Ratio = "0.0"
1524
+			} else {
1525
+				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(newTotal))*100), 64)
1526
+				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
1527
+			}
1528
+		}
1529
+
1530
+		break
1531
+	case 4:
1532
+		var newTotal int64
1533
+		type weight struct {
1534
+			WeightAfter float64 `json:"weight_after"`
1535
+			DryWeight   float64 `json:"dry_weight"`
1536
+		}
1537
+		var weights []*weight
1538
+		//var weightAdd []float64
1539
+		db.Raw("Select xt_assessment_after_dislysis.weight_after as weight_after ,xt_assessment_before_dislysis.dry_weight as dry_weight 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)
1540
+
1541
+		var total_one int64
1542
+		var total_two int64
1543
+		var total_three int64
1544
+		for _, item := range weights {
1545
+			if item.WeightAfter != 0 && item.DryWeight != 0 {
1546
+				if item.WeightAfter-item.DryWeight == 0.3 || item.WeightAfter-item.DryWeight == -0.3 {
1547
+					total_one++
1548
+
1549
+				}
1550
+
1551
+				if item.WeightAfter-item.DryWeight > 0.3 && item.WeightAfter-item.DryWeight < -0.3 {
1552
+					total_two++
1553
+
1554
+				}
1555
+			}
1556
+
1557
+			if item.WeightAfter == 0 {
1558
+				total_three++
1559
+			}
1560
+
1561
+		}
1562
+
1563
+		newTotal = total_one + total_two + total_three
1564
+
1565
+		newItem := &otherItemAmount{
1566
+			Total: total_one,
1567
+			Name:  "达到干体重",
1568
+			Ratio: "0",
1569
+		}
1570
+		newItem1 := &otherItemAmount{
1571
+			Total: total_two,
1572
+			Name:  "未达到干体重",
1573
+			Ratio: "0",
1574
+		}
1575
+		newItem2 := &otherItemAmount{
1576
+			Total: total_three,
1577
+			Name:  "其他或卧床",
1578
+			Ratio: "0",
1579
+		}
1580
+
1581
+		items = append(items, newItem)
1582
+		items = append(items, newItem1)
1583
+		items = append(items, newItem2)
1584
+		for _, item := range items {
1585
+			if math.IsNaN(float64(item.Total) / float64(newTotal)) {
1586
+				item.Ratio = "0.0"
1587
+			} else {
1588
+				float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(newTotal))*100), 64)
1589
+				item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
1590
+			}
1591
+		}
1592
+
1593
+		break
1594
+	}
1595
+	if tempErr != nil {
1596
+		return nil, err
1597
+	}
1598
+
1599
+	fmt.Println(items)
1600
+	return items, nil
1601
+}
1602
+func GetNewDialysisBloodChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int) (item []otherItemAmount, err error) {
1603
+	db := XTReadDB()
1604
+	switch statistics_type {
1605
+	case 1:
1606
+		var assessments []Assessment
1607
+		err = db.Joins("JOIN xt_patients ON xt_patients.id = xt_assessment_before_dislysis.patient_id").
1608
+			Where("xt_assessment_before_dislysis.assessment_date >= ? AND xt_assessment_before_dislysis.assessment_date <= ? AND xt_assessment_before_dislysis.user_org_id = ?", start_time, end_time, user_org_id).
1609
+			Find(&assessments).Error
1610
+		if err != nil {
1611
+			log.Fatal("Query execution error:", err)
1612
+		}
1613
+
1614
+		var total, metStandard, unmetStandard int
1615
+
1616
+		// Iterate through the result set
1617
+		for _, assessment := range assessments {
1618
+			// Fetch patient information
1619
+			var patient Patient
1620
+			err = db.First(&patient, assessment.PatientID).Error
1621
+			if err != nil {
1622
+				log.Printf("Skipping record due to missing patient data for ID: %v", assessment.PatientID)
1623
+				continue
1624
+			}
1625
+
1626
+			// Calculate the patient's age
1627
+			age, err := calculateAge(patient.IDCardNo)
1628
+			if err != nil {
1629
+				log.Printf("Skipping record due to invalid ID card number: %v", patient.IDCardNo)
1630
+				continue
1631
+			}
1632
+
1633
+			// Update the total count of patients
1634
+			total++
1635
+
1636
+			// Determine if the patient meets the standard based on their age and blood pressure
1637
+			if (age < 60 && assessment.SystolicBP < 140 && assessment.DiastolicBP < 90) || (age >= 60 && assessment.SystolicBP < 160 && assessment.DiastolicBP < 90) {
1638
+				metStandard++
1639
+			} else {
1640
+				unmetStandard++
1641
+			}
1642
+		}
1643
+
1644
+		// Calculate and print the results
1645
+		if total > 0 {
1646
+			metPercentage := float64(metStandard) / float64(total) * 100
1647
+			unmetPercentage := float64(unmetStandard) / float64(total) * 100
1648
+			fmt.Printf("Total patients: %d\n", total)
1649
+			fmt.Printf("Met standard: %d (%.2f%%)\n", metStandard, metPercentage)
1650
+			fmt.Printf("Unmet standard: %d (%.2f%%)\n", unmetStandard, unmetPercentage)
1651
+
1652
+			var items otherItemAmount
1653
+			items.Name = "达标患者"
1654
+			items.Ratio = strconv.FormatFloat(metPercentage, 'f', 1, 32)
1655
+			items.Total = int64(metStandard)
1656
+			item = append(item, items)
1657
+
1658
+			var items2 otherItemAmount
1659
+			items2.Name = "未达标患者"
1660
+			items2.Ratio = strconv.FormatFloat(unmetPercentage, 'f', 1, 32)
1661
+			items2.Total = int64(unmetStandard)
1662
+			item = append(item, items2)
1663
+
1664
+		}
1665
+	case 2:
1666
+		var assessments []AssessmentAfter
1667
+		err = db.Joins("JOIN xt_patients ON xt_patients.id = xt_assessment_after_dislysis.patient_id").
1668
+			Where("xt_assessment_after_dislysis.assessment_date >= ? AND xt_assessment_after_dislysis.assessment_date <= ? AND xt_assessment_before_dislysis.user_org_id = ?", start_time, end_time, user_org_id).
1669
+			Find(&assessments).Error
1670
+		if err != nil {
1671
+			log.Fatal("Query execution error:", err)
1672
+		}
1673
+
1674
+		var total, metStandard, unmetStandard int
1675
+
1676
+		// Iterate through the result set
1677
+		for _, assessment := range assessments {
1678
+			// Fetch patient information
1679
+			var patient Patient
1680
+			err = db.First(&patient, assessment.PatientID).Error
1681
+			if err != nil {
1682
+				log.Printf("Skipping record due to missing patient data for ID: %v", assessment.PatientID)
1683
+				continue
1684
+			}
1685
+
1686
+			// Calculate the patient's age
1687
+			age, err := calculateAge(patient.IDCardNo)
1688
+			if err != nil {
1689
+				log.Printf("Skipping record due to invalid ID card number: %v", patient.IDCardNo)
1690
+				continue
1691
+			}
1692
+
1693
+			// Update the total count of patients
1694
+			total++
1695
+
1696
+			// Determine if the patient meets the standard based on their age and blood pressure
1697
+			if (age < 60 && assessment.SystolicBP < 140 && assessment.DiastolicBP < 90) || (age >= 60 && assessment.SystolicBP < 160 && assessment.DiastolicBP < 90) {
1698
+				metStandard++
1699
+			} else {
1700
+				unmetStandard++
1701
+			}
1702
+		}
1703
+
1704
+		// Calculate and print the results
1705
+		if total > 0 {
1706
+			metPercentage := float64(metStandard) / float64(total) * 100
1707
+			unmetPercentage := float64(unmetStandard) / float64(total) * 100
1708
+			fmt.Printf("Total patients: %d\n", total)
1709
+			fmt.Printf("Met standard: %d (%.2f%%)\n", metStandard, metPercentage)
1710
+			fmt.Printf("Unmet standard: %d (%.2f%%)\n", unmetStandard, unmetPercentage)
1711
+
1712
+			var items otherItemAmount
1713
+			items.Name = "达标患者"
1714
+			items.Ratio = strconv.FormatFloat(metPercentage, 'f', 1, 32)
1715
+			items.Total = int64(metStandard)
1716
+			item = append(item, items)
1717
+
1718
+			var items2 otherItemAmount
1719
+			items2.Name = "未达标患者"
1720
+			items2.Ratio = strconv.FormatFloat(unmetPercentage, 'f', 1, 32)
1721
+			items2.Total = int64(unmetStandard)
1722
+			item = append(item, items2)
1723
+		}
1724
+
1725
+		break
1726
+	}
1727
+	return
1728
+}
1729
+func calculateAge(idCardNo string) (int, error) {
1730
+	if len(idCardNo) < 14 {
1731
+		return 0, fmt.Errorf("invalid ID card number")
1732
+	}
1733
+
1734
+	// Extract birth year, month, and day from ID card number
1735
+	year := idCardNo[6:10]
1736
+	month := idCardNo[10:12]
1737
+	day := idCardNo[12:14]
1738
+
1739
+	// Parse the birth date
1740
+	birthDate, err := time.Parse("20060102", year+month+day)
1741
+	if err != nil {
1742
+		return 0, err
1743
+	}
1744
+
1745
+	// Calculate age
1746
+	now := time.Now()
1747
+	age := now.Year() - birthDate.Year()
1748
+	if now.YearDay() < birthDate.YearDay() {
1749
+		age--
1750
+	}
1751
+
1752
+	return age, nil
1753
+}
1754
+
1755
+// 定义结果结构体
1756
+type DialysisDataTwo struct {
1757
+	DialysisNo        string   `json:"dialysis_no"`
1758
+	PatientName       string   `json:"patient_name"`
1759
+	Gender            string   `json:"gender"`
1760
+	Age               int      `json:"age"`
1761
+	AssessmentDate    string   `json:"assessment_date"` // 使用 string 存储日期,或使用 time.Time
1762
+	DryWeight         float64  `json:"dry_weight"`
1763
+	WeightBefore      float64  `json:"weight_before"`
1764
+	WeightAfter       float64  `json:"weight_after"`
1765
+	LastWeightAfter   *float64 `json:"last_weight_after"` // 使用指针处理可能为空的值
1766
+	WeightAdd         *float64 `json:"weight_add"`        // 使用指针处理可能为空的值
1767
+	DryWeightCategory string   `json:"dry_weight_category"`
1768
+	WeightStatus      string   `json:"weight_status"`
1769
+}
1770
+
1771
+func GetNewDialysisWeightDetailTableTen(user_org_id int64, start_time int64, end_time int64, addType, dryType, afterType, page, limit int64) ([]DialysisDataTwo, int64, error) {
1772
+	offset := (page - 1) * limit
1773
+	var dialysisData []DialysisDataTwo
1774
+	var total int64
1775
+	// 构建基本查询
1776
+	query := readDb.Table("xt_assessment_before_dislysis b").
1777
+		Select(`
1778
+			p.dialysis_no AS dialysis_no, 
1779
+			p.name AS patient_name, 
1780
+			p.gender AS gender, 
1781
+			FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS age,
1782
+			b.assessment_date AS assessment_date, 
1783
+			b.dry_weight AS dry_weight, 
1784
+			b.weight_before AS weight_before, 
1785
+			a.weight_after AS weight_after,
1786
+			(
1787
+				SELECT a2.weight_after 
1788
+				FROM xt_assessment_after_dislysis a2
1789
+				JOIN xt_assessment_before_dislysis b2 
1790
+				ON a2.patient_id = b2.patient_id 
1791
+				AND a2.assessment_date = b2.assessment_date
1792
+				WHERE b2.patient_id = b.patient_id 
1793
+				AND b2.assessment_date < b.assessment_date
1794
+				ORDER BY b2.assessment_date DESC LIMIT 1
1795
+			) AS last_weight_after,
1796
+			CASE 
1797
+				WHEN (
1798
+					SELECT a2.weight_after 
1799
+					FROM xt_assessment_after_dislysis a2
1800
+					JOIN xt_assessment_before_dislysis b2 
1801
+					ON a2.patient_id = b2.patient_id 
1802
+					AND a2.assessment_date = b2.assessment_date
1803
+					WHERE b2.patient_id = b.patient_id 
1804
+					AND b2.assessment_date < b.assessment_date
1805
+					ORDER BY b2.assessment_date DESC LIMIT 1
1806
+				) IS NOT NULL
1807
+				THEN (b.weight_before - (
1808
+					SELECT a2.weight_after 
1809
+					FROM xt_assessment_after_dislysis a2
1810
+					JOIN xt_assessment_before_dislysis b2 
1811
+					ON a2.patient_id = b2.patient_id 
1812
+					AND a2.assessment_date = b2.assessment_date
1813
+					WHERE b2.patient_id = b.patient_id 
1814
+					AND b2.assessment_date < b.assessment_date
1815
+					ORDER BY b2.assessment_date DESC LIMIT 1
1816
+				)) / (
1817
+					SELECT a2.weight_after 
1818
+					FROM xt_assessment_after_dislysis a2
1819
+					JOIN xt_assessment_before_dislysis b2 
1820
+					ON a2.patient_id = b2.patient_id 
1821
+					AND a2.assessment_date = b2.assessment_date
1822
+					WHERE b2.patient_id = b.patient_id 
1823
+					AND b2.assessment_date < b.assessment_date
1824
+					ORDER BY b2.assessment_date DESC LIMIT 1
1825
+				)
1826
+				ELSE NULL
1827
+			END AS weight_add,
1828
+			CASE 
1829
+				WHEN b.dry_weight IS NOT NULL THEN 
1830
+					CASE 
1831
+						WHEN b.dry_weight < 40 THEN '小于40'
1832
+						WHEN b.dry_weight BETWEEN 40 AND 50 THEN '40~50'
1833
+						WHEN b.dry_weight BETWEEN 50 AND 60 THEN '50~60'
1834
+						WHEN b.dry_weight BETWEEN 60 AND 70 THEN '60~70'
1835
+						WHEN b.dry_weight > 70 THEN '大于70'
1836
+					END
1837
+				ELSE '其他'
1838
+			END AS dry_weight_category,
1839
+			CASE 
1840
+				WHEN b.dry_weight IS NOT NULL THEN 
1841
+					CASE 
1842
+						WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标'
1843
+						ELSE '不达标'
1844
+					END
1845
+				ELSE '其他'
1846
+			END AS weight_status
1847
+		`).
1848
+		Joins("JOIN xt_patients p ON p.id = b.patient_id").
1849
+		Joins("JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date AND a.status = 1").
1850
+		Where("b.user_org_id = ?", user_org_id).
1851
+		Where("b.assessment_date >= ?", start_time).
1852
+		Where("b.assessment_date <= ?", end_time).
1853
+		Where("b.status = ?", 1)
1854
+	// 根据传入的 add_type 值动态构建条件
1855
+	addTypeCondition(query, addType)
1856
+	// 根据传入的 dry_type 值动态构建条件
1857
+	dryTypeCondition(query, dryType)
1858
+	// 根据传入的 after_type 值动态构建条件
1859
+	afterTypeCondition(query, afterType)
1860
+	// 获取总记录数
1861
+	if err := query.Count(&total).Error; err != nil {
1862
+		return nil, 0, fmt.Errorf("count query failed: %v", err)
1863
+	}
1864
+	// 获取分页数据
1865
+	rows, err := query.Order("p.id, b.assessment_date").Offset(int(offset)).Limit(int(limit)).Rows()
1866
+	if err != nil {
1867
+		return nil, 0, fmt.Errorf("pagination query failed: %v", err)
1868
+	}
1869
+	defer rows.Close()
1870
+	// 处理结果集
1871
+	for rows.Next() {
1872
+		var data DialysisDataTwo
1873
+		if err := rows.Scan(
1874
+			&data.DialysisNo,
1875
+			&data.PatientName,
1876
+			&data.Gender,
1877
+			&data.Age,
1878
+			&data.AssessmentDate,
1879
+			&data.DryWeight,
1880
+			&data.WeightBefore,
1881
+			&data.WeightAfter,
1882
+			&data.LastWeightAfter,
1883
+			&data.WeightAdd,
1884
+			&data.DryWeightCategory,
1885
+			&data.WeightStatus,
1886
+		); err != nil {
1887
+			return nil, 0, fmt.Errorf("row scan failed: %v", err)
1888
+		}
1889
+		// 将每一行结果追加到切片中
1890
+		dialysisData = append(dialysisData, data)
1891
+	}
1892
+	return dialysisData, total, nil
1893
+}
1894
+
1895
+// addType 条件处理
1896
+func addTypeCondition(query *gorm.DB, addType int64) {
1897
+	switch addType {
1898
+	case 1:
1899
+		query.Where("weight_add <= 0.03")
1900
+	case 2:
1901
+		query.Where("weight_add > 0.03 AND weight_add < 0.05")
1902
+	case 3:
1903
+		query.Where("weight_add >= 0.05")
1904
+	case 4:
1905
+		query.Where("weight_add IS NULL")
1906
+	}
1907
+}
1908
+
1909
+// dryType 条件处理
1910
+func dryTypeCondition(query *gorm.DB, dryType int64) {
1911
+	switch dryType {
1912
+	case 1:
1913
+		query.Where("dry_weight_category = '小于40'")
1914
+	case 2:
1915
+		query.Where("dry_weight_category = '40~50'")
1916
+	case 3:
1917
+		query.Where("dry_weight_category = '50~60'")
1918
+	case 4:
1919
+		query.Where("dry_weight_category = '60~70'")
1920
+	case 5:
1921
+		query.Where("dry_weight_category = '大于70'")
1922
+	}
1923
+}
1924
+
1925
+// afterType 条件处理
1926
+func afterTypeCondition(query *gorm.DB, afterType int64) {
1927
+	switch afterType {
1928
+	case 1:
1929
+		query.Where("weight_status = '达标'")
1930
+	case 2:
1931
+		query.Where("weight_status = '不达标'")
1932
+	case 3:
1933
+		query.Where("weight_status = '其他'")
1934
+	}
1935
+}
1936
+
1937
+type DialysisDataThree struct {
1938
+	DialysisNo          string  `json:"透析号"`
1939
+	PatientName         string  `json:"患者姓名"`
1940
+	Gender              string  `json:"性别"`
1941
+	Age                 int     `json:"年龄"`
1942
+	AssessmentDate      string  `json:"透析日期"`
1943
+	DryWeight           float64 `json:"干体重"`
1944
+	PreDialysisBP       string  `json:"透前血压"`
1945
+	PostDialysisBP      string  `json:"透后血压"`
1946
+	MonitoringBP        string  `json:"监测记录血压"`
1947
+	UltrafiltrationRate float64 `json:"超滤率"`
1948
+	UltrafiltrationVol  float64 `json:"超滤总量"`
1949
+	BPStatus            string  `json:"血压达标状态"`
1950
+}
1951
+
1952
+func GetNewDialysisBPDetailTableTen(user_org_id int64, start_time int64, end_time int64, addType, page, limit int64) ([]DialysisDataThree, int64, error) {
1953
+	offset := (page - 1) * limit
1954
+	var total int64
1955
+	var results []DialysisDataThree
1956
+	// SQL 查询
1957
+	query := `
1958
+		SELECT
1959
+			p.dialysis_no AS 透析号,
1960
+			p.name AS 患者姓名,
1961
+			p.gender AS 性别,
1962
+			FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS 年龄,
1963
+			b.assessment_date AS 透析日期,
1964
+			b.dry_weight AS 干体重,
1965
+			CONCAT(b.systolic_blood_pressure, '/', b.diastolic_blood_pressure) AS 透前血压,
1966
+			CONCAT(a.systolic_blood_pressure, '/', a.diastolic_blood_pressure) AS 透后血压,
1967
+			GROUP_CONCAT(CONCAT(m.systolic_blood_pressure, '/', m.diastolic_blood_pressure) ORDER BY m.monitoring_date ASC SEPARATOR ',') AS 监测记录血压,
1968
+			(SELECT mr.ultrafiltration_rate
1969
+			 FROM xt_monitoring_record mr
1970
+			 WHERE mr.patient_id = p.id AND mr.monitoring_date = b.assessment_date
1971
+			 ORDER BY mr.operate_time DESC
1972
+			 LIMIT 1) AS 超滤率,
1973
+			(SELECT mr.ultrafiltration_volume
1974
+			 FROM xt_monitoring_record mr
1975
+			 WHERE mr.patient_id = p.id AND mr.monitoring_date = b.assessment_date
1976
+			 ORDER BY mr.operate_time DESC
1977
+			 LIMIT 1) AS 超滤总量,
1978
+			CASE 
1979
+				WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
1980
+					CASE 
1981
+						WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN '达标'
1982
+						ELSE '不达标'
1983
+					END
1984
+				WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
1985
+					CASE 
1986
+						WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN '达标'
1987
+						ELSE '不达标'
1988
+					END
1989
+			END AS 血压达标状态
1990
+		FROM
1991
+			xt_patients p
1992
+		JOIN
1993
+			xt_assessment_before_dislysis b ON p.id = b.patient_id
1994
+		JOIN
1995
+			xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date
1996
+		JOIN
1997
+			xt_monitoring_record m ON p.id = m.patient_id AND m.monitoring_date = b.assessment_date
1998
+		WHERE
1999
+			b.user_org_id = ?
2000
+			AND b.assessment_date >= ?
2001
+			AND b.assessment_date <= ?
2002
+			AND (
2003
+				(? = 1 AND CASE 
2004
+					WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
2005
+						CASE 
2006
+							WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN 1
2007
+							ELSE 0
2008
+						END
2009
+					WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
2010
+						CASE 
2011
+							WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN 1
2012
+							ELSE 0
2013
+						END
2014
+				END = 1)
2015
+				OR
2016
+				(? = 2 AND CASE 
2017
+					WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
2018
+						CASE 
2019
+							WHEN b.systolic_blood_pressure >= 140 AND b.diastolic_blood_pressure >= 90 THEN 1
2020
+							ELSE 0
2021
+						END
2022
+					WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
2023
+						CASE 
2024
+							WHEN b.systolic_blood_pressure >= 160 AND b.diastolic_blood_pressure >= 90 THEN 1
2025
+							ELSE 0
2026
+						END
2027
+				END = 1)
2028
+			)
2029
+		GROUP BY
2030
+			p.id, b.assessment_date
2031
+		ORDER BY
2032
+			p.id, b.assessment_date
2033
+		LIMIT ? OFFSET ?;
2034
+	`
2035
+
2036
+	// 计算总数
2037
+	countQuery := `
2038
+		SELECT COUNT(*)
2039
+		FROM
2040
+			xt_patients p
2041
+		JOIN
2042
+			xt_assessment_before_dislysis b ON p.id = b.patient_id
2043
+		WHERE
2044
+			b.user_org_id = ?
2045
+			AND b.assessment_date >= ?
2046
+			AND b.assessment_date <= ?
2047
+	`
2048
+
2049
+	// 执行统计查询
2050
+	if err := readDb.Raw(countQuery, user_org_id, start_time, end_time).Scan(&total).Error; err != nil {
2051
+		return nil, 0, fmt.Errorf("error calculating total count: %v", err)
2052
+	}
2053
+
2054
+	// 执行数据查询
2055
+	if err := readDb.Raw(query, user_org_id, start_time, end_time, addType, addType, limit, offset).Scan(&results).Error; err != nil {
2056
+		return nil, 0, fmt.Errorf("error executing query: %v", err)
2057
+	}
2058
+
2059
+	return results, total, nil
2060
+}