statistis_qc_service.go 83KB

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