statistis_qc_service.go 107KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935
  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, keyword string) ([]DialysisDataTwo, int64, error) {
  1867. offset := (page - 1) * limit
  1868. //var dialysisData []DialysisDataTwo
  1869. var total int64
  1870. keyword = "%" + keyword + "%"
  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("JOIN xt_patients p ON p.id = b.patient_id and p.name like ?", keyword).
  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. }