statistis_qc_service.go 107KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936
  1. package service
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. "math"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "XT_New/models"
  12. "github.com/jinzhu/gorm"
  13. )
  14. func GetDialysisTotalDatas() {
  15. }
  16. func GetNewDialysiTotal(startime int64, endtime int64, orgid int64, origin int64) (int64, error) {
  17. counts := models.PatientPrescriptionCountStruct{}
  18. var err error
  19. if origin == 1 { //透析记录,上机为准
  20. db := XTReadDB().Table("xt_dialysis_order as x").Joins("join xt_dialysis_prescription p on p.patient_id = x.patient_id and p.record_date = x.dialysis_date")
  21. err = db.Select("count(x.id) as count").Where("x.dialysis_date >= ? and x.dialysis_date<=? and x.user_org_id = ? AND x.status = 1", startime, endtime, orgid).Scan(&counts).Error
  22. return counts.Count, err
  23. } else {
  24. var count int64
  25. var schs []models.Schedule
  26. db := XTReadDB().Model(&models.Schedule{})
  27. err := db.
  28. Group("patient_id, schedule_date").
  29. Where("schedule_date >= ? AND schedule_date <= ? and user_org_id = ? and status = 1", startime, endtime, orgid).
  30. Find(&schs).
  31. Error
  32. count = int64(len(schs))
  33. return count, err
  34. }
  35. }
  36. type TreatmentMode struct {
  37. ModeID int `json:"mode_id"`
  38. ModeName string `json:"mode_name"`
  39. }
  40. type DialysisStat struct {
  41. Date string `json:"日期"`
  42. Counts map[string]int `json:"counts"`
  43. Total int `json:"合计"`
  44. }
  45. func GetTreatmentModes(org_id int64, start string, end string) (mode []models.MewTreatmentMode) {
  46. //XTReadDB().Model(&models.HisPrescription{}).Joins("join xt_treatment_mode mode on").Where("user_org_id = ?", org_id).Find(&modes).Error
  47. XTReadDB().Table("xt_dialysis_prescription p").Joins("join xt_treatment_mode mode on mode.id = p.mode_id").Where("p.user_org_id = ? and FROM_UNIXTIME(p.record_date) >= ? AND FROM_UNIXTIME(p.record_date) <= ?", org_id, start, end).Select("mode.name as name, p.mode_id as mode_id").Group("p.mode_id").Scan(&mode)
  48. return
  49. }
  50. func GetDialysisStats(start int64, end int64, mode int64, org_id int64, time_way int64) ([]map[string]interface{}, error) {
  51. // 将时间戳转换为time.Time类型
  52. t := time.Unix(start, 0)
  53. // 使用布局定义格式化时间
  54. layout := "2006-01-02"
  55. // 将时间格式化为字符串
  56. startDate := t.Format(layout) + " 00:00:00"
  57. t2 := time.Unix(end, 0)
  58. // 使用布局定义格式化时间
  59. //layout := "2006-01-02"
  60. // 将时间格式化为字符串
  61. endDate := t2.Format(layout) + " 00:00:00"
  62. //var stats []DialysisStat
  63. var modes []models.MewTreatmentMode
  64. fmt.Println(mode)
  65. if mode == 0 {
  66. modes = GetTreatmentModes(org_id, startDate, endDate)
  67. } else {
  68. modes_two := GetTreatmentModes(org_id, startDate, endDate)
  69. for _, item := range modes_two {
  70. if item.ModeID == mode {
  71. modes = append(modes, item)
  72. }
  73. }
  74. }
  75. // 获取透析模式
  76. if err != nil {
  77. return nil, err
  78. }
  79. var selectClauses []string
  80. // 构建动态查询语句
  81. if time_way == 1 {
  82. //selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0])}
  83. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0])}
  84. } else if time_way == 3 {
  85. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
  86. //selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0]+"-"+strings.Split(strings.Split(startDate, " ")[0], "-")[1])}
  87. } else if time_way == 4 {
  88. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
  89. //selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0])}
  90. } else {
  91. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
  92. }
  93. for _, mode := range modes {
  94. fmt.Println(mode)
  95. selectClauses = append(selectClauses, fmt.Sprintf("COALESCE(SUM(CASE WHEN t.name = '%s' THEN 1 ELSE 0 END), 0) AS `%s`", mode.Name, mode.Name))
  96. }
  97. selectClauses = append(selectClauses, "COUNT(*) AS `合计`")
  98. var rows *sql.Rows
  99. var query string
  100. if mode > 0 {
  101. query = fmt.Sprintf(`
  102. SELECT
  103. %s
  104. FROM
  105. xt_dialysis_prescription p
  106. JOIN
  107. xt_treatment_mode t ON p.mode_id = t.mode_id
  108. WHERE
  109. FROM_UNIXTIME(p.record_date) >= ? AND FROM_UNIXTIME(p.record_date) <= ? AND p.user_org_id = ? and p.mode_id = ?
  110. GROUP BY
  111. 日期
  112. `, strings.Join(selectClauses, ", "))
  113. rows, _ = readDb.Raw(query, startDate, endDate, org_id, mode).Rows()
  114. } else {
  115. query = fmt.Sprintf(`
  116. SELECT
  117. %s
  118. FROM
  119. xt_dialysis_prescription p
  120. JOIN
  121. xt_treatment_mode t ON p.mode_id = t.mode_id
  122. WHERE
  123. FROM_UNIXTIME(p.record_date) >= ? AND FROM_UNIXTIME(p.record_date) <= ? AND p.user_org_id = ?
  124. GROUP BY
  125. 日期
  126. `, strings.Join(selectClauses, ", "))
  127. rows, _ = readDb.Raw(query, startDate, endDate, org_id).Rows()
  128. }
  129. if err != nil {
  130. return nil, err
  131. }
  132. defer rows.Close()
  133. columns, err := rows.Columns()
  134. if err != nil {
  135. return nil, err
  136. }
  137. var results []map[string]interface{}
  138. for rows.Next() {
  139. // 创建一个长度为列数的切片,用于存储每一行的值
  140. columnValues := make([]interface{}, len(columns))
  141. columnPointers := make([]interface{}, len(columns))
  142. for i := range columnValues {
  143. columnPointers[i] = &columnValues[i]
  144. }
  145. // 扫描当前行的值
  146. if err := rows.Scan(columnPointers...); err != nil {
  147. return nil, err
  148. }
  149. // 将扫描到的值放入结果 map 中
  150. result := make(map[string]interface{})
  151. for i, colName := range columns {
  152. val := columnPointers[i].(*interface{})
  153. result[colName] = *val
  154. }
  155. results = append(results, result)
  156. }
  157. //// 解析查询结果
  158. //for rows.Next() {
  159. // var stat DialysisStat
  160. // stat.Counts = make(map[string]int)
  161. // cols := []interface{}{&stat.Date}
  162. // for _, mode := range modes {
  163. // var count int
  164. // cols = append(cols, &count)
  165. // stat.Counts[mode.Name] = count
  166. // }
  167. // var total int
  168. // cols = append(cols, &total)
  169. // stat.Total = total
  170. // if err := rows.Scan(cols...); err != nil {
  171. // return nil, err
  172. // }
  173. // stats = append(stats, stat)
  174. //}
  175. return results, nil
  176. }
  177. func GetScheduleStats(start int64, end int64, mode int64, org_id int64, time_way int64) ([]map[string]interface{}, error) {
  178. // 将时间戳转换为time.Time类型
  179. t := time.Unix(start, 0)
  180. // 使用布局定义格式化时间
  181. layout := "2006-01-02"
  182. // 将时间格式化为字符串
  183. startDate := t.Format(layout) + " 00:00:00"
  184. t2 := time.Unix(end, 0)
  185. // 使用布局定义格式化时间
  186. //layout := "2006-01-02"
  187. // 将时间格式化为字符串
  188. endDate := t2.Format(layout) + " 00:00:00"
  189. //var stats []DialysisStat
  190. var modes []models.MewTreatmentMode
  191. fmt.Println(mode)
  192. if mode == 0 {
  193. modes = GetTreatmentModes(org_id, startDate, endDate)
  194. } else {
  195. modes_two := GetTreatmentModes(org_id, startDate, endDate)
  196. for _, item := range modes_two {
  197. if item.ModeID == mode {
  198. modes = append(modes, item)
  199. }
  200. }
  201. }
  202. // 获取透析模式
  203. if err != nil {
  204. return nil, err
  205. }
  206. var selectClauses []string
  207. // 构建动态查询语句
  208. if time_way == 1 {
  209. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0])}
  210. } else if time_way == 3 {
  211. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0]+strings.Split(strings.Split(startDate, " ")[0], "-")[1])}
  212. } else if time_way == 4 {
  213. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(strings.Split(startDate, " ")[0], "-")[0])}
  214. } else {
  215. selectClauses = []string{fmt.Sprintf("'%s' AS `日期`", strings.Split(startDate, " ")[0]+"~"+strings.Split(endDate, " ")[0])}
  216. }
  217. for _, mode := range modes {
  218. fmt.Println(mode)
  219. selectClauses = append(selectClauses, fmt.Sprintf("COALESCE(SUM(CASE WHEN t.name = '%s' THEN 1 ELSE 0 END), 0) AS `%s`", mode.Name, mode.Name))
  220. }
  221. selectClauses = append(selectClauses, "COUNT(*) AS `合计`")
  222. var rows *sql.Rows
  223. var query string
  224. if mode > 0 {
  225. query = fmt.Sprintf(`
  226. SELECT
  227. %s
  228. FROM
  229. xt_schedule p
  230. JOIN
  231. xt_treatment_mode t ON p.mode_id = t.mode_id
  232. WHERE
  233. FROM_UNIXTIME(p.schedule_date) >= ? AND FROM_UNIXTIME(p.schedule_date) <= ? AND p.user_org_id = ? and p.mode_id = ?
  234. GROUP BY
  235. 日期
  236. `, strings.Join(selectClauses, ", "))
  237. rows, _ = readDb.Raw(query, startDate, endDate, org_id, mode).Rows()
  238. } else {
  239. query = fmt.Sprintf(`
  240. SELECT
  241. %s
  242. FROM
  243. xt_schedule p
  244. JOIN
  245. xt_treatment_mode t ON p.mode_id = t.mode_id
  246. WHERE
  247. FROM_UNIXTIME(p.schedule_date) >= ? AND FROM_UNIXTIME(p.schedule_date) <= ? AND p.user_org_id = ?
  248. GROUP BY
  249. 日期
  250. `, strings.Join(selectClauses, ", "))
  251. rows, _ = readDb.Raw(query, startDate, endDate, org_id).Rows()
  252. }
  253. if err != nil {
  254. return nil, err
  255. }
  256. defer rows.Close()
  257. columns, err := rows.Columns()
  258. if err != nil {
  259. return nil, err
  260. }
  261. var results []map[string]interface{}
  262. for rows.Next() {
  263. // 创建一个长度为列数的切片,用于存储每一行的值
  264. columnValues := make([]interface{}, len(columns))
  265. columnPointers := make([]interface{}, len(columns))
  266. for i := range columnValues {
  267. columnPointers[i] = &columnValues[i]
  268. }
  269. // 扫描当前行的值
  270. if err := rows.Scan(columnPointers...); err != nil {
  271. return nil, err
  272. }
  273. // 将扫描到的值放入结果 map 中
  274. result := make(map[string]interface{})
  275. for i, colName := range columns {
  276. val := columnPointers[i].(*interface{})
  277. result[colName] = *val
  278. }
  279. results = append(results, result)
  280. }
  281. //// 解析查询结果
  282. //for rows.Next() {
  283. // var stat DialysisStat
  284. // stat.Counts = make(map[string]int)
  285. // cols := []interface{}{&stat.Date}
  286. // for _, mode := range modes {
  287. // var count int
  288. // cols = append(cols, &count)
  289. // stat.Counts[mode.Name] = count
  290. // }
  291. // var total int
  292. // cols = append(cols, &total)
  293. // stat.Total = total
  294. // if err := rows.Scan(cols...); err != nil {
  295. // return nil, err
  296. // }
  297. // stats = append(stats, stat)
  298. //}
  299. return results, nil
  300. }
  301. //func GetScheduleStats(startDate int64, endDate int64, groupBy int64, mode int64, org_id int64) ([]DialysisStat, error) {
  302. // var stats []DialysisStat
  303. // var modes []models.TreatmentMode
  304. // if mode > 0 {
  305. // modes, _ = GetTreatmentModes()
  306. // } else {
  307. // modes_two, _ := GetTreatmentModes()
  308. // for _, item := range modes_two {
  309. // if item.ModeID == mode {
  310. // modes = append(modes, item)
  311. // }
  312. // }
  313. // }
  314. // // 获取透析模式
  315. // if err != nil {
  316. // return nil, err
  317. // }
  318. //
  319. // // 构建日期格式
  320. // dateFormat := "%Y-%m-%d"
  321. // switch groupBy {
  322. // case 2:
  323. // dateFormat = "%Y-%m-%d"
  324. // case 1:
  325. // dateFormat = "%Y-%u"
  326. // case 3:
  327. // dateFormat = "%Y-%m"
  328. // case 4:
  329. // dateFormat = "%Y"
  330. // default:
  331. // return nil, fmt.Errorf("invalid group by option")
  332. // }
  333. // // 构建动态查询语句
  334. // selectClauses := []string{fmt.Sprintf("DATE_FORMAT(p.schudle_date, '%s') AS `日期`", dateFormat)}
  335. // for _, mode := range modes {
  336. // selectClauses = append(selectClauses, fmt.Sprintf("SUM(CASE WHEN t.mode_name = '%s' THEN 1 ELSE 0 END) AS `%s`", mode.Name, mode.Name))
  337. // }
  338. // selectClauses = append(selectClauses, "COUNT(*) AS `合计`")
  339. //
  340. // query := fmt.Sprintf(`
  341. // SELECT
  342. // %s
  343. // FROM
  344. // xt_schedule p
  345. // JOIN
  346. // xt_treatment_mode t ON p.mode_id = t.mode_id
  347. // WHERE
  348. // p.schedule_date >= ? AND p.schedule_date <= ?
  349. // GROUP BY
  350. // DATE_FORMAT(p.schedule_date, '%s')
  351. // `, dateFormat, dateFormat, selectClauses)
  352. //
  353. // rows, err := readDb.Raw(query, startDate, endDate).Rows()
  354. // if err != nil {
  355. // return nil, err
  356. // }
  357. // defer rows.Close()
  358. //
  359. // // 解析查询结果
  360. // for rows.Next() {
  361. // var stat DialysisStat
  362. // stat.Counts = make(map[string]int)
  363. // cols := []interface{}{&stat.Date}
  364. // for _, mode := range modes {
  365. // var count int
  366. // cols = append(cols, &count)
  367. // stat.Counts[mode.Name] = count
  368. // }
  369. // var total int
  370. // cols = append(cols, &total)
  371. // stat.Total = total
  372. // if err := rows.Scan(cols...); err != nil {
  373. // return nil, err
  374. // }
  375. // stats = append(stats, stat)
  376. // }
  377. //
  378. // return stats, nil
  379. //}
  380. func GetNewDialysisCountMode(starttime int64, endtime int64, orgid int64, origin int64, mode_id int64) (counts []*models.PatientPrescriptionCountStruct, err error) {
  381. if origin == 1 {
  382. db := readDb.Table("xt_dialysis_order as o").Where("o.status = 1")
  383. if starttime > 0 {
  384. db = db.Where("o.dialysis_date >=?", starttime)
  385. }
  386. if endtime > 0 {
  387. db = db.Where("o.dialysis_date<=?", endtime)
  388. }
  389. if orgid > 0 {
  390. db = db.Where("o.user_org_id = ?", orgid)
  391. }
  392. if mode_id == 0 {
  393. err = db.Select("s.mode_id,count(s.mode_id) as count").Joins("join xt_dialysis_prescription as s on s.patient_id = o.patient_id and s.record_date = o.dialysis_date and s.status= 1 AND s.record_date >= ? AND s.record_date <= ? AND s.mode_id > 0 ", starttime, endtime).Group("s.mode_id").Scan(&counts).Error
  394. } else {
  395. err = db.Select("s.mode_id,count(s.mode_id) as count").Joins("join xt_dialysis_prescription as s on s.patient_id = o.patient_id and s.record_date = o.dialysis_date and s.status= 1 AND s.record_date >= ? AND s.record_date <= ? AND s.mode_id = ? ", starttime, endtime, mode_id).Group("s.mode_id").Scan(&counts).Error
  396. }
  397. return counts, err
  398. } else {
  399. err = readDb.Raw("select mode_id, count(aa.`mode_id`) as count from xt_schedule aa join (SELECT DISTINCT o.patient_id, o.`schedule_date` FROM xt_schedule AS o WHERE o.status = 1 AND o.schedule_date >= ? AND o.schedule_date <= ? AND o.user_org_id = ?) as b on aa.`patient_id` = b.`patient_id` and aa.`schedule_date` = b.`schedule_date` where aa.`status` = 1 and aa.schedule_date >= ? AND aa.schedule_date <= ? AND aa.user_org_id = ? Group by aa.`mode_id`", starttime, endtime, orgid, starttime, endtime, orgid).Find(&counts).Error
  400. return counts, err
  401. }
  402. }
  403. func GetNewDialysisCountModeTwo(starttime int64, endtime int64, orgid int64, origin int64, mode_id int64) (counts models.CustomDialysisData, err error) {
  404. // 将时间戳转换为time.Time类型
  405. t := time.Unix(starttime, 0)
  406. // 使用布局定义格式化时间
  407. layout := "2006-01-02"
  408. // 将时间格式化为字符串
  409. startDate := t.Format(layout) + " 00:00:00"
  410. t2 := time.Unix(endtime, 0)
  411. // 使用布局定义格式化时间
  412. //layout := "2006-01-02"
  413. // 将时间格式化为字符串
  414. endDate := t2.Format(layout) + " 00:00:00"
  415. //fmt.Println(formattedDate)
  416. // 将日期字符串解析为time.Time类型
  417. //start, _ := time.Parse("2006-01-02 15:04:05", formattedDate)
  418. //starttime = start.Unix()
  419. //fmt.Println(starttime)
  420. if origin == 1 {
  421. db := readDb.Table("xt_dialysis_order as o").Where("o.status = 1")
  422. if starttime > 0 {
  423. db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.dialysis_date), '%Y-%m-%d %H:%i:%s') >= ?", startDate)
  424. }
  425. if endtime > 0 {
  426. db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.dialysis_date), '%Y-%m-%d %H:%i:%s') <= ?", endDate)
  427. }
  428. if orgid > 0 {
  429. db = db.Where("o.user_org_id = ?", orgid)
  430. }
  431. err = db.Select("s.mode_id,count(s.mode_id) as count").Joins("join xt_dialysis_prescription as s on s.patient_id = o.patient_id and s.record_date = o.dialysis_date and s.status= 1 AND DATE_FORMAT(FROM_UNIXTIME(s.record_date), '%Y-%m-%d %H:%i:%s') >= ? AND DATE_FORMAT(FROM_UNIXTIME(s.record_date), '%Y-%m-%d %H:%i:%s') <= ? AND s.mode_id = ? ", startDate, endDate, mode_id).Group("s.mode_id").Scan(&counts).Error
  432. return counts, err
  433. } else {
  434. db := readDb.Table("xt_schedule as o").Where("o.status = 1").Select("patient_id, schedule_date").Group("mode_id")
  435. if starttime > 0 {
  436. db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.schedule_date),'%Y-%m-%d %H:%i:%s') >= ?", startDate)
  437. }
  438. if endtime > 0 {
  439. db = db.Where("DATE_FORMAT(FROM_UNIXTIME(o.schedule_date),'%Y-%m-%d %H:%i:%s') <= ?", endDate)
  440. }
  441. if orgid > 0 {
  442. db = db.Where("o.user_org_id = ?", orgid)
  443. }
  444. if mode_id > 0 {
  445. db = db.Where("o.mode_id = ?", mode_id)
  446. }
  447. err = db.Select("o.mode_id,count(o.mode_id) as count").Scan(&counts).Error
  448. return counts, err
  449. }
  450. }
  451. var anticoagulantMap = map[int]string{
  452. 1: "无肝素",
  453. 2: "普通肝素",
  454. 3: "低分子肝素",
  455. 4: "阿加曲班",
  456. 5: "枸橼酸钠",
  457. 6: "低分子肝素钙",
  458. 7: "低分子肝素钠",
  459. 8: "依诺肝素",
  460. 9: "达肝素",
  461. 10: "体外抗凝",
  462. 11: "那屈肝素",
  463. 12: "无抗凝剂",
  464. 13: "那屈肝素钙",
  465. 14: "肝素钙注射液",
  466. 15: "甲磺酸萘莫司他",
  467. 16: "低分子量肝素钙",
  468. 17: "肝素钠",
  469. }
  470. func GetAnticoagulantData(start_time int64, end_time int64, org_id int64) (map[string]int, error) {
  471. var results []struct {
  472. Anticoagulant int
  473. Count int
  474. }
  475. err := XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").
  476. Select("xt_dialysis_prescription.anticoagulant, COUNT(*) as count").
  477. Where("xt_dialysis_prescription.status = 1 and xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ? and xt_dialysis_prescription.user_org_id = ?", start_time, end_time, org_id).
  478. Group("xt_dialysis_prescription.anticoagulant").
  479. Scan(&results).Error
  480. if err != nil {
  481. return nil, err
  482. }
  483. anticoagulantData := make(map[string]int)
  484. for _, result := range results {
  485. if name, ok := anticoagulantMap[result.Anticoagulant]; ok {
  486. anticoagulantData[name] = result.Count
  487. }
  488. //else {
  489. // anticoagulantData[fmt.Sprintf("Unknown (%d)", result.Anticoagulant)] = result.Count
  490. //}z
  491. }
  492. return anticoagulantData, nil
  493. }
  494. func GetAnticoagulantTotal(start_time int64, end_time int64, org_id int64) (total int64, err error) {
  495. err = XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").
  496. Where("xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ? and xt_dialysis_prescription.user_org_id = ? and xt_dialysis_prescription.status = 1", start_time, end_time, org_id).
  497. Count(&total).Error
  498. return
  499. }
  500. func GetDialyzerSummary(org_id int64) ([]models.DialysisPrescription, error) {
  501. var Dialyzer []models.DialysisPrescription
  502. err := XTReadDB().Model(&models.DialysisPrescription{}).
  503. Select("dialysis_dialyszers").
  504. Where(" user_org_id = ? and status = 1 and dialysis_dialyszers <> ''", org_id).
  505. Group("dialysis_dialyszers").
  506. Find(&Dialyzer).Error
  507. if err != nil {
  508. return nil, err
  509. }
  510. return Dialyzer, nil
  511. }
  512. func GetIrrigationSummary(org_id int64) ([]models.DialysisPrescription, error) {
  513. var Dialyzer []models.DialysisPrescription
  514. err := XTReadDB().Model(&models.DialysisPrescription{}).
  515. Select("dialysis_irrigation").
  516. Where(" user_org_id = ? and status = 1 and dialysis_irrigation <> ''", org_id).
  517. Group("dialysis_irrigation").
  518. Find(&Dialyzer).Error
  519. if err != nil {
  520. return nil, err
  521. }
  522. return Dialyzer, nil
  523. }
  524. func GetDialysisStrainerSummary(org_id int64) ([]models.DialysisPrescription, error) {
  525. var Dialyzer []models.DialysisPrescription
  526. err := XTReadDB().Model(&models.DialysisPrescription{}).
  527. Select("dialysis_strainer").
  528. Where(" user_org_id = ? and status = 1 and dialysis_strainer <> ''", org_id).
  529. Group("dialysis_strainer").
  530. Find(&Dialyzer).Error
  531. if err != nil {
  532. return nil, err
  533. }
  534. return Dialyzer, nil
  535. }
  536. type DialyzerResult struct {
  537. Dialyzer string
  538. Count int
  539. }
  540. func GetDialyzerData(start_time int64, end_time int64, org_id int64) (dr []DialyzerResult, err error) {
  541. err = XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").
  542. Select("xt_dialysis_prescription.dialysis_dialyszers as dialyzer, COUNT(*) as count").
  543. Where("xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ? and xt_dialysis_prescription.user_org_id = ? and xt_dialysis_prescription.status = 1 and xt_dialysis_prescription.dialysis_dialyszers <> ''", start_time, end_time, org_id).
  544. Group("xt_dialysis_prescription.dialysis_dialyszers").
  545. Scan(&dr).Error
  546. return
  547. }
  548. func GetDialysisIrrigationData(start_time int64, end_time int64, org_id int64) (dr []DialyzerResult, err error) {
  549. err = XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").
  550. Select("xt_dialysis_prescription.dialysis_irrigation as dialyzer, COUNT(*) as count").
  551. Where("xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ? and xt_dialysis_prescription.user_org_id = ? and xt_dialysis_prescription.status = 1 and xt_dialysis_prescription.dialysis_irrigation <> '' ", start_time, end_time, org_id).
  552. Group("xt_dialysis_prescription.dialysis_irrigation").
  553. Scan(&dr).Error
  554. return
  555. }
  556. func GetDialysisStrainerData(start_time int64, end_time int64, org_id int64) (dr []DialyzerResult, err error) {
  557. err = XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").
  558. Select("xt_dialysis_prescription.dialysis_strainer as dialyzer, COUNT(*) as count").
  559. Where("xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ? and xt_dialysis_prescription.user_org_id = ? and xt_dialysis_prescription.status = 1 and xt_dialysis_prescription.dialysis_strainer <> ''", start_time, end_time, org_id).
  560. Group("xt_dialysis_prescription.dialysis_strainer").
  561. Scan(&dr).Error
  562. return
  563. }
  564. func GetIrrigationData(start_time int64, end_time int64, org_id int64) (dr []DialyzerResult, err error) {
  565. err = XTReadDB().Model(&models.DialysisPrescription{}).
  566. Select("dialysis_irrigation as dialyzer, COUNT(*) as count").
  567. Where("record_date >= ? and record_date <= ? and user_org_id = ? and status = 1", start_time, end_time, org_id).
  568. Group("dialysis_irrigation").
  569. Scan(&dr).Error
  570. return
  571. }
  572. func GetDialyzerTotal(start_time int64, end_time int64, org_id int64) (total int64, err error) {
  573. err = XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").
  574. Where("xt_dialysis_prescription.status = 1 and xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ? and xt_dialysis_prescription.user_org_id = ?", start_time, end_time, org_id).
  575. Count(&total).Error
  576. return
  577. }
  578. func GetPrescriptionByAnticoagulant(page int64, limit int64, orgid int64, anticoagulant int64, start_time int64, end_time int64) (solution []*models.DialysisPrescription, total int64, err error) {
  579. db := XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").Preload("QCPatients", "xt_patients.status = 1 and xt_patients.user_org_id = ?", orgid).Where("xt_dialysis_prescription.status = 1")
  580. if anticoagulant > 0 {
  581. db = db.Where("xt_dialysis_prescription.anticoagulant = ?", anticoagulant)
  582. }
  583. if orgid > 0 {
  584. db = db.Where("xt_dialysis_prescription.user_org_id = ?", orgid)
  585. }
  586. db = db.Where("xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ?", start_time, end_time)
  587. offset := (page - 1) * limit
  588. err = db.Count(&total).Offset(offset).Limit(limit).Find(&solution).Error
  589. return solution, total, err
  590. }
  591. func GetPrescriptionByDialyzer(page int64, limit int64, orgid int64, dialyzer string, start_time int64, end_time int64) (solution []*models.DialysisPrescription, total int64, err error) {
  592. db := XTReadDB().Model(&models.DialysisPrescription{}).Joins("join xt_dialysis_order oo on oo.patient_id = xt_dialysis_prescription.patient_id and oo.dialysis_date = xt_dialysis_prescription.record_date and oo.status = 1").Preload("QCPatients", "xt_patients.status = 1 and xt_patients.user_org_id = ?", orgid).Where("xt_dialysis_prescription.status = 1")
  593. if len(dialyzer) > 0 {
  594. db = db.Where("xt_dialysis_prescription.dialysis_dialyszers = ? or xt_dialysis_prescription.dialysis_irrigation = ? or xt_dialysis_prescription.dialysis_strainer = ?", dialyzer, dialyzer, dialyzer)
  595. }
  596. if orgid > 0 {
  597. db = db.Where("xt_dialysis_prescription.user_org_id = ?", orgid)
  598. }
  599. db = db.Where("xt_dialysis_prescription.record_date >= ? and xt_dialysis_prescription.record_date <= ? and xt_dialysis_prescription.status = 1", start_time, end_time)
  600. offset := (page - 1) * limit
  601. err = db.Count(&total).Offset(offset).Limit(limit).Find(&solution).Error
  602. return solution, total, err
  603. }
  604. type DialysisData struct {
  605. DialysisStatus string `json:"dialysis_status"`
  606. Count int `json:"count"`
  607. }
  608. type CustomData struct {
  609. DialysisNo string
  610. PatientName string
  611. DialysisDate string
  612. DialysisDuration string
  613. ActualDuration string
  614. Diff string
  615. Doctor string
  616. Nurse string
  617. }
  618. func GetDialysisCompletionRate(org_id int64, start_time int64, end_time int64) (map[string]int, error) {
  619. var results []DialysisData
  620. query := `
  621. SELECT
  622. CASE
  623. WHEN ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) <= 15 THEN '达到透析处方时间'
  624. WHEN TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) < -15 THEN '超出处方时间'
  625. ELSE '未到达处方时间'
  626. END AS dialysis_status,
  627. COUNT(*) AS count
  628. FROM
  629. xt_dialysis_order o
  630. JOIN
  631. xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
  632. JOIN
  633. xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
  634. WHERE
  635. o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?
  636. GROUP BY
  637. dialysis_status;
  638. `
  639. if err := readDb.Raw(query, org_id, org_id, org_id, start_time, end_time).Scan(&results).Error; err != nil {
  640. return nil, err
  641. }
  642. dialysisCompletionRate := make(map[string]int)
  643. for _, result := range results {
  644. dialysisCompletionRate[result.DialysisStatus] = result.Count
  645. }
  646. return dialysisCompletionRate, nil
  647. }
  648. func GetDialysisCompletionTotal(org_id int64, start_time int64, end_time int64) (int64, error) {
  649. var Count int64
  650. query := `
  651. SELECT
  652. COUNT(*) AS count
  653. FROM
  654. xt_dialysis_order o
  655. JOIN
  656. xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
  657. JOIN
  658. xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
  659. WHERE
  660. o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?
  661. `
  662. if err := readDb.Raw(query, org_id, org_id, org_id, start_time, end_time).Count(&Count).Error; err != nil {
  663. return 0, err
  664. }
  665. return Count, nil
  666. }
  667. func GetDialysisCompletionDetail(org_id int64, start_time int64, end_time int64, mode int64, limit int64, page int64) (results []interface{}, total int64, err error) {
  668. var query string
  669. if mode == 0 {
  670. query = `
  671. SELECT
  672. p.dialysis_no as dialysis_no,
  673. p.name as patient_name,
  674. FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
  675. CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
  676. CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
  677. ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
  678. p.prescription_doctor as doctor,
  679. o.finish_nurse as nurse,
  680. pp.id_card_no as id_card_no
  681. FROM
  682. xt_dialysis_order o
  683. JOIN
  684. xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
  685. JOIN
  686. xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
  687. JOIN
  688. xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
  689. WHERE
  690. o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?
  691. `
  692. readDb.Table("xt_dialysis_order o").
  693. Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
  694. Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
  695. Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
  696. Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ?", org_id, start_time, end_time).Count(&total)
  697. } else if mode == 1 {
  698. query = `
  699. SELECT
  700. pp.dialysis_no as dialysis_no,
  701. pp.name as patient_name,
  702. FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
  703. CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
  704. CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
  705. ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
  706. p.prescription_doctor as doctor,
  707. o.finish_nurse as nurse,
  708. pp.id_card_no as id_card_no
  709. FROM
  710. xt_dialysis_order o
  711. JOIN
  712. xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
  713. JOIN
  714. xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
  715. JOIN
  716. xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
  717. WHERE
  718. o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) <= 15
  719. `
  720. readDb.Table("xt_dialysis_order o").
  721. Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
  722. Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
  723. Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
  724. Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? and ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) <= 15", org_id, start_time, end_time).Count(&total)
  725. } else if mode == 2 {
  726. query = `
  727. SELECT
  728. pp.dialysis_no as dialysis_no,
  729. pp.name as patient_name,
  730. FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
  731. CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
  732. CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
  733. ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
  734. p.prescription_doctor as doctor,
  735. o.finish_nurse as nurse,
  736. pp.id_card_no as id_card_no
  737. FROM
  738. xt_dialysis_order o
  739. JOIN
  740. xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
  741. JOIN
  742. xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
  743. JOIN
  744. xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
  745. WHERE
  746. o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) < -15
  747. `
  748. readDb.Table("xt_dialysis_order o").
  749. Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
  750. Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
  751. Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
  752. Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? and TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) < 0", org_id, start_time, end_time).Count(&total)
  753. } else if mode == 3 {
  754. query = `
  755. SELECT
  756. pp.dialysis_no as dialysis_no,
  757. pp.name as patient_name,
  758. FROM_UNIXTIME(o.dialysis_date) as dialysis_date,
  759. CONCAT(p.dialysis_duration_hour, 'h', p.dialysis_duration_minute,'min') as dialysis_duration,
  760. CONCAT(a.actual_treatment_hour, 'h', a.actual_treatment_minute,'min') as actual_duration,
  761. ABS(TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0))) as diff,
  762. p.prescription_doctor as doctor,
  763. o.finish_nurse as nurse,
  764. pp.id_card_no as id_card_no
  765. FROM
  766. xt_dialysis_order o
  767. JOIN
  768. xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?
  769. JOIN
  770. xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?
  771. JOIN
  772. xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?
  773. WHERE
  774. o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? AND TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) > 15
  775. `
  776. readDb.Table("xt_dialysis_order o").
  777. Joins("JOIN xt_patients pp ON o.patient_id = pp.id AND pp.user_org_id = ?", org_id).
  778. Joins("JOIN xt_dialysis_prescription p ON o.dialysis_date = p.record_date AND o.patient_id = p.patient_id AND p.user_org_id = ?", org_id).
  779. Joins("JOIN xt_assessment_after_dislysis a ON o.dialysis_date = a.assessment_date AND o.patient_id = a.patient_id AND a.user_org_id = ?", org_id).
  780. Where("o.stage = 2 AND o.user_org_id = ? AND o.dialysis_date >= ? AND o.dialysis_date <= ? and TIMESTAMPDIFF(MINUTE, MAKETIME(p.dialysis_duration_hour, p.dialysis_duration_minute, 0), MAKETIME(a.actual_treatment_hour, a.actual_treatment_minute, 0)) > 15", org_id, start_time, end_time).Count(&total)
  781. }
  782. offset := (page - 1) * limit
  783. rows, err := readDb.Raw(query, org_id, org_id, org_id, org_id, start_time, end_time).Offset(offset).Limit(limit).Rows()
  784. if err != nil {
  785. fmt.Println(err)
  786. }
  787. defer rows.Close()
  788. // Define a map to hold the dynamic fields
  789. fields := map[string]interface{}{
  790. "dialysis_no": "",
  791. "patient_name": "",
  792. "dialysis_date": "",
  793. "dialysis_duration": "",
  794. "actual_duration": "",
  795. "diff": 0,
  796. "doctor": "",
  797. "nurse": "",
  798. "id_card_no": "",
  799. }
  800. // Create the dynamic struct type
  801. dynamicStructType := createDynamicStruct(fields)
  802. // Slice to hold the results
  803. //var results []interface{}
  804. // Iterate over the rows and scan into the dynamic struct
  805. for rows.Next() {
  806. // Create a new instance of the dynamic struct
  807. result := reflect.New(dynamicStructType).Interface()
  808. // Create a slice of pointers to the fields in the struct
  809. fieldPtrs := []interface{}{
  810. reflect.ValueOf(result).Elem().FieldByName("Dialysis_no").Addr().Interface(),
  811. reflect.ValueOf(result).Elem().FieldByName("Patient_name").Addr().Interface(),
  812. reflect.ValueOf(result).Elem().FieldByName("Dialysis_date").Addr().Interface(),
  813. reflect.ValueOf(result).Elem().FieldByName("Dialysis_duration").Addr().Interface(),
  814. reflect.ValueOf(result).Elem().FieldByName("Actual_duration").Addr().Interface(),
  815. reflect.ValueOf(result).Elem().FieldByName("Diff").Addr().Interface(),
  816. reflect.ValueOf(result).Elem().FieldByName("Doctor").Addr().Interface(),
  817. reflect.ValueOf(result).Elem().FieldByName("Nurse").Addr().Interface(),
  818. reflect.ValueOf(result).Elem().FieldByName("Id_card_no").Addr().Interface(),
  819. }
  820. // Scan the row into the struct
  821. if err := rows.Scan(fieldPtrs...); err != nil {
  822. //log.Fatalf("failed to scan row: %v", err)
  823. fmt.Println(err)
  824. }
  825. // Append the result to the slice
  826. results = append(results, result)
  827. }
  828. return results, total, err
  829. }
  830. type QualityControlStandard struct {
  831. ItemName string `json:"item_name"`
  832. ProjectMame string `json:"project_name"`
  833. InspectionMajor int64 `json:"inspection_major"`
  834. InspectionMinor int64 `json:"inspection_minor"`
  835. }
  836. func getQualityControlStandards(org_id int64) ([]QualityControlStandard, error) {
  837. var standards []QualityControlStandard
  838. if err := readDb.Model(&models.XtQualityControlStandard{}).Select("re.project_name as project_name,re.item_name as item_name,xt_quality_control_standard.inspection_major as inspection_major,xt_quality_control_standard.inspection_minor as inspection_minor").Joins("join xt_inspection_reference re on re.project_id = xt_quality_control_standard.inspection_major and re.item_id = xt_quality_control_standard.inspection_minor and re.org_id = ?", org_id).Where("xt_quality_control_standard.user_org_id = ? and xt_quality_control_standard.status = 1", org_id).Scan(&standards).Error; err != nil {
  839. return nil, err
  840. }
  841. return standards, nil
  842. }
  843. type DialysisQualityStat struct {
  844. Month string `json:"月"`
  845. Name string `json:"姓名"`
  846. Counts map[string]float64 `json:"counts"`
  847. }
  848. //func GetLatestInspectionValues(org_id int64, yearMonth string) ([]map[string]interface{}, error) {
  849. // standards, err := getQualityControlStandards(org_id)
  850. // if err != nil {
  851. // return nil, err
  852. // }
  853. //
  854. // var selectFields []string
  855. // for _, standard := range standards {
  856. // field := fmt.Sprintf("IFNULL(MAX(CASE WHEN i.item_name = %s THEN i.inspect_value END),'') AS `%s`",
  857. // "'"+standard.ItemName+"'", standard.ItemName)
  858. // selectFields = append(selectFields, field)
  859. // }
  860. //
  861. // query := fmt.Sprintf(`
  862. // SELECT
  863. // p.name as '姓名',
  864. // %s
  865. // FROM xt_inspection i
  866. // JOIN xt_patients p On p.id = i.patient_id
  867. // WHERE DATE_FORMAT(FROM_UNIXTIME(i.inspect_date), '%%Y-%%m') = ? and org_id = ?
  868. //
  869. // GROUP BY i.patient_id
  870. // `, strings.Join(selectFields, ", "))
  871. //
  872. // var results []map[string]interface{}
  873. // rows, err := readDb.Raw(query, yearMonth, org_id).Rows()
  874. // if err != nil {
  875. // return nil, err
  876. // }
  877. // defer rows.Close()
  878. //
  879. // columns, err := rows.Columns()
  880. // if err != nil {
  881. // return nil, err
  882. // }
  883. //
  884. // for rows.Next() {
  885. // // 创建一个长度为列数的切片,用于存储每一行的值
  886. // columnValues := make([]interface{}, len(columns))
  887. // columnPointers := make([]interface{}, len(columns))
  888. // for i := range columnValues {
  889. // columnPointers[i] = &columnValues[i]
  890. // }
  891. //
  892. // // 扫描当前行的值
  893. // if err := rows.Scan(columnPointers...); err != nil {
  894. // return nil, err
  895. // }
  896. //
  897. // // 将扫描到的值放入结果 map 中
  898. // result := make(map[string]interface{})
  899. // for i, colName := range columns {
  900. // val := columnPointers[i].(*interface{})
  901. // result[colName] = *val
  902. // }
  903. //
  904. // results = append(results, result)
  905. // }
  906. //
  907. // return results, nil
  908. //}
  909. func GetLatestInspectionValues(org_id int64, yearMonth string) ([]map[string]interface{}, error) {
  910. standards, err := getQualityControlStandards(org_id)
  911. if err != nil {
  912. return nil, err
  913. }
  914. var selectFields []string
  915. for _, standard := range standards {
  916. field := fmt.Sprintf("IFNULL(MAX(CASE WHEN latest_inspections.item_name = '%s' THEN latest_inspections.inspect_value END),'') AS `%s`",
  917. standard.ItemName, standard.ItemName)
  918. selectFields = append(selectFields, field)
  919. }
  920. query := fmt.Sprintf(`
  921. SELECT
  922. p.name as '姓名',
  923. %s
  924. FROM xt_patients p
  925. JOIN (
  926. SELECT
  927. i1.patient_id,
  928. i1.item_name,
  929. i1.inspect_value
  930. FROM
  931. xt_inspection i1
  932. JOIN (
  933. SELECT
  934. patient_id,
  935. item_name,
  936. MAX(inspect_date) AS latest_inspect_date
  937. FROM
  938. xt_inspection
  939. WHERE
  940. DATE_FORMAT(FROM_UNIXTIME(inspect_date), '%%Y-%%m') = ?
  941. AND org_id = ?
  942. GROUP BY
  943. patient_id, item_name
  944. ) latest
  945. ON
  946. i1.patient_id = latest.patient_id
  947. AND i1.item_name = latest.item_name
  948. AND i1.inspect_date = latest.latest_inspect_date
  949. ) latest_inspections
  950. ON p.id = latest_inspections.patient_id
  951. WHERE p.user_org_id = ? and p.lapseto = 1
  952. GROUP BY p.id, p.name
  953. `, strings.Join(selectFields, ", "))
  954. var results []map[string]interface{}
  955. rows, err := readDb.Raw(query, yearMonth, org_id, org_id).Rows() // 注意这里多传一个org_id参数
  956. if err != nil {
  957. return nil, err
  958. }
  959. defer rows.Close()
  960. columns, err := rows.Columns()
  961. if err != nil {
  962. return nil, err
  963. }
  964. for rows.Next() {
  965. // 创建一个长度为列数的切片,用于存储每一行的值
  966. columnValues := make([]interface{}, len(columns))
  967. columnPointers := make([]interface{}, len(columns))
  968. for i := range columnValues {
  969. columnPointers[i] = &columnValues[i]
  970. }
  971. // 扫描当前行的值
  972. if err := rows.Scan(columnPointers...); err != nil {
  973. return nil, err
  974. }
  975. // 将扫描到的值放入结果 map 中
  976. result := make(map[string]interface{})
  977. for i, colName := range columns {
  978. val := columnPointers[i].(*interface{})
  979. result[colName] = *val
  980. }
  981. results = append(results, result)
  982. }
  983. return results, nil
  984. }
  985. //func GetLatestInspectionValues(org_id int64, yearMonth string) ([]map[string]interface{}, error) {
  986. // standards, err := getQualityControlStandards(org_id)
  987. // if err != nil {
  988. // return nil, err
  989. // }
  990. //
  991. // var selectFields []string
  992. // for _, standard := range standards {
  993. // field := fmt.Sprintf("IFNULL(MAX(CASE WHEN latest_inspections.item_name = '%s' THEN latest_inspections.inspect_value END),'') AS `%s`",
  994. // standard.ItemName, standard.ItemName)
  995. // selectFields = append(selectFields, field)
  996. // }
  997. //
  998. // query := fmt.Sprintf(`
  999. // SELECT
  1000. // p.name AS '姓名',
  1001. // %s
  1002. // FROM xt_patients p
  1003. // LEFT JOIN (
  1004. // SELECT
  1005. // i1.patient_id,
  1006. // i1.item_name,
  1007. // i1.inspect_value
  1008. // FROM
  1009. // xt_inspection i1
  1010. // JOIN (
  1011. // SELECT
  1012. // patient_id,
  1013. // item_name,
  1014. // MAX(inspect_date) AS latest_inspect_date
  1015. // FROM
  1016. // xt_inspection
  1017. // WHERE
  1018. // DATE_FORMAT(FROM_UNIXTIME(inspect_date), '%%Y-%%m') = ?
  1019. // AND org_id = ?
  1020. // GROUP BY
  1021. // patient_id, item_name
  1022. // ) latest
  1023. // ON
  1024. // i1.patient_id = latest.patient_id
  1025. // AND i1.item_name = latest.item_name
  1026. // AND i1.inspect_date = latest.latest_inspect_date
  1027. // ) latest_inspections
  1028. // ON p.id = latest_inspections.patient_id
  1029. // WHERE p.user_org_id = ?
  1030. // GROUP BY p.id, p.name
  1031. // `, strings.Join(selectFields, ", "))
  1032. //
  1033. // var results []map[string]interface{}
  1034. // rows, err := readDb.Raw(query, yearMonth, org_id, org_id).Rows() // 注意这里多传一个org_id参数
  1035. // if err != nil {
  1036. // return nil, err
  1037. // }
  1038. // defer rows.Close()
  1039. //
  1040. // columns, err := rows.Columns()
  1041. // if err != nil {
  1042. // return nil, err
  1043. // }
  1044. //
  1045. // for rows.Next() {
  1046. // // 创建一个长度为列数的切片,用于存储每一行的值
  1047. // columnValues := make([]interface{}, len(columns))
  1048. // columnPointers := make([]interface{}, len(columns))
  1049. // for i := range columnValues {
  1050. // columnPointers[i] = &columnValues[i]
  1051. // }
  1052. //
  1053. // // 扫描当前行的值
  1054. // if err := rows.Scan(columnPointers...); err != nil {
  1055. // return nil, err
  1056. // }
  1057. //
  1058. // // 将扫描到的值放入结果 map 中
  1059. // result := make(map[string]interface{})
  1060. // for i, colName := range columns {
  1061. // val := columnPointers[i].(*interface{})
  1062. // result[colName] = *val
  1063. // }
  1064. //
  1065. // results = append(results, result)
  1066. // }
  1067. //
  1068. // return results, nil
  1069. //}
  1070. func createDynamicStruct(fields map[string]interface{}) reflect.Type {
  1071. var structFields []reflect.StructField
  1072. for name, value := range fields {
  1073. structFields = append(structFields, reflect.StructField{
  1074. Name: strings.Title(name),
  1075. Type: reflect.TypeOf(value),
  1076. Tag: reflect.StructTag(fmt.Sprintf(`json:"%s"`, name)),
  1077. })
  1078. }
  1079. return reflect.StructOf(structFields)
  1080. }
  1081. func GetDialysisPrescriptionInfo(start_date string, end_date string, mode int64, org_id int64, page int64, limit int64) (qcp []models.QCPrescription, total int64, err error) {
  1082. offset := (page - 1) * limit
  1083. err = readDb.Model(&models.QCPrescription{}).Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  1084. return readUserDb.Where("status = 1 and org_id=?", org_id)
  1085. }).Preload("QCPatients", "status = 1 and user_org_id = ?", org_id).Preload("QCDialysisOrder", func(db *gorm.DB) *gorm.DB {
  1086. return db.Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  1087. return readUserDb.Where("status = 1 and org_id=?", org_id)
  1088. }).Preload("DeviceNumber", "status = 1 and org_id = ?", org_id).Where("status = 1 AND user_org_id = ?", org_id)
  1089. }).Preload("QCAssessmentAfterDislysis", "status = 1 and user_org_id = ?", org_id).Where("FROM_UNIXTIME(record_date, '%Y-%m-%d') >= ? and FROM_UNIXTIME(record_date, '%Y-%m-%d') <= ? and user_org_id = ? and mode_id = ? and status = 1", start_date, end_date, org_id, mode).Count(&total).Offset(offset).Limit(limit).Find(&qcp).Error
  1090. return
  1091. }
  1092. func GetScheduleInfo(start_date string, end_date string, mode int64, org_id int64, page int64, limit int64) (qcp []models.QCSchedule, total int64, err error) {
  1093. offset := (page - 1) * limit
  1094. err = readDb.Model(&models.QCSchedule{}).Preload("QCPatients", "status = 1 and user_org_id =?", org_id).Preload("QCSPrescription", func(db *gorm.DB) *gorm.DB {
  1095. return db.Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  1096. return readUserDb.Where("status = 1 and org_id=?", org_id)
  1097. }).Where("status = 1 AND user_org_id = ?", org_id)
  1098. }).Preload("QCAssessmentAfterDislysis", "status = 1 and user_org_id = ?", org_id).Preload("QCDialysisOrder", func(db *gorm.DB) *gorm.DB {
  1099. return db.Preload("DeviceNumber", "status = 1").Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  1100. return readUserDb.Where("status = 1 and org_id=?", org_id)
  1101. }).Where("status = 1 AND user_org_id = ?", org_id)
  1102. }).Where("FROM_UNIXTIME(schedule_date, '%Y-%m-%d') >= ? and FROM_UNIXTIME(schedule_date, '%Y-%m-%d') <= ? and user_org_id = ? and mode_id = ? and status = 1", start_date, end_date, org_id, mode).Count(&total).Offset(offset).Limit(limit).Find(&qcp).Error
  1103. return
  1104. }
  1105. type otherItemAmount struct {
  1106. Total int64 `json:"total"`
  1107. Name string `json:"name"`
  1108. Ratio string `json:"ratio"`
  1109. }
  1110. // xt_patients model
  1111. type Patient struct {
  1112. ID uint `gorm:"primaryKey"`
  1113. IDCardNo string `gorm:"column:id_card_no"`
  1114. }
  1115. func (Patient) TableName() string {
  1116. return "xt_patients"
  1117. }
  1118. // xt_assessment_before_dislysis model
  1119. type Assessment struct {
  1120. ID uint `gorm:"id"`
  1121. PatientID uint `gorm:"column:patient_id"`
  1122. SystolicBP float64 `gorm:"column:systolic_blood_pressure"`
  1123. DiastolicBP float64 `gorm:"column:diastolic_blood_pressure"`
  1124. AssessmentDate int64 `gorm:"column:assessment_date"`
  1125. UserOrgID int `gorm:"column:user_org_id"`
  1126. }
  1127. func (Assessment) TableName() string {
  1128. return "xt_assessment_before_dislysis"
  1129. }
  1130. // xt_assessment_before_dislysis model
  1131. type AssessmentAfter struct {
  1132. ID uint `gorm:"id"`
  1133. PatientID uint `gorm:"column:patient_id"`
  1134. SystolicBP float64 `gorm:"column:systolic_blood_pressure"`
  1135. DiastolicBP float64 `gorm:"column:diastolic_blood_pressure"`
  1136. AssessmentDate int64 `gorm:"column:assessment_date"`
  1137. UserOrgID int `gorm:"column:user_org_id"`
  1138. }
  1139. func (AssessmentAfter) TableName() string {
  1140. return "xt_assessment_after_dislysis"
  1141. }
  1142. type WeightDetail struct {
  1143. DialysisNo string
  1144. PatientName string
  1145. Gender int64
  1146. IDCardNo string
  1147. DialysisDate string
  1148. DryWeight float64
  1149. LastWeightAfter float64
  1150. WeightBefore float64
  1151. }
  1152. func GetNewDialysisWeightChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int) (item []*otherItemAmount, err error) {
  1153. db := XTReadDB()
  1154. var items []*otherItemAmount
  1155. var tempErr error
  1156. var Total int64
  1157. switch statistics_type {
  1158. case 1:
  1159. db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).Count(&Total)
  1160. tempErr = db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).
  1161. Select("CASE WHEN dry_weight < 40 THEN '小于40kg'" +
  1162. " WHEN dry_weight >= 40 AND dry_weight < 50 THEN '40~50kg'" +
  1163. " WHEN dry_weight >= 50 AND dry_weight < 60 THEN '50~60kg'" +
  1164. " WHEN dry_weight >= 60 AND dry_weight < 70 THEN '60~70kg'" +
  1165. " WHEN dry_weight >= 70 THEN '大于70kg'" +
  1166. " ELSE '未知' END AS name, COUNT(*) AS total",
  1167. ).Group("name").Scan(&items).Error
  1168. var isHasConditionOne bool = false
  1169. var isHasConditionTwo bool = false
  1170. var isHasConditionThree bool = false
  1171. var isHasConditionFour bool = false
  1172. var isHasConditionFive bool = false
  1173. for _, item := range items {
  1174. if item.Name == "小于40kg" {
  1175. isHasConditionOne = true
  1176. }
  1177. if item.Name == "40~50kg" {
  1178. isHasConditionTwo = true
  1179. }
  1180. if item.Name == "60~70kg" {
  1181. isHasConditionThree = true
  1182. }
  1183. if item.Name == "大于70kg" {
  1184. isHasConditionFour = true
  1185. }
  1186. if item.Name == "待定/卧床" {
  1187. isHasConditionFive = true
  1188. }
  1189. }
  1190. if !isHasConditionOne {
  1191. newItem := &otherItemAmount{
  1192. Total: 0,
  1193. Name: "小于40kg",
  1194. Ratio: "0",
  1195. }
  1196. items = append(items, newItem)
  1197. }
  1198. if !isHasConditionTwo {
  1199. newItem := &otherItemAmount{
  1200. Total: 0,
  1201. Name: "40~50kg",
  1202. Ratio: "0",
  1203. }
  1204. items = append(items, newItem)
  1205. }
  1206. if !isHasConditionThree {
  1207. newItem := &otherItemAmount{
  1208. Total: 0,
  1209. Name: "60~70kg",
  1210. Ratio: "0",
  1211. }
  1212. items = append(items, newItem)
  1213. }
  1214. if !isHasConditionFour {
  1215. newItem := &otherItemAmount{
  1216. Total: 0,
  1217. Name: "大于70kg",
  1218. Ratio: "0",
  1219. }
  1220. items = append(items, newItem)
  1221. }
  1222. if !isHasConditionFive {
  1223. newItem := &otherItemAmount{
  1224. Total: 0,
  1225. Name: "未知",
  1226. Ratio: "0",
  1227. }
  1228. items = append(items, newItem)
  1229. }
  1230. for _, item := range items {
  1231. if math.IsNaN(float64(item.Total) / float64(Total)) {
  1232. item.Ratio = "0.0"
  1233. } else {
  1234. float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(Total))*100), 64)
  1235. item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
  1236. }
  1237. }
  1238. break
  1239. case 2:
  1240. //db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).Count(&Total)
  1241. //db.Raw("Select count(*) from `xt_assessment_before_dislysis` LEFT JOIN `xt_assessment_after_dislysis` On xt_assessment_before_dislysis.`patient_id` = xt_assessment_after_dislysis.`patient_id` AND xt_assessment_before_dislysis.assessment_date = xt_assessment_after_dislysis.assessment_date AND xt_assessment_after_dislysis.weight_after != 0 Where xt_assessment_before_dislysis.user_org_id = ? AND xt_assessment_before_dislysis.created_time >= ? AND xt_assessment_before_dislysis.created_time <= ? Order by xt_assessment_before_dislysis.assessment_date desc", user_org_id, start_time, end_time).Count(&Total)
  1242. var newTotal int64
  1243. type weight struct {
  1244. WeightAfter float64 `json:"weight_after"`
  1245. WeightBefore float64 `json:"weight_before"`
  1246. }
  1247. //var weights []*weight
  1248. var weightAdd []float64
  1249. //db.Raw("Select xt_assessment_after_dislysis.weight_after as weight_after ,xt_assessment_before_dislysis.weight_before as weight_before from `xt_assessment_before_dislysis` LEFT JOIN `xt_assessment_after_dislysis` On xt_assessment_before_dislysis.`patient_id` = xt_assessment_after_dislysis.`patient_id` AND xt_assessment_before_dislysis.assessment_date = xt_assessment_after_dislysis.assessment_date AND xt_assessment_after_dislysis.weight_after <> 0 AND xt_assessment_after_dislysis.user_org_id = ? Where xt_assessment_before_dislysis.user_org_id = ? AND xt_assessment_before_dislysis.created_time >= ? AND xt_assessment_before_dislysis.created_time <= ? Order by xt_assessment_before_dislysis.assessment_date desc", user_org_id, user_org_id, start_time, end_time).Scan(&weights)
  1250. //for index, _ := range weights {
  1251. // if index+1 < len(weights) {
  1252. // if weights[index+1].WeightAfter == 0 || weights[index].WeightBefore == 0 {
  1253. // continue
  1254. // }
  1255. // weightAdd = append(weightAdd, ((weights[index].WeightBefore - weights[index+1].WeightAfter) / weights[index+1].WeightAfter))
  1256. // }
  1257. //}
  1258. data, _ := GetNewDialysisWeightDetailTableTenOne(user_org_id, start_time, end_time)
  1259. for _, item := range data {
  1260. fmt.Println(item.WeightAdd)
  1261. weightAdd = append(weightAdd, item.WeightAdd)
  1262. }
  1263. var total_one int64
  1264. var total_two int64
  1265. var total_three int64
  1266. var total_four int64
  1267. for _, item := range weightAdd {
  1268. fmt.Println(item)
  1269. if item <= 0.03 && item == 0 {
  1270. total_four++
  1271. }
  1272. if item <= 0.03 && item != 0 {
  1273. total_one++
  1274. }
  1275. if item > 0.03 && item < 0.05 {
  1276. total_two++
  1277. }
  1278. if item >= 0.05 {
  1279. total_three++
  1280. }
  1281. }
  1282. newTotal = total_one + total_two + total_three + total_four
  1283. newItem := &otherItemAmount{
  1284. Total: total_one,
  1285. Name: "体重增长<=3%",
  1286. Ratio: "0",
  1287. }
  1288. newItem1 := &otherItemAmount{
  1289. Total: total_two,
  1290. Name: "3%<体重增长<5%",
  1291. Ratio: "0",
  1292. }
  1293. newItem2 := &otherItemAmount{
  1294. Total: total_three,
  1295. Name: "体重增长>=5%",
  1296. Ratio: "0",
  1297. }
  1298. newItem3 := &otherItemAmount{
  1299. Total: total_four,
  1300. Name: "其他",
  1301. Ratio: "0",
  1302. }
  1303. items = append(items, newItem)
  1304. items = append(items, newItem1)
  1305. items = append(items, newItem2)
  1306. items = append(items, newItem3)
  1307. for _, item := range items {
  1308. if math.IsNaN(float64(item.Total) / float64(newTotal)) {
  1309. item.Ratio = "0.0"
  1310. } else {
  1311. float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(newTotal))*100), 64)
  1312. item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
  1313. }
  1314. }
  1315. break
  1316. case 3:
  1317. //db.Table("xt_assessment_before_dislysis ").Where("user_org_id=? and status=1 and created_time >= ? and created_time <= ?", user_org_id, start_time, end_time).Count(&Total)
  1318. //db.Raw("Select count(*) from `xt_assessment_before_dislysis` LEFT JOIN `xt_assessment_after_dislysis` On xt_assessment_before_dislysis.`patient_id` = xt_assessment_after_dislysis.`patient_id` AND xt_assessment_before_dislysis.assessment_date = xt_assessment_after_dislysis.assessment_date AND xt_assessment_after_dislysis.weight_after != 0 Where xt_assessment_before_dislysis.user_org_id = ? AND xt_assessment_before_dislysis.created_time >= ? AND xt_assessment_before_dislysis.created_time <= ? Order by xt_assessment_before_dislysis.assessment_date desc", user_org_id, start_time, end_time).Count(&Total)
  1319. var newTotal int64
  1320. type weight struct {
  1321. WeightAfter float64 `json:"weight_after"`
  1322. WeightBefore float64 `json:"weight_before"`
  1323. }
  1324. //var weights []*weight
  1325. var weightAdd []float64
  1326. data, _ := GetNewDialysisWeightDetailTableTenTwo(user_org_id, start_time, end_time)
  1327. for _, item := range data {
  1328. fmt.Println(item.WeightAdd)
  1329. weightAdd = append(weightAdd, item.WeightAdd)
  1330. }
  1331. var total_one int64
  1332. var total_two int64
  1333. var total_three int64
  1334. var total_four int64
  1335. for _, item := range weightAdd {
  1336. fmt.Println(item)
  1337. if item <= 0.03 && item == 0 {
  1338. total_four++
  1339. }
  1340. if item <= 0.03 && item != 0 {
  1341. total_one++
  1342. }
  1343. if item > 0.03 && item < 0.05 {
  1344. total_two++
  1345. }
  1346. if item >= 0.05 {
  1347. total_three++
  1348. }
  1349. }
  1350. newTotal = total_one + total_two + total_three + total_four
  1351. newItem := &otherItemAmount{
  1352. Total: total_one,
  1353. Name: "体重增长<=3%",
  1354. Ratio: "0",
  1355. }
  1356. newItem1 := &otherItemAmount{
  1357. Total: total_two,
  1358. Name: "3%<体重增长<5%",
  1359. Ratio: "0",
  1360. }
  1361. newItem2 := &otherItemAmount{
  1362. Total: total_three,
  1363. Name: "体重增长>=5%",
  1364. Ratio: "0",
  1365. }
  1366. newItem3 := &otherItemAmount{
  1367. Total: total_four,
  1368. Name: "其他",
  1369. Ratio: "0",
  1370. }
  1371. items = append(items, newItem)
  1372. items = append(items, newItem1)
  1373. items = append(items, newItem2)
  1374. items = append(items, newItem3)
  1375. for _, item := range items {
  1376. if math.IsNaN(float64(item.Total) / float64(newTotal)) {
  1377. item.Ratio = "0.0"
  1378. } else {
  1379. float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(newTotal))*100), 64)
  1380. item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
  1381. }
  1382. }
  1383. break
  1384. case 4:
  1385. var newTotal int64
  1386. type weight struct {
  1387. WeightAfter float64 `json:"weight_after"`
  1388. DryWeight float64 `json:"dry_weight"`
  1389. }
  1390. var weights []*weight
  1391. //var weightAdd []float64
  1392. db.Raw("Select xt_assessment_after_dislysis.weight_after as weight_after ,xt_assessment_before_dislysis.dry_weight as dry_weight from `xt_assessment_before_dislysis` LEFT JOIN `xt_assessment_after_dislysis` On xt_assessment_before_dislysis.`patient_id` = xt_assessment_after_dislysis.`patient_id` AND xt_assessment_before_dislysis.assessment_date = xt_assessment_after_dislysis.assessment_date AND xt_assessment_after_dislysis.weight_after <> 0 AND xt_assessment_after_dislysis.user_org_id = ? Where xt_assessment_before_dislysis.user_org_id = ? AND xt_assessment_before_dislysis.created_time >= ? AND xt_assessment_before_dislysis.created_time <= ? Order by xt_assessment_before_dislysis.assessment_date desc", user_org_id, user_org_id, start_time, end_time).Scan(&weights)
  1393. var total_one int64
  1394. var total_two int64
  1395. var total_three int64
  1396. //var total_four int64
  1397. for _, item := range weights {
  1398. if item.WeightAfter != 0 && item.DryWeight != 0 {
  1399. if item.WeightAfter-item.DryWeight <= 0.3 && item.WeightAfter-item.DryWeight >= -0.3 {
  1400. total_one++
  1401. } else if item.WeightAfter-item.DryWeight > 0.3 || item.WeightAfter-item.DryWeight < -0.3 {
  1402. total_two++
  1403. } else {
  1404. total_three++
  1405. }
  1406. }
  1407. if item.WeightAfter == 0 {
  1408. total_three++
  1409. }
  1410. if item.DryWeight == 0 {
  1411. total_three++
  1412. }
  1413. }
  1414. newTotal = total_one + total_two + total_three
  1415. newItem := &otherItemAmount{
  1416. Total: total_one,
  1417. Name: "达到干体重",
  1418. Ratio: "0",
  1419. }
  1420. newItem1 := &otherItemAmount{
  1421. Total: total_two,
  1422. Name: "未达到干体重",
  1423. Ratio: "0",
  1424. }
  1425. newItem2 := &otherItemAmount{
  1426. Total: total_three,
  1427. Name: "其他或卧床",
  1428. Ratio: "0",
  1429. }
  1430. items = append(items, newItem)
  1431. items = append(items, newItem1)
  1432. items = append(items, newItem2)
  1433. for _, item := range items {
  1434. if math.IsNaN(float64(item.Total) / float64(newTotal)) {
  1435. item.Ratio = "0.0"
  1436. } else {
  1437. float_value, _ := strconv.ParseFloat(fmt.Sprintf("%.1f", (float64(item.Total)/float64(newTotal))*100), 64)
  1438. item.Ratio = strconv.FormatFloat(float_value, 'f', 1, 32)
  1439. }
  1440. }
  1441. break
  1442. }
  1443. if tempErr != nil {
  1444. return nil, err
  1445. }
  1446. fmt.Println(items)
  1447. return items, nil
  1448. }
  1449. func GetNewDialysisBloodChartData(user_org_id int64, start_time int64, end_time int64, statistics_type int) (item []otherItemAmount, err error) {
  1450. db := XTReadDB()
  1451. switch statistics_type {
  1452. case 1:
  1453. var assessments []Assessment
  1454. err = db.Joins("JOIN xt_patients ON xt_patients.id = xt_assessment_before_dislysis.patient_id").
  1455. Where("xt_assessment_before_dislysis.assessment_date >= ? AND xt_assessment_before_dislysis.assessment_date <= ? AND xt_assessment_before_dislysis.user_org_id = ?", start_time, end_time, user_org_id).
  1456. Find(&assessments).Error
  1457. if err != nil {
  1458. log.Fatal("Query execution error:", err)
  1459. }
  1460. var total, metStandard, unmetStandard int
  1461. // Iterate through the result set
  1462. for _, assessment := range assessments {
  1463. // Fetch patient information
  1464. var patient Patient
  1465. err = db.First(&patient, assessment.PatientID).Error
  1466. if err != nil {
  1467. log.Printf("Skipping record due to missing patient data for ID: %v", assessment.PatientID)
  1468. continue
  1469. }
  1470. // Calculate the patient's age
  1471. age, err := calculateAge(patient.IDCardNo)
  1472. if err != nil {
  1473. log.Printf("Skipping record due to invalid ID card number: %v", patient.IDCardNo)
  1474. continue
  1475. }
  1476. // Update the total count of patients
  1477. total++
  1478. // Determine if the patient meets the standard based on their age and blood pressure
  1479. if (age < 60 && assessment.SystolicBP < 140 && assessment.DiastolicBP < 90) || (age >= 60 && assessment.SystolicBP < 160 && assessment.DiastolicBP < 90) {
  1480. metStandard++
  1481. } else {
  1482. unmetStandard++
  1483. }
  1484. }
  1485. // Calculate and print the results
  1486. if total > 0 {
  1487. metPercentage := float64(metStandard) / float64(total) * 100
  1488. unmetPercentage := float64(unmetStandard) / float64(total) * 100
  1489. fmt.Printf("Total patients: %d\n", total)
  1490. fmt.Printf("Met standard: %d (%.2f%%)\n", metStandard, metPercentage)
  1491. fmt.Printf("Unmet standard: %d (%.2f%%)\n", unmetStandard, unmetPercentage)
  1492. var items otherItemAmount
  1493. items.Name = "达标患者"
  1494. items.Ratio = strconv.FormatFloat(metPercentage, 'f', 1, 32)
  1495. items.Total = int64(metStandard)
  1496. item = append(item, items)
  1497. var items2 otherItemAmount
  1498. items2.Name = "未达标患者"
  1499. items2.Ratio = strconv.FormatFloat(unmetPercentage, 'f', 1, 32)
  1500. items2.Total = int64(unmetStandard)
  1501. item = append(item, items2)
  1502. }
  1503. case 2:
  1504. var assessments []AssessmentAfter
  1505. err = db.Joins("JOIN xt_patients ON xt_patients.id = xt_assessment_after_dislysis.patient_id").
  1506. Where("xt_assessment_after_dislysis.assessment_date >= ? AND xt_assessment_after_dislysis.assessment_date <= ? AND xt_assessment_after_dislysis.user_org_id = ?", start_time, end_time, user_org_id).
  1507. Find(&assessments).Error
  1508. if err != nil {
  1509. log.Fatal("Query execution error:", err)
  1510. }
  1511. var total, metStandard, unmetStandard int
  1512. // Iterate through the result set
  1513. for _, assessment := range assessments {
  1514. // Fetch patient information
  1515. var patient Patient
  1516. err = db.First(&patient, assessment.PatientID).Error
  1517. if err != nil {
  1518. log.Printf("Skipping record due to missing patient data for ID: %v", assessment.PatientID)
  1519. continue
  1520. }
  1521. // Calculate the patient's age
  1522. age, err := calculateAge(patient.IDCardNo)
  1523. if err != nil {
  1524. log.Printf("Skipping record due to invalid ID card number: %v", patient.IDCardNo)
  1525. continue
  1526. }
  1527. // Update the total count of patients
  1528. total++
  1529. // Determine if the patient meets the standard based on their age and blood pressure
  1530. if (age < 60 && assessment.SystolicBP < 140 && assessment.DiastolicBP < 90) || (age >= 60 && assessment.SystolicBP < 160 && assessment.DiastolicBP < 90) {
  1531. metStandard++
  1532. } else {
  1533. unmetStandard++
  1534. }
  1535. }
  1536. // Calculate and print the results
  1537. if total > 0 {
  1538. metPercentage := float64(metStandard) / float64(total) * 100
  1539. unmetPercentage := float64(unmetStandard) / float64(total) * 100
  1540. fmt.Printf("Total patients: %d\n", total)
  1541. fmt.Printf("Met standard: %d (%.2f%%)\n", metStandard, metPercentage)
  1542. fmt.Printf("Unmet standard: %d (%.2f%%)\n", unmetStandard, unmetPercentage)
  1543. var items otherItemAmount
  1544. items.Name = "达标患者"
  1545. items.Ratio = strconv.FormatFloat(metPercentage, 'f', 1, 32)
  1546. items.Total = int64(metStandard)
  1547. item = append(item, items)
  1548. var items2 otherItemAmount
  1549. items2.Name = "未达标患者"
  1550. items2.Ratio = strconv.FormatFloat(unmetPercentage, 'f', 1, 32)
  1551. items2.Total = int64(unmetStandard)
  1552. item = append(item, items2)
  1553. }
  1554. break
  1555. }
  1556. return
  1557. }
  1558. func calculateAge(idCardNo string) (int, error) {
  1559. if len(idCardNo) < 14 {
  1560. return 0, fmt.Errorf("invalid ID card number")
  1561. }
  1562. // Extract birth year, month, and day from ID card number
  1563. year := idCardNo[6:10]
  1564. month := idCardNo[10:12]
  1565. day := idCardNo[12:14]
  1566. // Parse the birth date
  1567. birthDate, err := time.Parse("20060102", year+month+day)
  1568. if err != nil {
  1569. return 0, err
  1570. }
  1571. // Calculate age
  1572. now := time.Now()
  1573. age := now.Year() - birthDate.Year()
  1574. if now.YearDay() < birthDate.YearDay() {
  1575. age--
  1576. }
  1577. return age, nil
  1578. }
  1579. // 定义结果结构体
  1580. type DialysisDataTwo struct {
  1581. DialysisNo string `json:"dialysis_no"`
  1582. PatientName string `json:"patient_name"`
  1583. Gender string `json:"gender"`
  1584. Age int `json:"age"`
  1585. AssessmentDate string `json:"assessment_date"` // 使用 string 存储日期,或使用 time.Time
  1586. DryWeight float64 `json:"dry_weight"`
  1587. WeightBefore float64 `json:"weight_before"`
  1588. WeightAfter float64 `json:"weight_after"`
  1589. LastWeightAfter float64 `json:"last_weight_after"` // 使用指针处理可能为空的值
  1590. WeightAdd float64 `json:"weight_add"` // 使用指针处理可能为空的值
  1591. DryWeightCategory string `json:"dry_weight_category"`
  1592. WeightStatus string `json:"weight_status"`
  1593. }
  1594. // func GetNewDialysisWeightDetailTableTen(user_org_id int64, start_time int64, end_time int64, addType, dryType, afterType, page, limit int64) ([]DialysisDataTwo, int64, error) {
  1595. // offset := (page - 1) * limit
  1596. // var dialysisData []DialysisDataTwo
  1597. // var total int64
  1598. // // 构建基本查询
  1599. // query := readDb.Table("xt_assessment_before_dislysis b").
  1600. // Select(`
  1601. // p.dialysis_no AS dialysis_no,
  1602. // p.name AS patient_name,
  1603. // p.gender AS gender,
  1604. // FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS age,
  1605. // b.assessment_date AS assessment_date,
  1606. // b.dry_weight AS dry_weight,
  1607. // b.weight_before AS weight_before,
  1608. // a.weight_after AS weight_after,
  1609. // (
  1610. // SELECT a2.weight_after
  1611. // FROM xt_assessment_after_dislysis a2
  1612. // JOIN xt_assessment_before_dislysis b2
  1613. // ON a2.patient_id = b2.patient_id
  1614. // AND a2.assessment_date = b2.assessment_date
  1615. // WHERE b2.patient_id = b.patient_id
  1616. // AND b2.assessment_date < b.assessment_date
  1617. // ORDER BY b2.assessment_date DESC LIMIT 1
  1618. // ) AS last_weight_after,
  1619. // CASE
  1620. // WHEN (
  1621. // SELECT a2.weight_after
  1622. // FROM xt_assessment_after_dislysis a2
  1623. // JOIN xt_assessment_before_dislysis b2
  1624. // ON a2.patient_id = b2.patient_id
  1625. // AND a2.assessment_date = b2.assessment_date
  1626. // WHERE b2.patient_id = b.patient_id
  1627. // AND b2.assessment_date < b.assessment_date
  1628. // ORDER BY b2.assessment_date DESC LIMIT 1
  1629. // ) IS NOT NULL
  1630. // THEN (b.weight_before - (
  1631. // SELECT a2.weight_after
  1632. // FROM xt_assessment_after_dislysis a2
  1633. // JOIN xt_assessment_before_dislysis b2
  1634. // ON a2.patient_id = b2.patient_id
  1635. // AND a2.assessment_date = b2.assessment_date
  1636. // WHERE b2.patient_id = b.patient_id
  1637. // AND b2.assessment_date < b.assessment_date
  1638. // ORDER BY b2.assessment_date DESC LIMIT 1
  1639. // )) / (
  1640. // SELECT a2.weight_after
  1641. // FROM xt_assessment_after_dislysis a2
  1642. // JOIN xt_assessment_before_dislysis b2
  1643. // ON a2.patient_id = b2.patient_id
  1644. // AND a2.assessment_date = b2.assessment_date
  1645. // WHERE b2.patient_id = b.patient_id
  1646. // AND b2.assessment_date < b.assessment_date
  1647. // ORDER BY b2.assessment_date DESC LIMIT 1
  1648. // )
  1649. // ELSE NULL
  1650. // END AS weight_add,
  1651. // CASE
  1652. // WHEN b.dry_weight IS NOT NULL THEN
  1653. // CASE
  1654. // WHEN b.dry_weight < 40 THEN '小于40'
  1655. // WHEN b.dry_weight BETWEEN 40 AND 50 THEN '40~50'
  1656. // WHEN b.dry_weight BETWEEN 50 AND 60 THEN '50~60'
  1657. // WHEN b.dry_weight BETWEEN 60 AND 70 THEN '60~70'
  1658. // WHEN b.dry_weight > 70 THEN '大于70'
  1659. // END
  1660. // ELSE '其他'
  1661. // END AS dry_weight_category,
  1662. // CASE
  1663. // WHEN b.dry_weight IS NOT NULL THEN
  1664. // CASE
  1665. // WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标'
  1666. // ELSE '不达标'
  1667. // END
  1668. // ELSE '其他'
  1669. // END AS weight_status
  1670. // `).
  1671. // Joins("JOIN xt_patients p ON p.id = b.patient_id").
  1672. // Joins("JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date AND a.status = 1").
  1673. // Where("b.user_org_id = ?", user_org_id).
  1674. // Where("b.assessment_date >= ?", start_time).
  1675. // Where("b.assessment_date <= ?", end_time).
  1676. // Where("b.status = ?", 1)
  1677. //
  1678. // fmt.Println("dry_type")
  1679. // fmt.Println(dryType)
  1680. // switch dryType {
  1681. // case 1:
  1682. // query.Where("dry_weight_category = '小于40'")
  1683. // case 2:
  1684. // query.Where("dry_weight_category = '40~50'")
  1685. // case 3:
  1686. // query.Where("dry_weight_category = '50~60'")
  1687. // case 4:
  1688. // query.Where("dry_weight_category = '60~70'")
  1689. // case 5:
  1690. // query.Where("dry_weight_category = '大于70'")
  1691. // }
  1692. //
  1693. // // 根据传入的 add_type 值动态构建条件
  1694. // addTypeCondition(query, addType)
  1695. // // 根据传入的 dry_type 值动态构建条件
  1696. // //fmt.Println("dry_type")
  1697. // //fmt.Println(dryType)
  1698. //
  1699. // //dryTypeCondition(query, dryType)
  1700. // // 根据传入的 after_type 值动态构建条件
  1701. // afterTypeCondition(query, afterType)
  1702. // // 获取总记录数
  1703. // if err := query.Count(&total).Error; err != nil {
  1704. // return nil, 0, fmt.Errorf("count query failed: %v", err)
  1705. // }
  1706. // // 获取分页数据
  1707. // rows, err := query.Order("p.id, b.assessment_date").Offset(int(offset)).Limit(int(limit)).Rows()
  1708. // if err != nil {
  1709. // return nil, 0, fmt.Errorf("pagination query failed: %v", err)
  1710. // }
  1711. // defer rows.Close()
  1712. // // 处理结果集
  1713. // for rows.Next() {
  1714. // var data DialysisDataTwo
  1715. // if err := rows.Scan(
  1716. // &data.DialysisNo,
  1717. // &data.PatientName,
  1718. // &data.Gender,
  1719. // &data.Age,
  1720. // &data.AssessmentDate,
  1721. // &data.DryWeight,
  1722. // &data.WeightBefore,
  1723. // &data.WeightAfter,
  1724. // &data.LastWeightAfter,
  1725. // &data.WeightAdd,
  1726. // &data.DryWeightCategory,
  1727. // &data.WeightStatus,
  1728. // ); err != nil {
  1729. // return nil, 0, fmt.Errorf("row scan failed: %v", err)
  1730. // }
  1731. // // 将每一行结果追加到切片中
  1732. // dialysisData = append(dialysisData, data)
  1733. // }
  1734. // return dialysisData, total, nil
  1735. // }
  1736. //func GetNewDialysisWeightDetailTableTen(
  1737. // user_org_id int64,
  1738. // start_time int64,
  1739. // end_time int64,
  1740. // addType, dryType, afterType, page, limit int64,
  1741. //) ([]DialysisDataTwo, int64, error) {
  1742. // offset := (page - 1) * limit
  1743. // var total int64
  1744. //
  1745. // // 构建基本查询
  1746. // query := readDb.Table("xt_assessment_before_dislysis b").
  1747. // Select(`
  1748. // p.dialysis_no AS dialysis_no,
  1749. // p.name AS patient_name,
  1750. // p.gender AS gender,
  1751. // FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS age,
  1752. // b.assessment_date AS assessment_date,
  1753. // b.dry_weight AS dry_weight,
  1754. // b.weight_before AS weight_before,
  1755. // a.weight_after AS weight_after,
  1756. // (
  1757. // SELECT a2.weight_after
  1758. // FROM xt_assessment_after_dislysis a2
  1759. // JOIN xt_assessment_before_dislysis b2
  1760. // ON a2.patient_id = b2.patient_id
  1761. // AND a2.assessment_date = b2.assessment_date
  1762. // WHERE b2.patient_id = b.patient_id
  1763. // AND b2.assessment_date < b.assessment_date
  1764. // ORDER BY b2.assessment_date DESC LIMIT 1
  1765. // ) AS last_weight_after,
  1766. // CASE
  1767. // WHEN (
  1768. // SELECT a2.weight_after
  1769. // FROM xt_assessment_after_dislysis a2
  1770. // JOIN xt_assessment_before_dislysis b2
  1771. // ON a2.patient_id = b2.patient_id
  1772. // AND a2.assessment_date = b2.assessment_date
  1773. // WHERE b2.patient_id = b.patient_id
  1774. // AND b2.assessment_date < b.assessment_date
  1775. // ORDER BY b2.assessment_date DESC LIMIT 1
  1776. // ) IS NOT NULL
  1777. // THEN (b.weight_before - (
  1778. // SELECT a2.weight_after
  1779. // FROM xt_assessment_after_dislysis a2
  1780. // JOIN xt_assessment_before_dislysis b2
  1781. // ON a2.patient_id = b2.patient_id
  1782. // AND a2.assessment_date = b2.assessment_date
  1783. // WHERE b2.patient_id = b.patient_id
  1784. // AND b2.assessment_date < b.assessment_date
  1785. // ORDER BY b2.assessment_date DESC LIMIT 1
  1786. // )) / (
  1787. // SELECT a2.weight_after
  1788. // FROM xt_assessment_after_dislysis a2
  1789. // JOIN xt_assessment_before_dislysis b2
  1790. // ON a2.patient_id = b2.patient_id
  1791. // AND a2.assessment_date = b2.assessment_date
  1792. // WHERE b2.patient_id = b.patient_id
  1793. // AND b2.assessment_date < b.assessment_date
  1794. // ORDER BY b2.assessment_date DESC LIMIT 1
  1795. // )
  1796. // ELSE NULL
  1797. // END AS weight_add,
  1798. // CASE
  1799. // WHEN b.dry_weight IS NOT NULL THEN
  1800. // CASE
  1801. // WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标'
  1802. // ELSE '不达标'
  1803. // END
  1804. // ELSE '其他'
  1805. // END AS weight_status
  1806. // `).
  1807. // Joins("left JOIN xt_patients p ON p.id = b.patient_id").
  1808. // Joins("left JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date AND a.status = 1").
  1809. // Where("b.user_org_id = ?", user_org_id).
  1810. // Where("b.assessment_date >= ?", start_time).
  1811. // Where("b.assessment_date <= ?", end_time).
  1812. // Where("b.status = ?", 1)
  1813. //
  1814. // // 处理干重过滤
  1815. // switch dryType {
  1816. // case 5:
  1817. // query = query.Where("b.dry_weight < ?", 40)
  1818. // case 1:
  1819. // query = query.Where("b.dry_weight >= ? AND b.dry_weight < ?", 40, 50)
  1820. // case 2:
  1821. // query = query.Where("b.dry_weight >= ? AND b.dry_weight < ?", 50, 60)
  1822. // case 3:
  1823. // query = query.Where("b.dry_weight >= ? AND b.dry_weight < ?", 60, 70)
  1824. // case 4:
  1825. // query = query.Where("b.dry_weight >= ?", 70)
  1826. // case 6:
  1827. // query = query.Where("b.dry_weight IS NULL OR b.dry_weight = ''")
  1828. // }
  1829. //
  1830. // // 处理加重过滤
  1831. // switch addType {
  1832. // case 1:
  1833. // query = query.Where("weight_add <= 0.03")
  1834. // case 2:
  1835. // query = query.Where("weight_add > 0.03 AND weight_add < 0.05")
  1836. // case 3:
  1837. // query = query.Where("weight_add >= 0.05")
  1838. // case 4:
  1839. // query = query.Where("weight_add IS NULL")
  1840. // }
  1841. //
  1842. // // 处理状态过滤
  1843. // switch afterType {
  1844. // case 1:
  1845. // query = query.Having("CASE WHEN b.dry_weight IS NOT NULL THEN CASE WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标' ELSE '不达标' END ELSE '其他' END = ?", "达标")
  1846. // case 2:
  1847. // query = query.Having("CASE WHEN b.dry_weight IS NOT NULL THEN CASE WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标' ELSE '不达标' END ELSE '其他' END = ?", "不达标")
  1848. // case 3:
  1849. // query = query.Having("CASE WHEN b.dry_weight IS NOT NULL THEN CASE WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标' ELSE '不达标' END ELSE '其他' END = ?", "其他")
  1850. // }
  1851. //
  1852. // // 获取总记录数
  1853. // if err := query.Count(&total).Error; err != nil {
  1854. // return nil, 0, fmt.Errorf("count query failed: %v", err)
  1855. // }
  1856. //
  1857. // var data []DialysisDataTwo
  1858. // query.Order("p.id, b.assessment_date").Offset(int(offset)).Limit(int(limit)).Find(&data)
  1859. // fmt.Println(data)
  1860. // return data, total, nil
  1861. //}
  1862. func GetNewDialysisWeightDetailTableTen(
  1863. user_org_id int64,
  1864. start_time int64,
  1865. end_time int64,
  1866. addType, dryType, afterType, page, limit int64,
  1867. ) ([]DialysisDataTwo, int64, error) {
  1868. offset := (page - 1) * limit
  1869. //var dialysisData []DialysisDataTwo
  1870. var total int64
  1871. // 构建基本查询
  1872. query := readDb.Table("xt_assessment_before_dislysis b").
  1873. Select(`
  1874. p.dialysis_no AS dialysis_no,
  1875. p.name AS patient_name,
  1876. p.gender AS gender,
  1877. FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS age,
  1878. b.assessment_date AS assessment_date,
  1879. b.dry_weight AS dry_weight,
  1880. b.weight_before AS weight_before,
  1881. a.weight_after AS weight_after,
  1882. (
  1883. SELECT a2.weight_after
  1884. FROM xt_assessment_after_dislysis a2
  1885. JOIN xt_assessment_before_dislysis b2
  1886. ON a2.patient_id = b2.patient_id
  1887. AND a2.assessment_date = b2.assessment_date
  1888. WHERE b2.patient_id = b.patient_id
  1889. AND b2.assessment_date < b.assessment_date
  1890. ORDER BY b2.assessment_date DESC LIMIT 1
  1891. ) AS last_weight_after,
  1892. CASE
  1893. WHEN (
  1894. SELECT a2.weight_after
  1895. FROM xt_assessment_after_dislysis a2
  1896. JOIN xt_assessment_before_dislysis b2
  1897. ON a2.patient_id = b2.patient_id
  1898. AND a2.assessment_date = b2.assessment_date
  1899. WHERE b2.patient_id = b.patient_id
  1900. AND b2.assessment_date < b.assessment_date
  1901. ORDER BY b2.assessment_date DESC LIMIT 1
  1902. ) IS NOT NULL
  1903. THEN (b.weight_before - (
  1904. SELECT a2.weight_after
  1905. FROM xt_assessment_after_dislysis a2
  1906. JOIN xt_assessment_before_dislysis b2
  1907. ON a2.patient_id = b2.patient_id
  1908. AND a2.assessment_date = b2.assessment_date
  1909. WHERE b2.patient_id = b.patient_id
  1910. AND b2.assessment_date < b.assessment_date
  1911. ORDER BY b2.assessment_date DESC LIMIT 1
  1912. )) / (
  1913. SELECT a2.weight_after
  1914. FROM xt_assessment_after_dislysis a2
  1915. JOIN xt_assessment_before_dislysis b2
  1916. ON a2.patient_id = b2.patient_id
  1917. AND a2.assessment_date = b2.assessment_date
  1918. WHERE b2.patient_id = b.patient_id
  1919. AND b2.assessment_date < b.assessment_date
  1920. ORDER BY b2.assessment_date DESC LIMIT 1
  1921. )
  1922. ELSE NULL
  1923. END AS weight_add,
  1924. CASE
  1925. WHEN a.weight_after IS NULL THEN '其他'
  1926. WHEN b.dry_weight IS NOT NULL THEN
  1927. CASE
  1928. WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标'
  1929. ELSE '不达标'
  1930. END
  1931. ELSE '其他'
  1932. END AS weight_status
  1933. `).
  1934. Joins("left JOIN xt_patients p ON p.id = b.patient_id").
  1935. Joins("left JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date AND a.status = 1").
  1936. Where("b.user_org_id = ?", user_org_id).
  1937. Where("b.assessment_date >= ?", start_time).
  1938. Where("b.assessment_date <= ?", end_time).
  1939. Where("b.status = ?", 1)
  1940. switch dryType {
  1941. case 5:
  1942. query = query.Where("b.dry_weight < ?", 40)
  1943. case 1:
  1944. query = query.Where("b.dry_weight >= ? AND b.dry_weight < ?", 40, 50)
  1945. case 2:
  1946. query = query.Where("b.dry_weight >= ? AND b.dry_weight < ?", 50, 60)
  1947. case 3:
  1948. query = query.Where("b.dry_weight >= ? AND b.dry_weight < ?", 60, 70)
  1949. case 4:
  1950. query = query.Where("b.dry_weight >= ?", 70)
  1951. case 6:
  1952. query = query.Where("b.dry_weight IS NULL OR b.dry_weight = ''")
  1953. }
  1954. switch addType {
  1955. case 1:
  1956. query = query.Where(`
  1957. (
  1958. CASE
  1959. WHEN (
  1960. SELECT a2.weight_after
  1961. FROM xt_assessment_after_dislysis a2
  1962. JOIN xt_assessment_before_dislysis b2
  1963. ON a2.patient_id = b2.patient_id
  1964. AND a2.assessment_date = b2.assessment_date
  1965. WHERE b2.patient_id = b.patient_id
  1966. AND b2.assessment_date < b.assessment_date
  1967. ORDER BY b2.assessment_date DESC LIMIT 1
  1968. ) IS NOT NULL
  1969. THEN (b.weight_before - (
  1970. SELECT a2.weight_after
  1971. FROM xt_assessment_after_dislysis a2
  1972. JOIN xt_assessment_before_dislysis b2
  1973. ON a2.patient_id = b2.patient_id
  1974. AND a2.assessment_date = b2.assessment_date
  1975. WHERE b2.patient_id = b.patient_id
  1976. AND b2.assessment_date < b.assessment_date
  1977. ORDER BY b2.assessment_date DESC LIMIT 1
  1978. )) / (
  1979. SELECT a2.weight_after
  1980. FROM xt_assessment_after_dislysis a2
  1981. JOIN xt_assessment_before_dislysis b2
  1982. ON a2.patient_id = b2.patient_id
  1983. AND a2.assessment_date = b2.assessment_date
  1984. WHERE b2.patient_id = b.patient_id
  1985. AND b2.assessment_date < b.assessment_date
  1986. ORDER BY b2.assessment_date DESC LIMIT 1
  1987. )
  1988. ELSE NULL
  1989. END
  1990. ) <= 0.03
  1991. `)
  1992. case 2:
  1993. query = query.Where(`
  1994. (
  1995. CASE
  1996. WHEN (
  1997. SELECT a2.weight_after
  1998. FROM xt_assessment_after_dislysis a2
  1999. JOIN xt_assessment_before_dislysis b2
  2000. ON a2.patient_id = b2.patient_id
  2001. AND a2.assessment_date = b2.assessment_date
  2002. WHERE b2.patient_id = b.patient_id
  2003. AND b2.assessment_date < b.assessment_date
  2004. ORDER BY b2.assessment_date DESC LIMIT 1
  2005. ) IS NOT NULL
  2006. THEN (b.weight_before - (
  2007. SELECT a2.weight_after
  2008. FROM xt_assessment_after_dislysis a2
  2009. JOIN xt_assessment_before_dislysis b2
  2010. ON a2.patient_id = b2.patient_id
  2011. AND a2.assessment_date = b2.assessment_date
  2012. WHERE b2.patient_id = b.patient_id
  2013. AND b2.assessment_date < b.assessment_date
  2014. ORDER BY b2.assessment_date DESC LIMIT 1
  2015. )) / (
  2016. SELECT a2.weight_after
  2017. FROM xt_assessment_after_dislysis a2
  2018. JOIN xt_assessment_before_dislysis b2
  2019. ON a2.patient_id = b2.patient_id
  2020. AND a2.assessment_date = b2.assessment_date
  2021. WHERE b2.patient_id = b.patient_id
  2022. AND b2.assessment_date < b.assessment_date
  2023. ORDER BY b2.assessment_date DESC LIMIT 1
  2024. )
  2025. ELSE NULL
  2026. END
  2027. ) > 0.03 AND (
  2028. CASE
  2029. WHEN (
  2030. SELECT a2.weight_after
  2031. FROM xt_assessment_after_dislysis a2
  2032. JOIN xt_assessment_before_dislysis b2
  2033. ON a2.patient_id = b2.patient_id
  2034. AND a2.assessment_date = b2.assessment_date
  2035. WHERE b2.patient_id = b.patient_id
  2036. AND b2.assessment_date < b.assessment_date
  2037. ORDER BY b2.assessment_date DESC LIMIT 1
  2038. ) IS NOT NULL
  2039. THEN (b.weight_before - (
  2040. SELECT a2.weight_after
  2041. FROM xt_assessment_after_dislysis a2
  2042. JOIN xt_assessment_before_dislysis b2
  2043. ON a2.patient_id = b2.patient_id
  2044. AND a2.assessment_date = b2.assessment_date
  2045. WHERE b2.patient_id = b.patient_id
  2046. AND b2.assessment_date < b.assessment_date
  2047. ORDER BY b2.assessment_date DESC LIMIT 1
  2048. )) / (
  2049. SELECT a2.weight_after
  2050. FROM xt_assessment_after_dislysis a2
  2051. JOIN xt_assessment_before_dislysis b2
  2052. ON a2.patient_id = b2.patient_id
  2053. AND a2.assessment_date = b2.assessment_date
  2054. WHERE b2.patient_id = b.patient_id
  2055. AND b2.assessment_date < b.assessment_date
  2056. ORDER BY b2.assessment_date DESC LIMIT 1
  2057. )
  2058. ELSE NULL
  2059. END
  2060. ) < 0.05
  2061. `)
  2062. case 3:
  2063. query = query.Where(`
  2064. (
  2065. CASE
  2066. WHEN (
  2067. SELECT a2.weight_after
  2068. FROM xt_assessment_after_dislysis a2
  2069. JOIN xt_assessment_before_dislysis b2
  2070. ON a2.patient_id = b2.patient_id
  2071. AND a2.assessment_date = b2.assessment_date
  2072. WHERE b2.patient_id = b.patient_id
  2073. AND b2.assessment_date < b.assessment_date
  2074. ORDER BY b2.assessment_date DESC LIMIT 1
  2075. ) IS NOT NULL
  2076. THEN (b.weight_before - (
  2077. SELECT a2.weight_after
  2078. FROM xt_assessment_after_dislysis a2
  2079. JOIN xt_assessment_before_dislysis b2
  2080. ON a2.patient_id = b2.patient_id
  2081. AND a2.assessment_date = b2.assessment_date
  2082. WHERE b2.patient_id = b.patient_id
  2083. AND b2.assessment_date < b.assessment_date
  2084. ORDER BY b2.assessment_date DESC LIMIT 1
  2085. )) / (
  2086. SELECT a2.weight_after
  2087. FROM xt_assessment_after_dislysis a2
  2088. JOIN xt_assessment_before_dislysis b2
  2089. ON a2.patient_id = b2.patient_id
  2090. AND a2.assessment_date = b2.assessment_date
  2091. WHERE b2.patient_id = b.patient_id
  2092. AND b2.assessment_date < b.assessment_date
  2093. ORDER BY b2.assessment_date DESC LIMIT 1
  2094. )
  2095. ELSE NULL
  2096. END
  2097. ) >= 0.05
  2098. `)
  2099. case 4:
  2100. query = query.Where(`
  2101. (
  2102. SELECT a2.weight_after
  2103. FROM xt_assessment_after_dislysis a2
  2104. JOIN xt_assessment_before_dislysis b2
  2105. ON a2.patient_id = b2.patient_id
  2106. AND a2.assessment_date = b2.assessment_date
  2107. WHERE b2.patient_id = b.patient_id
  2108. AND b2.assessment_date < b.assessment_date
  2109. ORDER BY b2.assessment_date DESC LIMIT 1
  2110. ) IS NULL
  2111. `)
  2112. }
  2113. switch afterType {
  2114. case 1:
  2115. query = query.Where(`
  2116. CASE
  2117. WHEN a.weight_after IS NULL THEN '其他'
  2118. WHEN b.dry_weight IS NOT NULL THEN
  2119. CASE
  2120. WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标'
  2121. ELSE '不达标'
  2122. END
  2123. ELSE '其他'
  2124. END = ?`, "达标")
  2125. case 2:
  2126. query = query.Where(`
  2127. CASE
  2128. WHEN a.weight_after IS NULL THEN '其他'
  2129. WHEN b.dry_weight IS NOT NULL THEN
  2130. CASE
  2131. WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标'
  2132. ELSE '不达标'
  2133. END
  2134. ELSE '其他'
  2135. END = ?`, "不达标")
  2136. case 3:
  2137. query = query.Where(`
  2138. CASE
  2139. WHEN a.weight_after IS NULL THEN '其他'
  2140. WHEN b.dry_weight IS NOT NULL THEN
  2141. CASE
  2142. WHEN ABS(a.weight_after - b.dry_weight) <= 0.3 THEN '达标'
  2143. ELSE '不达标'
  2144. END
  2145. ELSE '其他'
  2146. END = ?`, "其他")
  2147. }
  2148. //// 获取总记录数
  2149. if err := query.Count(&total).Error; err != nil {
  2150. return nil, 0, fmt.Errorf("count query failed: %v", err)
  2151. }
  2152. var data []DialysisDataTwo
  2153. query.Order("p.id, b.assessment_date").Offset(int(offset)).Limit(int(limit)).Find(&data)
  2154. return data, total, nil
  2155. }
  2156. func GetNewDialysisWeightDetailTableTenOne(
  2157. user_org_id int64,
  2158. start_time int64,
  2159. end_time int64) ([]DialysisDataTwo, error) {
  2160. // 构建基本查询
  2161. query := readDb.Table("xt_assessment_before_dislysis b").
  2162. Select(`
  2163. CASE
  2164. WHEN (
  2165. SELECT a2.weight_after
  2166. FROM xt_assessment_after_dislysis a2
  2167. JOIN xt_assessment_before_dislysis b2
  2168. ON a2.patient_id = b2.patient_id
  2169. AND a2.assessment_date = b2.assessment_date
  2170. WHERE b2.patient_id = b.patient_id
  2171. AND b2.assessment_date < b.assessment_date
  2172. ORDER BY b2.assessment_date DESC LIMIT 1
  2173. ) IS NOT NULL
  2174. THEN (b.weight_before - (
  2175. SELECT a2.weight_after
  2176. FROM xt_assessment_after_dislysis a2
  2177. JOIN xt_assessment_before_dislysis b2
  2178. ON a2.patient_id = b2.patient_id
  2179. AND a2.assessment_date = b2.assessment_date
  2180. WHERE b2.patient_id = b.patient_id
  2181. AND b2.assessment_date < b.assessment_date
  2182. ORDER BY b2.assessment_date DESC LIMIT 1
  2183. )) / (
  2184. SELECT a2.weight_after
  2185. FROM xt_assessment_after_dislysis a2
  2186. JOIN xt_assessment_before_dislysis b2
  2187. ON a2.patient_id = b2.patient_id
  2188. AND a2.assessment_date = b2.assessment_date
  2189. WHERE b2.patient_id = b.patient_id
  2190. AND b2.assessment_date < b.assessment_date
  2191. ORDER BY b2.assessment_date DESC LIMIT 1
  2192. )
  2193. ELSE NULL
  2194. END AS weight_add
  2195. `).
  2196. Joins("left JOIN xt_patients p ON p.id = b.patient_id").
  2197. Joins("left JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date AND a.status = 1").
  2198. Where("b.user_org_id = ?", user_org_id).
  2199. Where("b.assessment_date >= ?", start_time).
  2200. Where("b.assessment_date <= ?", end_time).
  2201. Where("b.status = ?", 1)
  2202. var data []DialysisDataTwo
  2203. query.Order("p.id, b.assessment_date").Find(&data)
  2204. return data, nil
  2205. }
  2206. func GetNewDialysisWeightDetailTableTenTwo(
  2207. user_org_id int64,
  2208. start_time int64,
  2209. end_time int64) ([]DialysisDataTwo, error) {
  2210. // Construct the base query
  2211. query := readDb.Table("xt_assessment_before_dislysis b").
  2212. Select(`
  2213. (b.weight_before - b.dry_weight) / b.dry_weight * 100 AS weight_add
  2214. `).
  2215. Joins("left JOIN xt_patients p ON p.id = b.patient_id").
  2216. Joins("left JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date AND a.status = 1").
  2217. Where("b.user_org_id = ?", user_org_id).
  2218. Where("b.assessment_date >= ?", start_time).
  2219. Where("b.assessment_date <= ?", end_time).
  2220. Where("b.status = ?", 1)
  2221. var data []DialysisDataTwo
  2222. query.Order("p.id, b.assessment_date").Find(&data)
  2223. return data, nil
  2224. }
  2225. // addType 条件处理
  2226. func addTypeCondition(query *gorm.DB, addType int64) {
  2227. }
  2228. // dryType 条件处理
  2229. func dryTypeCondition(query *gorm.DB, dryType int64) {
  2230. }
  2231. // afterType 条件处理
  2232. func afterTypeCondition(query *gorm.DB, afterType int64) {
  2233. switch afterType {
  2234. case 1:
  2235. query = query.Where("weight_status = '达标'")
  2236. case 2:
  2237. query = query.Where("weight_status = '不达标'")
  2238. case 3:
  2239. query = query.Where("weight_status = '其他'")
  2240. }
  2241. }
  2242. type DialysisDataThree struct {
  2243. DialysisNo string `json:"dialysis_no"`
  2244. PatientName string `json:"patient_name"`
  2245. Gender string `json:"gender"`
  2246. Age int `json:"age"`
  2247. AssessmentDate string `json:"assessment_date"`
  2248. DryWeight float64 `json:"dry_weight"`
  2249. PreDialysisBP string `json:"pre_dialysis_bp"`
  2250. PostDialysisBP string `json:"post_dialysis_bp"`
  2251. MonitoringBP string `json:"monitoring_bp"`
  2252. UltrafiltrationRate float64 `json:"ultrafiltration_rate"`
  2253. UltrafiltrationVol float64 `json:"ultrafiltration_vol"`
  2254. BPStatus string `json:"bp_status"`
  2255. ActualUltrafiltration float64 `json:"actual_ultrafiltration"`
  2256. }
  2257. // func GetNewDialysisBPDetailTableTen(user_org_id int64, start_time int64, end_time int64, addType, page, limit int64) ([]DialysisDataThree, int64, error) {
  2258. // offset := (page - 1) * limit
  2259. // var total int64
  2260. // var results []DialysisDataThree
  2261. // // SQL 查询
  2262. // query := `
  2263. // SELECT
  2264. // p.dialysis_no AS 透析号,
  2265. // p.name AS 患者姓名,
  2266. // p.gender AS 性别,
  2267. // FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS 年龄,
  2268. // b.assessment_date AS 透析日期,
  2269. // b.dry_weight AS 干体重,
  2270. // CONCAT(b.systolic_blood_pressure, '/', b.diastolic_blood_pressure) AS 透前血压,
  2271. // CONCAT(a.systolic_blood_pressure, '/', a.diastolic_blood_pressure) AS 透后血压,
  2272. // GROUP_CONCAT(CONCAT(m.systolic_blood_pressure, '/', m.diastolic_blood_pressure) ORDER BY m.monitoring_date ASC SEPARATOR ',') AS 监测记录血压,
  2273. // (SELECT mr.ultrafiltration_rate
  2274. // FROM xt_monitoring_record mr
  2275. // WHERE mr.patient_id = p.id AND mr.monitoring_date = b.assessment_date
  2276. // ORDER BY mr.operate_time DESC
  2277. // LIMIT 1) AS 超滤率,
  2278. // (SELECT mr.ultrafiltration_volume
  2279. // FROM xt_monitoring_record mr
  2280. // WHERE mr.patient_id = p.id AND mr.monitoring_date = b.assessment_date
  2281. // ORDER BY mr.operate_time DESC
  2282. // LIMIT 1) AS 超滤总量,
  2283. // CASE
  2284. // WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2285. // CASE
  2286. // WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2287. // ELSE '不达标'
  2288. // END
  2289. // WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2290. // CASE
  2291. // WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2292. // ELSE '不达标'
  2293. // END
  2294. // END AS 血压达标状态
  2295. // FROM
  2296. // xt_patients p
  2297. // JOIN
  2298. // xt_assessment_before_dislysis b ON p.id = b.patient_id
  2299. // JOIN
  2300. // xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date
  2301. // JOIN
  2302. // xt_monitoring_record m ON p.id = m.patient_id AND m.monitoring_date = b.assessment_date
  2303. // WHERE
  2304. // b.user_org_id = ?
  2305. // AND b.assessment_date >= ?
  2306. // AND b.assessment_date <= ?
  2307. // AND (
  2308. // (? = 1 AND CASE
  2309. // WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2310. // CASE
  2311. // WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN 1
  2312. // ELSE 0
  2313. // END
  2314. // WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2315. // CASE
  2316. // WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN 1
  2317. // ELSE 0
  2318. // END
  2319. // END = 1)
  2320. // OR
  2321. // (? = 2 AND CASE
  2322. // WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2323. // CASE
  2324. // WHEN b.systolic_blood_pressure >= 140 AND b.diastolic_blood_pressure >= 90 THEN 1
  2325. // ELSE 0
  2326. // END
  2327. // WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2328. // CASE
  2329. // WHEN b.systolic_blood_pressure >= 160 AND b.diastolic_blood_pressure >= 90 THEN 1
  2330. // ELSE 0
  2331. // END
  2332. // END = 1)
  2333. // )
  2334. // GROUP BY
  2335. // p.id, b.assessment_date
  2336. // ORDER BY
  2337. // p.id, b.assessment_date
  2338. // LIMIT ? OFFSET ?;
  2339. // `
  2340. //
  2341. // // 计算总数
  2342. // countQuery := `
  2343. // SELECT COUNT(*)
  2344. // FROM
  2345. // xt_patients p
  2346. // JOIN
  2347. // xt_assessment_before_dislysis b ON p.id = b.patient_id
  2348. // WHERE
  2349. // b.user_org_id = ?
  2350. // AND b.assessment_date >= ?
  2351. // AND b.assessment_date <= ?
  2352. // `
  2353. //
  2354. // // 执行统计查询
  2355. // if err := readDb.Raw(countQuery, user_org_id, start_time, end_time).Scan(&total).Error; err != nil {
  2356. // return nil, 0, fmt.Errorf("error calculating total count: %v", err)
  2357. // }
  2358. //
  2359. // // 执行数据查询
  2360. // if err := readDb.Raw(query, user_org_id, start_time, end_time, addType, addType, limit, offset).Scan(&results).Error; err != nil {
  2361. // return nil, 0, fmt.Errorf("error executing query: %v", err)
  2362. // }
  2363. //
  2364. // return results, total, nil
  2365. // }
  2366. func GetNewDialysisBPDetailTableTenOne(
  2367. user_org_id int64,
  2368. start_time int64,
  2369. end_time int64,
  2370. addType, page, limit int64,
  2371. ) ([]DialysisDataThree, int64, error) {
  2372. offset := (page - 1) * limit
  2373. var results []DialysisDataThree
  2374. var total int64
  2375. // 构建基本查询
  2376. query := readDb.Table("xt_assessment_after_dislysis b").
  2377. Select(`
  2378. p.dialysis_no AS dialysis_no,
  2379. b.actual_ultrafiltration as actual_ultrafiltration,
  2380. p.name AS patient_name,
  2381. p.gender AS gender,
  2382. FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS age,
  2383. b.assessment_date AS assessment_date,
  2384. b.dry_weight AS dry_weight,
  2385. CONCAT(a.systolic_blood_pressure, '/', a.diastolic_blood_pressure) AS pre_dialysis_bp,
  2386. CONCAT(b.systolic_blood_pressure, '/', b.diastolic_blood_pressure) AS post_dialysis_bp,
  2387. GROUP_CONCAT(CONCAT(m.systolic_blood_pressure, '/', m.diastolic_blood_pressure) ORDER BY m.monitoring_date ASC SEPARATOR ',') AS monitoring_bp,
  2388. (
  2389. SELECT mr.ultrafiltration_rate
  2390. FROM xt_monitoring_record mr
  2391. WHERE mr.patient_id = p.id
  2392. AND mr.monitoring_date = b.assessment_date
  2393. ORDER BY mr.operate_time DESC LIMIT 1
  2394. ) AS ultrafiltration_rate,
  2395. (
  2396. SELECT mr.ultrafiltration_volume
  2397. FROM xt_monitoring_record mr
  2398. WHERE mr.patient_id = p.id
  2399. AND mr.monitoring_date = b.assessment_date
  2400. ORDER BY mr.operate_time DESC LIMIT 1
  2401. ) AS ultrafiltration_vol,
  2402. CASE
  2403. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2404. CASE
  2405. WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2406. ELSE '不达标'
  2407. END
  2408. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2409. CASE
  2410. WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2411. ELSE '不达标'
  2412. END
  2413. END AS bp_status
  2414. `).
  2415. Joins("JOIN xt_patients p ON p.id = b.patient_id").
  2416. Joins("JOIN xt_assessment_before_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date").
  2417. Joins("JOIN xt_monitoring_record m ON p.id = m.patient_id AND m.monitoring_date = b.assessment_date").
  2418. Where("b.user_org_id = ?", user_org_id).
  2419. Where("b.assessment_date >= ?", start_time).
  2420. Where("b.assessment_date <= ?", end_time).
  2421. Group("p.id, b.assessment_date")
  2422. // 根据传入的 addType 值动态构建条件
  2423. switch addType {
  2424. case 1:
  2425. query = query.Where(`
  2426. CASE
  2427. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2428. b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90
  2429. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2430. b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90
  2431. END`)
  2432. case 2:
  2433. query = query.Where(`
  2434. CASE
  2435. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2436. b.systolic_blood_pressure >= 140 AND b.diastolic_blood_pressure >= 90
  2437. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2438. b.systolic_blood_pressure >= 160 AND b.diastolic_blood_pressure >= 90
  2439. END`)
  2440. }
  2441. // 获取总记录数
  2442. if err := query.Count(&total).Error; err != nil {
  2443. return nil, 0, fmt.Errorf("count query failed: %v", err)
  2444. }
  2445. // 获取分页数据
  2446. if err := query.Order("p.id, b.assessment_date").
  2447. Offset(int(offset)).
  2448. Limit(int(limit)).
  2449. Scan(&results).Error; err != nil {
  2450. return nil, 0, fmt.Errorf("query execution failed: %v", err)
  2451. }
  2452. return results, total, nil
  2453. }
  2454. func GetNewDialysisBPDetailTableTen(
  2455. user_org_id int64,
  2456. start_time int64,
  2457. end_time int64,
  2458. addType, page, limit int64,
  2459. ) ([]DialysisDataThree, int64, error) {
  2460. offset := (page - 1) * limit
  2461. var results []DialysisDataThree
  2462. var total int64
  2463. // 构建基本查询
  2464. query := readDb.Table("xt_assessment_before_dislysis b").
  2465. Select(`
  2466. p.dialysis_no AS dialysis_no,
  2467. a.actual_ultrafiltration as actual_ultrafiltration,
  2468. p.name AS patient_name,
  2469. p.gender AS gender,
  2470. FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) AS age,
  2471. b.assessment_date AS assessment_date,
  2472. b.dry_weight AS dry_weight,
  2473. CONCAT(b.systolic_blood_pressure, '/', b.diastolic_blood_pressure) AS pre_dialysis_bp,
  2474. CONCAT(a.systolic_blood_pressure, '/', a.diastolic_blood_pressure) AS post_dialysis_bp,
  2475. GROUP_CONCAT(CONCAT(m.systolic_blood_pressure, '/', m.diastolic_blood_pressure) ORDER BY m.monitoring_date ASC SEPARATOR ',') AS monitoring_bp,
  2476. (
  2477. SELECT mr.ultrafiltration_rate
  2478. FROM xt_monitoring_record mr
  2479. WHERE mr.patient_id = p.id
  2480. AND mr.monitoring_date = b.assessment_date
  2481. ORDER BY mr.operate_time DESC LIMIT 1
  2482. ) AS ultrafiltration_rate,
  2483. (
  2484. SELECT mr.ultrafiltration_volume
  2485. FROM xt_monitoring_record mr
  2486. WHERE mr.patient_id = p.id
  2487. AND mr.monitoring_date = b.assessment_date
  2488. ORDER BY mr.operate_time DESC LIMIT 1
  2489. ) AS ultrafiltration_vol,
  2490. CASE
  2491. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2492. CASE
  2493. WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2494. ELSE '不达标'
  2495. END
  2496. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2497. CASE
  2498. WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2499. ELSE '不达标'
  2500. END
  2501. END AS bp_status
  2502. `).
  2503. Joins("JOIN xt_patients p ON p.id = b.patient_id").
  2504. Joins("JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date").
  2505. Joins("JOIN xt_monitoring_record m ON p.id = m.patient_id AND m.monitoring_date = b.assessment_date").
  2506. Where("b.user_org_id = ?", user_org_id).
  2507. Where("b.assessment_date >= ?", start_time).
  2508. Where("b.assessment_date <= ?", end_time).
  2509. Group("p.id, b.assessment_date")
  2510. // 根据传入的 addType 值动态构建条件
  2511. switch addType {
  2512. case 1:
  2513. query = query.Where(`
  2514. CASE
  2515. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2516. b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90
  2517. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2518. b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90
  2519. END`)
  2520. case 2:
  2521. query = query.Where(`
  2522. CASE
  2523. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2524. b.systolic_blood_pressure >= 140 AND b.diastolic_blood_pressure >= 90
  2525. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2526. b.systolic_blood_pressure >= 160 AND b.diastolic_blood_pressure >= 90
  2527. END`)
  2528. }
  2529. // 获取总记录数
  2530. if err := query.Count(&total).Error; err != nil {
  2531. return nil, 0, fmt.Errorf("count query failed: %v", err)
  2532. }
  2533. // 获取分页数据
  2534. if err := query.Order("p.id, b.assessment_date").
  2535. Offset(int(offset)).
  2536. Limit(int(limit)).
  2537. Scan(&results).Error; err != nil {
  2538. return nil, 0, fmt.Errorf("query execution failed: %v", err)
  2539. }
  2540. return results, total, nil
  2541. }
  2542. func GetNewDialysisBPDetailTableTenThree(
  2543. user_org_id int64,
  2544. start_time int64,
  2545. end_time int64,
  2546. ) (item []otherItemAmount, err error) {
  2547. var results []DialysisDataThree
  2548. var total int64
  2549. // 构建基本查询
  2550. query := readDb.Table("xt_assessment_before_dislysis b").
  2551. Select(`
  2552. CASE
  2553. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2554. CASE
  2555. WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2556. ELSE '不达标'
  2557. END
  2558. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2559. CASE
  2560. WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2561. ELSE '不达标'
  2562. END
  2563. END AS bp_status
  2564. `).
  2565. Joins("JOIN xt_patients p ON p.id = b.patient_id").
  2566. Joins("JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date").
  2567. Where("b.user_org_id = ?", user_org_id).
  2568. Where("b.assessment_date >= ?", start_time).
  2569. Where("b.assessment_date <= ?", end_time).
  2570. Group("p.id, b.assessment_date")
  2571. // 获取总记录数
  2572. query.Count(&total)
  2573. // 获取分页数据
  2574. query.Order("p.id, b.assessment_date").Scan(&results)
  2575. var metStandard, unmetStandard int
  2576. for _, result := range results {
  2577. if result.BPStatus == "达标" {
  2578. metStandard++
  2579. } else {
  2580. unmetStandard++
  2581. }
  2582. }
  2583. if total > 0 {
  2584. metPercentage := float64(metStandard) / float64(total) * 100
  2585. unmetPercentage := float64(unmetStandard) / float64(total) * 100
  2586. fmt.Printf("Total patients: %d\n", total)
  2587. fmt.Printf("Met standard: %d (%.2f%%)\n", metStandard, metPercentage)
  2588. fmt.Printf("Unmet standard: %d (%.2f%%)\n", unmetStandard, unmetPercentage)
  2589. var items otherItemAmount
  2590. items.Name = "达标患者"
  2591. items.Ratio = strconv.FormatFloat(metPercentage, 'f', 1, 32)
  2592. items.Total = int64(metStandard)
  2593. item = append(item, items)
  2594. var items2 otherItemAmount
  2595. items2.Name = "未达标患者"
  2596. items2.Ratio = strconv.FormatFloat(unmetPercentage, 'f', 1, 32)
  2597. items2.Total = int64(unmetStandard)
  2598. item = append(item, items2)
  2599. }
  2600. return
  2601. }
  2602. func GetNewDialysisBPDetailTableTenFour(
  2603. user_org_id int64,
  2604. start_time int64,
  2605. end_time int64,
  2606. ) (item []otherItemAmount, err error) {
  2607. var results []DialysisDataThree
  2608. var total int64
  2609. // 构建基本查询
  2610. query := readDb.Table("xt_assessment_after_dislysis b").
  2611. Select(`
  2612. CASE
  2613. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) < 60 THEN
  2614. CASE
  2615. WHEN b.systolic_blood_pressure < 140 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2616. ELSE '不达标'
  2617. END
  2618. WHEN FLOOR((YEAR(CURDATE()) - SUBSTRING(p.id_card_no, 7, 4))) >= 60 THEN
  2619. CASE
  2620. WHEN b.systolic_blood_pressure < 160 OR b.diastolic_blood_pressure < 90 THEN '达标'
  2621. ELSE '不达标'
  2622. END
  2623. END AS bp_status
  2624. `).
  2625. Joins("JOIN xt_patients p ON p.id = b.patient_id").
  2626. Joins("JOIN xt_assessment_after_dislysis a ON p.id = a.patient_id AND b.assessment_date = a.assessment_date").
  2627. Where("b.user_org_id = ?", user_org_id).
  2628. Where("b.assessment_date >= ?", start_time).
  2629. Where("b.assessment_date <= ?", end_time).
  2630. Group("p.id, b.assessment_date")
  2631. // 获取总记录数
  2632. query.Count(&total)
  2633. // 获取分页数据
  2634. query.Order("p.id, b.assessment_date").Scan(&results)
  2635. var metStandard, unmetStandard int
  2636. for _, result := range results {
  2637. if result.BPStatus == "达标" {
  2638. metStandard++
  2639. } else {
  2640. unmetStandard++
  2641. }
  2642. }
  2643. if total > 0 {
  2644. metPercentage := float64(metStandard) / float64(total) * 100
  2645. unmetPercentage := float64(unmetStandard) / float64(total) * 100
  2646. fmt.Printf("Total patients: %d\n", total)
  2647. fmt.Printf("Met standard: %d (%.2f%%)\n", metStandard, metPercentage)
  2648. fmt.Printf("Unmet standard: %d (%.2f%%)\n", unmetStandard, unmetPercentage)
  2649. var items otherItemAmount
  2650. items.Name = "达标患者"
  2651. items.Ratio = strconv.FormatFloat(metPercentage, 'f', 1, 32)
  2652. items.Total = int64(metStandard)
  2653. item = append(item, items)
  2654. var items2 otherItemAmount
  2655. items2.Name = "未达标患者"
  2656. items2.Ratio = strconv.FormatFloat(unmetPercentage, 'f', 1, 32)
  2657. items2.Total = int64(unmetStandard)
  2658. item = append(item, items2)
  2659. }
  2660. return
  2661. }