2 Commitit 48bff22e5c ... 7b9f2a0127

Tekijä SHA1 Viesti Päivämäärä
  张保健 7b9f2a0127 1111 2 kuukautta sitten
  张保健 c4efccb744 1111 2 kuukautta sitten

+ 41 - 7
controllers/lis.go Näytä tiedosto

@@ -9,7 +9,9 @@ import (
9 9
 	"fmt"
10 10
 	_ "github.com/astaxie/beego"
11 11
 	_ "github.com/jinzhu/gorm"
12
+	"net"
12 13
 	_ "strconv"
14
+	"strings"
13 15
 	"time"
14 16
 )
15 17
 
@@ -26,13 +28,45 @@ func (c *LisController) SyncChydLis() {
26 28
 	return
27 29
 }
28 30
 
29
-//func (c *LisController) Test() {
30
-//	service.SyncJhhjyyLis()
31
-//	c.ServeSuccessJSON(map[string]interface{}{
32
-//		"resultList": "12345",
33
-//	})
34
-//	return
35
-//}
31
+func (c *LisController) Test() {
32
+	var ipWhitelist = []string{"192.168.2.6", "192.168.1.1"}
33
+	ip := c.Ctx.Request.Header.Get("X-Forwarded-For")
34
+	if ip == "" {
35
+		// 如果没有 X-Forwarded-For,则使用 RemoteAddr
36
+		// 注意:RemoteAddr 可能包含端口号,需要进行处理
37
+		ip, _, _ = net.SplitHostPort(c.Ctx.Request.RemoteAddr)
38
+	}
39
+
40
+	// 如果 X-Forwarded-For 包含多个 IP 地址(逗号分隔),则通常取第一个
41
+	// 这通常是因为请求经过了多个代理
42
+	ips := strings.Split(ip, ",")
43
+	if len(ips) > 0 {
44
+		ip = strings.TrimSpace(ips[0])
45
+	}
46
+
47
+	utils.InfoLog("IP:%v", ip)
48
+
49
+	ipFlag := false
50
+	for _, allowedIP := range ipWhitelist {
51
+		if ip == allowedIP {
52
+			ipFlag = true
53
+		}
54
+	}
55
+
56
+	if ipFlag {
57
+		c.ServeSuccessJSON(map[string]interface{}{
58
+			"flag": "1",
59
+			"msg":  "认证通过",
60
+		})
61
+	} else {
62
+		c.ServeSuccessJSON(map[string]interface{}{
63
+			"flag": "0",
64
+			"msg":  "IP认证通过未通过",
65
+		})
66
+	}
67
+
68
+	return
69
+}
36 70
 
37 71
 func (c *LisController) Schedule() {
38 72
 	for i := 762429; i > 0; i-- {

+ 4 - 1
main.go Näytä tiedosto

@@ -15,7 +15,7 @@ func init() {
15 15
 }
16 16
 
17 17
 func main() {
18
-	service.BeginAutoSyncLis()
18
+	//service.BeginAutoSyncLis()
19 19
 	//service.SyncStsyLis() //  汕头三优  打开程序马上运行LIS同步
20 20
 	//service.SyncLisSgyhs() //  韶关源和盛  打开程序马上运行LIS同步
21 21
 	//service.SyncLisPljx(10597) //  揭阳景熹透析中心  打开程序马上运行LIS同步
@@ -25,5 +25,8 @@ func main() {
25 25
 	//service.SyncSclsyyyyyz() // 石狮盛誉血液透析中心  打开程序马上运行LIS同步
26 26
 	//service.SyncSccdkfyyLis() // 成都城东康复医院  打开程序马上运行LIS同步
27 27
 	//service.SyncSclsyyyyyz(orgDb) // 深圳五洲医院  打开程序马上运行LIS同步
28
+	//service.SyncGzkyLis() // 广州康允 打开程序马上运行LIS同步
29
+	//service.SyncLisZqshtx() // 肇庆三鹤 打开程序马上运行LIS同步
30
+	//service.SyncBjncHis()
28 31
 	beego.Run()
29 32
 }

+ 11 - 1
routers/router.go Näytä tiedosto

@@ -3,9 +3,19 @@ package routers
3 3
 import (
4 4
 	"IC/controllers"
5 5
 	"github.com/astaxie/beego"
6
+	"github.com/astaxie/beego/plugins/cors"
6 7
 )
7 8
 
8 9
 func init() {
10
+	beego.InsertFilter("*", beego.BeforeRouter, cors.Allow(&cors.Options{
11
+		//AllowAllOrigins:  true,
12
+		AllowOrigins: []string{"https://xt.kuyicloud.com", "http://localhost:8081", "http://localhost:8082", "https://pad.kuyicloud.com", "http://pad.kuyicloud.com", "http://pad.test.sgjyun.com", "https://pad.test.sgjyun.com", "http://admin.xt.test.sgjyun.com", "http://admin.xt.kuyicloud.com", "http://mobile.sgjyun.com", "http://mobile.kuyicloud.com", "https://mobile.kuyicloud.com"},
13
+		//AllowOrigins:     []string{"https://xt.kuyicloud.com", "http://localhost:9528", "http://xt.test.shengws.com","https://xt.test.shengws.com", "http://xt.test.sgjyun.com","https://xt.test.sgjyun.com", "http://localhost:8081", "http://localhost:8082", "https://pad.kuyicloud.com", "http://pad.kuyicloud.com", "http://pad.test.sgjyun.com","https://pad.test.sgjyun.com", "http://admin.xt.test.sgjyun.com", "http://admin.xt.kuyicloud.com","http://mobile.sgjyun.com","http://mobile.kuyicloud.com"},
14
+		AllowMethods:     []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
15
+		AllowHeaders:     []string{"Origin", "Authorization", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type", "X-XSRF-TOKEN", "Permission", "KyToken"},
16
+		ExposeHeaders:    []string{"Content-Length", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Content-Type"},
17
+		AllowCredentials: true,
18
+	}))
9 19
 	beego.Router("/", &controllers.MainController{})
10 20
 	//beego.Router("/api/lis/getlist", &controllers.LisController{}, "get:GetList")
11 21
 	//beego.Router("/api/lis/synctobase", &controllers.LisController{}, "get:SyncToBase")
@@ -40,5 +50,5 @@ func init() {
40 50
 	//beego.Router("/api/lis/syncbjnc", &controllers.LisController{}, "get:SyncBjncLis")
41 51
 	//beego.Router("/api/lis/synczhra", &controllers.LisController{}, "get:SyncZhraLis")
42 52
 	beego.Router("/api/lis/syncchyd", &controllers.LisController{}, "get:SyncChydLis")
43
-	//beego.Router("/test", &controllers.LisController{}, "get:Test")
53
+	beego.Router("/test", &controllers.LisController{}, "get:Test")
44 54
 }

+ 773 - 0
service/bjnc_service.go Näytä tiedosto

@@ -0,0 +1,773 @@
1
+package service
2
+
3
+import (
4
+	"IC/models"
5
+	_ "IC/models"
6
+	"IC/utils"
7
+	"bytes"
8
+	"encoding/json"
9
+	_ "encoding/json"
10
+	_ "encoding/xml"
11
+	"fmt"
12
+	_ "github.com/jinzhu/gorm"
13
+	"io/ioutil"
14
+	"net/http"
15
+	"strconv"
16
+	"strings"
17
+	"time"
18
+)
19
+
20
+func GetbjncProjectID(org_id int64, project_name string) (project_id int64, err error) {
21
+	var inspection_reference models.MiddleInspectionReference
22
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ?", org_id, project_name).First(&inspection_reference).Error
23
+	if inspection_reference.ID > 0 {
24
+		return inspection_reference.ProjectId, err
25
+	} else {
26
+		err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? ", org_id, project_name).First(&inspection_reference).Error
27
+		if inspection_reference.ID > 0 {
28
+			return inspection_reference.ProjectId, err
29
+		} else {
30
+			err = readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
31
+			if inspection_reference.ProjectId > 0 {
32
+				return inspection_reference.ProjectId + 1, err
33
+			} else {
34
+				return 1060601, err
35
+			}
36
+		}
37
+	}
38
+}
39
+
40
+// 根据机构ID和检验检查小项名称获取该检查的item_id,如没有,则创建一个
41
+func GetbjncItemID(org_id int64, project_name string, item_name string, project_id int64) (item_id int64, err error) {
42
+	var inspection_reference models.MiddleInspectionReference
43
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? and item_name = ?", org_id, project_name, item_name).First(&inspection_reference).Error
44
+	if inspection_reference.ID > 0 {
45
+		return inspection_reference.ItemId, err
46
+	} else {
47
+		err := readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id = ? and project_id = ? ", org_id, project_id).Select("max(item_id) as item_id").First(&inspection_reference).Error
48
+		if inspection_reference.ItemId > 0 {
49
+			return inspection_reference.ItemId + 1, err
50
+		} else {
51
+			return project_id*100 + 1, err
52
+		}
53
+	}
54
+}
55
+
56
+// 北京南诚中西医结合医院Lis同步
57
+func SyncBjncLis() (err error) {
58
+	org_id := int64(10606)
59
+
60
+	// 第一步:获取上一次同步的时间点
61
+	syncLastInfo, _ := GetSyncTimeByOrgIDForYs(org_id)
62
+	var sync_time int64
63
+	if syncLastInfo.ID > 0 {
64
+		sync_time = syncLastInfo.SyncTime - 60*60*6
65
+	} else {
66
+		sync_time = 1714492800
67
+	}
68
+
69
+	loc, _ := time.LoadLocation("Local") //重要:获取时区
70
+	sync_time_temp := time.Unix(sync_time, 0)
71
+	startTimeStr := sync_time_temp.Format("2006-01-02 15:04:05")
72
+	end_time := time.Now().Unix()
73
+	end_time_temp := time.Unix(end_time, 0)
74
+	endTimeStr := end_time_temp.Format("2006-01-02 15:04:05")
75
+	// 第二步:获取所有患者的病历号
76
+
77
+	patientList, _ := GetPatientGzjhByOrgId(org_id)
78
+	if len(patientList) > 0 {
79
+		for _, patient := range patientList {
80
+			if len(patient.IdCardNo) > 0 || len(patient.DialysisNo) > 0 {
81
+				//patient_id := patient.ID
82
+				utils.InfoLog("startTimeStr:%v", startTimeStr)
83
+				// utils.InfoLog("VipStr:%v", VipStr)
84
+				// 跟进身份证获取patientID
85
+				patientList, _ := BjncGetPatientInfo(patient.IdCardNo, endTimeStr)
86
+
87
+				var bjncPatient BjncPatientInfo
88
+				if err := json.Unmarshal([]byte(patientList), &bjncPatient); err != nil {
89
+					utils.ErrorLog("解析失败:%v", err)
90
+				}
91
+
92
+				utils.InfoLog("patientId:%v", bjncPatient.Result[0].Patientid)
93
+
94
+				reportList, _ := BjncGetLisReport(bjncPatient.Result[0].Patientid, startTimeStr, endTimeStr)
95
+				var lisReport BjncLisReport
96
+				if err := json.Unmarshal([]byte(reportList), &lisReport); err != nil {
97
+					utils.ErrorLog("解析失败:%v", err)
98
+				}
99
+				utils.InfoLog("reportList:%v", lisReport)
100
+
101
+				if len(lisReport.Result) > 0 {
102
+					for _, linfo := range lisReport.Result {
103
+						infoReprot, _ := BjncGetReportInfo(linfo.Reportno, startTimeStr, endTimeStr)
104
+						var reportInfo ReportDetail
105
+						if err := json.Unmarshal([]byte(infoReprot), &reportInfo); err != nil {
106
+							utils.ErrorLog("解析失败:%v", err)
107
+						}
108
+
109
+						for _, ivalue := range reportInfo.Result {
110
+							theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", ivalue.Testtime, loc) //使用模板在对应时区转化为time.time类型
111
+							start_temp_Time := theTime.Format("2006-01-02 15:04")
112
+							SxTime, _ := time.ParseInLocation("2006-01-02 15:04", start_temp_Time, loc)
113
+							start_time := SxTime.Unix()
114
+
115
+							project_id, _ := GetbjncProjectID(org_id, ivalue.Combinationname)
116
+							item_id, _ := GetbjncItemID(org_id, ivalue.Combinationname, ivalue.Itemname, project_id)
117
+							tx := writeMiddleDb.Begin()
118
+							var inspection models.MiddleInspection
119
+							var inspection_reference models.MiddleInspectionReference
120
+
121
+							var total int
122
+							var RangeOptions string
123
+							var RangeMin string
124
+							var RangeMax string
125
+							var ItemType int
126
+							Range := strings.Split(ivalue.Referscope, "-")
127
+							if len(Range) > 1 {
128
+								RangeMin = Range[0]
129
+								RangeMax = Range[1]
130
+								ItemType = 1
131
+							} else {
132
+								ItemType = 2
133
+								RangeOptions = ivalue.Referscope
134
+							}
135
+
136
+							err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and project_id = ? and item_id = ? and status = 1", org_id, project_id, item_id).Find(&inspection_reference).Count(&total).Error
137
+							if total <= 0 {
138
+								inspection_reference.OrgId = org_id
139
+								inspection_reference.ProjectName = ivalue.Combinationname
140
+								inspection_reference.Project = ivalue.Combinationname
141
+								inspection_reference.ProjectId = project_id
142
+								inspection_reference.ItemName = ivalue.Itemname
143
+								// inspection_reference.ItemNameAddition = strconv.FormatInt(info.ItemId, 10)
144
+								inspection_reference.ItemId = item_id
145
+								inspection_reference.RangeType = ItemType
146
+								inspection_reference.RangeMin = RangeMin
147
+								inspection_reference.RangeMax = RangeMax
148
+								// inspection_reference.RangeValue = RangeValue
149
+								inspection_reference.RangeOptions = RangeOptions
150
+								inspection_reference.Unit = ivalue.Unit
151
+								inspection_reference.Status = 1
152
+								inspection_reference.CreatedTime = time.Now().Unix()
153
+								inspection_reference.UpdatedTime = time.Now().Unix()
154
+								inspection_reference.InspectDate = ivalue.Testtime
155
+								inspection_reference.UTime = ivalue.Testtime
156
+								err = tx.Model(&models.MiddleInspectionReference{}).Create(&inspection_reference).Error
157
+								if err != nil {
158
+									tx.Rollback()
159
+								}
160
+							}
161
+							var itotal int
162
+							err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, project_id, item_id, start_time, patient.ID).Find(&inspection).Count(&itotal).Error
163
+							if itotal <= 0 {
164
+								// inspection.InspectValue = strings.Replace(LisInfo.Testresult, "&gt;", ">", -1)
165
+								// inspection.InspectValue = strings.Replace(LiLisInfo.Testresult, "&lt;", "<", -1)
166
+								inspection.PatientId = patient.ID
167
+								inspection.OrgId = org_id
168
+								inspection.ProjectId = project_id
169
+								inspection.ItemName = inspection_reference.ItemName
170
+								inspection.ProjectName = inspection_reference.ProjectName
171
+								inspection.InspectType = ItemType
172
+								inspection.ItemId = item_id
173
+								inspection.InspectValue = ivalue.Itemreportresult
174
+								inspection.InspectDate = start_temp_Time
175
+								inspection.RecordDate = start_time
176
+								// inspection.InspectTips = report.Resultstate
177
+								inspection.Status = 1
178
+								inspection.CreatedTime = time.Now().Unix()
179
+								inspection.UpdatedTime = time.Now().Unix()
180
+								// inspection.UTime = record_date.Format(timeLayout)
181
+								// inspection.HisUserId = strconv.FormatInt(patient_id, 10)
182
+								err = tx.Model(&models.MiddleInspection{}).Create(&inspection).Error
183
+								if err != nil {
184
+									tx.Rollback()
185
+								}
186
+							}
187
+							tx.Commit()
188
+						}
189
+					}
190
+				}
191
+
192
+			} else {
193
+				continue
194
+			}
195
+		}
196
+	}
197
+	var syncInfo models.MiddleSyncInfo
198
+	syncInfo.OrgId = org_id
199
+	syncInfo.SyncTime = time.Now().Unix()
200
+	syncInfo.SyncResultType = 1
201
+	syncInfo.SyncRsultRemark = "同步成功"
202
+	syncInfo.SyncTotalNum = 0
203
+	syncInfo.SyncSuccessNum = 0
204
+	syncInfo.SyncInfo = ""
205
+	syncInfo.CreateTime = time.Now().Unix()
206
+	syncInfo.UpdateTime = time.Now().Unix()
207
+
208
+	cwderr := CreateSyncInfo(&syncInfo)
209
+	if cwderr != nil {
210
+		utils.ErrorLog("创建同步信息失败:%v", cwderr)
211
+		return
212
+	}
213
+	SyncToFjtftx()
214
+	return
215
+}
216
+
217
+type BjncPatientInfo struct {
218
+	Msg    string `json:"msg"`
219
+	Code   string `json:"code"`
220
+	Result []struct {
221
+		Patientid    int64  `json:"patientId"`
222
+		Visitid      int64  `json:"visitId"`
223
+		Outpatientno string `json:"outPatientNo"`
224
+		Patientname  string `json:"patientName"`
225
+		Idcardno     string `json:"idCardNo"`
226
+	} `json:"result"`
227
+}
228
+
229
+func BjncGetPatientInfo(id_card_no string, endTime string) (string, string) {
230
+	// 1.生成签名sign
231
+	var sync_time int64
232
+	sync_time = 1690819200 // 2023-08-01 00:00:00
233
+	sync_time_temp := time.Unix(sync_time, 0)
234
+	startTimeStr := sync_time_temp.Format("2006-01-02 15:04:05")
235
+	signData := make(map[string]interface{})
236
+	//signData["dateType"] = "07"
237
+	signData["startTime"] = startTimeStr
238
+	signData["idCardNo"] = id_card_no
239
+	signData["endTime"] = endTime
240
+	bytesData, _ := json.Marshal(signData)
241
+	inputLog := string(bytesData)
242
+	signStr := "body=" + inputLog + "&operUserCode=100&serv=getRegisterInfo&key=A3195B3D179B01F66C86703E0890A95F"
243
+	signTemp := utils.String2md5(signStr)
244
+	sign := strings.ToUpper(signTemp)
245
+
246
+	// 2.请求参数
247
+	inputData := make(map[string]interface{})
248
+	inputData["body"] = signData
249
+	inputData["serv"] = "getRegisterInfo"
250
+	inputData["operUserCode"] = "100"
251
+	inputData["sign"] = sign
252
+
253
+	postData, err := json.Marshal(inputData)
254
+	postStr := string(postData)
255
+	utils.InfoLog("1111111111:%v", postStr)
256
+	if err != nil {
257
+		fmt.Println(err.Error())
258
+		return err.Error(), ""
259
+	}
260
+
261
+	reader := bytes.NewReader(postData)
262
+	url := "http://123.127.8.35:18090/esb/listener/openapi/StandardInterface"
263
+
264
+	request, err := http.NewRequest("POST", url, reader)
265
+	if err != nil {
266
+		fmt.Println(err.Error())
267
+		return err.Error(), ""
268
+	}
269
+
270
+	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
271
+	request.Header.Set("code", "XTXT")
272
+
273
+	client := http.Client{}
274
+	resp, err := client.Do(request)
275
+	if err != nil {
276
+		fmt.Println(err.Error())
277
+		return err.Error(), ""
278
+	}
279
+	respBytes, err := ioutil.ReadAll(resp.Body)
280
+	if err != nil {
281
+		fmt.Println(err.Error())
282
+		return err.Error(), ""
283
+	}
284
+	str := string(respBytes)
285
+	utils.InfoLog("22222222:%v", str)
286
+	return str, inputLog
287
+}
288
+
289
+type BjncLisReport struct {
290
+	Code   string `json:"code"`
291
+	Msg    string `json:"msg"`
292
+	Result []struct {
293
+		Patientid     string `json:"patientId"`
294
+		Patientname   string `json:"patientName"`
295
+		Reportno      int64  `json:"reportNo"`
296
+		Visitid       string `json:"visitId"`
297
+		Applydeptname string `json:"applyDeptName"`
298
+		Reportname    string `json:"reportName"`
299
+	} `json:"result"`
300
+}
301
+
302
+func BjncGetLisReport(id_card_no int64, startTime string, endTime string) (string, string) {
303
+	// 1.生成签名sign
304
+	signData := make(map[string]interface{})
305
+	signData["patientId"] = strconv.FormatInt(id_card_no, 10)
306
+	signData["dateType"] = "16"
307
+	signData["startTime"] = startTime
308
+	signData["endTime"] = endTime
309
+	bytesData, _ := json.Marshal(signData)
310
+	inputLog := string(bytesData)
311
+	signStr := "body=" + inputLog + "&operUserCode=100&serv=getLisReport&key=A3195B3D179B01F66C86703E0890A95F"
312
+	signTemp := utils.String2md5(signStr)
313
+	sign := strings.ToUpper(signTemp)
314
+
315
+	// 2.请求参数
316
+	inputData := make(map[string]interface{})
317
+	inputData["body"] = signData
318
+	inputData["serv"] = "getLisReport"
319
+	inputData["operUserCode"] = "100"
320
+	inputData["sign"] = sign
321
+
322
+	postData, err := json.Marshal(inputData)
323
+	postStr := string(postData)
324
+	utils.InfoLog("1111111111:%v", postStr)
325
+	if err != nil {
326
+		fmt.Println(err.Error())
327
+		return err.Error(), ""
328
+	}
329
+
330
+	reader := bytes.NewReader(postData)
331
+	url := "http://123.127.8.35:18090/esb/listener/openapi/StandardInterface"
332
+
333
+	request, err := http.NewRequest("POST", url, reader)
334
+	if err != nil {
335
+		fmt.Println(err.Error())
336
+		return err.Error(), ""
337
+	}
338
+
339
+	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
340
+	request.Header.Set("code", "XTXT")
341
+
342
+	client := http.Client{}
343
+	resp, err := client.Do(request)
344
+	if err != nil {
345
+		fmt.Println(err.Error())
346
+		return err.Error(), ""
347
+	}
348
+	respBytes, err := ioutil.ReadAll(resp.Body)
349
+	if err != nil {
350
+		fmt.Println(err.Error())
351
+		return err.Error(), ""
352
+	}
353
+	str := string(respBytes)
354
+	utils.InfoLog("22222222:%v", str)
355
+	return str, inputLog
356
+}
357
+
358
+type ReportDetail struct {
359
+	Msg    string `json:"msg"`
360
+	Code   string `json:"code"`
361
+	Result []struct {
362
+		Detailid         string `json:"detailId"`
363
+		Reportno         string `json:"reportNo"`
364
+		Testtime         string `json:"testTime"`
365
+		Combinationcode  string `json:"combinationCode"`
366
+		Combinationname  string `json:"combinationName"`
367
+		Itemcode         string `json:"itemCode"`
368
+		Itemname         string `json:"itemName"`
369
+		Abbreviation     string `json:"abbreviation"`
370
+		Itemreportresult string `json:"itemReportResult"`
371
+		Unit             string `json:"unit"`
372
+		Resultpoint      string `json:"resultPoint"`
373
+		Rownr            string `json:"rownr"`
374
+		Referlow         string `json:"referLow"`
375
+		Referhigh        string `json:"referHigh"`
376
+		Referscope       string `json:"referScope"`
377
+		Low              string `json:"low"`
378
+		High             string `json:"high"`
379
+	} `json:"result"`
380
+}
381
+
382
+func BjncGetReportInfo(report_no int64, startTime string, endTime string) (string, string) {
383
+	// 1.生成签名sign
384
+	signData := make(map[string]interface{})
385
+	signData["reportNo"] = strconv.FormatInt(report_no, 10)
386
+	signData["dateType"] = "16"
387
+	signData["startTime"] = startTime
388
+	signData["endTime"] = endTime
389
+	bytesData, _ := json.Marshal(signData)
390
+	inputLog := string(bytesData)
391
+	signStr := "body=" + inputLog + "&operUserCode=100&serv=getLisReportDetail&key=A3195B3D179B01F66C86703E0890A95F"
392
+	signTemp := utils.String2md5(signStr)
393
+	sign := strings.ToUpper(signTemp)
394
+
395
+	// 2.请求参数
396
+	inputData := make(map[string]interface{})
397
+	inputData["body"] = signData
398
+	inputData["serv"] = "getLisReportDetail"
399
+	inputData["operUserCode"] = "100"
400
+	inputData["sign"] = sign
401
+
402
+	postData, err := json.Marshal(inputData)
403
+	postStr := string(postData)
404
+	utils.InfoLog("1111111111:%v", postStr)
405
+	if err != nil {
406
+		fmt.Println(err.Error())
407
+		return err.Error(), ""
408
+	}
409
+
410
+	reader := bytes.NewReader(postData)
411
+	url := "http://123.127.8.35:18090/esb/listener/openapi/StandardInterface"
412
+
413
+	request, err := http.NewRequest("POST", url, reader)
414
+	if err != nil {
415
+		fmt.Println(err.Error())
416
+		return err.Error(), ""
417
+	}
418
+
419
+	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
420
+	request.Header.Set("code", "XTXT")
421
+
422
+	client := http.Client{}
423
+	resp, err := client.Do(request)
424
+	if err != nil {
425
+		fmt.Println(err.Error())
426
+		return err.Error(), ""
427
+	}
428
+	respBytes, err := ioutil.ReadAll(resp.Body)
429
+	if err != nil {
430
+		fmt.Println(err.Error())
431
+		return err.Error(), ""
432
+	}
433
+	str := string(respBytes)
434
+	utils.InfoLog("22222222:%v", str)
435
+	return str, inputLog
436
+}
437
+
438
+func SyncBjncHis() (err error) {
439
+	org_id := int64(10606)
440
+	redisClient := RedisClient()
441
+	defer redisClient.Close()
442
+
443
+	// 第一步:获取上一次同步的时间点
444
+	sync_time_tt, _ := redisClient.Get("bjncyyyy_sync_time").Result()
445
+
446
+	sync_time, _ := strconv.ParseInt(sync_time_tt, 10, 64)
447
+
448
+	if sync_time == 0 {
449
+		sync_time = time.Now().Unix() - 60*60*10
450
+		//sync_time = 1719763200
451
+	}
452
+
453
+	loc, _ := time.LoadLocation("Local") //重要:获取时区
454
+	sync_time_temp := time.Unix(sync_time, 0)
455
+	startTimeStr := sync_time_temp.Format("2006-01-02 15:04:05")
456
+	end_time := time.Now().Unix()
457
+	end_time_temp := time.Unix(end_time, 0)
458
+	endTimeStr := end_time_temp.Format("2006-01-02 15:04:05")
459
+
460
+	new_sync_time := time.Now().Unix() - 60*60
461
+	redisClient.Set("bjncyyyy_sync_time", new_sync_time, time.Minute*60*24)
462
+	// 第二步:获取所有患者的病历号
463
+
464
+	patientList, _ := GetPatientGzjhByOrgId(org_id)
465
+	if len(patientList) > 0 {
466
+		for _, patient := range patientList {
467
+			if len(patient.IdCardNo) > 0 || len(patient.DialysisNo) > 0 {
468
+				//patient_id := patient.ID
469
+				utils.InfoLog("IdCardNo:%v", patient.IdCardNo)
470
+				// utils.InfoLog("VipStr:%v", VipStr)
471
+
472
+				result, _ := BjncGetHis(patient.IdCardNo, startTimeStr, endTimeStr)
473
+				var bjncHis BjncHis
474
+				if err := json.Unmarshal([]byte(result), &bjncHis); err != nil {
475
+					utils.ErrorLog("解析失败:%v", err)
476
+				}
477
+				fmt.Println(bjncHis)
478
+				for _, cinfo := range bjncHis.Result {
479
+					fmt.Println(cinfo.Patientid)
480
+					// 查询该患者当天是否有排班信息
481
+
482
+					STime, _ := time.ParseInLocation("2006-01-02 15:04:05", cinfo.Itemeffectivetimelow, loc) //使用模板在对应时区转化为time.time类型
483
+					formattedTime := STime.Format("2006-01-02")
484
+					StTime, _ := time.ParseInLocation("2006-01-02", formattedTime, loc)
485
+					schedulesTime := StTime.Unix()
486
+
487
+					theTime, _ := time.ParseInLocation("2006-01-02 15:04:05", cinfo.Itemeffectivetimelow, loc) //使用模板在对应时区转化为time.time类型
488
+					start_temp_Time := theTime.Format("2006-01-02 15:04")
489
+					SxTime, _ := time.ParseInLocation("2006-01-02 15:04", start_temp_Time, loc)
490
+					start_time := SxTime.Unix()
491
+					utils.InfoLog("start_time:%v", start_time)
492
+
493
+					schedulesInfo, _ := GetSchedulesByPatientID(org_id, schedulesTime, patient.ID)
494
+					if schedulesInfo.ID > 0 {
495
+						start_time = theTime.Unix()
496
+					} else {
497
+						continue
498
+					}
499
+
500
+					// 根据同步来的 advice_id 来查询库里是否已经存在
501
+					advice_info, _ := GetAdviceBySyncAdviceIdForScyyyy(org_id, cinfo.Medicaladviceid, schedulesTime, patient.ID)
502
+					utils.InfoLog("Orderstatuscode:%v", cinfo.Orderstatuscode)
503
+					utils.InfoLog("AdviceName:%v", cinfo.Diagproname)
504
+					if advice_info.ID > 0 {
505
+						if cinfo.Orderstatuscode == 4 || cinfo.Orderstatuscode == 5 {
506
+							advice_info.Status = 0
507
+							SaveDoctorAdviceHandle(&advice_info)
508
+						} else {
509
+							continue
510
+						}
511
+					} else {
512
+						if cinfo.Orderstatuscode == 1 || cinfo.Orderstatuscode == 8 {
513
+							// 根据姓名获取医生ID
514
+							var doctor_id int64
515
+							temp_doctor_id, _ := redisClient.Get("bjncyyyy_doctor_id_" + cinfo.Orderdoctorcode).Result()
516
+							if len(temp_doctor_id) == 0 {
517
+								doctor, _ := GetAdminUserId(org_id, cinfo.Orderdoctorname)
518
+								doctor_id = doctor.AdminUserId
519
+								if doctor_id > 0 {
520
+									redisClient.Set("bjncyyyy_doctor_id_"+cinfo.Orderdoctorcode, doctor_id, time.Minute*60*2)
521
+								} else {
522
+									continue
523
+								}
524
+							} else {
525
+								doctor_id, _ = strconv.ParseInt(temp_doctor_id, 10, 64)
526
+							}
527
+							//
528
+							//	// 根据排班班次,固定医嘱时间
529
+
530
+							advice := models.XtDoctorAdvice{
531
+								UserOrgId:             org_id,
532
+								PatientId:             patient.ID,
533
+								AdviceType:            2,
534
+								AdviceDate:            schedulesTime,
535
+								StartTime:             start_time,
536
+								AdviceName:            cinfo.Diagproname,
537
+								RecordDate:            schedulesTime,
538
+								SingleDose:            cinfo.Dosequantity,
539
+								SingleDoseUnit:        cinfo.Dosequantityunit,
540
+								PrescribingNumber:     cinfo.Amount,
541
+								PrescribingNumberUnit: cinfo.Unit,
542
+								DeliveryWay:           cinfo.Routename,
543
+								ExecutionFrequency:    cinfo.Executefrequencyname,
544
+								AdviceDoctor:          doctor_id,
545
+								CreatedTime:           time.Now().Unix(),
546
+								UpdatedTime:           time.Now().Unix(),
547
+								SyncAdviceId:          cinfo.Medicaladviceid,
548
+								ExecutionState:        2,
549
+								Status:                1,
550
+								IsSync:                1,
551
+							}
552
+							utils.InfoLog("advice:%v", advice)
553
+
554
+							if len(cinfo.Diagproname) > 0 {
555
+								handleerr := CreateDoctorAdviceHandle(&advice)
556
+								if handleerr != nil {
557
+									utils.ErrorLog("添加医嘱信息失败:%v", handleerr)
558
+									continue
559
+								}
560
+							} else {
561
+								continue
562
+							}
563
+						} else {
564
+							continue
565
+						}
566
+					}
567
+				}
568
+			}
569
+		}
570
+	}
571
+
572
+	//var syncInfo models.MiddleSyncInfo
573
+	//syncInfo.OrgId = org_id
574
+	//syncInfo.SyncTime = time.Now().Unix()
575
+	//syncInfo.SyncResultType = 1
576
+	//syncInfo.SyncRsultRemark = "同步成功"
577
+	//syncInfo.SyncTotalNum = 0
578
+	//syncInfo.SyncSuccessNum = 0
579
+	//syncInfo.SyncInfo = ""
580
+	//syncInfo.CreateTime = time.Now().Unix()
581
+	//syncInfo.UpdateTime = time.Now().Unix()
582
+	//
583
+	//cwderr := CreateSyncInfo(&syncInfo)
584
+	//if cwderr != nil {
585
+	//	utils.ErrorLog("创建同步信息失败:%v", cwderr)
586
+	//	return
587
+	//}
588
+	//SyncToFjtftx()
589
+	return
590
+}
591
+
592
+type BjncHis struct {
593
+	Msg    string `json:"msg"`
594
+	Code   string `json:"code"`
595
+	Result []struct {
596
+		Patientid             string  `json:"patientId"`
597
+		Visitid               string  `json:"visitId"`
598
+		Outpatientno          string  `json:"outPatientNo"`
599
+		Patientname           string  `json:"patientName"`
600
+		Idcardno              string  `json:"idCardNo"`
601
+		Orderstatuscode       int64   `json:"orderStatusCode"`
602
+		Ordercreatetime       string  `json:"orderCreateTime"`
603
+		Orderdoctorcode       string  `json:"orderDoctorCode"`
604
+		Orderdoctorname       string  `json:"orderDoctorName"`
605
+		Medicaladviceid       int64   `json:"medicalAdviceId"`
606
+		Medicalordername      string  `json:"medicalOrderName"`
607
+		Itemname              string  `json:"itemName"`
608
+		Itemeffectivetimelow  string  `json:"itemEffectiveTimeLow"`
609
+		Executefrequencyname  string  `json:"executeFrequencyName"`
610
+		Routename             string  `json:"routeName"`
611
+		Dosequantity          float64 `json:"doseQuantity"`
612
+		Dosequantityunit      string  `json:"doseQuantityUnit"`
613
+		Totaldosequantity     float64 `json:"totalDoseQuantity"`
614
+		Totaldosequantityunit string  `json:"totalDoseQuantityUnit"`
615
+		Diagproname           string  `json:"diagProName"`
616
+		Amount                float64 `json:"amount"`
617
+		Unit                  string  `json:"unit"`
618
+	} `json:"result"`
619
+}
620
+
621
+func BjncGetHis(id_card_no string, startTime string, endTime string) (string, string) {
622
+	// 1.生成签名sign
623
+	signData := make(map[string]interface{})
624
+	signData["dateType"] = "07"
625
+	signData["medicalOrderType"] = "1,2,3,A,B,D,E,L,N,O"
626
+	signData["idCardNo"] = id_card_no
627
+	signData["startTime"] = startTime
628
+	signData["endTime"] = endTime
629
+	bytesData, _ := json.Marshal(signData)
630
+	inputLog := string(bytesData)
631
+	signStr := "body=" + inputLog + "&operUserCode=100&serv=getMedicalAdvice&key=A3195B3D179B01F66C86703E0890A95F"
632
+	signTemp := utils.String2md5(signStr)
633
+	sign := strings.ToUpper(signTemp)
634
+
635
+	// 2.请求参数
636
+	inputData := make(map[string]interface{})
637
+	inputData["body"] = signData
638
+	inputData["serv"] = "getMedicalAdvice"
639
+	inputData["operUserCode"] = "100"
640
+	inputData["sign"] = sign
641
+
642
+	postData, err := json.Marshal(inputData)
643
+	postStr := string(postData)
644
+	utils.InfoLog("1111111111:%v", postStr)
645
+	if err != nil {
646
+		fmt.Println(err.Error())
647
+		return err.Error(), ""
648
+	}
649
+
650
+	reader := bytes.NewReader(postData)
651
+	url := "http://123.127.8.35:18090/esb/listener/openapi/StandardInterface"
652
+
653
+	request, err := http.NewRequest("POST", url, reader)
654
+	if err != nil {
655
+		fmt.Println(err.Error())
656
+		return err.Error(), ""
657
+	}
658
+
659
+	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
660
+	request.Header.Set("code", "XTXT")
661
+
662
+	client := http.Client{}
663
+	resp, err := client.Do(request)
664
+	if err != nil {
665
+		fmt.Println(err.Error())
666
+		return err.Error(), ""
667
+	}
668
+	respBytes, err := ioutil.ReadAll(resp.Body)
669
+	if err != nil {
670
+		fmt.Println(err.Error())
671
+		return err.Error(), ""
672
+	}
673
+	str := string(respBytes)
674
+	utils.InfoLog("22222222:%v", str)
675
+	return str, inputLog
676
+}
677
+
678
+//
679
+//func FjtjGetLac(lab01 int64) (string, string) {
680
+//	inputData := make(map[string]interface{})
681
+//
682
+//	inputData["lab01"] = lab01
683
+//
684
+//	var inputLog string
685
+//	bytesData, err := json.Marshal(inputData)
686
+//	inputLog = string(bytesData)
687
+//	fmt.Println(string(bytesData))
688
+//	if err != nil {
689
+//		fmt.Println(err.Error())
690
+//		return err.Error(), ""
691
+//	}
692
+//	reader := bytes.NewReader(bytesData)
693
+//	url := "http://hip.zptfyy.com/esb/listener/getLac1"
694
+//
695
+//	request, err := http.NewRequest("POST", url, reader)
696
+//	if err != nil {
697
+//		fmt.Println(err.Error())
698
+//		return err.Error(), ""
699
+//	}
700
+//
701
+//	request.Header.Set("Content-Type", "application/json;charset=UTF-8")
702
+//	request.Header.Set("code", "xt")
703
+//
704
+//	client := http.Client{}
705
+//	resp, err := client.Do(request)
706
+//	if err != nil {
707
+//		fmt.Println(err.Error())
708
+//		return err.Error(), ""
709
+//	}
710
+//	respBytes, err := ioutil.ReadAll(resp.Body)
711
+//	if err != nil {
712
+//		fmt.Println(err.Error())
713
+//		return err.Error(), ""
714
+//	}
715
+//	str := string(respBytes)
716
+//	return str, inputLog
717
+//}
718
+//
719
+//// 根据机构ID和检验检查名称获取该检查的project_id,如没有,则创建一个
720
+//func GetfjtfProjectID(org_id int64, project_name string) (project_id int64, err error) {
721
+//	var inspection_reference models.MiddleInspectionReference
722
+//	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ?", org_id, project_name).First(&inspection_reference).Error
723
+//	if inspection_reference.ID > 0 {
724
+//		return inspection_reference.ProjectId, err
725
+//	} else {
726
+//		err = readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
727
+//		if inspection_reference.ProjectId > 0 {
728
+//			return inspection_reference.ProjectId + 1, err
729
+//		} else {
730
+//			return 330001, err
731
+//		}
732
+//	}
733
+//}
734
+//
735
+//// 根据机构ID和检验检查小项名称获取该检查的item_id,如没有,则创建一个
736
+//func GetFjtfItemID(org_id int64, project_name string, item_name string, project_id int64) (item_id int64, err error) {
737
+//	var inspection_reference models.MiddleInspectionReference
738
+//	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ? and item_name = ?", org_id, project_name, item_name).First(&inspection_reference).Error
739
+//	if inspection_reference.ID > 0 {
740
+//		return inspection_reference.ItemId, err
741
+//	} else {
742
+//		err := readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id = ? and project_id = ? ", org_id, project_id).Select("max(item_id) as item_id").First(&inspection_reference).Error
743
+//		utils.InfoLog("inspection_reference: %v", inspection_reference)
744
+//		if inspection_reference.ItemId > 0 {
745
+//			return inspection_reference.ItemId + 1, err
746
+//		} else {
747
+//			return project_id*100 + 1, err
748
+//		}
749
+//	}
750
+//}
751
+//
752
+//func SyncToFjtftx() {
753
+//	utils.TraceLog("检验检查同步任务开始执行")
754
+//	org_id := int64(10330)
755
+//
756
+//	// 第一步:跟进org_id 去中间库查出需要同步的数据
757
+//	inspection_references, _ := GetSyncInspectionReferenceByOrgId(org_id)
758
+//	inspections, _ := GetSyncInspectionByOrgId(org_id)
759
+//
760
+//	// 第二步:将数据同步到业务库
761
+//	if len(inspection_references) > 0 {
762
+//		for _, inspection_reference := range inspection_references {
763
+//			SyncInspectionReference(&inspection_reference)
764
+//		}
765
+//	}
766
+//
767
+//	if len(inspections) > 0 {
768
+//		for _, inspection := range inspections {
769
+//			SyncInspection(&inspection)
770
+//		}
771
+//	}
772
+//	utils.SuccessLog("检验检查同步任务完成")
773
+//}

+ 359 - 0
service/chyd_service.go Näytä tiedosto

@@ -0,0 +1,359 @@
1
+package service
2
+
3
+import (
4
+	"IC/models"
5
+	"IC/utils"
6
+	_ "IC/utils"
7
+	"encoding/json"
8
+	_ "encoding/json"
9
+	"encoding/xml"
10
+	_ "fmt"
11
+	"github.com/astaxie/beego/httplib"
12
+	_ "github.com/jinzhu/gorm"
13
+	"net/url"
14
+	"strconv"
15
+	"strings"
16
+	"time"
17
+)
18
+
19
+type XmlKeyChyd struct {
20
+	XMLName    xml.Name `xml:"string"`
21
+	StringName string   `xml:"name,attr"`
22
+	InnerText  string   `xml:",innerxml"`
23
+}
24
+
25
+// 获取艾迪康的key
26
+func GetAdKeyChyd(logid string, password string) (key string) {
27
+	Domain := "http://183.63.151.26:8081/AdWebService_new/ADReportWebService.asmx/Login?"
28
+	apiurl := "logid=" + logid + "&password=" + password
29
+	apiurl = url.PathEscape(apiurl)
30
+	apiurl = Domain + apiurl
31
+	XmlKeyChyd := XmlKeyChyd{}
32
+	httplib.Get(apiurl).ToXML(&XmlKeyChyd)
33
+	return XmlKeyChyd.InnerText
34
+}
35
+
36
+type ADStringChyd struct {
37
+	XMLName        xml.Name         `xml:"string" json:"string"`
38
+	NewDataSetChyd rpnewDataSetChyd `xml:"NewDataSet" json:"NewDataSet"`
39
+}
40
+
41
+type rpnewDataSetChyd struct {
42
+	ListTableChyd []rplisttableChyd `xml:"listtable" json:"listtable"`
43
+}
44
+
45
+type rplisttableChyd struct {
46
+	Id              string `xml:"Id" json:"Id"`
47
+	ReportType      string `xml:"ReportType" json:"ReportType"`
48
+	AdiconBarcode   string `xml:"AdiconBarcode" json:"AdiconBarcode"`
49
+	PatientName     string `xml:"PatientName" json:"PatientName"`
50
+	Bgrq            string `xml:"Bgrq" json:"Bgrq"`
51
+	Instrument      string `xml:"Instrument" json:"Instrument"`
52
+	LisDate         string `xml:"LisDate" json:"LisDate"`
53
+	Sampleid        string `xml:"Sampleid" json:"Sampleid"`
54
+	CustomerBarcode string `xml:"CustomerBarcode" json:"CustomerBarcode"`
55
+	Repno           string `xml:"Repno" json:"Repno"`
56
+	// PdfFileName		string `xml:"PdfFileName" json:"PdfFileName"`
57
+	// DownFlag		string `xml:"DownFlag" json:"DownFlag"`
58
+	// DownDate		string `xml:"DownDate" json:"DownDate"`
59
+	Sjrq string `xml:"Sjrq" json:"Sjrq"`
60
+	// Sjys		string `xml:"Sjys" json:"Sjys"`
61
+	// Brnl		string `xml:"Brnl" json:"Brnl"`
62
+	// Brxb		string `xml:"Brxb" json:"Brxb"`
63
+	Bbzl string `xml:"bbzl" json:"bbzl"`
64
+	// Bzlbid		string `xml:"Bzlbid" json:"Bzlbid"`
65
+	// PDFFileType		string `xml:"PDFFileType" json:"PDFFileType"`
66
+	// PageType		string `xml:"PageType" json:"PageType"`
67
+	PatientNo string `xml:"PatientNo" json:"PatientNo"`
68
+	// SfzId		string `xml:"SfzId" json:"SfzId"`
69
+	// CertificatesType		string `xml:"CertificatesType" json:"CertificatesType"`
70
+	// Nationality		string `xml:"Nationality" json:"Nationality"`
71
+	// SerialNumber		string `xml:"SerialNumber" json:"SerialNumber"`
72
+	// Str1		string `xml:"Str1" json:"Str1"`
73
+	// Str2		string `xml:"Str2" json:"Str2"`
74
+	// Str3		string `xml:"Str3" json:"Str3"`
75
+	// Str4		string `xml:"Str4" json:"Str4"`
76
+	// Str5		string `xml:"Str5" json:"Str5"`
77
+	// TWBG		string `xml:"TWBG" json:"TWBG"`
78
+}
79
+
80
+// 获取机构一段时间内检验检查列表
81
+func GetAdGetReportListChyd(Key string, BeginDateTime string, EndDateTime string, TypeDateTime string, AgainFlag string) (key ADStringChyd) {
82
+	Domain := "http://183.63.151.26:8081/AdWebService_new/ADReportWebService.asmx/GetReportList"
83
+	//apiurl := "Key=" + Key + "&BeginDateTime=" + BeginDateTime + "&EndDateTime=" + EndDateTime + "&TypeDateTime=" + TypeDateTime + "&AgainFlag=" + AgainFlag
84
+	//apiurl = url.PathEscape(apiurl)
85
+	//apiurl = Domain + apiurl
86
+	//utils.InfoLog("url0: %v", apiurl)
87
+	var xmlKey ADStringChyd
88
+	req := httplib.Post(Domain)
89
+	req.Param("Key", Key)
90
+	req.Param("BeginDateTime", BeginDateTime)
91
+	req.Param("EndDateTime", EndDateTime)
92
+	req.Param("TypeDateTime", TypeDateTime)
93
+	req.Param("AgainFlag", AgainFlag)
94
+	xmlString, _ := req.String()
95
+	xmlString = strings.Replace(xmlString, "&lt;", "<", -1)
96
+	xmlString = strings.Replace(xmlString, "&gt;", ">", -1)
97
+	xml.Unmarshal([]byte(xmlString), &xmlKey)
98
+	return xmlKey
99
+}
100
+
101
+type AdkCheckChyd struct {
102
+	Cgbg AdkSResult `json:"常规报告"`
103
+}
104
+
105
+type AdkSResult struct {
106
+	Item []AdkItem `json:"item"`
107
+}
108
+
109
+type AdkItem struct {
110
+	Adiconbarcode   string `json:"AdiconBarcode"`
111
+	Patientname     string `json:"PatientName"`
112
+	Sex             string `json:"Sex"`
113
+	Age             string `json:"Age"`
114
+	Reportdate      string `json:"ReportDate"`
115
+	Itemcode        string `json:"ItemCode"`
116
+	ItemnameCn      string `json:"ItemName_CN"`
117
+	ItemnameEn      string `json:"ItemName_EN"`
118
+	Result          string `json:"Result"`
119
+	Resulthint      string `json:"ResultHint"`
120
+	Resultreference string `json:"ResultReference"`
121
+	Resultunit      string `json:"ResultUnit"`
122
+	Zhmc            string `json:"zhmc"`
123
+}
124
+
125
+func GetAdkInfoChyd(key string, id string) (str AdkCheckChyd, checkStr string) {
126
+	Domain := "http://183.63.151.26:8081/AdWebService_new/ADReportWebService.asmx/GetJSONReportItemListByAdiconBarocde?"
127
+	//apiurl := "key=" + key + "&AdiconBarocde=" + id
128
+	//apiurl = url.PathEscape(apiurl)
129
+	//apiurl = Domain + apiurl
130
+	//utils.InfoLog("url1: %v", apiurl)
131
+	xmlKey := XmlKeyChyd{}
132
+	rep := httplib.Post(Domain)
133
+	rep.Param("Key", key)
134
+	rep.Param("AdiconBarcode", id)
135
+	rep.ToXML(&xmlKey)
136
+	utils.InfoLog("InnerText: %v", xmlKey.InnerText)
137
+	var checkJSON AdkCheckChyd
138
+	json.Unmarshal([]byte(xmlKey.InnerText), &checkJSON)
139
+
140
+	return checkJSON, xmlKey.InnerText
141
+}
142
+
143
+// 从化意达透析中心Lis同步
144
+func SyncLisChyd(flag int64) (err error) {
145
+	// 第一步:获取艾迪康下发的Key
146
+	org_id := int64(10318)
147
+	login := "RH0222"
148
+	password := "Abc123123"
149
+	key := GetAdKeyChyd(login, password)
150
+	utils.InfoLog("key:%v", key)
151
+	// 第二步:获取上一次同步的时间点
152
+	syncLastInfo, _ := GetSyncTimeByOrgIDForYs(org_id)
153
+	var sync_time int64
154
+	if syncLastInfo.ID > 0 {
155
+		sync_time = syncLastInfo.SyncTime
156
+	} else {
157
+		sync_time = 1704038400
158
+	}
159
+
160
+	if flag > 0 {
161
+		sync_time = 1704038400
162
+	}
163
+
164
+	nowTimes := time.Now().Unix()
165
+	// syncTimes := time.Unix(sync_time,0).Format("2006-01-02")
166
+	if sync_time < nowTimes {
167
+		for i := sync_time; i < nowTimes; i = i + 86400 {
168
+			tempsyncTimes := time.Unix(i, 0).Format("2006-01-02")
169
+			adString := GetAdGetReportListChyd(key, tempsyncTimes, tempsyncTimes, "2", "1")
170
+			listtable := adString.NewDataSetChyd.ListTableChyd
171
+			if len(listtable) >= 1 {
172
+				// 第三步:根据检查列表获取的ID来获取检验检查详情
173
+				for _, list := range listtable {
174
+					listId := list.AdiconBarcode
175
+					checkInfo, _ := GetAdkInfoChyd(key, listId)
176
+					//utils.InfoLog("checkStr: %v", checkStr)
177
+					for _, info := range checkInfo.Cgbg.Item {
178
+						// 根据姓名 去查询对应的patient_id
179
+						patient, _ := GetPatientID(org_id, info.Patientname)
180
+						utils.InfoLog("patient: %v", patient)
181
+						if patient.ID > 0 {
182
+							ChydReportInfoHandle(info, org_id, patient.ID)
183
+						}
184
+					}
185
+				}
186
+				var syncInfo models.MiddleSyncInfo
187
+				syncInfo.OrgId = org_id
188
+
189
+				syncInfo.SyncTime = i
190
+				syncInfo.SyncResultType = 1
191
+				syncInfo.SyncRsultRemark = "同步成功"
192
+				syncInfo.SyncTotalNum = 0
193
+				syncInfo.SyncSuccessNum = 0
194
+				syncInfo.SyncInfo = ""
195
+				syncInfo.CreateTime = time.Now().Unix()
196
+				syncInfo.UpdateTime = time.Now().Unix()
197
+
198
+				cwderr := CreateSyncInfo(&syncInfo)
199
+				if cwderr != nil {
200
+					utils.ErrorLog("创建同步信息失败:%v", cwderr)
201
+					return
202
+				}
203
+			}
204
+		}
205
+
206
+	}
207
+	SyncToChyd()
208
+	return
209
+}
210
+
211
+func SyncToChyd() {
212
+
213
+	utils.TraceLog("检验检查同步任务开始执行")
214
+	org_id := int64(10318)
215
+
216
+	// 第一步:跟进org_id 去中间库查出需要同步的数据
217
+	inspection_references, _ := GetSyncInspectionReferenceByOrgId(org_id)
218
+	inspections, _ := GetSyncInspectionByOrgId(org_id)
219
+
220
+	// 第二步:将数据同步到业务库
221
+	if len(inspection_references) > 0 {
222
+		for _, inspection_reference := range inspection_references {
223
+			SyncInspectionReference(&inspection_reference)
224
+		}
225
+	}
226
+
227
+	if len(inspections) > 0 {
228
+		for _, inspection := range inspections {
229
+			SyncInspection(&inspection)
230
+		}
231
+	}
232
+	utils.SuccessLog("检验检查同步任务完成")
233
+}
234
+
235
+// 根据机构ID和检验检查小项名称获取该检查的item_id,如没有,则创建一个
236
+func GetChydItemID(org_id int64, project_name string, item_name string, project_id int64) (item_id int64, err error) {
237
+	var inspection_reference models.MiddleInspectionReference
238
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ? and item_name = ?", org_id, project_name, item_name).First(&inspection_reference).Error
239
+	if inspection_reference.ID > 0 {
240
+		return inspection_reference.ItemId, err
241
+	} else {
242
+		err := readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id = ? and project_id = ? ", org_id, project_id).Select("max(item_id) as item_id").First(&inspection_reference).Error
243
+		utils.InfoLog("inspection_reference: %v", inspection_reference)
244
+		if inspection_reference.ItemId > 0 {
245
+			return inspection_reference.ItemId + 1, err
246
+		} else {
247
+			return project_id*100 + 1, err
248
+		}
249
+	}
250
+}
251
+
252
+// 根据机构ID和检验检查名称获取该检查的project_id,如没有,则创建一个
253
+func GetChydProjectID(org_id int64, project_name string) (project_id int64, err error) {
254
+	var inspection_reference models.MiddleInspectionReference
255
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ?", org_id, project_name).First(&inspection_reference).Error
256
+	if inspection_reference.ID > 0 {
257
+		return inspection_reference.ProjectId, err
258
+	} else {
259
+		err = readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
260
+		if inspection_reference.ProjectId > 0 {
261
+			return inspection_reference.ProjectId + 1, err
262
+		} else {
263
+			return 1031801, err
264
+		}
265
+	}
266
+}
267
+
268
+func ChydReportInfoHandle(CheckInfo AdkItem, org_id int64, patientId int64) {
269
+	tx := writeMiddleDb.Begin()
270
+	var total int
271
+	var RangeMin string
272
+	var RangeMax string
273
+
274
+	timstr := strings.Split(CheckInfo.Reportdate, ".")
275
+	recordDateStr := timstr[0]
276
+
277
+	if len(recordDateStr) == 0 {
278
+		recordDateStr = time.Now().Format("2006-01-02 15:04")
279
+	}
280
+
281
+	record_date_str, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", recordDateStr)
282
+	record_date := record_date_str.Unix()
283
+	inspect_date := time.Unix(record_date, 0).Format("2006-01-02 15:04")
284
+
285
+	// // 判断检查类型
286
+	ItemType := 1
287
+	Range := strings.Split(CheckInfo.Resultreference, "-")
288
+	if len(Range) > 1 {
289
+		RangeMin = Range[0]
290
+		RangeMax = Range[1]
291
+		ItemType = 1
292
+	} else {
293
+		ItemType = 2
294
+	}
295
+
296
+	var inspection models.MiddleInspection
297
+	var inspection_reference models.MiddleInspectionReference
298
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and project = ? and item_code = ? and status = 1", org_id, CheckInfo.Zhmc, CheckInfo.Itemcode).Find(&inspection_reference).Count(&total).Error
299
+	if inspection_reference.ID > 0 {
300
+		ItemType = inspection_reference.RangeType
301
+	}
302
+	if total <= 0 {
303
+		//  如果配置表里没有相关配置,则创建project_id,item_id和相关配置信息
304
+		project_id, _ := GetChydProjectID(org_id, CheckInfo.Zhmc)
305
+		item_id, _ := GetChydItemID(org_id, CheckInfo.Zhmc, CheckInfo.ItemnameCn, project_id)
306
+
307
+		inspection_reference.OrgId = org_id
308
+		inspection_reference.ProjectName = CheckInfo.Zhmc
309
+		inspection_reference.Project = CheckInfo.Zhmc
310
+		inspection_reference.ProjectId = project_id
311
+		inspection_reference.ItemName = CheckInfo.ItemnameCn
312
+		inspection_reference.ItemNameAddition = CheckInfo.ItemnameEn
313
+		inspection_reference.ItemId = item_id
314
+		inspection_reference.ItemCode = CheckInfo.Itemcode
315
+		inspection_reference.RangeType = ItemType
316
+		inspection_reference.RangeMin = RangeMin
317
+		inspection_reference.RangeMax = RangeMax
318
+		// inspection_reference.RangeValue = RangeValue
319
+		//inspection_reference.RangeOptions = RangeOptions
320
+		inspection_reference.Unit = CheckInfo.Resultunit
321
+		inspection_reference.Status = 1
322
+		inspection_reference.CreatedTime = time.Now().Unix()
323
+		inspection_reference.UpdatedTime = time.Now().Unix()
324
+		inspection_reference.InspectDate = inspect_date
325
+		inspection_reference.UTime = inspect_date
326
+		inspection_reference.Adiconbarcode = CheckInfo.Adiconbarcode
327
+		err = tx.Model(&models.MiddleInspectionReference{}).Create(&inspection_reference).Error
328
+		if err != nil {
329
+			tx.Rollback()
330
+		}
331
+	}
332
+
333
+	var itotal int
334
+	err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, inspection_reference.ProjectId, inspection_reference.ItemId, record_date, patientId).Find(&inspection).Count(&itotal).Error
335
+	if itotal <= 0 {
336
+		inspection.PatientId = patientId
337
+		inspection.OrgId = org_id
338
+		inspection.ProjectId = inspection_reference.ProjectId
339
+		inspection.ItemName = inspection_reference.ItemName
340
+		inspection.ProjectName = inspection_reference.ProjectName
341
+		inspection.InspectType = ItemType
342
+		inspection.ItemId = inspection_reference.ItemId
343
+		inspection.InspectValue = CheckInfo.Result
344
+		inspection.InspectDate = inspect_date
345
+		inspection.RecordDate = record_date
346
+		//inspection.InspectTips = result.AntiCode
347
+		inspection.Status = 1
348
+		inspection.CreatedTime = time.Now().Unix()
349
+		inspection.UpdatedTime = time.Now().Unix()
350
+		inspection.UTime = inspect_date
351
+		inspection.HisUserId = strconv.FormatInt(patientId, 10)
352
+		inspection.Adiconbarcode = CheckInfo.Adiconbarcode
353
+		err = tx.Model(&models.MiddleInspection{}).Create(&inspection).Error
354
+		if err != nil {
355
+			tx.Rollback()
356
+		}
357
+	}
358
+	tx.Commit()
359
+}

+ 27 - 19
service/cron.go Näytä tiedosto

@@ -5,10 +5,8 @@ import (
5 5
 	"IC/utils"
6 6
 	"encoding/json"
7 7
 	_ "fmt"
8
-	oracle "github.com/dzwvip/gorm-oracle"
9 8
 	_ "github.com/jinzhu/gorm"
10 9
 	"github.com/robfig/cron/v3"
11
-	"gorm.io/gorm"
12 10
 	_ "strings"
13 11
 	"time"
14 12
 )
@@ -31,11 +29,11 @@ func BeginAutoSyncLis() {
31 29
 	utils.InfoLog("开启自动检验检查同步定时任务")
32 30
 	createLisSyncCronJob := newWithSeconds()
33 31
 
34
-	orgDb, err := gorm.Open(oracle.Open("oracle://zjybase:zjybase@10.0.0.248:1521/orcl"), &gorm.Config{})
35
-
36
-	if err != nil {
37
-		utils.InfoLog("创建数据库连接失败:%v", err)
38
-	}
32
+	//orgDb, err := gorm.Open(oracle.Open("oracle://zjybase:zjybase@10.0.0.248:1521/orcl"), &gorm.Config{})
33
+	//
34
+	//if err != nil {
35
+	//	utils.InfoLog("创建数据库连接失败:%v", err)
36
+	//}
39 37
 
40 38
 	//specys := "0 0 */1 * * ?" // 每天凌晨3点同步 唐山朝阳医院
41 39
 	//createLisSyncCronJob.AddFunc(specys, func() {
@@ -82,10 +80,10 @@ func BeginAutoSyncLis() {
82 80
 	//	SyncLisSzwz()
83 81
 	//})
84 82
 
85
-	//spec8 := "0 25 */2 * * ?" // 每个小时同步一次 汕头三优透析中心LIS对接,本地部署的
86
-	//createLisSyncCronJob.AddFunc(spec8, func() {
87
-	//	SyncStsyLis()
88
-	//})
83
+	spec8 := "0 25 */3 * * ?" // 每个小时同步一次 汕头三优透析中心LIS对接,本地部署的
84
+	createLisSyncCronJob.AddFunc(spec8, func() {
85
+		SyncStsyLis()
86
+	})
89 87
 
90 88
 	//spec9 := "0 57 * * * ?" // 每个小时同步一次 遵化仁爱医院LIS对接,本地部署的
91 89
 	//createLisSyncCronJob.AddFunc(spec9, func() {
@@ -132,15 +130,25 @@ func BeginAutoSyncLis() {
132 130
 	//	SyncJhhjyyLis()
133 131
 	//})
134 132
 
135
-	spec18 := "1 * * * * ?" // 每个30秒同步一次 四川乐山友谊医院医嘱对接,本地部署的
136
-	createLisSyncCronJob.AddFunc(spec18, func() {
137
-		SyncSclsyyyyyz(orgDb)
138
-	})
133
+	//spec18 := "1 * * * * ?" // 每个30秒同步一次 四川乐山友谊医院医嘱对接,本地部署的
134
+	//createLisSyncCronJob.AddFunc(spec18, func() {
135
+	//	SyncSclsyyyyyz(orgDb)
136
+	//})
139 137
 
140
-	spec19 := "* 35 */4 * * ?" // 每个2个小时同步一次 四川乐山友谊医院LIS对接,本地部署的
141
-	createLisSyncCronJob.AddFunc(spec19, func() {
142
-		SyncScyyyyLis()
143
-	})
138
+	//spec19 := "* 35 */4 * * ?" // 每个2个小时同步一次 四川乐山友谊医院LIS对接,本地部署的
139
+	//createLisSyncCronJob.AddFunc(spec19, func() {
140
+	//	SyncScyyyyLis()
141
+	//})
142
+
143
+	//spec20 := "* 15 */2 * * ?" // 每个2个小时同步一次 四川乐山友谊医院LIS对接,本地部署的
144
+	//createLisSyncCronJob.AddFunc(spec20, func() {
145
+	//	SyncGzkyLis()
146
+	//})
147
+
148
+	//spec21 := "1 * * * * ?" // 每个30秒同步一次 四川乐山友谊医院医嘱对接,本地部署的
149
+	//createLisSyncCronJob.AddFunc(spec21, func() {
150
+	//	SyncBjncHis()
151
+	//})
144 152
 
145 153
 	createLisSyncCronJob.Start()
146 154
 }

+ 260 - 0
service/jhhjyy_service.go Näytä tiedosto

@@ -0,0 +1,260 @@
1
+package service
2
+
3
+import (
4
+	"IC/models"
5
+	"IC/utils"
6
+	_ "encoding/json"
7
+	_ "fmt"
8
+	"github.com/jinzhu/gorm"
9
+	"strings"
10
+	"time"
11
+)
12
+
13
+type jhhjyyLis struct {
14
+	HisUserId    string `json:"his_user_id"`
15
+	PatientName  string `json:"patient_name"`
16
+	ProjectId    string `json:"project_id"`
17
+	ProjectName  string `json:"project_name"`
18
+	InspectDate  string `json:"inspect_date"`
19
+	ItemId       string `json:"item_id"`
20
+	ItemName     string `json:"item_name"`
21
+	ItemType     string `json:"item_type"`
22
+	ItemValue    string `json:"item_value"`
23
+	RangeMin     string `json:"range_min"`
24
+	RangeMax     string `json:"range_max"`
25
+	RangeValue   string `json:"range_value"`
26
+	RangeOptions string `json:"range_options"`
27
+	Unit         string `json:"unit"`
28
+	State        string `json:"state"`
29
+	CTime        string `json:"c_time"`
30
+	UTime        string `json:"u_time"`
31
+}
32
+
33
+func (jhhjyyLis) TableName() string {
34
+	return "GetJianYanXX"
35
+}
36
+
37
+func GetJhhjyyLis(rdb *gorm.DB, synctime string, his_user_id string, patient_name string) (record []*jhhjyyLis, err error) {
38
+	err = rdb.Model(&jhhjyyLis{}).Where("c_time >= ? and (his_user_id = ? or patient_name = ?)", synctime, his_user_id, patient_name).Find(&record).Error
39
+	return
40
+}
41
+
42
+//// 根据机构ID和患者身份证号码获取患者信息
43
+//func GetUserInIdcardNoByOrg(org_id int64) (patients []*models.Patients, err error) {
44
+//	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? and status = 1 ", org_id).Find(&patients).Error
45
+//	return
46
+//}
47
+
48
+// 根据机构ID和检验检查名称获取该检查的project_id,如没有,则创建一个
49
+func GetJhhjyyProjectID(org_id int64, project_name string, item_name string) (project_id int64, err error) {
50
+	var inspection_reference models.MiddleInspectionReference
51
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? and item_name = ? ", org_id, project_name, item_name).First(&inspection_reference).Error
52
+	if inspection_reference.ID > 0 {
53
+		return inspection_reference.ProjectId, err
54
+	} else {
55
+		err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? ", org_id, project_name).First(&inspection_reference).Error
56
+		if inspection_reference.ID > 0 {
57
+			return inspection_reference.ProjectId, err
58
+		} else {
59
+			err = readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
60
+			if inspection_reference.ProjectId > 0 {
61
+				return inspection_reference.ProjectId + 1, err
62
+			} else {
63
+				return 1062901, err
64
+			}
65
+		}
66
+	}
67
+}
68
+
69
+// 根据机构ID和检验检查小项名称获取该检查的item_id,如没有,则创建一个
70
+func GetJhhjyyItemID(org_id int64, project_name string, item_name string, project_id int64) (item_id int64, err error) {
71
+	var inspection_reference models.MiddleInspectionReference
72
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? and item_name = ?", org_id, project_name, item_name).First(&inspection_reference).Error
73
+	if inspection_reference.ID > 0 {
74
+		return inspection_reference.ItemId, err
75
+	} else {
76
+		err := readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id = ? and project_id = ? ", org_id, project_id).Select("max(item_id) as item_id").First(&inspection_reference).Error
77
+		if inspection_reference.ItemId > 0 {
78
+			return inspection_reference.ItemId + 1, err
79
+		} else {
80
+			return project_id*100 + 1, err
81
+		}
82
+	}
83
+}
84
+
85
+// 湖南郴州嘉禾恒佳医院Lis同步
86
+func SyncJhhjyyLis() (err error) {
87
+	org_id := int64(10629)
88
+
89
+	org := &models.DataUploadConfig{
90
+		OrgId:  org_id,
91
+		DbHost: "192.168.5.253",
92
+		DbPort: "1433",
93
+		DbPass: "XtUser",
94
+		DbUser: "XtUser",
95
+		DbName: "HealthOne",
96
+	}
97
+
98
+	orgDb, err := CreateSqlServiceDB(org.DbHost, org.DbPort, org.DbUser, org.DbPass, org.DbName)
99
+	if err != nil {
100
+		utils.ErrorLog("创建数据库连接失败:%v", err)
101
+		return
102
+	}
103
+
104
+	// 第一步:获取上一次同步的时间点
105
+	syncLastInfo, _ := GetSyncTimeByOrgIDForYs(org_id)
106
+	var sync_time int64
107
+	if syncLastInfo.ID > 0 {
108
+		sync_time = syncLastInfo.SyncTime
109
+	} else {
110
+		sync_time = 1704038400 // 2023-01-01
111
+	}
112
+	// 第二步:获取时间内所有检验结果
113
+	sync_time_temp := time.Unix(sync_time, 0)
114
+	startTimeStr := sync_time_temp.Format("2006-01-02 15:04:05")
115
+
116
+	patients, _ := GetUserInIdcardNoByOrg(org_id)
117
+
118
+	if len(patients) > 0 {
119
+		for _, patient := range patients {
120
+			userCardId := patient.IdCardNo
121
+			// 根据姓名获取患者ID
122
+			jhhyyyLis, _ := GetJhhjyyLis(orgDb, startTimeStr, userCardId, patient.Name)
123
+			if len(jhhyyyLis) > 0 {
124
+				for _, LisInfo := range jhhyyyLis {
125
+					project_id, _ := GetJhhjyyProjectID(org_id, LisInfo.ProjectName, LisInfo.ItemName)
126
+					item_id, _ := GetJhhjyyItemID(org_id, LisInfo.ProjectName, LisInfo.ItemName, project_id)
127
+					tx := writeMiddleDb.Begin()
128
+					var inspection models.MiddleInspection
129
+					var inspection_reference models.MiddleInspectionReference
130
+
131
+					timeLayout := "2006-01-02 15:04"
132
+					loc, _ := time.LoadLocation("Local")
133
+
134
+					utils.InfoLog("1111111---%v", LisInfo.InspectDate)
135
+					timstr := strings.Split(LisInfo.InspectDate, "T")
136
+					timstem := strings.Split(timstr[1], "Z")
137
+					tempRecord := timstr[0] + " " + timstem[0]
138
+					utils.InfoLog("2222222---%v", tempRecord)
139
+
140
+					recordTime, _ := time.ParseInLocation("2006-01-02 15:04:05", tempRecord, loc)
141
+					recordTimeInt := recordTime.Unix()
142
+					recordTimeStr := time.Unix(recordTimeInt, 0).Format(timeLayout)
143
+
144
+					var total int
145
+					var RangeOptions string
146
+					var RangeMin string
147
+					var RangeMax string
148
+					var ItemType int
149
+					Range := strings.Split(LisInfo.RangeValue, "-")
150
+					if len(Range) > 1 {
151
+						RangeMin = Range[0]
152
+						RangeMax = Range[1]
153
+						ItemType = 1
154
+					} else {
155
+						ItemType = 2
156
+						RangeOptions = LisInfo.RangeValue
157
+					}
158
+
159
+					err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and project_id = ? and item_id = ? and status = 1", org_id, project_id, item_id).Find(&inspection_reference).Count(&total).Error
160
+					if total <= 0 {
161
+						inspection_reference.OrgId = org_id
162
+						inspection_reference.ProjectName = LisInfo.ProjectName
163
+						inspection_reference.Project = LisInfo.ProjectName
164
+						inspection_reference.ProjectId = project_id
165
+						inspection_reference.ItemName = LisInfo.ItemName
166
+						// inspection_reference.ItemNameAddition = strconv.FormatInt(info.ItemId, 10)
167
+						inspection_reference.ItemId = item_id
168
+						inspection_reference.RangeType = ItemType
169
+						inspection_reference.RangeMin = RangeMin
170
+						inspection_reference.RangeMax = RangeMax
171
+						// inspection_reference.RangeValue = RangeValue
172
+						inspection_reference.RangeOptions = RangeOptions
173
+						inspection_reference.Unit = LisInfo.Unit
174
+						inspection_reference.Status = 1
175
+						inspection_reference.CreatedTime = time.Now().Unix()
176
+						inspection_reference.UpdatedTime = time.Now().Unix()
177
+						inspection_reference.InspectDate = recordTimeStr
178
+						inspection_reference.UTime = recordTimeStr
179
+						err = tx.Model(&models.MiddleInspectionReference{}).Create(&inspection_reference).Error
180
+						if err != nil {
181
+							tx.Rollback()
182
+						}
183
+					}
184
+					var itotal int
185
+					err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, project_id, item_id, recordTimeStr, patient.ID).Find(&inspection).Count(&itotal).Error
186
+					if itotal <= 0 {
187
+						// inspection.InspectValue = strings.Replace(LisInfo.Testresult, "&gt;", ">", -1)
188
+						// inspection.InspectValue = strings.Replace(LiLisInfo.Testresult, "&lt;", "<", -1)
189
+						inspection.PatientId = patient.ID
190
+						inspection.OrgId = org_id
191
+						inspection.ProjectId = project_id
192
+						inspection.ItemName = inspection_reference.ItemName
193
+						inspection.ProjectName = inspection_reference.ProjectName
194
+						inspection.InspectType = ItemType
195
+						inspection.ItemId = item_id
196
+						inspection.InspectValue = LisInfo.ItemValue
197
+						inspection.InspectDate = recordTimeStr
198
+						inspection.RecordDate = recordTimeInt
199
+						// inspection.InspectTips = report.Resultstate
200
+						inspection.Status = 1
201
+						inspection.CreatedTime = time.Now().Unix()
202
+						inspection.UpdatedTime = time.Now().Unix()
203
+						// inspection.UTime = record_date.Format(timeLayout)
204
+						// inspection.HisUserId = strconv.FormatInt(patient_id, 10)
205
+						err = tx.Model(&models.MiddleInspection{}).Create(&inspection).Error
206
+						if err != nil {
207
+							tx.Rollback()
208
+						}
209
+					}
210
+					tx.Commit()
211
+				}
212
+			} else {
213
+				continue
214
+			}
215
+		}
216
+
217
+		var syncInfo models.MiddleSyncInfo
218
+		syncInfo.OrgId = org_id
219
+		syncInfo.SyncTime = time.Now().Unix()
220
+		syncInfo.SyncResultType = 1
221
+		syncInfo.SyncRsultRemark = "同步成功"
222
+		syncInfo.SyncTotalNum = 0
223
+		syncInfo.SyncSuccessNum = 0
224
+		syncInfo.SyncInfo = ""
225
+		syncInfo.CreateTime = time.Now().Unix()
226
+		syncInfo.UpdateTime = time.Now().Unix()
227
+
228
+		cwderr := CreateSyncInfo(&syncInfo)
229
+		if cwderr != nil {
230
+			utils.ErrorLog("创建同步信息失败:%v", cwderr)
231
+			return
232
+		}
233
+	}
234
+	SyncToJhhjyy()
235
+	return
236
+}
237
+
238
+func SyncToJhhjyy() {
239
+
240
+	utils.TraceLog("检验检查同步任务开始执行")
241
+	org_id := int64(10629)
242
+
243
+	// 第一步:跟进org_id 去中间库查出需要同步的数据
244
+	inspection_references, _ := GetSyncInspectionReferenceByOrgId(org_id)
245
+	inspections, _ := GetSyncInspectionByOrgId(org_id)
246
+
247
+	// 第二步:将数据同步到业务库
248
+	if len(inspection_references) > 0 {
249
+		for _, inspection_reference := range inspection_references {
250
+			SyncInspectionReference(&inspection_reference)
251
+		}
252
+	}
253
+
254
+	if len(inspections) > 0 {
255
+		for _, inspection := range inspections {
256
+			SyncInspection(&inspection)
257
+		}
258
+	}
259
+	utils.SuccessLog("检验检查同步任务完成")
260
+}

+ 465 - 0
service/sclsyyyy_service.go Näytä tiedosto

@@ -0,0 +1,465 @@
1
+package service
2
+
3
+import (
4
+	"IC/models"
5
+	"IC/utils"
6
+	_ "encoding/json"
7
+	_ "fmt"
8
+	oracle "github.com/dzwvip/gorm-oracle"
9
+	"gorm.io/gorm"
10
+	"strconv"
11
+	"strings"
12
+	"time"
13
+)
14
+
15
+// 四川乐山友谊医院 HIS医嘱同步+LIS检验结果同步
16
+
17
+type scyyyylis struct {
18
+	HisUserId    string `gorm:"column:HIS_USER_ID" json:"HIS_USER_ID"`
19
+	PatientName  string `gorm:"column:PATIENT_NAME" json:"PATIENT_NAME"`
20
+	ProjectId    string `gorm:"column:PROJECT_ID" json:"PROJECT_ID"`
21
+	ProjectName  string `gorm:"column:PROJECT_NAME" json:"PROJECT_NAME"`
22
+	InspectDate  string `gorm:"column:INSPECT_DATE" json:"INSPECT_DATE"`
23
+	ItemId       string `gorm:"column:ITEM_ID" json:"ITEM_ID"`
24
+	ItemName     string `gorm:"column:ITEM_NAME" json:"ITEM_NAME"`
25
+	ItemType     int64  `gorm:"column:ITEM_TYPE" json:"ITEM_TYPE"`
26
+	ItemValue    string `gorm:"column:ITEM_VALUE" json:"ITEM_VALUE"`
27
+	RangeMin     string `gorm:"column:RANGE_MIN" json:"RANGE_MIN"`
28
+	RangeMax     string `gorm:"column:RANGE_MAX" json:"RANGE_MAX"`
29
+	RangeValue   string `gorm:"column:RANGE_VALUE" json:"RANGE_VALUE"`
30
+	RangeOptions string `gorm:"column:RANGE_OPTIONS" json:"RANGE_OPTIONS"`
31
+	Unit         string `gorm:"column:UNIT" json:"UNIT"`
32
+	State        int64  `gorm:"column:STATE" json:"STATE"`
33
+	CTime        string `gorm:"column:C_TIME" json:"C_TIME"`
34
+	UTime        string `gorm:"column:U_TIME" json:"U_TIME"`
35
+}
36
+
37
+func (scyyyylis) TableName() string {
38
+	return "yyyyxthy"
39
+}
40
+
41
+func GetSclsyyyyLis(rdb *gorm.DB, c_time string) (record []*scyyyylis, err error) {
42
+	err = rdb.Model(&scyyyylis{}).Where("C_TIME >= TO_DATE(?, 'YYYY-MM-DD HH24:MI:SS')", c_time).Find(&record).Error
43
+	return
44
+}
45
+
46
+// 根据机构ID和检验检查名称获取该检查的project_id,如没有,则创建一个
47
+func GetScyyyyProjectID(org_id int64, project_name string, item_name string) (project_id int64, err error) {
48
+	var inspection_reference models.MiddleInspectionReference
49
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? and item_name = ? ", org_id, project_name, item_name).First(&inspection_reference).Error
50
+	if inspection_reference.ID > 0 {
51
+		return inspection_reference.ProjectId, err
52
+	} else {
53
+		err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? ", org_id, project_name).First(&inspection_reference).Error
54
+		if inspection_reference.ID > 0 {
55
+			return inspection_reference.ProjectId, err
56
+		} else {
57
+			err = readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
58
+			if inspection_reference.ProjectId > 0 {
59
+				return inspection_reference.ProjectId + 1, err
60
+			} else {
61
+				return 1067701, err
62
+			}
63
+		}
64
+	}
65
+}
66
+
67
+// 根据机构ID和检验检查小项名称获取该检查的item_id,如没有,则创建一个
68
+func GetScyyyyItemID(org_id int64, project_name string, item_name string, project_id int64) (item_id int64, err error) {
69
+	var inspection_reference models.MiddleInspectionReference
70
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project = ? and item_name = ?", org_id, project_name, item_name).First(&inspection_reference).Error
71
+	if inspection_reference.ID > 0 {
72
+		return inspection_reference.ItemId, err
73
+	} else {
74
+		err := readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id = ? and project_id = ? ", org_id, project_id).Select("max(item_id) as item_id").First(&inspection_reference).Error
75
+		if inspection_reference.ItemId > 0 {
76
+			return inspection_reference.ItemId + 1, err
77
+		} else {
78
+			return project_id*100 + 1, err
79
+		}
80
+	}
81
+}
82
+
83
+// 四川乐山友谊医院Lis同步
84
+func SyncScyyyyLis() (err error) {
85
+	org_id := int64(10677)
86
+	orgDb, err := gorm.Open(oracle.Open("oracle://zjybase:zjybase@10.0.0.248:1521/orcl"), &gorm.Config{})
87
+
88
+	if err != nil {
89
+		utils.InfoLog("创建数据库连接失败:%v", err)
90
+	}
91
+
92
+	// 第一步:获取上一次同步的时间点
93
+	syncLastInfo, _ := GetSyncTimeByOrgIDForYs(org_id)
94
+	var sync_time int64
95
+	if syncLastInfo.ID > 0 {
96
+		sync_time = syncLastInfo.SyncTime
97
+	} else {
98
+		sync_time = 1704038400 // 2024-01-01
99
+	}
100
+
101
+	// 第二步:获取时间内所有检验结果
102
+	sync_time_temp := time.Unix(sync_time, 0)
103
+	startTimeStr := sync_time_temp.Format("2006-01-02 15:04:05")
104
+
105
+	yyyyLis, _ := GetSclsyyyyLis(orgDb, startTimeStr)
106
+	if len(yyyyLis) > 0 {
107
+		for _, LisInfo := range yyyyLis {
108
+			var patientInfo models.Patients
109
+			// 根据身份证号获取患者信息
110
+			if len(LisInfo.HisUserId) > 0 {
111
+				patientInfo, _ = GetPatientsInfoByIDCardNo(LisInfo.HisUserId, org_id)
112
+				if patientInfo.ID <= 0 {
113
+					continue
114
+				}
115
+			} else {
116
+				patientInfo, _ = GetPatientsInfoByName(LisInfo.PatientName, org_id)
117
+				if patientInfo.ID <= 0 {
118
+					continue
119
+				}
120
+			}
121
+
122
+			timeLayout := "2006-01-02 15:04"
123
+			loc, _ := time.LoadLocation("Local")
124
+
125
+			timstr := strings.Split(LisInfo.InspectDate, "T")
126
+			timstem := strings.Split(timstr[1], "+")
127
+			tempRecord := timstr[0] + " " + timstem[0]
128
+			recordTime, _ := time.ParseInLocation("2006-01-02 15:04:05", tempRecord, loc)
129
+			recordTimeInt := recordTime.Unix()
130
+			recordTimeStr := time.Unix(recordTimeInt, 0).Format(timeLayout)
131
+
132
+			project_id, _ := GetScyyyyProjectID(org_id, LisInfo.ProjectName, LisInfo.ItemName)
133
+			item_id, _ := GetScyyyyItemID(org_id, LisInfo.ProjectName, LisInfo.ItemName, project_id)
134
+			tx := writeMiddleDb.Begin()
135
+			var inspection models.MiddleInspection
136
+			var inspection_reference models.MiddleInspectionReference
137
+
138
+			var total int
139
+			var RangeOptions string
140
+			var RangeMin string
141
+			var RangeMax string
142
+			var ItemType int
143
+			Range := strings.Split(LisInfo.RangeValue, "--")
144
+			if len(Range) > 1 {
145
+				RangeMin = Range[0]
146
+				RangeMax = Range[1]
147
+				ItemType = 1
148
+			} else {
149
+				ItemType = 2
150
+				RangeOptions = LisInfo.RangeValue
151
+			}
152
+
153
+			err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and project_id = ? and item_id = ? and status = 1", org_id, project_id, item_id).Find(&inspection_reference).Count(&total).Error
154
+			if total <= 0 {
155
+				inspection_reference.OrgId = org_id
156
+				inspection_reference.ProjectName = LisInfo.ProjectName
157
+				inspection_reference.Project = LisInfo.ProjectName
158
+				inspection_reference.ProjectId = project_id
159
+				inspection_reference.ItemName = LisInfo.ItemName
160
+				// inspection_reference.ItemNameAddition = strconv.FormatInt(info.ItemId, 10)
161
+				inspection_reference.ItemId = item_id
162
+				inspection_reference.RangeType = ItemType
163
+				inspection_reference.RangeMin = RangeMin
164
+				inspection_reference.RangeMax = RangeMax
165
+				// inspection_reference.RangeValue = RangeValue
166
+				inspection_reference.RangeOptions = RangeOptions
167
+				inspection_reference.Unit = LisInfo.Unit
168
+				inspection_reference.Status = 1
169
+				inspection_reference.CreatedTime = time.Now().Unix()
170
+				inspection_reference.UpdatedTime = time.Now().Unix()
171
+				inspection_reference.InspectDate = recordTimeStr
172
+				inspection_reference.UTime = recordTimeStr
173
+				err = tx.Model(&models.MiddleInspectionReference{}).Create(&inspection_reference).Error
174
+				if err != nil {
175
+					tx.Rollback()
176
+				}
177
+			}
178
+			var itotal int
179
+			err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, project_id, item_id, recordTimeStr, patientInfo.ID).Find(&inspection).Count(&itotal).Error
180
+			if itotal <= 0 {
181
+				// inspection.InspectValue = strings.Replace(LisInfo.Testresult, "&gt;", ">", -1)
182
+				// inspection.InspectValue = strings.Replace(LiLisInfo.Testresult, "&lt;", "<", -1)
183
+				inspection.PatientId = patientInfo.ID
184
+				inspection.OrgId = org_id
185
+				inspection.ProjectId = project_id
186
+				inspection.ItemName = inspection_reference.ItemName
187
+				inspection.ProjectName = inspection_reference.ProjectName
188
+				inspection.InspectType = ItemType
189
+				inspection.ItemId = item_id
190
+				inspection.InspectValue = LisInfo.ItemValue
191
+				inspection.InspectDate = recordTimeStr
192
+				inspection.RecordDate = recordTimeInt
193
+				// inspection.InspectTips = report.Resultstate
194
+				inspection.Status = 1
195
+				inspection.CreatedTime = time.Now().Unix()
196
+				inspection.UpdatedTime = time.Now().Unix()
197
+				// inspection.UTime = record_date.Format(timeLayout)
198
+				// inspection.HisUserId = strconv.FormatInt(patient_id, 10)
199
+				err = tx.Model(&models.MiddleInspection{}).Create(&inspection).Error
200
+				if err != nil {
201
+					tx.Rollback()
202
+				}
203
+			}
204
+			tx.Commit()
205
+		}
206
+		var syncInfo models.MiddleSyncInfo
207
+		syncInfo.OrgId = org_id
208
+		syncInfo.SyncTime = time.Now().Unix()
209
+		syncInfo.SyncResultType = 1
210
+		syncInfo.SyncRsultRemark = "同步成功"
211
+		syncInfo.SyncTotalNum = 0
212
+		syncInfo.SyncSuccessNum = 0
213
+		syncInfo.SyncInfo = ""
214
+		syncInfo.CreateTime = time.Now().Unix()
215
+		syncInfo.UpdateTime = time.Now().Unix()
216
+
217
+		cwderr := CreateSyncInfo(&syncInfo)
218
+		if cwderr != nil {
219
+			utils.ErrorLog("创建同步信息失败:%v", cwderr)
220
+			return
221
+		}
222
+	}
223
+
224
+	SyncToSclsyyyy()
225
+	return
226
+}
227
+
228
+func SyncToSclsyyyy() {
229
+	utils.TraceLog("检验检查同步任务开始执行")
230
+	org_id := int64(10677)
231
+
232
+	// 第一步:跟进org_id 去中间库查出需要同步的数据
233
+	inspection_references, _ := GetSyncInspectionReferenceByOrgId(org_id)
234
+	inspections, _ := GetSyncInspectionByOrgId(org_id)
235
+
236
+	// 第二步:将数据同步到业务库
237
+	if len(inspection_references) > 0 {
238
+		for _, inspection_reference := range inspection_references {
239
+			SyncInspectionReference(&inspection_reference)
240
+		}
241
+	}
242
+
243
+	if len(inspections) > 0 {
244
+		for _, inspection := range inspections {
245
+			SyncInspection(&inspection)
246
+		}
247
+	}
248
+	utils.SuccessLog("检验检查同步任务完成")
249
+}
250
+
251
+type yyyyxtyz struct {
252
+	HisUserId             string `gorm:"column:HIS_USER_ID" json:"HIS_USER_ID" form:"HIS_USER_ID"`
253
+	UserName              string `gorm:"column:USER_NAME" json:"USER_NAME" form:"USER_NAME"`
254
+	DoctorId              string `gorm:"column:DOCTOR_ID" json:"DOCTOR_ID" form:"DOCTOR_ID"`
255
+	DoctorName            string `gorm:"column:DOCTOR_NAME" json:"DOCTOR_NAME" form:"DOCTOR_NAME"`
256
+	AdviceId              int64  `gorm:"column:ADVICE_ID" json:"ADVICE_ID" form:"ADVICE_ID"`
257
+	MedListCodg           string `gorm:"column:MED_LIST_CODG" json:"MED_LIST_CODG" form:"MED_LIST_CODG"`
258
+	StartTime             string `gorm:"column:START_TIME" json:"START_TIME" form:"START_TIME"`
259
+	AdviceName            string `gorm:"column:ADVICE_NAME" json:"ADVICE_NAME" form:"ADVICE_NAME"`
260
+	AdviceDesc            string `gorm:"column:ADVICE_DESC" json:"ADVICE_DESC" form:"ADVICE_DESC"`
261
+	SingleDose            string `gorm:"column:SINGLE_DOSE" json:"SINGLE_DOSE" form:"SINGLE_DOSE"`
262
+	SingleDoseUnit        string `gorm:"column:SINGLE_DOSE_UNIT" json:"SINGLE_DOSE_UNIT" form:"SINGLE_DOSE_UNIT"`
263
+	PrescribingNumber     string `gorm:"column:PRESCRIBING_NUMBER" json:"PRESCRIBING_NUMBER" form:"PRESCRIBING_NUMBER"`
264
+	PrescribingNumberUnit string `gorm:"column:PRESCRIBING_NUMBER_UNIT" json:"PRESCRIBING_NUMBER_UNIT" form:"PRESCRIBING_NUMBER_UNIT"`
265
+	DeliveryWay           string `gorm:"column:DELIVERY_WAY" json:"DELIVERY_WAY" form:"DELIVERY_WAY"`
266
+	ExecutionFrequency    string `gorm:"column:EXECUTION_FREQUENCY" json:"EXECUTION_FREQUENCY" form:"EXECUTION_FREQUENCY"`
267
+	State                 int64  `gorm:"column:STATE" json:"STATE" form:"STATE"`
268
+	CTime                 string `gorm:"column:CREATE_TIME" json:"CREATE_TIME" form:"CREATE_TIME"`
269
+	UTime                 string `gorm:"column:UPDATE_TIME" json:"UPDATE_TIME" form:"UPDATE_TIME"`
270
+}
271
+
272
+func (yyyyxtyz) TableName() string {
273
+	return "yyyyxtyz"
274
+}
275
+
276
+func GetSclsyyyyyz(rdb *gorm.DB, update_time string) (record []*yyyyxtyz, err error) {
277
+	err = rdb.Model(&yyyyxtyz{}).Where("update_time >= ?", update_time).Find(&record).Error
278
+	return
279
+}
280
+
281
+func GetAdviceBySyncAdviceIdForScyyyy(orgId int64, sync_advice_id int64, advice_date int64, patient_id int64) (advice models.XtDoctorAdvice, err error) {
282
+	err = readDb.Model(&models.XtDoctorAdvice{}).Where(" user_org_id = ? AND advice_date = ? and patient_id = ? AND sync_advice_id = ? AND status = 1 ", orgId, advice_date, patient_id, sync_advice_id).First(&advice).Error
283
+	return
284
+}
285
+
286
+// 根据姓名获取patient_id
287
+func GetSchedulesByPatientID(org_id int64, schedulesTime int64, patient_id int64) (schedules models.DialysisSchedule, err error) {
288
+	err = readDb.Model(&models.DialysisSchedule{}).Where("user_org_id = ? and  schedule_date = ? and patient_id = ? and status = 1", org_id, schedulesTime, patient_id).First(&schedules).Error
289
+	return
290
+}
291
+
292
+// 四川乐山友谊医院医嘱同步
293
+func SyncSclsyyyyyz(orgDb *gorm.DB) (err error) {
294
+	// 第一步:获取上次同步时间
295
+	org_id := int64(10677)
296
+
297
+	redisClient := RedisClient()
298
+	defer redisClient.Close()
299
+	sync_time_tt, _ := redisClient.Get("sclsyyyy_sync_time").Result()
300
+
301
+	sync_time, _ := strconv.ParseInt(sync_time_tt, 10, 64)
302
+	if sync_time == 0 {
303
+		sync_time = time.Now().Unix() - 60*60*10
304
+	}
305
+	// 需要把时间戳转换为日期格式
306
+	syncTimeStr := time.Unix(sync_time, 0).Format("2006-01-02 15:04:05")
307
+	new_sync_time := time.Now().Unix() - 60*3
308
+	schedulesDateStr := time.Now().Format("2006-01-02")
309
+	schedulesDate, _ := utils.ParseTimeStringToTime("2006-01-02", schedulesDateStr)
310
+	schedulesTime := schedulesDate.Unix()
311
+	utils.InfoLog("syncTimeStr:%v", syncTimeStr)
312
+	utils.InfoLog("schedulesTime:%v", schedulesTime)
313
+
314
+	// 切换为当前时间
315
+	redisClient.Set("sclsyyyy_sync_time", new_sync_time, time.Minute*60*24)
316
+	// 第二步: 获取该时间段内有更新的医嘱
317
+	yzList, _ := GetSclsyyyyyz(orgDb, syncTimeStr)
318
+	if len(yzList) > 0 {
319
+		loc, _ := time.LoadLocation("Local") //重要:获取时区
320
+		for _, yz := range yzList {
321
+			if yz.DeliveryWay == "口服" {
322
+				continue
323
+			}
324
+			var dflag int64
325
+			dflag = 0
326
+			utils.InfoLog("AdviceName:%v", yz.AdviceName)
327
+			if strings.Contains(yz.AdviceName, "注射") {
328
+				dflag = 1
329
+			}
330
+
331
+			if strings.Contains(yz.AdviceName, "血液") {
332
+				dflag = 1
333
+			}
334
+
335
+			if strings.Contains(yz.AdviceName, "低分子肝素") {
336
+				dflag = 1
337
+			}
338
+
339
+			if strings.Contains(yz.AdviceName, "左卡") {
340
+				dflag = 1
341
+			}
342
+
343
+			if strings.Contains(yz.AdviceName, "促红素") {
344
+				dflag = 1
345
+			}
346
+
347
+			if strings.Contains(yz.AdviceName, "奈莫司他") {
348
+				dflag = 1
349
+			}
350
+
351
+			if strings.Contains(yz.AdviceName, "葡萄糖") {
352
+				dflag = 1
353
+			}
354
+
355
+			if strings.Contains(yz.AdviceName, "吸氧") {
356
+				dflag = 1
357
+			}
358
+
359
+			if strings.Contains(yz.AdviceName, "抢救") {
360
+				dflag = 1
361
+			}
362
+
363
+			if strings.Contains(yz.AdviceName, "电脑血糖") {
364
+				dflag = 1
365
+			}
366
+
367
+			if strings.Contains(yz.AdviceName, "血液透析") {
368
+				yz.SingleDose = ""
369
+				yz.SingleDoseUnit = ""
370
+				yz.PrescribingNumber = "1"
371
+				yz.PrescribingNumberUnit = "次"
372
+			}
373
+
374
+			utils.InfoLog("dflag:%v", dflag)
375
+
376
+			if dflag == 0 {
377
+				continue
378
+			}
379
+
380
+			var patientInfo models.Patients
381
+			// 根据身份证号获取患者信息
382
+			if len(yz.HisUserId) > 0 {
383
+				patientInfo, _ = GetPatientsInfoByIDCardNo(yz.HisUserId, org_id)
384
+				if patientInfo.ID <= 0 {
385
+					continue
386
+				}
387
+			} else {
388
+				patientInfo, _ = GetPatientsInfoByName(yz.UserName, org_id)
389
+				if patientInfo.ID <= 0 {
390
+					continue
391
+				}
392
+			}
393
+			// 查询该患者当天是否有排班信息
394
+			theTime, _ := time.ParseInLocation("2006-01-02 15:04", yz.StartTime, loc) //使用模板在对应时区转化为time.time类型
395
+			start_time := theTime.Unix()
396
+
397
+			schedulesInfo, _ := GetSchedulesByPatientID(org_id, schedulesTime, patientInfo.ID)
398
+			if schedulesInfo.ID > 0 {
399
+				start_time = theTime.Unix()
400
+			} else {
401
+				continue
402
+			}
403
+
404
+			// 根据同步来的 advice_id 来查询库里是否已经存在
405
+			advice_info, _ := GetAdviceBySyncAdviceIdForScyyyy(org_id, yz.AdviceId, schedulesTime, patientInfo.ID)
406
+			if advice_info.ID > 0 {
407
+				continue
408
+			} else {
409
+				// 根据姓名获取医生ID
410
+				var doctor_id int64
411
+				temp_doctor_id, _ := redisClient.Get("sclsyyyy_doctor_id_" + yz.DoctorId).Result()
412
+				if len(temp_doctor_id) == 0 {
413
+					doctor, _ := GetAdminUserId(org_id, yz.DoctorName)
414
+					doctor_id = doctor.AdminUserId
415
+					if doctor_id > 0 {
416
+						redisClient.Set("sclsyyyy_doctor_id_"+yz.DoctorId, doctor_id, time.Minute*60*2)
417
+					} else {
418
+						continue
419
+					}
420
+				} else {
421
+					doctor_id, _ = strconv.ParseInt(temp_doctor_id, 10, 64)
422
+				}
423
+
424
+				// 根据排班班次,固定医嘱时间
425
+				SingleDose, _ := strconv.ParseFloat(yz.SingleDose, 64)
426
+				PrescribingNumber, _ := strconv.ParseFloat(yz.PrescribingNumber, 64)
427
+				advice := models.XtDoctorAdvice{
428
+					UserOrgId:             org_id,
429
+					PatientId:             patientInfo.ID,
430
+					AdviceType:            2,
431
+					AdviceDate:            schedulesTime,
432
+					StartTime:             start_time,
433
+					AdviceName:            yz.AdviceName,
434
+					AdviceDesc:            yz.AdviceDesc,
435
+					RecordDate:            schedulesTime,
436
+					SingleDose:            SingleDose,
437
+					SingleDoseUnit:        yz.SingleDoseUnit,
438
+					PrescribingNumber:     PrescribingNumber,
439
+					PrescribingNumberUnit: yz.PrescribingNumberUnit,
440
+					DeliveryWay:           yz.DeliveryWay,
441
+					ExecutionFrequency:    yz.ExecutionFrequency,
442
+					AdviceDoctor:          doctor_id,
443
+					CreatedTime:           time.Now().Unix(),
444
+					UpdatedTime:           time.Now().Unix(),
445
+					SyncAdviceId:          yz.AdviceId,
446
+					ExecutionState:        2,
447
+					Status:                1,
448
+					IsSync:                1,
449
+				}
450
+				utils.InfoLog("advice:%v", advice)
451
+
452
+				if len(yz.AdviceName) > 0 {
453
+					handleerr := CreateDoctorAdviceHandle(&advice)
454
+					if handleerr != nil {
455
+						utils.ErrorLog("添加医嘱信息失败:%v", handleerr)
456
+						continue
457
+					}
458
+				} else {
459
+					continue
460
+				}
461
+			}
462
+		}
463
+	}
464
+	return
465
+}

+ 12 - 14
service/sssy_service.go Näytä tiedosto

@@ -666,7 +666,7 @@ func UploadSYData(org_id int64) {
666 666
 
667 667
 func SyncSYData2() {
668 668
 	org_id := int64(10191)
669
-	start_time := "2024-04-20"
669
+	start_time := "2022-01-10"
670 670
 	end_time := "2024-04-26"
671 671
 	record, _ := GetLastSyncResultRecord(org_id)
672 672
 	if record.ID > 0 {
@@ -675,7 +675,7 @@ func SyncSYData2() {
675 675
 	}
676 676
 	loc, _ := time.LoadLocation("Local")
677 677
 	theTime, _ := time.ParseInLocation("2006-01-02", start_time, loc)
678
-	newtheTime := theTime.Unix() - 60*60*24*3
678
+	newtheTime := theTime.Unix() - 60*60*24
679 679
 
680 680
 	SyncTime := time.Unix(newtheTime, 0)
681 681
 	syncTimeStr := SyncTime.Format("2006-01-02")
@@ -821,7 +821,7 @@ func SyncSYData2() {
821 821
 	}
822 822
 
823 823
 	SyncToSssytx()
824
-	UpdateJg()
824
+	//UpdateJg()
825 825
 }
826 826
 
827 827
 func SyncToSssytx() {
@@ -830,21 +830,19 @@ func SyncToSssytx() {
830 830
 	org_id := int64(10191)
831 831
 
832 832
 	// 第一步:跟进org_id 去中间库查出需要同步的数据
833
-	//inspection_references, _ := GetSyncInspectionReferenceByOrgId(org_id)
833
+	inspection_references, _ := GetSyncInspectionReferenceByOrgId(org_id)
834 834
 	inspections, _ := GetSyncInspectionByOrgId(org_id)
835 835
 
836 836
 	// 第二步:将数据同步到业务库
837
-	//if len(inspection_references) > 0 {
838
-	//	for _, inspection_reference := range inspection_references {
839
-	//		SyncInspectionReference(&inspection_reference)
840
-	//	}
841
-	//}
837
+	if len(inspection_references) > 0 {
838
+		for _, inspection_reference := range inspection_references {
839
+			SyncInspectionReference(&inspection_reference)
840
+		}
841
+	}
842 842
 
843 843
 	if len(inspections) > 0 {
844 844
 		for _, inspection := range inspections {
845
-			if inspection.SysProjectId > 0 && inspection.SysItemId > 0 {
846
-				SyncSssyInspection(&inspection)
847
-			}
845
+			SyncSssyInspection(&inspection)
848 846
 		}
849 847
 	}
850 848
 	utils.SuccessLog("检验检查同步任务完成")
@@ -890,9 +888,9 @@ func SyncSssyInspection(data *models.MiddleInspection) error {
890 888
 		inspection.PatientId = data.PatientId
891 889
 		inspection.ProjectName = data.ProjectName
892 890
 		// inspection.Project = data.ProjectName
893
-		inspection.ProjectId = data.SysProjectId
891
+		inspection.ProjectId = data.ProjectId
894 892
 		inspection.ItemName = data.ItemName
895
-		inspection.ItemId = data.SysItemId
893
+		inspection.ItemId = data.ItemId
896 894
 		inspection.InspectType = int64(data.InspectType)
897 895
 		inspection.InspectValue = data.InspectValue
898 896
 		inspection.InspectTips = data.InspectTips

+ 1 - 1
service/sy_service.go Näytä tiedosto

@@ -192,7 +192,7 @@ func SyncStsyLis() (err error) {
192 192
 					}
193 193
 				}
194 194
 				var itotal int
195
-				err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, project_id, item_id, recordTimeStr, patient.ID).Find(&inspection).Count(&itotal).Error
195
+				err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, project_id, item_id, recordTimeInt, patient.ID).Find(&inspection).Count(&itotal).Error
196 196
 				if itotal <= 0 {
197 197
 					// inspection.InspectValue = strings.Replace(LisInfo.Testresult, "&gt;", ">", -1)
198 198
 					// inspection.InspectValue = strings.Replace(LiLisInfo.Testresult, "&lt;", "<", -1)

+ 4 - 4
service/xml_service.go Näytä tiedosto

@@ -38,7 +38,7 @@ func GetGPReportListData(start_date string, end_date string, key string) (result
38 38
 	}
39 39
 
40 40
 	// 创建POST请求
41
-	url := "http://gpis.cnhiqc.com:9799/InstituteLISService.asmx"
41
+	url := "https://gpis.cnhiqc.com/api/InstituteLISService.asmx"
42 42
 	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
43 43
 	if err != nil {
44 44
 		fmt.Println("Request creation error:", err)
@@ -192,7 +192,7 @@ func GetGPResultDataTwo(item models.GPReportListResultData, key string) (results
192 192
 		}
193 193
 
194 194
 		// 创建POST请求
195
-		url := "http://gpis.cnhiqc.com:9799/InstituteLISService.asmx"
195
+		url := "https://gpis.cnhiqc.com/api/InstituteLISService.asmx"
196 196
 		req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
197 197
 		if err != nil {
198 198
 			fmt.Println("Request creation error:", err)
@@ -273,7 +273,7 @@ func GetGPResultDataTwo(item models.GPReportListResultData, key string) (results
273 273
 			}
274 274
 
275 275
 			// 创建POST请求
276
-			url := "http://gpis.cnhiqc.com:9799/InstituteLISService.asmx"
276
+			url := "https://gpis.cnhiqc.com/api/InstituteLISService.asmx"
277 277
 			req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
278 278
 			if err != nil {
279 279
 				fmt.Println("Request creation error:", err)
@@ -358,7 +358,7 @@ func PostInspectApply(key string, apply models.JYApply, list []models.CustomerAp
358 358
 	fmt.Println(string(requestBody))
359 359
 
360 360
 	// 创建POST请求
361
-	url := "http://gpis.cnhiqc.com:9799/InstituteLISService.asmx"
361
+	url := "https://gpis.cnhiqc.com/api/InstituteLISService.asmx"
362 362
 	req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
363 363
 	if err != nil {
364 364
 		fmt.Println("Request creation error:", err)

+ 527 - 0
service/zqsh_service.go Näytä tiedosto

@@ -0,0 +1,527 @@
1
+package service
2
+
3
+import (
4
+	"IC/models"
5
+	"IC/utils"
6
+	"encoding/json"
7
+	"encoding/xml"
8
+	"github.com/astaxie/beego/httplib"
9
+	"net/url"
10
+	"strconv"
11
+	"strings"
12
+	"time"
13
+)
14
+
15
+type RequestResultZqsh struct {
16
+	Msg        string `json:"msg"`
17
+	ResultGzjh []struct {
18
+		AdviceId               int64   `json:"医嘱ID"`
19
+		OtherId                int64   `json:"相关ID"`
20
+		Source                 int     `json:"病人来源"`
21
+		PatientId              int64   `json:"病人ID"`
22
+		JzId                   int64   `json:"就诊ID"`
23
+		BabyId                 int     `json:"婴儿ID"`
24
+		PatientDepartmentId    int     `json:"病人科室ID"`
25
+		OrderId                int     `json:"次序"`
26
+		AdviceStatus           int     `json:"医嘱状态"`
27
+		AdviceType             int     `json:"医嘱类型"`
28
+		DiagnosisType          string  `json:"诊疗类型"`
29
+		DiagnosisItemId        int     `json:"诊疗项目ID"`
30
+		CheckMethd             string  `json:"检查方法"`
31
+		ChargeItemId           int     `json:"收费项目ID"`
32
+		Day                    int     `json:"天数"`
33
+		JiLiang                float64 `json:"剂量"`
34
+		YongLiang              string  `json:"用量"`
35
+		DanLiang               float64 `json:"单量"`
36
+		Shuliang               float64 `json:"数量"`
37
+		Advice                 string  `json:"医嘱"`
38
+		GeiYaoTuJing           string  `json:"给药途径"`
39
+		ShuoMing               string  `json:"说明"`
40
+		ZhiXingKeShiId         int     `json:"执行科室ID"`
41
+		ZhiXingKeShi           string  `json:"执行科室"`
42
+		PN                     string  `json:"P(+)或N(-)表示阳性或阴性"`
43
+		ZhiXingPinCi           string  `json:"执行频次"`
44
+		PinLvCiShu             int     `json:"频率次数"`
45
+		PinLvJianGe            int     `json:"频率间隔"`
46
+		JianGeDanWei           string  `json:"间隔单位"`
47
+		ZhiXingShiJianFangAn   string  `json:"执行时间方案"`
48
+		JiJiaTeXing            int     `json:"计价特性"`
49
+		ZhiXingXingZhi         int     `json:"执行性质"`
50
+		ZhiXingBiaoZhi         int     `json:"执行标记"`
51
+		KeFouFenLing           int     `json:"可否分零"`
52
+		JinJiBiaoZhi           int     `json:"紧急标志"`
53
+		KaiShiZhiXingShiJian   int64   `json:"开始执行时间"`
54
+		ZhiXingZhongZhiShiJian int64   `json:"执行终止时间"`
55
+		ShangCiZhiXingShiJian  int64   `json:"上次执行时间"`
56
+		KaiZhuKeShiId          int     `json:"开嘱科室ID"`
57
+		DoctorCode             string  `json:"医师编码"`
58
+		Doctor                 string  `json:"开嘱医师"`
59
+		AdviceTime             int64   `json:"开嘱时间"`
60
+		StopTime               int64   `json:"停嘱时间"`
61
+		ApplyId                int     `json:"申请ID"`
62
+		UploadLable            int     `json:"上传标志"`
63
+		CheckResult            int     `json:"审查结果"`
64
+		NoPrint                int     `json:"忽略打印"`
65
+		Summary                string  `json:"摘要"`
66
+		AdviceOrderId          int64   `json:"医嘱单id"`
67
+		GeiYaoKeShi            int     `json:"给药科室"`
68
+		GeiYaoXingZhi          int     `json:"给药性质"`
69
+		GroupNo                int     `json:"组号"`
70
+		Speed                  string  `json:"滴速"`
71
+		ShouRiCiShu            float64 `json:"首日次数"`
72
+		MoRiCiShu              float64 `json:"末日次数"`
73
+		AdviceDoctorId         int     `json:"开嘱医师ID"`
74
+		AdviceNurseId          int     `json:"开嘱护士ID"`
75
+		OperaId                int     `json:"操作员ID"`
76
+		Opera                  string  `json:"操作员"`
77
+		CheckTime              int64   `json:"审核时间"`
78
+		ReplyAdviceTime        int64   `json:"重整医嘱时间"`
79
+	} `json:"result"`
80
+	Code string `json:"code"`
81
+}
82
+
83
+type XmlKeyZqsh struct {
84
+	XMLName    xml.Name `xml:"string"`
85
+	StringName string   `xml:"name,attr"`
86
+	InnerText  string   `xml:",innerxml"`
87
+}
88
+
89
+// 获取艾迪康的key
90
+func GetZqshAdKey(logid string, password string) (key string) {
91
+	Domain := "http://183.63.151.26:8081/AdWebService_new/ADReportWebService.asmx/Login?"
92
+	apiurl := "logid=" + logid + "&password=" + password
93
+	apiurl = url.PathEscape(apiurl)
94
+	utils.InfoLog("apiUrl: %v", apiurl)
95
+	apiurl = Domain + apiurl
96
+	xmlKey := XmlKeyZqsh{}
97
+	httplib.Get(apiurl).ToXML(&xmlKey)
98
+	utils.InfoLog("xmlKey: %v", xmlKey)
99
+	return xmlKey.InnerText
100
+}
101
+
102
+type ADStringZqsh struct {
103
+	XMLName    xml.Name         `xml:"string" json:"string"`
104
+	NewDataSet rpnewDataSetZqsh `xml:"NewDataSet" json:"NewDataSetZqsh"`
105
+}
106
+
107
+type rpnewDataSetZqsh struct {
108
+	ListTable []rplisttableZqsh `xml:"listtable" json:"listtableZqsh"`
109
+}
110
+
111
+type rplisttableZqsh struct {
112
+	Id          string `xml:"Id" json:"Id"`
113
+	PatientName string `xml:"PatientName" json:"PatientName"`
114
+	Bgrq        string `xml:"Bgrq" json:"Bgrq"`
115
+	Instrument  string `xml:"Instrument" json:"Instrument"`
116
+	LisDate     string `xml:"LisDate" json:"LisDate"`
117
+	Sampleid    string `xml:"Sampleid" json:"Sampleid"`
118
+}
119
+
120
+type ReportListZqshXml struct {
121
+	XMLName       xml.Name `xml:"GetReportList"`
122
+	Key           string   `xml:"Key"`
123
+	BeginDateTime string   `xml:"BeginDateTime"`
124
+	EndDateTime   string   `xml:"EndDateTime"`
125
+	TypeDateTime  string   `xml:"TypeDateTime"`
126
+	AgainFlag     string   `xml:"AgainFlag"`
127
+}
128
+
129
+// 获取机构一段时间内检验检查列表
130
+func GetAdGetReportListZqsh(Key string, BeginDateTime string, EndDateTime string, TypeDateTime string, AgainFlag string) (key ADStringZqsh) {
131
+	Domain := "http://183.63.151.26:8081/AdWebService_new/ADReportWebService.asmx/GetReportList"
132
+	var xmlKey ADStringZqsh
133
+	reportPost := httplib.Post(Domain)
134
+	reportPost.Param("Key", Key)
135
+	reportPost.Param("BeginDateTime", BeginDateTime)
136
+	reportPost.Param("EndDateTime", EndDateTime)
137
+	reportPost.Param("TypeDateTime", TypeDateTime)
138
+	reportPost.Param("AgainFlag", AgainFlag)
139
+	reportPost.Header("Content-Type", "application/xml")
140
+
141
+	xmlString, _ := reportPost.String()
142
+	xmlString = strings.Replace(xmlString, "&lt;", "<", -1)
143
+	xmlString = strings.Replace(xmlString, "&gt;", ">", -1)
144
+	xml.Unmarshal([]byte(xmlString), &xmlKey)
145
+	return xmlKey
146
+}
147
+
148
+type adkCheckZqsh struct {
149
+	ApplyId     string          `json:"applyid"`
150
+	ReportNo    string          `json:"reportno"`
151
+	PatName     string          `json:"patname"`
152
+	Sex         string          `json:"sex"`
153
+	Age         string          `json:"age"`
154
+	DptName     string          `json:"dptname"`
155
+	Testtype    string          `json:"testtype"`
156
+	Testcode    string          `json:"testcode"`
157
+	ExecuteTime string          `json:"receivetime"`
158
+	Checktime   string          `json:"checktime"`
159
+	Checkcode   string          `json:"checkcode"`
160
+	Result      []adkResultZqsh `json:"result"`
161
+}
162
+
163
+func GetAdkInfoZqsh(key string, id string) (str []adkCheckZqsh, checkStr string) {
164
+	Domain := "http://183.63.151.26:8081/AdWebService_new/ADReportWebService.asmx/GetJSONReportItemListById"
165
+
166
+	reportPost := httplib.Post(Domain)
167
+	reportPost.Param("Key", key)
168
+	reportPost.Param("id", id)
169
+	reportPost.Header("Content-Type", "application/xml")
170
+	xmlKey := XmlKey{}
171
+	reportPost.ToXML(&xmlKey)
172
+	var checkJSON []adkCheckZqsh
173
+	json.Unmarshal([]byte(xmlKey.InnerText), &checkJSON)
174
+	return checkJSON, xmlKey.InnerText
175
+}
176
+
177
+// 广州暨华血液透析中心Lis同步
178
+func SyncLisZqshtx() (err error) {
179
+	// 第一步:获取艾迪康下发的Key
180
+	org_id := int64(10215)
181
+	login := "RH0647"
182
+	password := "abc123456"
183
+	key := GetZqshAdKey(login, password)
184
+	utils.InfoLog("key: %v", key)
185
+	// 第二步:获e取上一次同步的时间点
186
+	syncLastInfo, _ := GetSyncTimeByOrgIDForYs(org_id)
187
+	var sync_time int64
188
+	if syncLastInfo.ID > 0 {
189
+		sync_time = syncLastInfo.SyncTime + 86400
190
+	} else {
191
+		sync_time = 1711900800
192
+	}
193
+	nowTimes := time.Now().Unix()
194
+	// syncTimes := time.Unix(sync_time,0).Format("2006-01-02")
195
+	if sync_time < nowTimes {
196
+		for i := sync_time; i < nowTimes; i = i + 86400 {
197
+			tempsyncTimes := time.Unix(i, 0).Format("2006-01-02")
198
+			utils.InfoLog("tempsyncTimes:%v", tempsyncTimes)
199
+			adString := GetAdGetReportListZqsh(key, tempsyncTimes, tempsyncTimes, "2", "2")
200
+			listtable := adString.NewDataSet.ListTable
201
+			utils.InfoLog("listtable: %v", listtable)
202
+			if len(listtable) > 3 {
203
+				// 第三步:根据检查列表获取的ID来获取检验检查详情
204
+				for _, list := range listtable {
205
+					listId := list.Id
206
+					utils.InfoLog("listId: %v", listId)
207
+					checkInfo, checkStr := GetAdkInfoZqsh(key, listId)
208
+					utils.InfoLog("checkInfo: %v", checkInfo)
209
+					for _, info := range checkInfo {
210
+						// 根据姓名 去查询对应的patient_id
211
+						patient, _ := GetPatientIDZqsh(org_id, info.PatName)
212
+						utils.InfoLog("patient: %v", patient)
213
+						if patient.ID > 0 {
214
+							middleReportHandle := models.MiddleReportHandle{
215
+								OrgId:       org_id,
216
+								HisUserId:   strconv.FormatInt(patient.ID, 10),
217
+								ApplyNo:     info.ApplyId,
218
+								ReportId:    info.ReportNo,
219
+								Name:        info.PatName,
220
+								Sex:         info.Sex,
221
+								Age:         info.Age,
222
+								Dept:        info.DptName,
223
+								PatientId:   strconv.FormatInt(patient.ID, 10),
224
+								RequestTime: info.ExecuteTime,
225
+								ExecuteTime: info.ExecuteTime,
226
+								ReceiveTime: info.ExecuteTime,
227
+								CheckTime:   info.ExecuteTime,
228
+								ReportInfo:  checkStr,
229
+								CreatedTime: time.Now().Unix(),
230
+								UpdatedTime: time.Now().Unix(),
231
+							}
232
+							handleerr := CreateReportHandle(&middleReportHandle)
233
+							if handleerr != nil {
234
+								utils.ErrorLog("创建检验检查操作数据失败:%v", handleerr)
235
+								return
236
+							}
237
+
238
+							ZqshReportInfoHandle(info, org_id, patient.ID)
239
+						}
240
+					}
241
+				}
242
+				var syncInfo models.MiddleSyncInfo
243
+				syncInfo.OrgId = org_id
244
+
245
+				syncInfo.SyncTime = i
246
+				syncInfo.SyncResultType = 1
247
+				syncInfo.SyncRsultRemark = "同步成功"
248
+				syncInfo.SyncTotalNum = 0
249
+				syncInfo.SyncSuccessNum = 0
250
+				syncInfo.SyncInfo = ""
251
+				syncInfo.CreateTime = time.Now().Unix()
252
+				syncInfo.UpdateTime = time.Now().Unix()
253
+
254
+				cwderr := CreateSyncInfo(&syncInfo)
255
+				if cwderr != nil {
256
+					utils.ErrorLog("创建同步信息失败:%v", cwderr)
257
+					return
258
+				}
259
+			}
260
+		}
261
+
262
+	}
263
+	SyncToZqshtx()
264
+
265
+	return
266
+}
267
+
268
+// 根据姓名获取patient_id
269
+func GetPatientIDZqsh(org_id int64, patient_name string) (patient models.Patients, err error) {
270
+	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? and status = 1 and name = ? ", org_id, patient_name).First(&patient).Error
271
+	return
272
+}
273
+
274
+func GetProjectInfoZqsh(item_id int64, org_id int64) (project_info models.MiddleInspectionReference, err error) {
275
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and item_id = ?", org_id, item_id).First(&project_info).Error
276
+	return
277
+}
278
+
279
+// 修改配置信息
280
+// func UpdateInspectionReference(InspectionReference *models.MiddleInspectionReference) error {
281
+// 	err := readMiddleDb.Model(&models.MiddleInspectionReference{}).Updates(&InspectionReference).Error
282
+// 	return err
283
+// }
284
+
285
+// 根据机构ID和检验检查名称获取该检查的project_id,如没有,则创建一个
286
+func GetZqshProjectID(org_id int64, project_name string) (project_id int64, err error) {
287
+	var inspection_reference models.MiddleInspectionReference
288
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ?", org_id, project_name).First(&inspection_reference).Error
289
+	if inspection_reference.ID > 0 {
290
+		return inspection_reference.ProjectId, err
291
+	} else {
292
+		err = readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
293
+		utils.InfoLog("inspection_reference: %v", inspection_reference)
294
+		if inspection_reference.ProjectId > 0 {
295
+			return inspection_reference.ProjectId + 1, err
296
+		} else {
297
+			return 1021501, err
298
+		}
299
+	}
300
+}
301
+
302
+// // 根据机构ID和检验检查名称获取该检查的project_id,如没有,则创建一个
303
+// func GetGzjhProjectID(org_id int64, project_name string) (project_id int64, err error) {
304
+// 	var inspection_reference models.MiddleInspectionReference
305
+// 	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and status = 1 and project_name = ?", org_id, project_name).First(&inspection_reference).Error
306
+// 	if inspection_reference.ID > 0 {
307
+// 		return inspection_reference.ProjectId, err
308
+// 	} else {
309
+// 		err = readMiddleDb.Table("xt_middle_inspection_reference").Where("org_id=? ", org_id).Select("max(project_id) as project_id").Scan(&inspection_reference).Error
310
+// 		if inspection_reference.ProjectId > 0 {
311
+// 			return inspection_reference.ProjectId + 1, err
312
+// 		} else {
313
+// 			return 116001, err
314
+// 		}
315
+// 	}
316
+// }
317
+
318
+func ZqshReportInfoHandle(CheckInfo adkCheckZqsh, org_id int64, patientId int64) {
319
+	// 1.先把所有的检查项弄出来
320
+	for _, info := range CheckInfo.Result {
321
+		// 根据project_id和item_id 判断该项是否存在
322
+		curitemcode, _ := strconv.ParseInt(info.Itemcode, 10, 64)
323
+		reference, _ := GetProjectInfoZqsh(curitemcode, org_id)
324
+		utils.InfoLog("info: %v", info)
325
+		utils.InfoLog("reference: %v", info)
326
+		if reference.ID > 0 {
327
+			if reference.ProjectId > 0 {
328
+				LgthYsSyncZqsh(info, reference.ProjectId, curitemcode, org_id, patientId, CheckInfo.ExecuteTime)
329
+			} else {
330
+				project_id := int64(0)
331
+				if len(info.Groupitemcode) > 0 {
332
+					// 对没有project信息的项目进行修改
333
+					project_id, _ = GetZqshProjectID(org_id, info.Groupitemname)
334
+					reference.ProjectId = project_id
335
+					reference.ProjectName = info.Groupitemcode
336
+					reference.Project = info.Groupitemcode
337
+					// 修改配置信息
338
+					UpdateInspectionReference(&reference)
339
+				}
340
+				LgthYsSyncZqsh(info, project_id, curitemcode, org_id, patientId, CheckInfo.ExecuteTime)
341
+			}
342
+		} else {
343
+			project_id := int64(0)
344
+			if len(info.Groupitemcode) > 0 {
345
+				project_id, _ = GetZqshProjectID(org_id, info.Groupitemname)
346
+			}
347
+			LgthYsSyncZqsh(info, project_id, curitemcode, org_id, patientId, CheckInfo.ExecuteTime)
348
+		}
349
+	}
350
+
351
+	//SyncLisZqshtx()
352
+}
353
+
354
+type adkResultZqsh struct {
355
+	Testno        string `json:"testno"`
356
+	Reportno      string `json:"reportno"`
357
+	Itemord       string `json:"itemord"`
358
+	Itemcode      string `json:"itemcode"`
359
+	Itemname      string `json:"itemname"`
360
+	ItemEname     string `json:"itemename"`
361
+	Result        string `json:"result"`
362
+	Units         string `json:"units"`
363
+	Testdate      string `json:"testdate"`
364
+	Eqpname       string `json:"eqpname"`
365
+	Groupitemcode string `json:"groupitemcode"`
366
+	Groupitemname string `json:"groupitemname"`
367
+	Limit         string `json:"limit"`
368
+	Resultstate   string `json:"resultstate"`
369
+	Criticalflag  string `json:"criticalflag"`
370
+	Itemename     string `json:"itemename"`
371
+}
372
+
373
+// 从机构将数据同步到中间库
374
+func LgthYsSyncZqsh(report adkResultZqsh, project_id int64, item_id int64, org_id int64, patient_id int64, receivetime string) (*models.MiddleInspectionReference, error) {
375
+	tx := writeMiddleDb.Begin()
376
+	var inspection models.MiddleInspection
377
+	var inspection_reference models.MiddleInspectionReference
378
+	recordDateStr := receivetime
379
+
380
+	if len(receivetime) == 0 {
381
+		recordDateStr = time.Now().Format("2006-01-02 15:04")
382
+	}
383
+
384
+	record_date_str, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", recordDateStr)
385
+	record_date := record_date_str.Unix()
386
+	inspect_date := time.Unix(record_date, 0).Format("2006-01-02 15:04")
387
+	// date, _ := utils.ParseTimeStringToTime("2006-01-02 15:04", recordDateStr)
388
+	// record_date,_ := utils.ParseTimeStringToTime("2006-01-02", date.Format("2006-01-02"))
389
+	var total int
390
+	var RangeOptions string
391
+	var RangeMin string
392
+	var RangeMax string
393
+
394
+	// // 判断检查类型
395
+	ItemType := 1
396
+	Range := strings.Split(report.Limit, "-")
397
+	if len(Range) > 1 {
398
+		RangeMin = Range[0]
399
+		RangeMax = Range[1]
400
+		ItemType = 1
401
+	} else {
402
+		ItemType = 2
403
+		RangeOptions = report.Limit
404
+	}
405
+
406
+	err = readMiddleDb.Model(&models.MiddleInspectionReference{}).Where("org_id = ? and project_id = ? and item_id = ? and status = 1", org_id, project_id, item_id).Find(&inspection_reference).Count(&total).Error
407
+	if inspection_reference.ID > 0 {
408
+		ItemType = inspection_reference.RangeType
409
+	}
410
+	if total <= 0 {
411
+		inspection_reference.OrgId = org_id
412
+		inspection_reference.ProjectName = report.Groupitemname
413
+		inspection_reference.Project = report.Groupitemcode
414
+		inspection_reference.ProjectId = project_id
415
+		inspection_reference.ItemName = report.Itemname
416
+		inspection_reference.ItemNameAddition = report.ItemEname
417
+		inspection_reference.ItemId = item_id
418
+		inspection_reference.RangeType = ItemType
419
+		inspection_reference.RangeMin = RangeMin
420
+		inspection_reference.RangeMax = RangeMax
421
+		// inspection_reference.RangeValue = RangeValue
422
+		inspection_reference.RangeOptions = RangeOptions
423
+		inspection_reference.Unit = report.Units
424
+		inspection_reference.Status = 1
425
+		inspection_reference.CreatedTime = time.Now().Unix()
426
+		inspection_reference.UpdatedTime = time.Now().Unix()
427
+		inspection_reference.InspectDate = inspect_date
428
+		inspection_reference.UTime = inspect_date
429
+		err = tx.Model(&models.MiddleInspectionReference{}).Create(&inspection_reference).Error
430
+		if err != nil {
431
+			tx.Rollback()
432
+		}
433
+	}
434
+
435
+	var itotal int
436
+	err = readMiddleDb.Model(&models.MiddleInspection{}).Where("org_id = ? and project_id = ? and item_id = ? and record_date = ? and patient_id = ?  and status = 1", org_id, project_id, item_id, record_date, patient_id).Find(&inspection).Count(&itotal).Error
437
+	if itotal <= 0 {
438
+		report.Result = strings.Replace(report.Result, "&gt;", ">", -1)
439
+		report.Result = strings.Replace(report.Result, "&lt;", "<", -1)
440
+		inspection.PatientId = patient_id
441
+		inspection.OrgId = org_id
442
+		inspection.ProjectId = project_id
443
+		inspection.ItemName = inspection_reference.ItemName
444
+		inspection.ProjectName = inspection_reference.ProjectName
445
+		inspection.InspectType = ItemType
446
+		inspection.ItemId = item_id
447
+		inspection.InspectValue = report.Result
448
+		inspection.InspectDate = inspect_date
449
+		inspection.RecordDate = record_date
450
+		inspection.InspectTips = report.Resultstate
451
+		inspection.Status = 1
452
+		inspection.CreatedTime = time.Now().Unix()
453
+		inspection.UpdatedTime = time.Now().Unix()
454
+		inspection.UTime = inspect_date
455
+		inspection.HisUserId = strconv.FormatInt(patient_id, 10)
456
+		err = tx.Model(&models.MiddleInspection{}).Create(&inspection).Error
457
+		if err != nil {
458
+			tx.Rollback()
459
+		}
460
+	}
461
+
462
+	// 	//处理检验检查操作表里同步条数和状态
463
+	// 	cur_num := Head.ReportInfoItemHandleNum + 1
464
+	// 	Head.ReportInfoItemHandleNum = cur_num
465
+	// 	handleType := 2
466
+	// 	if cur_num == Head.ReportInfoItemNum {
467
+	// 		handleType = 1
468
+	// 	}
469
+	// 	middleReportHandle := models.MiddleReportHandle{
470
+	// 		ID:							Head.ID,
471
+	// 		ReportInfoItemHandleNum:	cur_num,
472
+	// 		HandleType:					int64(handleType),
473
+	// 		UpdatedTime:				time.Now().Unix(),
474
+	// 	}
475
+	// 	err = UpdateReportHandleListyOrgID(&middleReportHandle)
476
+	// 	if err != nil {
477
+	// 		tx.Rollback()
478
+	// 	}
479
+	// }
480
+
481
+	tx.Commit()
482
+	return nil, err
483
+}
484
+
485
+// 根据姓名获取patient_id
486
+func GetPatientGzjhListZqsh(org_id int64, schedulesTime int64) (schedules []*models.DialysisSchedule, err error) {
487
+	err = readDb.Model(&models.DialysisSchedule{}).Where("user_org_id = ? and status = 1 and  schedule_date = ?", org_id, schedulesTime).Preload("Patients", "status = 1").Find(&schedules).Error
488
+	return
489
+}
490
+
491
+// 根据姓名获取admin_user_id
492
+func GetAdminUserIdZqsh(org_id int64, doctor_name string) (doctor models.UserAdminRole, err error) {
493
+	err = writeUserDb.Model(&models.UserAdminRole{}).Where("org_id = ? and status = 1 and  user_name = ?", org_id, doctor_name).First(&doctor).Error
494
+	return
495
+}
496
+
497
+func GetPatientGzjhByOrgIdZqsh(org_id int64) (patientList []*models.Patients, err error) {
498
+	err = readDb.Model(&models.Patients{}).Where("user_org_id = ? and status = 1", org_id).Find(&patientList).Error
499
+	return
500
+}
501
+
502
+func SyncToZqshtx() {
503
+	utils.TraceLog("检验检查同步任务开始执行")
504
+	org_id := int64(10215)
505
+
506
+	// 第一步:跟进org_id 去中间库查出需要同步的数据
507
+	inspection_references, _ := GetSyncInspectionReferenceByOrgId(org_id)
508
+	inspections, _ := GetSyncInspectionByOrgId(org_id)
509
+
510
+	// 第二步:将数据同步到业务库
511
+	if len(inspection_references) > 0 {
512
+		for _, inspection_reference := range inspection_references {
513
+			if inspection_reference.ProjectId > 0 && inspection_reference.ItemId > 0 {
514
+				SyncInspectionReference(&inspection_reference)
515
+			}
516
+		}
517
+	}
518
+
519
+	if len(inspections) > 0 {
520
+		for _, inspection := range inspections {
521
+			if inspection.ProjectId > 0 && inspection.ItemId > 0 {
522
+				SyncInspection(&inspection)
523
+			}
524
+		}
525
+	}
526
+	utils.SuccessLog("检验检查同步任务完成")
527
+}