dialysis_api_controller.go 181KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990
  1. package mobile_api_controllers
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/jinzhu/gorm"
  7. "reflect"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "Xcx_New/enums"
  12. "Xcx_New/models"
  13. "Xcx_New/service"
  14. "Xcx_New/utils"
  15. "github.com/astaxie/beego"
  16. "math"
  17. "net/http"
  18. "net/url"
  19. )
  20. // type DialysisTestAPIController struct {
  21. // MobileBaseAPIController
  22. // }
  23. // [get]/m/api/test
  24. // func (this *DialysisTestAPIController) Test() {
  25. // orgID := int64(3907)
  26. // now := time.Now()
  27. // nextWeek := now.AddDate(0, 0, 7)
  28. // nextWeekMon, nextWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextWeek)
  29. // nextTwoWeek := now.AddDate(0, 0, 14)
  30. // nextTwoWeekMon, nextTwoWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextTwoWeek)
  31. // nextWeekSchs, getNextWeekSchErr := service.GetWeekSchedule(orgID, nextWeekMon.Unix(), nextWeekSun.Unix())
  32. // nextTwoWeekSchs, getNextTwoWeekSchErr := service.GetWeekSchedule(orgID, nextTwoWeekMon.Unix(), nextTwoWeekSun.Unix())
  33. // if getNextWeekSchErr != nil || getNextTwoWeekSchErr != nil {
  34. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  35. // return
  36. // }
  37. // exchangeErr := service.ExchangeScheduleTimeWithWeekSchedules(orgID, nextWeekSchs, nextTwoWeekSchs)
  38. // if exchangeErr != nil {
  39. // this.ErrorLog("%v", exchangeErr)
  40. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  41. // return
  42. // }
  43. // this.ServeSuccessJSON(map[string]interface{}{
  44. // // "now": now,
  45. // // "next_week": nextWeek,f
  46. // // "next_week_mon": nextWeekMon,
  47. // // "next_week_sun": nextWeekSun,
  48. // // "next_two_week_mon": nextTwoWeekMon,
  49. // // "next_two_week_sun": nextTwoWeekSun,
  50. // "next_week_schs": nextWeekSchs,
  51. // "next_two_week_schs": nextTwoWeekSchs,
  52. // })
  53. // }
  54. type DialysisAPIController struct {
  55. MobileBaseAPIAuthController
  56. }
  57. // /m/api/scheduals [get]
  58. // @param type:int
  59. // @param date:string
  60. func (this *DialysisAPIController) Scheduals() {
  61. schedualType, _ := this.GetInt64("type")
  62. schedualDate := this.GetString("date")
  63. if schedualType != 0 && schedualType != 1 && schedualType != 2 && schedualType != 3 {
  64. schedualType = 0
  65. }
  66. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  67. if parseDateErr != nil {
  68. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  69. return
  70. }
  71. adminInfo := this.GetMobileAdminUserInfo()
  72. orgID := adminInfo.Org.Id
  73. redis := service.RedisClient()
  74. defer redis.Close()
  75. // cur_date := time.Now().Format("2006-01-02")
  76. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  77. scheduals_json_str, _ := redis.Get(redis.Context(),key).Result()
  78. if len(scheduals_json_str) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  79. scheduals, err := service.MobileGetDialysisScheduals(orgID, date.Unix(), schedualType)
  80. if err != nil {
  81. this.ErrorLog("获取排班信息失败:%v", err)
  82. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  83. } else {
  84. if len(scheduals) > 0 {
  85. //缓存数据
  86. scheduals_json, err := json.Marshal(scheduals)
  87. if err == nil {
  88. redis.Set(redis.Context(),key, scheduals_json, time.Second*60)
  89. }
  90. }
  91. this.ServeSuccessJSON(map[string]interface{}{
  92. "scheduals": scheduals,
  93. })
  94. }
  95. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  96. var dat []map[string]interface{}
  97. if err := json.Unmarshal([]byte(scheduals_json_str), &dat); err == nil {
  98. } else {
  99. }
  100. this.ServeSuccessJSON(map[string]interface{}{
  101. "scheduals": dat,
  102. "redis": "true",
  103. "date": schedualDate,
  104. })
  105. }
  106. }
  107. // /m/api/waiting_scheduals [get]
  108. // @param date:string
  109. func (this *DialysisAPIController) WaitingScheduals() {
  110. schedualDate := this.GetString("date")
  111. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  112. if parseDateErr != nil && len(schedualDate) != 0 {
  113. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  114. return
  115. }
  116. adminInfo := this.GetMobileAdminUserInfo()
  117. orgID := adminInfo.Org.Id
  118. redis := service.RedisClient()
  119. defer redis.Close()
  120. // cur_date := time.Now().Format("2006-01-02")
  121. key := "wait_scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  122. wait_scheduals, _ := redis.Get(redis.Context(),key).Result()
  123. if len(wait_scheduals) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  124. scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  125. if err != nil {
  126. this.ErrorLog("获取排班信息失败:%v", err)
  127. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  128. } else {
  129. returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  130. for _, s := range scheduals {
  131. returnScheduals = append(returnScheduals, s)
  132. }
  133. if len(returnScheduals) > 0 {
  134. //缓存数据
  135. wait_scheduals_json, err := json.Marshal(scheduals)
  136. if err == nil {
  137. redis.Set(redis.Context(),key, wait_scheduals_json, time.Second*30)
  138. }
  139. }
  140. this.ServeSuccessJSON(map[string]interface{}{
  141. "scheduals": scheduals,
  142. })
  143. }
  144. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  145. var dat []map[string]interface{}
  146. if err := json.Unmarshal([]byte(wait_scheduals), &dat); err == nil {
  147. } else {
  148. }
  149. this.ServeSuccessJSON(map[string]interface{}{
  150. "scheduals": dat,
  151. "redis": "true",
  152. "date": schedualDate,
  153. })
  154. }
  155. }
  156. //else{
  157. // fmt.Println("33333333")
  158. //
  159. // scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  160. // if err != nil {
  161. // this.ErrorLog("获取排班信息失败:%v", err)
  162. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  163. // } else {
  164. // returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  165. // for _, s := range scheduals {
  166. //
  167. // returnScheduals = append(returnScheduals, s)
  168. // }
  169. //
  170. // this.ServeSuccessJSON(map[string]interface{}{
  171. // "scheduals": returnScheduals,
  172. // })
  173. // }
  174. //
  175. // }
  176. //if err == nil{
  177. //
  178. //
  179. //
  180. //
  181. //
  182. //}else{
  183. //}
  184. // /m/api/dialysis/record [get]
  185. // @param patient_id:int
  186. // @param date:string (yyyy-MM-dd)
  187. func (this *DialysisAPIController) DialysisRecord() {
  188. patientID, _ := this.GetInt64("patient_id")
  189. recordDateStr := this.GetString("date")
  190. if patientID <= 0 {
  191. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  192. return
  193. }
  194. if len(recordDateStr) == 0 {
  195. recordDateStr = time.Now().Format("2006-01-02")
  196. }
  197. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  198. if parseDateErr != nil {
  199. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  200. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  201. return
  202. }
  203. adminInfo := this.GetMobileAdminUserInfo()
  204. patient, getPatientErr := service.MobileGetPatientDetail(adminInfo.Org.Id, patientID)
  205. if getPatientErr != nil {
  206. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  207. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  208. return
  209. } else if patient == nil {
  210. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  211. return
  212. }
  213. schedual, getSchedualErr := service.MobileGetSchedualDetail(adminInfo.Org.Id, patientID, date.Unix())
  214. if getSchedualErr != nil {
  215. this.ErrorLog("获取患者排班信息失败:%v", getSchedualErr)
  216. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  217. return
  218. }
  219. receiverTreatmentAccess, getRTARErr := service.MobileGetReceiverTreatmentAccessRecord(adminInfo.Org.Id, patientID, date.Unix())
  220. if getRTARErr != nil {
  221. this.ErrorLog("获取接诊评估失败:%v", getRTARErr)
  222. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  223. return
  224. }
  225. predialysisEvaluation, getPEErr := service.MobileGetPredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  226. if getPEErr != nil {
  227. this.ErrorLog("获取透前评估失败:%v", getPEErr)
  228. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  229. return
  230. }
  231. lastPredialysisEvaluation, getLPEErr := service.MobileGetLastTimePredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  232. if getLPEErr != nil {
  233. this.ErrorLog("获取上一次透前评估失败:%v", getLPEErr)
  234. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  235. return
  236. }
  237. doctorAdvices, getDoctorAdvicesErr := service.MobileGetDoctorAdvicesByGroups(adminInfo.Org.Id, patientID, date.Unix())
  238. if getDoctorAdvicesErr != nil {
  239. this.ErrorLog("获取临时医嘱失败:%v", getDoctorAdvicesErr)
  240. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  241. return
  242. }
  243. dialysisOrder, getDialysisOrderErr := service.MobileGetSchedualDialysisRecord(adminInfo.Org.Id, patientID, date.Unix())
  244. if getDialysisOrderErr != nil {
  245. this.ErrorLog("获取透析记录失败:%v", getDialysisOrderErr)
  246. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  247. return
  248. }
  249. doubleCheck, getDoubleCheckErr := service.MobileGetDoubleCheck(adminInfo.Org.Id, patientID, date.Unix())
  250. if getDoubleCheckErr != nil {
  251. this.ErrorLog("获取双人核对记录失败:%v", getDoubleCheckErr)
  252. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  253. return
  254. }
  255. monitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecords(adminInfo.Org.Id, patientID, date.Unix())
  256. if getMonitorRecordsErr != nil {
  257. this.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  258. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  259. return
  260. }
  261. var lastMonitorRecord *models.MonitoringRecord
  262. lastMonitorRecord, getLastErr := service.MobileGetLastMonitorRecord(adminInfo.Org.Id, patientID, date.Unix())
  263. if getLastErr != nil {
  264. this.ErrorLog("获取上一次透析的监测记录失败:%v", getLastErr)
  265. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  266. return
  267. }
  268. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  269. if getAADErr != nil {
  270. this.ErrorLog("获取透后评估失败:%v", getAADErr)
  271. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  272. return
  273. }
  274. lastAssessmentAfterDislysis, getLAADErr := service.MobileGetLastTimeAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  275. if getLAADErr != nil {
  276. this.ErrorLog("获取上一次透后评估失败:%v", getLAADErr)
  277. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  278. return
  279. }
  280. treatmentSummary, getTreatmentSummaryErr := service.MobileGetTreatmentSummary(adminInfo.Org.Id, patientID, date.Unix())
  281. if getTreatmentSummaryErr != nil {
  282. this.ErrorLog("获取治疗小结失败:%v", getTreatmentSummaryErr)
  283. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  284. return
  285. }
  286. dialysisPrescribe, _ := service.MobileGetDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, date.Unix(), schedual.ModeId)
  287. //if getDialysisPrescribeErr != nil {
  288. // this.ErrorLog("获取透析处方失败:%v", getDialysisPrescribeErr)
  289. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  290. // return
  291. //}
  292. dialysisSolution, _ := service.MobileGetDialysisSolutionByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  293. //if getDialysisSolutionErr != nil {
  294. // this.ErrorLog("获取透析方案失败:%v", getDialysisSolutionErr)
  295. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  296. // return
  297. //}
  298. lastDialysisPrescribe, _ := service.MobileGetLastDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  299. //fmt.Println("上次透析处方",lastDialysisPrescribe.DialyzerPerfusionApparatus)
  300. //if getDialysisPrescribeErr != nil {
  301. // this.ErrorLog("获取透析处方失败:%v", getDialysisPrescribeErr)
  302. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  303. // return
  304. //}
  305. //获取系统透析处方模版
  306. systemDialysisPrescribe, _ := service.MobileGetSystemDialysisPrescribeByModeId(adminInfo.Org.Id, schedual.ModeId)
  307. //if getSystemDialysisPrescribeErr != nil {
  308. // this.ErrorLog("获取系统透析处方失败:%v", getSystemDialysisPrescribeErr)
  309. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  310. // return
  311. //}
  312. //dialysisSolution, getDialysisSolutionErr := service.MobileGetDialysisSolution(adminInfo.Org.Id, patientID)
  313. //operators, _ := service.GetAllAdminUserES(adminInfo.Org.Id, adminInfo.App.Id)
  314. _, is_open_config := service.FindXTHisRecordByOrgId(adminInfo.Org.Id)
  315. _, is_project_open_config := service.FindXTHisProjectByOrgId(adminInfo.Org.Id)
  316. projects, _ := service.GetHisPrescriptionProjects(adminInfo.Org.Id, patientID, date.Unix())
  317. stockType, _ := service.GetStockType(adminInfo.Org.Id)
  318. prepare, _ := service.GetDialyStockOut(adminInfo.Org.Id, date.Unix(), patientID)
  319. //获取最后一次血管通路
  320. lastAssessment, parseDateErr := service.GetLastPassWayAssessment(adminInfo.Org.Id, patientID)
  321. prescribeOne, parseDateErr := service.MobileGetDialysisPrescribeByModeIdOne(adminInfo.Org.Id, patientID, date.Unix())
  322. var his_advices []*models.HisDoctorAdviceInfo
  323. if is_open_config.IsOpen == 1 {
  324. his_advices, _ = service.GetAllHisDoctorAdvice(adminInfo.Org.Id, patientID, date.Unix())
  325. }
  326. if getLPEErr != nil {
  327. this.ErrorLog("获取上一次透前评估失败:%v", getLPEErr)
  328. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  329. return
  330. }
  331. lastDryWeightDislysis, getDryErr := service.MobileGetLastDryWeight(adminInfo.Org.Id, patientID)
  332. if getDryErr != nil {
  333. this.ErrorLog("获取最后一条干体重失败:%v", getDryErr)
  334. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  335. return
  336. }
  337. //headNurses, _ := service.GetAllSpecialPermissionAdminUsersWithoutStatus(adminInfo.Org.Id, adminInfo.App.Id, models.SpecialPermissionTypeHeadNurse)
  338. _, gobalConfig := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  339. //goodTypes, _ := service.FindAllGoodTypeByType(1) //查出所有库存配置的系统类型
  340. //goodInfos, _ := service.FindAllGoodInfo(adminInfo.Org.Id) //查出所有库存配置的系统类型
  341. operators, _ := service.GetAllStarfEs(adminInfo.Org.Id)
  342. //consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patientID, date.Unix())
  343. //lastConsumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patientID, date.Unix())
  344. returnData := map[string]interface{}{
  345. "patient": patient,
  346. "schedual": schedual,
  347. "prescription": dialysisPrescribe,
  348. "solution": dialysisSolution,
  349. "last_prescription": lastDialysisPrescribe,
  350. "receiver_treatment_access": receiverTreatmentAccess,
  351. "predialysis_evaluation": predialysisEvaluation,
  352. "doctor_advices": doctorAdvices,
  353. "double_check": doubleCheck,
  354. "assessment_after_dislysis": assessmentAfterDislysis,
  355. "treatment_summary": treatmentSummary,
  356. "monitor_records": monitorRecords,
  357. "dialysis_order": dialysisOrder,
  358. "operators": operators,
  359. "last_predialysis_evaluation": lastPredialysisEvaluation,
  360. "last_assessment_after_dislysis": lastAssessmentAfterDislysis,
  361. "last_monitor_record": lastMonitorRecord,
  362. "config": gobalConfig,
  363. "dry_weight": lastDryWeightDislysis,
  364. "system_prescription": systemDialysisPrescribe,
  365. "his_advices": his_advices,
  366. "is_open_config": is_open_config,
  367. "stockType": stockType,
  368. "prepare": prepare,
  369. "lastAssessment": lastAssessment,
  370. "prescribeOne": prescribeOne,
  371. "is_project_open_config": is_project_open_config,
  372. "project": projects,
  373. }
  374. this.ServeSuccessJSON(returnData)
  375. }
  376. func (c *DialysisAPIController) GetDialysisGlobalConfig() {
  377. adminInfo := c.GetMobileAdminUserInfo()
  378. adminUsers, _ := service.GetAllAdminUsers(adminInfo.Org.Id, adminInfo.App.Id)
  379. devices, _ := service.GetValidDevicesBy(adminInfo.Org.Id, 0, 0)
  380. device_numbers, _ := service.GetAllValidDeviceNumbers(adminInfo.Org.Id)
  381. returnData := map[string]interface{}{
  382. "admin_users": adminUsers,
  383. "devices": devices,
  384. "device_numbers": device_numbers,
  385. }
  386. c.ServeSuccessJSON(returnData)
  387. }
  388. func (c *DialysisAPIController) PostAtreatmentInfo() {
  389. id, _ := c.GetInt64("patient", 0)
  390. recordDateStr := c.GetString("record_date")
  391. propagandaAndEducationContent := c.GetString("propagandaAndEducationContent")
  392. summaryContent := c.GetString("summaryContent")
  393. changeMedicalNurseId, _ := c.GetInt64("changeMedicalNurse", 0)
  394. treatNurseId, _ := c.GetInt64("treatNurse", 0)
  395. checkStaffId, _ := c.GetInt64("checkStaff", 0)
  396. deboardNurseId, _ := c.GetInt64("deboardNurse", 0)
  397. treatDoctor, _ := c.GetInt64("treatDoctor", 0)
  398. nursingRecord := c.GetString("nursing_record")
  399. fmt.Println("护理记录", nursingRecord)
  400. specialRecord := c.GetString("special_record")
  401. fmt.Println("特殊记录", specialRecord)
  402. adminUserInfo := c.GetMobileAdminUserInfo()
  403. changeMedicalNurseId = adminUserInfo.AdminUser.Id
  404. checkStaffId = adminUserInfo.AdminUser.Id
  405. deboardNurseId = adminUserInfo.AdminUser.Id
  406. treatDoctor = adminUserInfo.AdminUser.Id
  407. if id <= 0 {
  408. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  409. return
  410. }
  411. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  412. if patient.ID == 0 {
  413. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  414. return
  415. }
  416. if len(recordDateStr) == 0 {
  417. recordDateStr = time.Now().Format("2006-01-02")
  418. }
  419. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  420. if parseDateErr != nil {
  421. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  422. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  423. return
  424. }
  425. //now := time.Now()
  426. //year, month, day := now.Date()
  427. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  428. //todayTimeStamp := today_time.Unix()
  429. summary := models.TreatmentSummary{
  430. UserOrgId: adminUserInfo.Org.Id,
  431. PatientId: id,
  432. AssessmentDate: recordDate.Unix(),
  433. Mission: propagandaAndEducationContent,
  434. DialysisSummary: summaryContent,
  435. SjNurse: changeMedicalNurseId,
  436. ZlNurse: treatNurseId,
  437. HdNurse: checkStaffId,
  438. XjNurse: deboardNurseId,
  439. ZlDoctor: treatDoctor,
  440. CreatedTime: time.Now().Unix(),
  441. Status: 1,
  442. NursingRecord: nursingRecord,
  443. SpecialRecord: specialRecord,
  444. }
  445. _, treatmentSummary := service.FindTreatmentSummaryByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  446. if treatmentSummary.ID == 0 { //新增
  447. summary.Creater = adminUserInfo.AdminUser.Id
  448. service.AddSigleSummaryRecord(&summary)
  449. c.ServeSuccessJSON(map[string]interface{}{
  450. "summary": summary,
  451. })
  452. } else { //修改
  453. //if treatmentSummary.Creater != adminUserInfo.AdminUser.Id {
  454. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  455. // if getPermissionErr != nil {
  456. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  457. // return
  458. // } else if headNursePermission == nil {
  459. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  460. // return
  461. // }
  462. //}
  463. summary.Creater = treatmentSummary.Creater
  464. summary.CreatedTime = treatmentSummary.CreatedTime
  465. summary.Modifier = adminUserInfo.AdminUser.Id
  466. summary.ID = treatmentSummary.ID
  467. service.UpdateSummeRecord(&summary)
  468. c.ServeSuccessJSON(map[string]interface{}{
  469. "summary": summary,
  470. })
  471. }
  472. }
  473. func (c *DialysisAPIController) PostDoubleCheck() {
  474. id, _ := c.GetInt64("patient", 0)
  475. recordDateStr := c.GetString("record_date")
  476. checkTimeStr := c.GetString("check_time")
  477. firstCheckTimeStr := c.GetString("first_check_time")
  478. creater, _ := c.GetInt64("creater", 0)
  479. modifier, _ := c.GetInt64("modifier", 0)
  480. dialysis_item_check, _ := c.GetInt64("dialysis_item_check", 0)
  481. dialysis_parameter_check, _ := c.GetInt64("dialysis_parameter_check", 0)
  482. vascular_access_verification, _ := c.GetInt64("vascular_access_verification", 0)
  483. pipeline_connection_check, _ := c.GetInt64("pipeline_connection_check", 0)
  484. dialysis_item_desc := c.GetString("dialysis_item_desc")
  485. dialysis_parameter_desc := c.GetString("dialysis_parameter_desc")
  486. vascular_access_desc := c.GetString("vascular_access_desc")
  487. pipeline_connection_desc := c.GetString("pipeline_connection_desc")
  488. collator, _ := c.GetInt64("collator", 0)
  489. if id <= 0 {
  490. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  491. return
  492. }
  493. adminUserInfo := c.GetMobileAdminUserInfo()
  494. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  495. if patient.ID == 0 {
  496. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  497. return
  498. }
  499. if len(recordDateStr) == 0 {
  500. recordDateStr = time.Now().Format("2006-01-02")
  501. }
  502. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  503. if parseDateErr != nil {
  504. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  505. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  506. return
  507. }
  508. var checkDate int64
  509. if len(checkTimeStr) == 0 {
  510. checkDate = 0
  511. } else {
  512. checkDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", checkTimeStr)
  513. checkDate = checkDateUnix.Unix()
  514. }
  515. var firstCheckDate int64
  516. if len(firstCheckTimeStr) == 0 {
  517. firstCheckDate = 0
  518. } else {
  519. firstCheckDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", firstCheckTimeStr)
  520. firstCheckDate = firstCheckDateUnix.Unix()
  521. }
  522. //now := time.Now()
  523. //year, month, day := now.Date()
  524. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  525. //todayTimeStamp := today_time.Unix()
  526. doubleCheck := models.DoubleCheck{
  527. UserOrgId: adminUserInfo.Org.Id,
  528. PatientId: id,
  529. DialysisItemCheck: dialysis_item_check,
  530. DialysisParameterCheck: dialysis_parameter_check,
  531. VascularAccessVerification: vascular_access_verification,
  532. PipelineConnectionCheck: pipeline_connection_check,
  533. DialysisItemDesc: dialysis_item_desc,
  534. DialysisParameterDesc: dialysis_parameter_desc,
  535. VascularAccessDesc: vascular_access_desc,
  536. PipelineConnectionDesc: pipeline_connection_desc,
  537. Collator: collator,
  538. Status: 1,
  539. CreatedTime: time.Now().Unix(),
  540. CheckDate: recordDate.Unix(),
  541. UpdatedTime: time.Now().Unix(),
  542. }
  543. _, check := service.FindDoubleCheckByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  544. if check.ID == 0 { //新增
  545. doubleCheck.FirstCheckTime = firstCheckDate
  546. doubleCheck.CheckTime = checkDate
  547. doubleCheck.Creater = creater
  548. doubleCheck.Modifier = modifier
  549. err := service.AddSigleDoubleCheck(&doubleCheck)
  550. if err == nil {
  551. c.ServeSuccessJSON(map[string]interface{}{
  552. "doubleCheck": &doubleCheck,
  553. })
  554. }
  555. } else { //修改
  556. doubleCheck.FirstCheckTime = firstCheckDate
  557. doubleCheck.CheckTime = checkDate
  558. doubleCheck.Creater = creater
  559. doubleCheck.Modifier = modifier
  560. doubleCheck.CreatedTime = check.CreatedTime
  561. doubleCheck.ID = check.ID
  562. err := service.UpdateDoubleCheck(&doubleCheck)
  563. if err == nil {
  564. c.ServeSuccessJSON(map[string]interface{}{
  565. "doubleCheck": &doubleCheck,
  566. })
  567. }
  568. }
  569. }
  570. func (c *DialysisAPIController) PostAcceptsAssessment() {
  571. id, _ := c.GetInt64("patient", 0)
  572. recordDateStr := c.GetString("record_date")
  573. way, _ := c.GetInt64("way", 0)
  574. consciousness, _ := c.GetInt64("consciousness", 0)
  575. appetite, _ := c.GetInt64("appetite", 0)
  576. condition, _ := c.GetInt64("condition", 0)
  577. posture, _ := c.GetInt64("posture")
  578. sick_condition, _ := c.GetInt64("sick_condition", 0)
  579. danger_level, _ := c.GetInt64("danger_level", 0)
  580. intake, _ := c.GetInt64("intake", 0)
  581. nutrition, _ := c.GetInt64("nutrition", 0)
  582. psychological_assessment, _ := c.GetInt64("psychological_assessment", 0)
  583. psychological_assessment_other := c.GetString("psychological_assessment_other")
  584. score := c.GetString("score")
  585. sick_condition_other := c.GetString("sick_condition_other")
  586. //precaution, _ := c.GetInt64("precaution", 0)
  587. precaution := c.GetString("precaution")
  588. precaution_other := c.GetString("precaution_other")
  589. psychological_other := c.GetString("psychological_other")
  590. admission_number := c.GetString("admission_number")
  591. tumble, _ := c.GetInt64("tumble")
  592. if id <= 0 {
  593. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  594. return
  595. }
  596. adminUserInfo := c.GetMobileAdminUserInfo()
  597. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  598. if patient.ID == 0 {
  599. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  600. return
  601. }
  602. //now := time.Now()
  603. //year, month, day := now.Date()
  604. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  605. //todayTimeStamp := today_time.Unix()
  606. if len(recordDateStr) == 0 {
  607. recordDateStr = time.Now().Format("2006-01-02")
  608. }
  609. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  610. if parseDateErr != nil {
  611. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  612. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  613. return
  614. }
  615. _, receiveTreatment := service.FindReceiveTreatmentAssesByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  616. receiveTreatmentAsses := models.ReceiveTreatmentAsses{
  617. UserOrgId: adminUserInfo.Org.Id,
  618. PatientId: id,
  619. RecordDate: recordDate.Unix(),
  620. Way: way,
  621. Consciousness: consciousness,
  622. Appetite: appetite,
  623. Condition: condition,
  624. SickCondition: sick_condition,
  625. DangerLevel: danger_level,
  626. Intake: intake,
  627. Nutrition: nutrition,
  628. PsychologicalAssessment: psychological_assessment,
  629. PsychologicalAssessmentOther: psychological_assessment_other,
  630. SickConditionOther: sick_condition_other,
  631. Posture: posture,
  632. CreatedTime: time.Now().Unix(),
  633. UpdateTime: time.Now().Unix(),
  634. Status: 1,
  635. Score: score,
  636. Precaution: precaution,
  637. PrecautionOther: precaution_other,
  638. PsychologicalOther: psychological_other,
  639. AdmissionNumber: admission_number,
  640. Tumble: tumble,
  641. }
  642. if receiveTreatment.ID == 0 { //新增
  643. receiveTreatmentAsses.Creater = adminUserInfo.AdminUser.Id
  644. err := service.AddSigleReceiveTreatmentAssesRecord(&receiveTreatmentAsses)
  645. if err == nil {
  646. c.ServeSuccessJSON(map[string]interface{}{
  647. "receiveTreatmentAsses": receiveTreatmentAsses,
  648. })
  649. }
  650. } else { //修改
  651. //if receiveTreatment.Creater != adminUserInfo.AdminUser.Id {
  652. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  653. // if getPermissionErr != nil {
  654. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  655. // return
  656. // } else if headNursePermission == nil {
  657. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  658. // return
  659. // }
  660. //}
  661. receiveTreatmentAsses.Creater = receiveTreatment.Creater
  662. receiveTreatmentAsses.CreatedTime = receiveTreatment.CreatedTime
  663. receiveTreatmentAsses.Modifier = adminUserInfo.AdminUser.Id
  664. receiveTreatmentAsses.ID = receiveTreatment.ID
  665. err := service.UpadateReceiveTreatmentAsses(&receiveTreatmentAsses)
  666. if err == nil {
  667. c.ServeSuccessJSON(map[string]interface{}{
  668. "receiveTreatmentAsses": receiveTreatmentAsses,
  669. })
  670. }
  671. }
  672. }
  673. func (c *DialysisAPIController) PostAssessmentAfterDislysis() {
  674. id, _ := c.GetInt64("patient", 0)
  675. recordDateStr := c.GetString("record_date")
  676. weightAfter, _ := c.GetFloat("weight_after", 0)
  677. additionalWeight, _ := c.GetFloat("additional_weight", 0)
  678. weightReduce, _ := c.GetFloat("weight_loss", 0)
  679. temperature, _ := c.GetFloat("temperature", 0)
  680. pulse_frequency, _ := c.GetFloat("pulse_frequency", 0)
  681. breathing_rate, _ := c.GetFloat("breathing_rate", 0)
  682. systolic_blood_pressure, _ := c.GetFloat("systolic_blood_pressure", 0)
  683. diastolic_blood_pressure, _ := c.GetFloat("diastolic_blood_pressure", 0)
  684. actual_ultrafiltration, _ := c.GetFloat("actual_ultrafiltration", 0)
  685. actual_displacement, _ := c.GetFloat("actual_displacement", 0)
  686. actualtreatHour, _ := c.GetInt64("actual_treatment_hour", 0)
  687. actualtreatmin, _ := c.GetInt64("actual_treatment_minute", 0)
  688. cruor := c.GetString("cruor")
  689. symptomsAfterDialysi := c.GetString("symptom_after_dialysis")
  690. internalFistula := c.GetString("internal_fistula")
  691. catheter := c.GetString("catheter")
  692. complications := c.GetString("complication")
  693. remark := c.GetString("remark")
  694. dialysateVolume, _ := c.GetInt64("dialysis_intakes", 0)
  695. dialysis_intakes_unit, _ := c.GetInt64("dialysis_intakes_unit", 0)
  696. blood_access_part_id, _ := c.GetInt64("blood_access_part_id", 0)
  697. blood_access_part_opera_id, _ := c.GetInt64("blood_access_part_opera_id", 0)
  698. puncturePointOozingBlood, _ := c.GetInt64("puncture_point_oozing_blood", 0)
  699. puncturePointHaematoma, _ := c.GetInt64("puncture_point_haematoma", 0)
  700. internalFistulaTremorAc, _ := c.GetInt64("internal_fistula_tremor_ac", 0)
  701. patientGose, _ := c.GetInt64("patient_gose", 0)
  702. inpatientDepartment := c.GetString("inpatient_department")
  703. observationContent := c.GetString("observation_content")
  704. observationContentOther := c.GetString("observation_content_other")
  705. dialysis_process, _ := c.GetInt64("dialysis_process", 0)
  706. in_advance_minute, _ := c.GetFloat("in_advance_minute", 0)
  707. in_advance_reason := c.GetString("in_advance_reason")
  708. hemostasis_minute, _ := c.GetInt64("hemostasis_minute", 0)
  709. hemostasis_opera, _ := c.GetInt64("hemostasis_opera", 0)
  710. tremor_noise, _ := c.GetInt64("tremor_noise", 0)
  711. disequilibrium_syndrome, _ := c.GetInt64("disequilibrium_syndrome", 0)
  712. disequilibrium_syndrome_option := c.GetString("disequilibrium_syndrome_option")
  713. arterial_tube, _ := c.GetInt64("arterial_tube", 0)
  714. intravenous_tube, _ := c.GetInt64("intravenous_tube", 0)
  715. dialyzer, _ := c.GetInt64("dialyzer", 0)
  716. in_advance_reason_other := c.GetString("in_advance_reason_other")
  717. is_eat, _ := c.GetInt64("is_eat", 0)
  718. cvc_a, _ := c.GetFloat("cvc_a", 0)
  719. cvc_v, _ := c.GetFloat("cvc_v", 0)
  720. channels, _ := c.GetInt64("channel", 0)
  721. return_blood, _ := c.GetInt64("return_blood", 0)
  722. rehydration_volume, _ := c.GetInt64("rehydration_volume", 0)
  723. dialysis_during, _ := c.GetInt64("dialysis_during", 0)
  724. stroke_volume, _ := c.GetInt64("stroke_volume", 0)
  725. blood_flow, _ := c.GetInt64("blood_flow", 0)
  726. //sealing_fluid_dispose, _ := c.GetInt64("sealing_fluid_dispose", 0)
  727. sealing_fluid_dispose := c.GetString("sealing_fluid_dispose")
  728. sealing_fluid_special := c.GetString("sealing_fluid_special")
  729. dosage_of_anticoagulants, _ := c.GetFloat("dosage_of_anticoagulants")
  730. supine_systolic_blood_pressure := c.GetString("supine_systolic_blood_pressure")
  731. setting_pressure := c.GetString("setting_pressure")
  732. supine_diastolic_blood_pressure := c.GetString("supine_diastolic_blood_pressure")
  733. diastolic_pressure := c.GetString("diastolic_pressure")
  734. other_complication := c.GetString("other_complication")
  735. ktv := c.GetString("ktv")
  736. urr := c.GetString("urr")
  737. hypertenison, _ := c.GetInt64("hypertenison")
  738. hypopiesia, _ := c.GetInt64("hypopiesia")
  739. leave_office_method, _ := c.GetInt64("leave_office_method")
  740. lapse, _ := c.GetInt64("lapse")
  741. consciousness, _ := c.GetInt64("consciousness")
  742. fallrisk, _ := c.GetInt64("fallrisk")
  743. machine_run := c.GetString("machine_run")
  744. if id <= 0 {
  745. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  746. return
  747. }
  748. adminUserInfo := c.GetMobileAdminUserInfo()
  749. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  750. if patient.ID == 0 {
  751. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  752. return
  753. }
  754. if len(recordDateStr) == 0 {
  755. recordDateStr = time.Now().Format("2006-01-02")
  756. }
  757. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  758. if parseDateErr != nil {
  759. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  760. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  761. return
  762. }
  763. //now := time.Now()
  764. //year, month, day := now.Date()
  765. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  766. //todayTimeStamp := today_time.Unix()
  767. //_, evaluation := service.FindPredialysisEvaluationByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  768. assessmentAfterDislysis := models.AssessmentAfterDislysis{
  769. UserOrgId: adminUserInfo.Org.Id,
  770. PatientId: id,
  771. AssessmentDate: recordDate.Unix(),
  772. Temperature: temperature,
  773. PulseFrequency: pulse_frequency,
  774. BreathingRate: breathing_rate,
  775. SystolicBloodPressure: systolic_blood_pressure,
  776. DiastolicBloodPressure: diastolic_blood_pressure,
  777. ActualUltrafiltration: actual_ultrafiltration,
  778. ActualDisplacement: actual_displacement,
  779. ActualTreatmentHour: actualtreatHour,
  780. ActualTreatmentMinute: actualtreatmin,
  781. WeightAfter: weightAfter,
  782. AdditionalWeight: additionalWeight,
  783. WeightLoss: weightReduce,
  784. Cruor: cruor,
  785. SymptomAfterDialysis: symptomsAfterDialysi,
  786. InternalFistula: internalFistula,
  787. Catheter: catheter,
  788. Complication: complications,
  789. DialysisIntakes: dialysateVolume,
  790. CreatedTime: time.Now().Unix(),
  791. Status: 1,
  792. Remark: remark,
  793. BloodAccessPartId: blood_access_part_id,
  794. BloodAccessPartOperaId: blood_access_part_opera_id,
  795. DialysisIntakesUnit: dialysis_intakes_unit,
  796. PuncturePointOozingBlood: puncturePointOozingBlood,
  797. PuncturePointHaematoma: puncturePointHaematoma,
  798. InternalFistulaTremorAc: internalFistulaTremorAc,
  799. PatientGose: patientGose,
  800. InpatientDepartment: inpatientDepartment,
  801. ObservationContent: observationContent,
  802. ObservationContentOther: observationContentOther,
  803. DialysisProcess: dialysis_process,
  804. InAdvanceMinute: in_advance_minute,
  805. InAdvanceReason: in_advance_reason,
  806. HemostasisMinute: hemostasis_minute,
  807. HemostasisOpera: hemostasis_opera,
  808. TremorNoise: tremor_noise,
  809. DisequilibriumSyndrome: disequilibrium_syndrome,
  810. DisequilibriumSyndromeOption: disequilibrium_syndrome_option,
  811. ArterialTube: arterial_tube,
  812. IntravenousTube: intravenous_tube,
  813. Dialyzer: dialyzer,
  814. InAdvanceReasonOther: in_advance_reason_other,
  815. IsEat: is_eat,
  816. CvcA: cvc_a,
  817. CvcV: cvc_v,
  818. Channel: channels,
  819. ReturnBlood: return_blood,
  820. RehydrationVolume: rehydration_volume,
  821. DialysisDuring: dialysis_during,
  822. StrokeVolume: stroke_volume,
  823. BloodFlow: blood_flow,
  824. SealingFluidDispose: sealing_fluid_dispose,
  825. SealingFluidSpecial: sealing_fluid_special,
  826. DosageOfAnticoagulants: dosage_of_anticoagulants,
  827. SupineDiastolicBloodPressure: supine_diastolic_blood_pressure,
  828. SupineSystolicBloodPressure: supine_systolic_blood_pressure,
  829. SettingPressure: setting_pressure,
  830. DiastolicPressure: diastolic_pressure,
  831. OtherComplication: other_complication,
  832. Ktv: ktv,
  833. Urr: urr,
  834. Hypopiesia: hypopiesia,
  835. Hypertenison: hypertenison,
  836. Lapse: lapse,
  837. LeaveOfficeMethod: leave_office_method,
  838. Consciousness: consciousness,
  839. Fallrisk: fallrisk,
  840. MachineRun: machine_run,
  841. }
  842. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  843. _, assessmentAfter := service.FindAssessmentAfterDislysisByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  844. if assessmentAfter.ID == 0 { //新增
  845. if appRole.UserType == 2 || appRole.UserType == 1 {
  846. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  847. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  848. } else {
  849. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  850. }
  851. err := service.AddSigleAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  852. if err == nil {
  853. c.ServeSuccessJSON(map[string]interface{}{
  854. "assessmentAfterDislysis": assessmentAfterDislysis,
  855. })
  856. }
  857. } else { //修改
  858. if appRole.UserType == 2 || appRole.UserType == 1 {
  859. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  860. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  861. } else {
  862. assessmentAfterDislysis.Modifier = adminUserInfo.AdminUser.Id
  863. if assessmentAfterDislysis.Creater == 0 {
  864. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  865. }
  866. }
  867. assessmentAfterDislysis.CreatedTime = assessmentAfter.CreatedTime
  868. assessmentAfterDislysis.ID = assessmentAfter.ID
  869. err := service.UpdateAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  870. if err == nil {
  871. c.ServeSuccessJSON(map[string]interface{}{
  872. "assessmentAfterDislysis": assessmentAfterDislysis,
  873. })
  874. }
  875. }
  876. }
  877. func (c *DialysisAPIController) PostDialysisPrescription() {
  878. id, _ := c.GetInt64("patient", 0)
  879. recordDateStr := c.GetString("record_date")
  880. if id <= 0 {
  881. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  882. return
  883. }
  884. adminUserInfo := c.GetMobileAdminUserInfo()
  885. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  886. if patient.ID == 0 {
  887. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  888. return
  889. }
  890. if len(recordDateStr) == 0 {
  891. recordDateStr = time.Now().Format("2006-01-02")
  892. }
  893. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  894. if parseDateErr != nil {
  895. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  896. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  897. return
  898. }
  899. mode_id, _ := c.GetInt64("mode_id", 0)
  900. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  901. dialyzer, _ := c.GetInt64("dialyzer", 0)
  902. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  903. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  904. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  905. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  906. replacement_total, _ := c.GetFloat("replacement_total", 0)
  907. replacement_way, _ := c.GetInt64("replacement_way", 0)
  908. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  909. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  910. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  911. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  912. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  913. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  914. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  915. kalium, _ := c.GetFloat("kalium", 0)
  916. sodium, _ := c.GetFloat("sodium", 0)
  917. calcium, _ := c.GetFloat("calcium", 0)
  918. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  919. glucose, _ := c.GetFloat("glucose", 0)
  920. // prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  921. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  922. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  923. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  924. conductivity, _ := c.GetFloat("conductivity", 0)
  925. remark := c.GetString("remark")
  926. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  927. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  928. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  929. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  930. body_fluid, _ := c.GetInt64("body_fluid", 0)
  931. special_medicine, _ := c.GetInt64("special_medicine", 0)
  932. special_medicine_other := c.GetString("special_medicine_other")
  933. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  934. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  935. blood_access, _ := c.GetInt64("blood_access", 0)
  936. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  937. body_fluid_other := c.GetString("body_fluid_other")
  938. niprocart, _ := c.GetInt64("niprocart", 0)
  939. jms, _ := c.GetInt64("jms", 0)
  940. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  941. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  942. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  943. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  944. filtryzer, _ := c.GetInt64("filtryzer", 0)
  945. target_ktv, _ := c.GetFloat("target_ktv", 0)
  946. dialyzers, _ := c.GetInt64("dialyzers", 0)
  947. injector, _ := c.GetInt64("injector", 0)
  948. bloodlines, _ := c.GetInt64("bloodlines", 0)
  949. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  950. safe_package, _ := c.GetInt64("package", 0)
  951. a_liquid, _ := c.GetInt64("a_liquid", 0)
  952. pre_impulse, parseDateErr := c.GetFloat("pre_impulse", 0)
  953. fmt.Println("预冲量", pre_impulse)
  954. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  955. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  956. blood := c.GetString("blood")
  957. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  958. dialysis_irrigation := c.GetString("dialysis_irrigation")
  959. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  960. displace_speed := c.GetString("displace_speed")
  961. illness, _ := c.GetInt64("illness")
  962. amylaceum := c.GetString("amylaceum")
  963. single_time := c.GetString("single_time")
  964. single_water := c.GetString("single_water")
  965. replacement_flow := c.GetString("replacement_flow")
  966. plasma_separator := c.GetString("plasma_separator")
  967. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  968. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  969. oxygen_flow := c.GetString("oxygen_flow")
  970. oxygen_time := c.GetString("oxygen_time")
  971. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  972. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  973. puncture_needle := c.GetString("puncture_needle")
  974. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  975. epo := c.GetString("epo")
  976. epo_count, _ := c.GetFloat("epo_count", 0)
  977. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  978. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  979. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  980. //
  981. //if template.TemplateId == 2 || template.TemplateId == 6 {
  982. // if appRole.UserType == 3 {
  983. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  984. // if getPermissionErr != nil {
  985. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  986. // return
  987. // } else if headNursePermission == nil {
  988. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  989. // return
  990. // }
  991. // }
  992. //}
  993. //TODO 需要根据角色去判断
  994. prescription := models.DialysisPrescription{
  995. UserOrgId: adminUserInfo.Org.Id,
  996. PatientId: id,
  997. RecordDate: recordDate.Unix(),
  998. ModeId: mode_id,
  999. DialysisDuration: dialysis_duration,
  1000. Dialyzer: dialyzer,
  1001. PerfusionApparatus: perfusion_apparatus,
  1002. BloodFlowVolume: blood_flow_volume,
  1003. DewaterAmount: dewater_amount,
  1004. DisplaceLiqui: displace_liqui,
  1005. ReplacementWay: replacement_way,
  1006. Anticoagulant: anticoagulant,
  1007. AnticoagulantShouji: anticoagulant_shouji,
  1008. AnticoagulantWeichi: anticoagulant_weichi,
  1009. AnticoagulantZongliang: anticoagulant_zongliang,
  1010. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1011. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1012. Kalium: kalium,
  1013. Sodium: sodium,
  1014. Calcium: calcium,
  1015. Bicarbonate: bicarbonate,
  1016. Glucose: glucose,
  1017. // DryWeight: dry_weight,
  1018. DialysateFlow: dialysate_flow,
  1019. DialysateTemperature: dialysate_temperature,
  1020. // PrescriptionDoctor: prescription_doctor,
  1021. ReplacementTotal: replacement_total,
  1022. Conductivity: conductivity,
  1023. Remark: remark,
  1024. Status: 1,
  1025. CreatedTime: time.Now().Unix(),
  1026. UpdatedTime: time.Now().Unix(),
  1027. DialysisDurationMinute: dialysisDurationMinute,
  1028. DialysisDurationHour: dialysisDurationHour,
  1029. TargetUltrafiltration: targetUltrafiltration,
  1030. DialysateFormulation: dialysateFormulation,
  1031. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1032. BodyFluid: body_fluid,
  1033. SpecialMedicine: special_medicine,
  1034. SpecialMedicineOther: special_medicine_other,
  1035. DisplaceLiquiPart: displace_liqui_part,
  1036. DisplaceLiquiValue: displace_liqui_value,
  1037. BloodAccess: blood_access,
  1038. Ultrafiltration: ultrafiltration,
  1039. BodyFluidOther: body_fluid_other,
  1040. Niprocart: niprocart,
  1041. Jms: jms,
  1042. FistulaNeedleSet: fistula_needle_set,
  1043. FistulaNeedleSet16: fistula_needle_set_16,
  1044. Hemoperfusion: hemoperfusion,
  1045. DialyserSterilised: dialyser_sterilised,
  1046. Filtryzer: filtryzer,
  1047. Dialyzers: dialyzers,
  1048. Injector: injector,
  1049. Bloodlines: bloodlines,
  1050. TubingHemodialysis: tubing_hemodialysis,
  1051. Package: safe_package,
  1052. ALiquid: a_liquid,
  1053. TargetKtv: target_ktv,
  1054. PreImpulse: pre_impulse,
  1055. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1056. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1057. Blood: blood,
  1058. DialysisDialyszers: dialysis_dialyszers,
  1059. DialysisIrrigation: dialysis_irrigation,
  1060. AntioxidantCommodityName: antioxidant_commodity_name,
  1061. DisplaceSpeed: displace_speed,
  1062. Illness: illness,
  1063. Amylaceum: amylaceum,
  1064. SingleTime: single_time,
  1065. SingleWater: single_water,
  1066. ReplacementFlow: replacement_flow,
  1067. PlasmaSeparator: plasma_separator,
  1068. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  1069. OxygenUptake: oxygen_uptake,
  1070. OxygenFlow: oxygen_flow,
  1071. OxygenTime: oxygen_time,
  1072. HemodialysisPipelines: hemodialysis_pipelines,
  1073. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  1074. PunctureNeedle: puncture_needle,
  1075. PunctureNeedleCount: puncture_needle_count,
  1076. Epo: epo,
  1077. EpoCount: epo_count,
  1078. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  1079. }
  1080. //查询最近透析准备表里是否存在 透析器 灌流器
  1081. //
  1082. //splitStr := strings.Split(dialysis_dialyszers, ",")
  1083. //
  1084. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  1085. //
  1086. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  1087. //if len(mation)>0{
  1088. // for _, item := range splitStr {
  1089. // for _,it := range mation{
  1090. // if(item == it.SpecificationName){
  1091. //
  1092. // //查询最近一次的透析器
  1093. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1094. //
  1095. // if errcode == gorm.ErrRecordNotFound{
  1096. // //插入数据
  1097. // prepare := models.DialysisBeforePrepare{
  1098. // UserOrgId: adminUserInfo.Org.Id,
  1099. // PatientId: id,
  1100. // RecordDate: recordDate.Unix(),
  1101. // GoodTypeId: it.GoodTypeId,
  1102. // GoodId: it.ID,
  1103. // Count: 1,
  1104. // Ctime: time.Now().Unix(),
  1105. // Creater: adminUserInfo.AdminUser.Id,
  1106. // Status:1,
  1107. //
  1108. // }
  1109. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1110. // fmt.Println("",errcode)
  1111. // }
  1112. // }
  1113. // }
  1114. //
  1115. // }
  1116. //
  1117. // for _, item := range splitIrrigation {
  1118. // for _,it := range mation{
  1119. // if(item == it.SpecificationName){
  1120. // //查询最近一次的透析器
  1121. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1122. // if errcode == gorm.ErrRecordNotFound{
  1123. // //插入数据
  1124. // prepare := models.DialysisBeforePrepare{
  1125. // UserOrgId: adminUserInfo.Org.Id,
  1126. // PatientId: id,
  1127. // RecordDate: recordDate.Unix(),
  1128. // GoodTypeId: it.GoodTypeId,
  1129. // GoodId: it.ID,
  1130. // Count: 1,
  1131. // Ctime: time.Now().Unix(),
  1132. // Creater: adminUserInfo.AdminUser.Id,
  1133. // Status:1,
  1134. //
  1135. // }
  1136. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1137. // fmt.Println(errcode)
  1138. // }
  1139. // }
  1140. // }
  1141. // }
  1142. //}
  1143. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1144. if dialysisPrescription.ID == 0 { //新增
  1145. //if mode_id > 0 {
  1146. // //service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1147. //}
  1148. if appRole.UserType == 2 || appRole.UserType == 1 {
  1149. prescription.PrescriptionDoctor = adminUserInfo.AdminUser.Id
  1150. }
  1151. prescription.Creater = adminUserInfo.AdminUser.Id
  1152. err := service.AddSigleRecord(&prescription)
  1153. if err == nil {
  1154. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1155. if updateErr != nil {
  1156. utils.ErrorLog("%v", updateErr)
  1157. }
  1158. c.ServeSuccessJSON(map[string]interface{}{
  1159. "prescription": prescription,
  1160. })
  1161. }
  1162. } else { //修改
  1163. //if mode_id > 0 {
  1164. // service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1165. //}
  1166. //if template.TemplateId == 1 {
  1167. // if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater != 0 {
  1168. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1169. // if getPermissionErr != nil {
  1170. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1171. // return
  1172. // } else if headNursePermission == nil {
  1173. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1174. // return
  1175. // }
  1176. // }
  1177. //}
  1178. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1179. prescription.Modifier = adminUserInfo.AdminUser.Id
  1180. if appRole.UserType == 2 || appRole.UserType == 1 {
  1181. prescription_doctor := adminUserInfo.AdminUser.Id
  1182. prescription.PrescriptionDoctor = prescription_doctor
  1183. } else {
  1184. prescription.PrescriptionDoctor = dialysisPrescription.PrescriptionDoctor
  1185. }
  1186. if dialysisPrescription.Creater == 0 { //体重称
  1187. prescription.Creater = adminUserInfo.AdminUser.Id
  1188. } else {
  1189. prescription.Creater = dialysisPrescription.Creater
  1190. }
  1191. prescription.ID = dialysisPrescription.ID
  1192. err := service.UpDateDialysisPrescription(&prescription)
  1193. if err == nil {
  1194. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1195. if updateErr != nil {
  1196. utils.ErrorLog("%v", updateErr)
  1197. }
  1198. c.ServeSuccessJSON(map[string]interface{}{
  1199. "prescription": prescription,
  1200. })
  1201. }
  1202. }
  1203. }
  1204. func (c *DialysisAPIController) Finish() {
  1205. id, _ := c.GetInt64("patient", 0)
  1206. recordDateStr := c.GetString("record_date")
  1207. nurseID, _ := c.GetInt64("nurse")
  1208. end_time := c.GetString("end_time")
  1209. if id <= 0 || nurseID <= 0 {
  1210. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1211. return
  1212. }
  1213. adminUserInfo := c.GetMobileAdminUserInfo()
  1214. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1215. if patient.ID == 0 {
  1216. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1217. return
  1218. }
  1219. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1220. if getNurseErr != nil {
  1221. c.ErrorLog("获取护士失败:%v", getNurseErr)
  1222. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1223. return
  1224. } else if nurse == nil {
  1225. c.ErrorLog("护士不存在")
  1226. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1227. return
  1228. }
  1229. if len(recordDateStr) == 0 {
  1230. recordDateStr = time.Now().Format("2006-01-02")
  1231. }
  1232. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1233. if parseDateErr != nil {
  1234. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1235. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1236. return
  1237. }
  1238. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  1239. if parseEndDateErr != nil {
  1240. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  1241. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1242. return
  1243. }
  1244. //now := time.Now()
  1245. //year, month, day := now.Date()
  1246. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  1247. //todayTimeStamp := today_time.Unix()
  1248. // 获取当天的第一条透析纪录
  1249. fmonitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecordFirst(adminUserInfo.Org.Id, id, recordDate.Unix())
  1250. if getMonitorRecordsErr != nil {
  1251. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1252. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1253. return
  1254. }
  1255. // 获取当前的最后一条透析纪录
  1256. endmonitorRecords, getMonitorRecordsErr := service.MobileGetLastMonitorRecord(adminUserInfo.Org.Id, id, recordDate.Unix())
  1257. if getMonitorRecordsErr != nil {
  1258. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1259. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1260. return
  1261. }
  1262. fmt.Println(endmonitorRecords.UltrafiltrationVolume)
  1263. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1264. if getAADErr != nil {
  1265. c.ErrorLog("获取透后评估失败:%v", getAADErr)
  1266. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1267. return
  1268. }
  1269. lastAssessmentAfterDislysis, _ := service.MobileGetLastTimeAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1270. _, dialysisOrder := service.FindDialysisRecordById(adminUserInfo.Org.Id, id, recordDate.Unix())
  1271. var tempassessmentAfterDislysis models.AssessmentAfterDislysis
  1272. if assessmentAfterDislysis != nil {
  1273. tempassessmentAfterDislysis = *assessmentAfterDislysis
  1274. tempassessmentAfterDislysis.UpdatedTime = time.Now().Unix()
  1275. } else {
  1276. tempassessmentAfterDislysis.CreatedTime = time.Now().Unix()
  1277. tempassessmentAfterDislysis.AssessmentDate = recordDate.Unix()
  1278. tempassessmentAfterDislysis.Status = 1
  1279. tempassessmentAfterDislysis.PatientId = id
  1280. tempassessmentAfterDislysis.UserOrgId = adminUserInfo.Org.Id
  1281. }
  1282. if dialysisOrder.Stage == 1 {
  1283. temp_time := (float64(endDate.Unix()) - float64(dialysisOrder.StartTime)) / 3600
  1284. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  1285. fmt.Println(value)
  1286. a, b := math.Modf(value)
  1287. c, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  1288. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  1289. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", c*60), 10, 64)
  1290. fmt.Println(hour)
  1291. fmt.Println(minute)
  1292. tempassessmentAfterDislysis.ActualTreatmentHour = hour
  1293. tempassessmentAfterDislysis.ActualTreatmentMinute = minute
  1294. }
  1295. if fmonitorRecords.ID > 0 && endmonitorRecords.ID > 0 {
  1296. //var num1 int64
  1297. //num1 = endmonitorRecords.OperateTime - fmonitorRecords.OperateTime
  1298. //fmt.Println(num1)
  1299. //sub := float64(num1 / 3600)
  1300. //fmt.Println(sub)
  1301. //tempassessmentAfterDislysis.ActualTreatmentHour = int64(math.Floor(sub))
  1302. //sub2 := float64(((endmonitorRecords.OperateTime - fmonitorRecords.OperateTime) % 3600) / 60)
  1303. //tempassessmentAfterDislysis.ActualTreatmentMinute = int64(math.Floor(sub2))
  1304. tempassessmentAfterDislysis.Temperature = endmonitorRecords.Temperature
  1305. tempassessmentAfterDislysis.PulseFrequency = endmonitorRecords.PulseFrequency
  1306. tempassessmentAfterDislysis.BreathingRate = endmonitorRecords.BreathingRate
  1307. tempassessmentAfterDislysis.SystolicBloodPressure = endmonitorRecords.SystolicBloodPressure
  1308. tempassessmentAfterDislysis.DiastolicBloodPressure = endmonitorRecords.DiastolicBloodPressure
  1309. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1310. tempassessmentAfterDislysis.ActualDisplacement = endmonitorRecords.DisplacementQuantity
  1311. }
  1312. if adminUserInfo.Org.Id == 10101 || adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 3877 {
  1313. evaluation, _ := service.MobileGetPredialysisEvaluation(adminUserInfo.Org.Id, id, recordDate.Unix())
  1314. if evaluation.SystolicBloodPressure == 0 {
  1315. evaluation.SystolicBloodPressure = fmonitorRecords.SystolicBloodPressure
  1316. pre := models.PredialysisEvaluation{
  1317. SystolicBloodPressure: evaluation.SystolicBloodPressure,
  1318. }
  1319. fmt.Println("prew", pre)
  1320. getNurseErr := service.UpdatePredialysisEvaluation(&pre, evaluation.ID)
  1321. fmt.Println(getNurseErr)
  1322. }
  1323. if evaluation.DiastolicBloodPressure == 0 {
  1324. evaluation.DiastolicBloodPressure = fmonitorRecords.DiastolicBloodPressure
  1325. pres := models.PredialysisEvaluation{
  1326. DiastolicBloodPressure: evaluation.DiastolicBloodPressure,
  1327. }
  1328. getNurseErr := service.UpdatePredialysisEvaluationTwo(&pres, evaluation.ID)
  1329. fmt.Println(getNurseErr)
  1330. }
  1331. if evaluation.PulseFrequency == 0 {
  1332. evaluation.PulseFrequency = fmonitorRecords.PulseFrequency
  1333. press := models.PredialysisEvaluation{
  1334. PulseFrequency: evaluation.PulseFrequency,
  1335. }
  1336. getNurseErr := service.UpdatePredialysisEvaluationThree(&press, evaluation.ID)
  1337. fmt.Println(getNurseErr)
  1338. }
  1339. }
  1340. if adminUserInfo.Org.Id == 9583 {
  1341. //获取透析处方的最后一条数据
  1342. diaPrescription, diaerr := service.GetLastDialysisPrescriptionByPatientId(adminUserInfo.Org.Id, id, recordDate.Unix())
  1343. if diaerr != nil {
  1344. c.ErrorLog("获取透析处方失败:%v", diaerr)
  1345. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1346. return
  1347. }
  1348. if diaPrescription.ID > 0 && adminUserInfo.Org.Id == 9583 {
  1349. tempassessmentAfterDislysis.ActualUltrafiltration = diaPrescription.TargetUltrafiltration
  1350. }
  1351. }
  1352. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10101 {
  1353. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume / 1000
  1354. }
  1355. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10060 {
  1356. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1357. }
  1358. if lastAssessmentAfterDislysis != nil {
  1359. tempassessmentAfterDislysis.BloodPressureType = lastAssessmentAfterDislysis.BloodPressureType
  1360. tempassessmentAfterDislysis.WeighingWay = lastAssessmentAfterDislysis.WeighingWay
  1361. tempassessmentAfterDislysis.Cruor = lastAssessmentAfterDislysis.Cruor
  1362. tempassessmentAfterDislysis.SymptomAfterDialysis = lastAssessmentAfterDislysis.SymptomAfterDialysis
  1363. tempassessmentAfterDislysis.InternalFistula = lastAssessmentAfterDislysis.InternalFistula
  1364. tempassessmentAfterDislysis.Catheter = lastAssessmentAfterDislysis.Catheter
  1365. tempassessmentAfterDislysis.Complication = lastAssessmentAfterDislysis.Complication
  1366. tempassessmentAfterDislysis.DialysisIntakes = lastAssessmentAfterDislysis.DialysisIntakes
  1367. tempassessmentAfterDislysis.DialysisIntakesFeed = lastAssessmentAfterDislysis.DialysisIntakesFeed
  1368. tempassessmentAfterDislysis.DialysisIntakesTransfusion = lastAssessmentAfterDislysis.DialysisIntakesTransfusion
  1369. tempassessmentAfterDislysis.DialysisIntakesBloodTransfusion = lastAssessmentAfterDislysis.DialysisIntakesBloodTransfusion
  1370. tempassessmentAfterDislysis.DialysisIntakesWashpipe = lastAssessmentAfterDislysis.DialysisIntakesWashpipe
  1371. tempassessmentAfterDislysis.BloodAccessPartId = lastAssessmentAfterDislysis.BloodAccessPartId
  1372. tempassessmentAfterDislysis.BloodAccessPartOperaId = lastAssessmentAfterDislysis.BloodAccessPartOperaId
  1373. tempassessmentAfterDislysis.PuncturePointOozingBlood = lastAssessmentAfterDislysis.PuncturePointOozingBlood
  1374. tempassessmentAfterDislysis.PuncturePointHaematoma = lastAssessmentAfterDislysis.PuncturePointHaematoma
  1375. tempassessmentAfterDislysis.InternalFistulaTremorAc = lastAssessmentAfterDislysis.InternalFistulaTremorAc
  1376. tempassessmentAfterDislysis.PatientGose = lastAssessmentAfterDislysis.PatientGose
  1377. tempassessmentAfterDislysis.InpatientDepartment = lastAssessmentAfterDislysis.InpatientDepartment
  1378. tempassessmentAfterDislysis.ObservationContent = lastAssessmentAfterDislysis.ObservationContent
  1379. tempassessmentAfterDislysis.ObservationContentOther = lastAssessmentAfterDislysis.ObservationContentOther
  1380. tempassessmentAfterDislysis.DryWeight = lastAssessmentAfterDislysis.DryWeight
  1381. tempassessmentAfterDislysis.DialysisProcess = lastAssessmentAfterDislysis.DialysisProcess
  1382. tempassessmentAfterDislysis.InAdvanceMinute = lastAssessmentAfterDislysis.InAdvanceMinute
  1383. tempassessmentAfterDislysis.InAdvanceReason = lastAssessmentAfterDislysis.InAdvanceReason
  1384. tempassessmentAfterDislysis.HemostasisMinute = lastAssessmentAfterDislysis.HemostasisMinute
  1385. tempassessmentAfterDislysis.HemostasisOpera = lastAssessmentAfterDislysis.HemostasisOpera
  1386. tempassessmentAfterDislysis.TremorNoise = lastAssessmentAfterDislysis.TremorNoise
  1387. tempassessmentAfterDislysis.DisequilibriumSyndrome = lastAssessmentAfterDislysis.DisequilibriumSyndrome
  1388. tempassessmentAfterDislysis.DisequilibriumSyndromeOption = lastAssessmentAfterDislysis.DisequilibriumSyndromeOption
  1389. tempassessmentAfterDislysis.ArterialTube = lastAssessmentAfterDislysis.ArterialTube
  1390. tempassessmentAfterDislysis.IntravenousTube = lastAssessmentAfterDislysis.IntravenousTube
  1391. tempassessmentAfterDislysis.Dialyzer = lastAssessmentAfterDislysis.Dialyzer
  1392. tempassessmentAfterDislysis.InAdvanceReasonOther = lastAssessmentAfterDislysis.InAdvanceReasonOther
  1393. tempassessmentAfterDislysis.IsEat = lastAssessmentAfterDislysis.IsEat
  1394. tempassessmentAfterDislysis.DialysisIntakesUnit = lastAssessmentAfterDislysis.DialysisIntakesUnit
  1395. tempassessmentAfterDislysis.CvcA = lastAssessmentAfterDislysis.CvcA
  1396. tempassessmentAfterDislysis.CvcV = lastAssessmentAfterDislysis.CvcV
  1397. tempassessmentAfterDislysis.Channel = lastAssessmentAfterDislysis.Channel
  1398. tempassessmentAfterDislysis.ReturnBlood = lastAssessmentAfterDislysis.ReturnBlood
  1399. tempassessmentAfterDislysis.RehydrationVolume = lastAssessmentAfterDislysis.RehydrationVolume
  1400. tempassessmentAfterDislysis.DialysisDuring = lastAssessmentAfterDislysis.DialysisDuring
  1401. tempassessmentAfterDislysis.StrokeVolume = lastAssessmentAfterDislysis.StrokeVolume
  1402. tempassessmentAfterDislysis.BloodFlow = lastAssessmentAfterDislysis.BloodFlow
  1403. tempassessmentAfterDislysis.SealingFluidDispose = lastAssessmentAfterDislysis.SealingFluidDispose
  1404. tempassessmentAfterDislysis.SealingFluidSpecial = lastAssessmentAfterDislysis.SealingFluidSpecial
  1405. }
  1406. err := service.UpdateAssessmentAfterDislysisRecord(&tempassessmentAfterDislysis)
  1407. if err != nil {
  1408. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1409. return
  1410. }
  1411. if dialysisOrder == nil {
  1412. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoStart)
  1413. return
  1414. }
  1415. if dialysisOrder.Stage == 2 {
  1416. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoEND)
  1417. return
  1418. }
  1419. if dialysisOrder.Stage == 1 {
  1420. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id)
  1421. //结束时候透析次数加1
  1422. service.UpdateSolutionByPatientId(id)
  1423. dialysisOrder.Stage = 2
  1424. dialysisOrder.FinishNurse = nurseID
  1425. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1426. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1427. dialysisOrder.EndTime = endDate.Unix()
  1428. go func() {
  1429. ssoDomain := beego.AppConfig.String("call_domain")
  1430. api := ssoDomain + "/index/downpatient"
  1431. values := make(url.Values)
  1432. values.Set("org_id", strconv.FormatInt(adminUserInfo.AdminUser.Id, 10))
  1433. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1434. values.Set("patient_id", strconv.FormatInt(id, 10))
  1435. http.PostForm(api, values)
  1436. }()
  1437. if err == nil {
  1438. c.ServeSuccessJSON(map[string]interface{}{
  1439. "dialysisOrder": dialysisOrder,
  1440. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1441. })
  1442. } else {
  1443. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1444. }
  1445. }
  1446. }
  1447. func (c *DialysisAPIController) GetAllZone() {
  1448. adminUserInfo := c.GetMobileAdminUserInfo()
  1449. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1450. if err == nil {
  1451. c.ServeSuccessJSON(map[string]interface{}{
  1452. "zone": zone,
  1453. })
  1454. }
  1455. }
  1456. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1457. adminUserInfo := c.GetMobileAdminUserInfo()
  1458. page, _ := c.GetInt64("page", 1)
  1459. limit, _ := c.GetInt64("limit", 10)
  1460. schedulType, _ := c.GetInt64("schedul_type", 0)
  1461. startTime, _ := c.GetInt64("schedul_time", 0)
  1462. partitionType, _ := c.GetInt64("partition_type", 0)
  1463. keywords := c.GetString("keywords")
  1464. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1465. if err == nil {
  1466. c.ServeSuccessJSON(map[string]interface{}{
  1467. "schedule": dialysisSchedule,
  1468. })
  1469. }
  1470. return
  1471. }
  1472. // /m/api/dialysis/start [post]
  1473. // @param patient_id:int
  1474. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1475. // @param nurse:int 上机护士
  1476. // @param bed:int 床位号
  1477. func (this *DialysisAPIController) StartDialysis() {
  1478. patientID, _ := this.GetInt64("patient_id")
  1479. recordDateStr := this.GetString("record_date")
  1480. nurseID, _ := this.GetInt64("nurse")
  1481. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1482. blood_drawing, _ := this.GetInt64("blood_drawing")
  1483. schedual_type, _ := this.GetInt64("schedual_type")
  1484. bedID, _ := this.GetInt64("bed")
  1485. start_time := this.GetString("start_time")
  1486. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1487. change_nurse, _ := this.GetInt64("change_nurse")
  1488. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1489. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1490. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1491. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1492. return
  1493. }
  1494. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1495. if parseStartDateErr != nil {
  1496. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1497. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1498. return
  1499. }
  1500. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1501. if parseErr != nil {
  1502. this.ErrorLog("时间解析失败:%v", parseErr)
  1503. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1504. return
  1505. }
  1506. adminUserInfo := this.GetMobileAdminUserInfo()
  1507. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1508. if getPatientErr != nil {
  1509. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1510. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1511. return
  1512. } else if patient == nil {
  1513. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1514. return
  1515. }
  1516. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1517. if getNurseErr != nil {
  1518. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1519. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1520. return
  1521. } else if nurse == nil {
  1522. this.ErrorLog("护士不存在")
  1523. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1524. return
  1525. }
  1526. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1527. //if getNurseErr != nil {
  1528. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  1529. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1530. // return
  1531. //} else if nurse == nil {
  1532. // this.ErrorLog("护士不存在")
  1533. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1534. // return
  1535. //}
  1536. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1537. if getDeviceNumberErr != nil {
  1538. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1539. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1540. return
  1541. } else if deviceNumber == nil {
  1542. this.ErrorLog("床位号不存在")
  1543. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1544. return
  1545. }
  1546. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1547. if getRecordErr != nil {
  1548. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1549. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1550. return
  1551. } else if dialysisRecord != nil {
  1552. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1553. return
  1554. }
  1555. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1556. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1557. timeLayout := "2006-01-02 15:04:05"
  1558. loc, _ := time.LoadLocation("Local")
  1559. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1560. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1561. schedulestartTime := theStartTime.Unix()
  1562. scheduleendTime := theEndTime.Unix()
  1563. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1564. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1565. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1566. //查询该床位是否有人用了
  1567. order, order_err := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1568. if err == gorm.ErrRecordNotFound { //空床位
  1569. // 修改了床位逻辑
  1570. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1571. if daySchedule.ID > 0 {
  1572. daySchedule.PartitionId = deviceNumber.ZoneID
  1573. daySchedule.BedId = bedID
  1574. daySchedule.ScheduleType = schedual_type
  1575. daySchedule.UpdatedTime = time.Now().Unix()
  1576. err := service.UpdateSchedule(&daySchedule)
  1577. if err != nil {
  1578. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1579. return
  1580. }
  1581. }
  1582. } else if err == nil {
  1583. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1584. if order_err == nil {
  1585. if order.ID > 0 { //该机位被其他人占用了
  1586. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1587. return
  1588. } else {
  1589. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1590. if daySchedule.ID > 0 {
  1591. daySchedule.PartitionId = deviceNumber.ZoneID
  1592. daySchedule.BedId = bedID
  1593. daySchedule.ScheduleType = schedual_type
  1594. daySchedule.UpdatedTime = time.Now().Unix()
  1595. err := service.UpdateSchedule(&daySchedule)
  1596. if err != nil {
  1597. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1598. return
  1599. }
  1600. }
  1601. }
  1602. } else if order_err == gorm.ErrRecordNotFound { //该床位没被占用
  1603. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1604. if daySchedule.ID > 0 {
  1605. daySchedule.PartitionId = deviceNumber.ZoneID
  1606. daySchedule.BedId = bedID
  1607. daySchedule.ScheduleType = schedual_type
  1608. daySchedule.UpdatedTime = time.Now().Unix()
  1609. err := service.UpdateSchedule(&daySchedule)
  1610. if err != nil {
  1611. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1612. return
  1613. }
  1614. }
  1615. }
  1616. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1617. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1618. return
  1619. }
  1620. } else if err != nil {
  1621. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1622. return
  1623. }
  1624. dialysisRecord = &models.DialysisOrder{
  1625. DialysisDate: recordDate.Unix(),
  1626. UserOrgId: adminUserInfo.Org.Id,
  1627. PatientId: patientID,
  1628. Stage: 1,
  1629. BedID: bedID,
  1630. StartNurse: nurseID,
  1631. Status: 1,
  1632. StartTime: startDate.Unix(),
  1633. CreatedTime: time.Now().Unix(),
  1634. UpdatedTime: time.Now().Unix(),
  1635. PunctureNurse: puncture_nurse,
  1636. Creator: adminUserInfo.AdminUser.Id,
  1637. Modifier: adminUserInfo.AdminUser.Id,
  1638. SchedualType: schedual_type,
  1639. WashpipeNurse: washpipe_nurse,
  1640. ChangeNurse: change_nurse,
  1641. DifficultPunctureNurse: difficult_puncture_nurse,
  1642. NewFistulaNurse: new_fistula_nurse,
  1643. }
  1644. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  1645. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1646. var tempdispose string
  1647. // 只针对中能建
  1648. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  1649. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  1650. }
  1651. var ultrafiltration_rate float64
  1652. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1653. //后期预增脱水量
  1654. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1655. fmt.Println(evaluation)
  1656. if prescription.ID > 0 {
  1657. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1658. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1659. if (template.TemplateId == 6 || template.TemplateId == 32) && adminUserInfo.Org.Id != 9671 { //adminUserInfo.Org.Id == 9538
  1660. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1661. }
  1662. //针对医师汇
  1663. if template.TemplateId == 6 {
  1664. dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  1665. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  1666. }
  1667. //针对监利大垸医院
  1668. if template.TemplateId == 41 {
  1669. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1670. fmt.Println("hhhh232332322323232332", ultrafiltration_rate)
  1671. }
  1672. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  1673. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1674. }
  1675. // 只针对方济医院
  1676. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  1677. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1678. ultrafiltration_rate = value
  1679. }
  1680. }
  1681. }
  1682. record := models.MonitoringRecord{
  1683. UserOrgId: adminUserInfo.Org.Id,
  1684. PatientId: patientID,
  1685. DialysisOrderId: dialysisRecord.ID,
  1686. MonitoringDate: schedulestartTime,
  1687. OperateTime: startDate.Unix(),
  1688. // MonitoringTime: recordTime,
  1689. MonitoringNurse: nurseID,
  1690. Dispose: tempdispose,
  1691. UltrafiltrationRate: ultrafiltration_rate,
  1692. UltrafiltrationVolume: 0,
  1693. Status: 1,
  1694. CreatedTime: time.Now().Unix(),
  1695. UpdatedTime: time.Now().Unix(),
  1696. }
  1697. //只针对广慈医院
  1698. if template.TemplateId == 26 || template.TemplateId == 25 || template.TemplateId == 28 || adminUserInfo.Org.Id == 9987 || adminUserInfo.Org.Id == 9526 || template.TemplateId == 32 {
  1699. // 查询病人是否有透前评估数据
  1700. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1701. //如果有数据就插入
  1702. if errcode == nil {
  1703. record.SystolicBloodPressure = befor.SystolicBloodPressure
  1704. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  1705. record.BreathingRate = befor.BreathingRate
  1706. record.PulseFrequency = befor.PulseFrequency
  1707. record.Temperature = befor.Temperature
  1708. }
  1709. }
  1710. // 如果当天有插入数据,则不再往透析纪录里插入数据
  1711. if newdialysisRecord.ID > 0 {
  1712. err := service.CreateMonitor(&record)
  1713. if err != nil {
  1714. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  1715. return
  1716. }
  1717. }
  1718. go func() {
  1719. ssoDomain := beego.AppConfig.String("call_domain")
  1720. api := ssoDomain + "/index/uppatient"
  1721. values := make(url.Values)
  1722. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  1723. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1724. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  1725. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  1726. http.PostForm(api, values)
  1727. }()
  1728. if createErr != nil {
  1729. this.ErrorLog("上机失败:%v", createErr)
  1730. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1731. return
  1732. }
  1733. this.ServeSuccessJSON(map[string]interface{}{
  1734. "dialysis_order": newdialysisRecord,
  1735. "monitor": record,
  1736. })
  1737. }
  1738. func (c *DialysisAPIController) PostSolution() {
  1739. id, _ := c.GetInt64("patient", 0)
  1740. recordDateStr := c.GetString("record_date")
  1741. if id <= 0 {
  1742. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1743. return
  1744. }
  1745. adminUserInfo := c.GetMobileAdminUserInfo()
  1746. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1747. if patient.ID == 0 {
  1748. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1749. return
  1750. }
  1751. if len(recordDateStr) == 0 {
  1752. recordDateStr = time.Now().Format("2006-01-02")
  1753. }
  1754. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1755. if parseDateErr != nil {
  1756. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1757. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1758. return
  1759. }
  1760. mode_id, _ := c.GetInt64("mode_id", 0)
  1761. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1762. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1763. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1764. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1765. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1766. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1767. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1768. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1769. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1770. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1771. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1772. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1773. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1774. kalium, _ := c.GetFloat("kalium", 0)
  1775. sodium, _ := c.GetFloat("sodium", 0)
  1776. calcium, _ := c.GetFloat("calcium", 0)
  1777. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1778. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1779. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1780. glucose, _ := c.GetFloat("glucose", 0)
  1781. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1782. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1783. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1784. conductivity, _ := c.GetFloat("conductivity", 0)
  1785. remark := c.GetString("remark")
  1786. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1787. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1788. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1789. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1790. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1791. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1792. special_medicine_other := c.GetString("special_medicine_other")
  1793. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1794. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1795. blood_access, _ := c.GetInt64("blood_access", 0)
  1796. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1797. body_fluid_other := c.GetString("body_fluid_other")
  1798. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1799. niprocart, _ := c.GetInt64("niprocart", 0)
  1800. jms, _ := c.GetInt64("jms", 0)
  1801. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1802. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1803. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1804. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1805. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1806. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1807. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1808. injector, _ := c.GetInt64("injector", 0)
  1809. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1810. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1811. safe_package, _ := c.GetInt64("package", 0)
  1812. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1813. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1814. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1815. blood := c.GetString("blood")
  1816. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  1817. dialysis_irrigation := c.GetString("dialysis_irrigation")
  1818. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  1819. displace_speed := c.GetString("displace_speed")
  1820. illness, _ := c.GetInt64("illness")
  1821. amylaceum := c.GetString("amylaceum")
  1822. single_time := c.GetString("single_time")
  1823. single_water := c.GetString("single_water")
  1824. replacement_flow := c.GetString("replacement_flow")
  1825. plasma_separator := c.GetString("plasma_separator")
  1826. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  1827. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  1828. oxygen_flow := c.GetString("oxygen_flow")
  1829. oxygen_time := c.GetString("oxygen_time")
  1830. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  1831. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  1832. puncture_needle := c.GetString("puncture_needle")
  1833. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  1834. epo := c.GetString("epo")
  1835. epo_count, _ := c.GetFloat("epo_count", 0)
  1836. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  1837. if mode_id > 0 {
  1838. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1839. }
  1840. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1841. //
  1842. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1843. // if appRole.UserType == 3 {
  1844. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1845. // if getPermissionErr != nil {
  1846. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1847. // return
  1848. // } else if headNursePermission == nil {
  1849. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1850. // return
  1851. // }
  1852. // }
  1853. //}
  1854. prescription := models.DialysisPrescription{
  1855. UserOrgId: adminUserInfo.Org.Id,
  1856. PatientId: id,
  1857. RecordDate: recordDate.Unix(),
  1858. ModeId: mode_id,
  1859. DialysisDuration: dialysis_duration,
  1860. Dialyzer: dialyzer,
  1861. PerfusionApparatus: perfusion_apparatus,
  1862. BloodFlowVolume: blood_flow_volume,
  1863. DewaterAmount: dewater_amount,
  1864. DisplaceLiqui: displace_liqui,
  1865. ReplacementWay: replacement_way,
  1866. Anticoagulant: anticoagulant,
  1867. AnticoagulantShouji: anticoagulant_shouji,
  1868. AnticoagulantWeichi: anticoagulant_weichi,
  1869. AnticoagulantZongliang: anticoagulant_zongliang,
  1870. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1871. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1872. Kalium: kalium,
  1873. Sodium: sodium,
  1874. Calcium: calcium,
  1875. Bicarbonate: bicarbonate,
  1876. Glucose: glucose,
  1877. // DryWeight: dry_weight,
  1878. DialysateFlow: dialysate_flow,
  1879. DialysateTemperature: dialysate_temperature,
  1880. Conductivity: conductivity,
  1881. Remark: remark,
  1882. Status: 1,
  1883. CreatedTime: time.Now().Unix(),
  1884. UpdatedTime: time.Now().Unix(),
  1885. DialysisDurationMinute: dialysisDurationMinute,
  1886. DialysisDurationHour: dialysisDurationHour,
  1887. TargetUltrafiltration: targetUltrafiltration,
  1888. DialysateFormulation: dialysateFormulation,
  1889. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1890. BodyFluid: body_fluid,
  1891. SpecialMedicine: special_medicine,
  1892. SpecialMedicineOther: special_medicine_other,
  1893. DisplaceLiquiPart: displace_liqui_part,
  1894. DisplaceLiquiValue: displace_liqui_value,
  1895. BloodAccess: blood_access,
  1896. Ultrafiltration: ultrafiltration,
  1897. BodyFluidOther: body_fluid_other,
  1898. ReplacementTotal: replacement_total,
  1899. Niprocart: niprocart,
  1900. Jms: jms,
  1901. FistulaNeedleSet: fistula_needle_set,
  1902. FistulaNeedleSet16: fistula_needle_set_16,
  1903. Hemoperfusion: hemoperfusion,
  1904. DialyserSterilised: dialyser_sterilised,
  1905. Filtryzer: filtryzer,
  1906. TargetKtv: target_ktv,
  1907. Dialyzers: dialyzers,
  1908. Injector: injector,
  1909. Bloodlines: bloodlines,
  1910. TubingHemodialysis: tubing_hemodialysis,
  1911. Package: safe_package,
  1912. ALiquid: a_liquid,
  1913. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1914. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1915. Blood: blood,
  1916. DialysisDialyszers: dialysis_dialyszers,
  1917. DialysisIrrigation: dialysis_irrigation,
  1918. AntioxidantCommodityName: antioxidant_commodity_name,
  1919. DisplaceSpeed: displace_speed,
  1920. Illness: illness,
  1921. Amylaceum: amylaceum,
  1922. SingleWater: single_water,
  1923. SingleTime: single_time,
  1924. ReplacementFlow: replacement_flow,
  1925. PlasmaSeparator: plasma_separator,
  1926. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  1927. OxygenUptake: oxygen_uptake,
  1928. OxygenTime: oxygen_time,
  1929. OxygenFlow: oxygen_flow,
  1930. HemodialysisPipelines: hemodialysis_pipelines,
  1931. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  1932. PunctureNeedle: puncture_needle,
  1933. PunctureNeedleCount: puncture_needle_count,
  1934. Epo: epo,
  1935. EpoCount: epo_count,
  1936. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  1937. }
  1938. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1939. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1940. //
  1941. if appRole.UserType == 2 || appRole.UserType == 1 {
  1942. prescription_doctor = adminUserInfo.AdminUser.Id
  1943. prescription.PrescriptionDoctor = prescription_doctor
  1944. }
  1945. if dialysisPrescription.ID == 0 { //新增
  1946. prescription.Creater = adminUserInfo.AdminUser.Id
  1947. } else { //修改
  1948. if dialysisPrescription.Creater == 0 {
  1949. prescription.Creater = adminUserInfo.AdminUser.Id
  1950. } else {
  1951. prescription.Creater = dialysisPrescription.Creater
  1952. }
  1953. //if/**/
  1954. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1955. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  1956. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1957. // if getPermissionErr != nil {
  1958. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1959. // return
  1960. // } else if headNursePermission == nil {
  1961. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1962. // return
  1963. // }
  1964. //}
  1965. //prescription.Creater = dialysisPrescription.Creater
  1966. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1967. prescription.Modifier = adminUserInfo.AdminUser.Id
  1968. prescription.ID = dialysisPrescription.ID
  1969. }
  1970. solution := models.DialysisSolution{
  1971. RegistrarsId: adminUserInfo.AdminUser.Id,
  1972. UserOrgId: adminUserInfo.Org.Id,
  1973. Doctor: prescription_doctor,
  1974. PatientId: id,
  1975. ModeId: mode_id,
  1976. DialysisDuration: dialysis_duration,
  1977. PerfusionApparatus: perfusion_apparatus,
  1978. BloodFlowVolume: blood_flow_volume,
  1979. Dewater: dewater_amount,
  1980. DisplaceLiqui: displace_liqui,
  1981. ReplacementWay: replacement_way,
  1982. Anticoagulant: anticoagulant,
  1983. AnticoagulantShouji: anticoagulant_shouji,
  1984. AnticoagulantWeichi: anticoagulant_weichi,
  1985. AnticoagulantZongliang: anticoagulant_zongliang,
  1986. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1987. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1988. Kalium: kalium,
  1989. Sodium: sodium,
  1990. Calcium: calcium,
  1991. Bicarbonate: bicarbonate,
  1992. Glucose: glucose,
  1993. // DryWeight: dry_weight,
  1994. DialysateFlow: dialysate_flow,
  1995. DialysateTemperature: dialysate_temperature,
  1996. Conductivity: conductivity,
  1997. Remark: remark,
  1998. Status: 1,
  1999. CreatedTime: time.Now().Unix(),
  2000. UpdatedTime: time.Now().Unix(),
  2001. DialysisDurationMinute: dialysisDurationMinute,
  2002. DialysisDurationHour: dialysisDurationHour,
  2003. TargetUltrafiltration: targetUltrafiltration,
  2004. DialysateFormulation: dialysateFormulation,
  2005. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2006. BodyFluid: body_fluid,
  2007. SpecialMedicine: special_medicine,
  2008. SpecialMedicineOther: special_medicine_other,
  2009. DisplaceLiquiPart: displace_liqui_part,
  2010. DisplaceLiquiValue: displace_liqui_value,
  2011. BloodAccess: blood_access,
  2012. Ultrafiltration: ultrafiltration,
  2013. BodyFluidOther: body_fluid_other,
  2014. ReplacementTotal: replacement_total,
  2015. TargetKtv: target_ktv,
  2016. DialysisDialyszers: dialysis_dialyszers,
  2017. DialysisIrrigation: dialysis_irrigation,
  2018. HemodialysisPipelines: hemodialysis_pipelines,
  2019. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2020. PunctureNeedle: puncture_needle,
  2021. PunctureNeedleCount: puncture_needle_count,
  2022. Epo: epo,
  2023. EpoCount: epo_count,
  2024. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2025. }
  2026. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  2027. //查询最近透析准备表里是否存在 透析器 灌流器
  2028. //splitStr := strings.Split(dialysis_dialyszers, ",")
  2029. //
  2030. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  2031. //
  2032. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  2033. //if len(mation)>0{
  2034. // for _, item := range splitStr {
  2035. // for _,it := range mation{
  2036. // if(item == it.SpecificationName){
  2037. //
  2038. // //查询最近一次的透析器
  2039. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2040. //
  2041. // if errcode == gorm.ErrRecordNotFound{
  2042. // //插入数据
  2043. // prepare := models.DialysisBeforePrepare{
  2044. // UserOrgId: adminUserInfo.Org.Id,
  2045. // PatientId: id,
  2046. // RecordDate: recordDate.Unix(),
  2047. // GoodTypeId: it.GoodTypeId,
  2048. // GoodId: it.ID,
  2049. // Count: 1,
  2050. // Ctime: time.Now().Unix(),
  2051. // Creater: adminUserInfo.AdminUser.Id,
  2052. // Status:1,
  2053. //
  2054. // }
  2055. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2056. // fmt.Println("",errcode)
  2057. // }
  2058. // }
  2059. // }
  2060. //
  2061. // }
  2062. //
  2063. // for _, item := range splitIrrigation {
  2064. // for _,it := range mation{
  2065. // if(item == it.SpecificationName){
  2066. // //查询最近一次的透析器
  2067. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2068. // if errcode == gorm.ErrRecordNotFound{
  2069. // //插入数据
  2070. // prepare := models.DialysisBeforePrepare{
  2071. // UserOrgId: adminUserInfo.Org.Id,
  2072. // PatientId: id,
  2073. // RecordDate: recordDate.Unix(),
  2074. // GoodTypeId: it.GoodTypeId,
  2075. // GoodId: it.ID,
  2076. // Count: 1,
  2077. // Ctime: time.Now().Unix(),
  2078. // Creater: adminUserInfo.AdminUser.Id,
  2079. // Status:1,
  2080. //
  2081. // }
  2082. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2083. // fmt.Println(errcode)
  2084. // }
  2085. // }
  2086. // }
  2087. // }
  2088. //}
  2089. c.ServeSuccessJSON(map[string]interface{}{
  2090. "solution": &solution,
  2091. "prescription": &prescription,
  2092. })
  2093. }
  2094. func (c *DialysisAPIController) GetAcceptsAssessment() {
  2095. patient, _ := c.GetInt64("patient", 0)
  2096. adminUserInfo := c.GetMobileAdminUserInfo()
  2097. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  2098. c.ServeSuccessJSON(map[string]interface{}{
  2099. "receiveTreatmentAsses": receiveTreatmentAsses,
  2100. })
  2101. }
  2102. func (this *DialysisAPIController) PostSignInfo() {
  2103. patientID, _ := this.GetInt64("patient_id")
  2104. recordDateStr := this.GetString("date")
  2105. if patientID <= 0 {
  2106. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2107. return
  2108. }
  2109. if len(recordDateStr) == 0 {
  2110. recordDateStr = time.Now().Format("2006-01-02")
  2111. }
  2112. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2113. if parseDateErr != nil {
  2114. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2115. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2116. return
  2117. }
  2118. adminInfo := this.GetMobileAdminUserInfo()
  2119. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  2120. if err != nil {
  2121. this.ErrorLog("签名失败:%v", err)
  2122. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2123. return
  2124. }
  2125. this.ServeSuccessJSON(map[string]interface{}{
  2126. "doctor_id": adminInfo.AdminUser.Id,
  2127. })
  2128. }
  2129. func (this *DialysisAPIController) GetLastMonitorRecord() {
  2130. patientID, _ := this.GetInt64("patient_id")
  2131. adminInfo := this.GetMobileAdminUserInfo()
  2132. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  2133. this.ServeSuccessJSON(map[string]interface{}{
  2134. "monitor": record,
  2135. })
  2136. }
  2137. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  2138. thisTime := time.Now()
  2139. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  2140. timeLayout := "2006-01-02 15:04:05"
  2141. loc, _ := time.LoadLocation("Local")
  2142. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2143. theAssessmentDateTime := theStartTime.Unix()
  2144. patientID, _ := this.GetInt64("patient_id")
  2145. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  2146. adminInfo := this.GetMobileAdminUserInfo()
  2147. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2148. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2149. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  2150. var ultrafiltration_rate float64
  2151. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2152. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2153. fmt.Println(evaluation)
  2154. if prescription.ID > 0 {
  2155. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2156. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2157. if template.TemplateId == 6 && adminInfo.Org.Id != 9538 {
  2158. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2159. record.UltrafiltrationRate = ultrafiltration_rate
  2160. }
  2161. //if template.TemplateId == 6 && adminInfo.Org.Id ==9671{
  2162. // dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  2163. // ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  2164. // record.UltrafiltrationRate = ultrafiltration_rate
  2165. //}
  2166. if template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 {
  2167. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1)
  2168. record.UltrafiltrationRate = ultrafiltration_rate
  2169. }
  2170. if template.TemplateId == 20 || template.TemplateId == 22 {
  2171. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2172. record.UltrafiltrationRate = ultrafiltration_rate
  2173. }
  2174. // 只针对方济医院
  2175. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  2176. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2177. ultrafiltration_rate = value
  2178. record.UltrafiltrationRate = ultrafiltration_rate
  2179. }
  2180. if template.TemplateId == 41 {
  2181. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2182. record.UltrafiltrationRate = ultrafiltration_rate
  2183. }
  2184. }
  2185. }
  2186. // record.UltrafiltrationRate = ultrafiltration_rate
  2187. record.UltrafiltrationVolume = 0
  2188. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 { //adminInfo.Org.Id == 3907 || adminInfo.Org.Id == 4 || adminInfo.Org.Id == 12 || adminInfo.Org.Id == 13 || adminInfo.Org.Id == 9535adminInfo.Org.Id == 3907 || adminInfo.Org.Id == 4 || adminInfo.Org.Id == 12 || adminInfo.Org.Id == 13 || adminInfo.Org.Id == 9535
  2189. if ultrafiltration_rate > 0 {
  2190. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  2191. record.UltrafiltrationVolume = value
  2192. }
  2193. }
  2194. if template.TemplateId == 6 || template.TemplateId == 20 || template.TemplateId == 22 || template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 || template.TemplateId == 41 { //adminInfo.Org.Id == 9538
  2195. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  2196. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2197. record.UltrafiltrationVolume = ultrafiltration_volume
  2198. }
  2199. }
  2200. this.ServeSuccessJSON(map[string]interface{}{
  2201. "monitor": record,
  2202. })
  2203. }
  2204. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  2205. record_id, _ := this.GetInt64("id")
  2206. nurseID, _ := this.GetInt64("nurse")
  2207. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  2208. bedID, _ := this.GetInt64("bed")
  2209. start_time := this.GetString("start_time")
  2210. schedual_type, _ := this.GetInt64("schedual_type")
  2211. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  2212. change_nurse, _ := this.GetInt64("change_nurse")
  2213. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  2214. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  2215. if record_id == 0 {
  2216. this.ErrorLog("id:%v", record_id)
  2217. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2218. return
  2219. }
  2220. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  2221. if parseStartDateErr != nil {
  2222. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  2223. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2224. return
  2225. }
  2226. adminUserInfo := this.GetMobileAdminUserInfo()
  2227. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2228. if getNurseErr != nil {
  2229. this.ErrorLog("获取护士失败:%v", getNurseErr)
  2230. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2231. return
  2232. } else if nurse == nil {
  2233. this.ErrorLog("护士不存在")
  2234. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2235. return
  2236. }
  2237. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  2238. //if getNurseErr != nil {
  2239. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  2240. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2241. // return
  2242. //} else if nurse == nil {
  2243. // this.ErrorLog("护士不存在")
  2244. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2245. // return
  2246. //}
  2247. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  2248. if getDeviceNumberErr != nil {
  2249. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  2250. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2251. return
  2252. } else if deviceNumber == nil {
  2253. this.ErrorLog("床位号不存在")
  2254. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2255. return
  2256. }
  2257. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  2258. //
  2259. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  2260. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2261. // if getPermissionErr != nil {
  2262. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2263. // return
  2264. // } else if headNursePermission == nil {
  2265. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2266. // return
  2267. // }
  2268. //}
  2269. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  2270. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  2271. timeLayout := "2006-01-02 15:04:05"
  2272. loc, _ := time.LoadLocation("Local")
  2273. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2274. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  2275. schedulestartTime := theStartTime.Unix()
  2276. scheduleendTime := theEndTime.Unix()
  2277. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  2278. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2279. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2280. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  2281. if err == gorm.ErrRecordNotFound { //空床位
  2282. // 修改了床位逻辑
  2283. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2284. if daySchedule.ID > 0 {
  2285. daySchedule.BedId = bedID
  2286. daySchedule.PartitionId = deviceNumber.ZoneID
  2287. daySchedule.ScheduleType = schedual_type
  2288. daySchedule.UpdatedTime = time.Now().Unix()
  2289. err := service.UpdateSchedule(&daySchedule)
  2290. if err != nil {
  2291. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2292. return
  2293. }
  2294. }
  2295. } else if err == nil {
  2296. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  2297. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2298. if daySchedule.ID > 0 {
  2299. daySchedule.BedId = bedID
  2300. daySchedule.PartitionId = deviceNumber.ZoneID
  2301. daySchedule.ScheduleType = schedual_type
  2302. daySchedule.UpdatedTime = time.Now().Unix()
  2303. err := service.UpdateSchedule(&daySchedule)
  2304. if err != nil {
  2305. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2306. return
  2307. }
  2308. }
  2309. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2310. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2311. return
  2312. }
  2313. } else if err != nil {
  2314. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2315. return
  2316. }
  2317. }
  2318. dialysisRecord := &models.DialysisOrder{
  2319. ID: record_id,
  2320. UserOrgId: adminUserInfo.Org.Id,
  2321. BedID: bedID,
  2322. StartNurse: nurseID,
  2323. StartTime: startDate.Unix(),
  2324. PunctureNurse: puncture_nurse,
  2325. Creator: adminUserInfo.AdminUser.Id,
  2326. Modifier: adminUserInfo.AdminUser.Id,
  2327. WashpipeNurse: washpipe_nurse,
  2328. SchedualType: schedual_type,
  2329. ChangeNurse: change_nurse,
  2330. DifficultPunctureNurse: difficult_puncture_nurse,
  2331. NewFistulaNurse: new_fistula_nurse,
  2332. }
  2333. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  2334. if updateErr != nil {
  2335. this.ErrorLog("修改上机失败:%v", updateErr)
  2336. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2337. return
  2338. }
  2339. if updateErr == nil {
  2340. if tempDialysisRecord.Stage == 2 {
  2341. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  2342. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2343. fmt.Println(value)
  2344. a, b := math.Modf(value)
  2345. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2346. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2347. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2348. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  2349. if updateAssessmentErr != nil {
  2350. utils.ErrorLog("%v", updateAssessmentErr)
  2351. }
  2352. }
  2353. }
  2354. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2355. this.ServeSuccessJSON(map[string]interface{}{
  2356. "dialysis_order": dialysisRecords,
  2357. })
  2358. }
  2359. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  2360. record_id, _ := c.GetInt64("id")
  2361. nurseID, _ := c.GetInt64("nurse")
  2362. end_time := c.GetString("end_time")
  2363. if record_id <= 0 || nurseID <= 0 {
  2364. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2365. return
  2366. }
  2367. adminUserInfo := c.GetMobileAdminUserInfo()
  2368. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2369. if getNurseErr != nil {
  2370. c.ErrorLog("获取护士失败:%v", getNurseErr)
  2371. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2372. return
  2373. } else if nurse == nil {
  2374. c.ErrorLog("护士不存在")
  2375. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2376. return
  2377. }
  2378. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  2379. if parseEndDateErr != nil {
  2380. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  2381. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2382. return
  2383. }
  2384. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2385. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2386. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2387. // if getPermissionErr != nil {
  2388. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2389. // return
  2390. // } else if headNursePermission == nil {
  2391. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2392. // return
  2393. // }
  2394. //}
  2395. dialysisRecord := &models.DialysisOrder{
  2396. ID: record_id,
  2397. UserOrgId: adminUserInfo.Org.Id,
  2398. EndTime: endDate.Unix(),
  2399. FinishNurse: nurseID,
  2400. FinishModifier: adminUserInfo.AdminUser.Id,
  2401. }
  2402. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  2403. if updateErr != nil {
  2404. c.ErrorLog("修改下机失败:%v", updateErr)
  2405. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2406. return
  2407. }
  2408. if updateErr == nil {
  2409. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  2410. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2411. a, b := math.Modf(value)
  2412. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2413. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2414. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2415. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  2416. if updateAssessmentErr != nil {
  2417. utils.ErrorLog("%v", updateAssessmentErr)
  2418. }
  2419. }
  2420. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2421. c.ServeSuccessJSON(map[string]interface{}{
  2422. "dialysis_order": dialysisRecords,
  2423. })
  2424. }
  2425. func (c *DialysisAPIController) GetLongAdvice() {
  2426. patient_id, _ := c.GetInt64("id")
  2427. adminUserInfo := c.GetMobileAdminUserInfo()
  2428. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  2429. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  2430. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  2431. c.ServeSuccessJSON(map[string]interface{}{
  2432. "status": "1",
  2433. })
  2434. return
  2435. } else { //开启推送提醒
  2436. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  2437. var advice_three []*models.DoctorAdvice
  2438. //groupNo := service.GetMaxLongAdviceGroupID(adminUserInfo.Org.Id, patient_id)
  2439. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id)
  2440. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id)
  2441. for _, advice := range advices {
  2442. if advice.FrequencyType == 3 {
  2443. t := time.Now()
  2444. week := int(t.Weekday())
  2445. fmt.Println(t.Weekday())
  2446. fmt.Println(week)
  2447. switch week {
  2448. case 1:
  2449. if strings.Index(advice.WeekDay, "周一") == -1 {
  2450. advice_three = append(advice_three, advice)
  2451. }
  2452. break
  2453. case 2:
  2454. if strings.Index(advice.WeekDay, "周二") == -1 {
  2455. advice_three = append(advice_three, advice)
  2456. }
  2457. break
  2458. case 3:
  2459. if strings.Index(advice.WeekDay, "周三") == -1 {
  2460. advice_three = append(advice_three, advice)
  2461. }
  2462. break
  2463. case 4:
  2464. if strings.Index(advice.WeekDay, "周四") == -1 {
  2465. advice_three = append(advice_three, advice)
  2466. }
  2467. break
  2468. case 5:
  2469. if strings.Index(advice.WeekDay, "周五") == -1 {
  2470. advice_three = append(advice_three, advice)
  2471. }
  2472. break
  2473. case 6:
  2474. if strings.Index(advice.WeekDay, "周六") == -1 {
  2475. advice_three = append(advice_three, advice)
  2476. }
  2477. break
  2478. case 0:
  2479. if strings.Index(advice.WeekDay, "周日") == -1 {
  2480. advice_three = append(advice_three, advice)
  2481. }
  2482. break
  2483. }
  2484. }
  2485. }
  2486. for _, advice := range advices_two {
  2487. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2488. now := p.Unix()
  2489. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2490. dayStr2 := "-" + dayStr
  2491. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2492. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2493. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2494. for _, ad := range advices {
  2495. advice_three = append(advice_three, ad)
  2496. }
  2497. }
  2498. if err == nil {
  2499. c.ServeSuccessJSON(map[string]interface{}{
  2500. "status": "2",
  2501. "advices": advices,
  2502. "advices_two": RemoveRepeatedElement(advice_three),
  2503. "is_open_remind": config.IsOpenRemind,
  2504. })
  2505. }
  2506. }
  2507. }
  2508. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  2509. newArr = make([]*models.DoctorAdvice, 0)
  2510. for i := 0; i < len(arr); i++ {
  2511. repeat := false
  2512. for j := i + 1; j < len(arr); j++ {
  2513. if arr[i].ID == arr[j].ID {
  2514. repeat = true
  2515. break
  2516. }
  2517. }
  2518. if !repeat {
  2519. newArr = append(newArr, arr[i])
  2520. }
  2521. }
  2522. return
  2523. }
  2524. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  2525. patient, _ := c.GetInt64("id", 0)
  2526. groupNo, _ := c.GetInt64("groupno", 0)
  2527. if patient <= 0 {
  2528. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2529. return
  2530. }
  2531. adminUserInfo := c.GetMobileAdminUserInfo()
  2532. dataBody := make(map[string]interface{}, 0)
  2533. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2534. if err != nil {
  2535. utils.ErrorLog(err.Error())
  2536. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2537. return
  2538. }
  2539. utils.ErrorLog("%v", dataBody)
  2540. timeLayout := "2006-01-02 15:04"
  2541. loc, _ := time.LoadLocation("Local")
  2542. timeLayout2 := "2006-01-02"
  2543. loc2, _ := time.LoadLocation("Local")
  2544. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  2545. utils.ErrorLog("advice_type")
  2546. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2547. return
  2548. }
  2549. adviceType := int64(2)
  2550. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  2551. utils.ErrorLog("advice_date")
  2552. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2553. return
  2554. }
  2555. adviceDate, _ := dataBody["advice_date"].(string)
  2556. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  2557. AdviceDate := theTime.Unix()
  2558. RecordDate := theTime.Unix()
  2559. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  2560. utils.ErrorLog("start_time")
  2561. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2562. return
  2563. }
  2564. startTime, _ := dataBody["start_time"].(string)
  2565. if len(startTime) == 0 {
  2566. utils.ErrorLog("len(start_time) == 0")
  2567. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2568. return
  2569. }
  2570. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  2571. if err != nil {
  2572. utils.ErrorLog(err.Error())
  2573. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2574. return
  2575. }
  2576. StartTime := theTime.Unix()
  2577. Remark := ""
  2578. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  2579. remark, _ := dataBody["remark"].(string)
  2580. Remark = remark
  2581. }
  2582. var advices []*models.GroupAdvice
  2583. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  2584. utils.ErrorLog("advices")
  2585. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2586. return
  2587. }
  2588. adviceNames := dataBody["advices"].([]interface{})
  2589. for _, adviceNameMap := range adviceNames {
  2590. adviceNameM := adviceNameMap.(map[string]interface{})
  2591. var advice models.GroupAdvice
  2592. advice.Remark = Remark
  2593. advice.AdviceType = adviceType
  2594. advice.StartTime = StartTime
  2595. advice.AdviceDate = AdviceDate
  2596. advice.RecordDate = RecordDate
  2597. advice.Status = 1
  2598. advice.CreatedTime = time.Now().Unix()
  2599. advice.UpdatedTime = time.Now().Unix()
  2600. advice.StopState = 2
  2601. advice.ExecutionState = 2
  2602. advice.UserOrgId = adminUserInfo.Org.Id
  2603. advice.PatientId = patient
  2604. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  2605. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  2606. utils.ErrorLog("advice_name")
  2607. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2608. return
  2609. }
  2610. adviceName, _ := adviceNameM["advice_name"].(string)
  2611. if len(adviceName) == 0 {
  2612. utils.ErrorLog("len(advice_name) == 0")
  2613. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2614. return
  2615. }
  2616. advice.AdviceName = adviceName
  2617. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  2618. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  2619. advice.DrugSpec = drugSpec
  2620. }
  2621. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  2622. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  2623. advice.AdviceDesc = adviceDesc
  2624. }
  2625. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  2626. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  2627. advice.DrugSpecUnit = drugSpecUnit
  2628. }
  2629. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  2630. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  2631. // advice.SingleDose = singleDose
  2632. //}
  2633. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  2634. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2635. advice.SingleDose = adviceNameM["single_dose"].(float64)
  2636. }
  2637. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  2638. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  2639. advice.SingleDoseUnit = singleDoseUnit
  2640. }
  2641. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  2642. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  2643. // advice.PrescribingNumber = prescribingNumber
  2644. //}
  2645. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  2646. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2647. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  2648. }
  2649. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  2650. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  2651. advice.PrescribingNumberUnit = prescribingNumberUnit
  2652. }
  2653. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  2654. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  2655. advice.DeliveryWay = deliveryWay
  2656. }
  2657. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  2658. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2659. advice.ExecutionFrequency = executionFrequency
  2660. }
  2661. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  2662. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  2663. advice.FrequencyType = frequency_type
  2664. }
  2665. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  2666. day_count := int64(adviceNameM["day_count"].(float64))
  2667. advice.DayCount = day_count
  2668. }
  2669. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  2670. week_day, _ := adviceNameM["week_day"].(string)
  2671. advice.WeekDay = week_day
  2672. }
  2673. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  2674. way := int64(adviceNameM["way"].(float64))
  2675. advice.Way = way
  2676. }
  2677. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  2678. drug_id := int64(adviceNameM["drug_id"].(float64))
  2679. advice.DrugId = drug_id
  2680. }
  2681. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  2682. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  2683. advice.DrugNameId = drug_name_id
  2684. }
  2685. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  2686. template_id, _ := adviceNameM["template_id"].(string)
  2687. advice.TemplateId = template_id
  2688. }
  2689. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  2690. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2691. advice.ExecutionFrequency = executionFrequency
  2692. }
  2693. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  2694. children := adviceNameM["child"].([]interface{})
  2695. if len(children) > 0 {
  2696. for _, childrenMap := range children {
  2697. childMap := childrenMap.(map[string]interface{})
  2698. var child models.GroupAdvice
  2699. child.Remark = Remark
  2700. child.AdviceType = adviceType
  2701. child.StartTime = StartTime
  2702. child.AdviceDate = AdviceDate
  2703. child.RecordDate = RecordDate
  2704. child.Status = 1
  2705. child.CreatedTime = time.Now().Unix()
  2706. child.UpdatedTime = time.Now().Unix()
  2707. child.StopState = 2
  2708. child.ExecutionState = 2
  2709. child.UserOrgId = adminUserInfo.Org.Id
  2710. child.PatientId = patient
  2711. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  2712. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  2713. utils.ErrorLog("child advice_name")
  2714. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2715. return
  2716. }
  2717. childAdviceName, _ := childMap["advice_name"].(string)
  2718. if len(childAdviceName) == 0 {
  2719. utils.ErrorLog("len(child advice_name) == 0")
  2720. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2721. return
  2722. }
  2723. child.AdviceName = childAdviceName
  2724. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  2725. childAdviceDesc, _ := childMap["advice_desc"].(string)
  2726. child.AdviceDesc = childAdviceDesc
  2727. }
  2728. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  2729. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  2730. child.DrugSpec = childDrugSpec
  2731. }
  2732. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  2733. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  2734. child.DrugSpecUnit = childDrugSpecUnit
  2735. }
  2736. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  2737. child.SingleDose = childMap["single_dose"].(float64)
  2738. }
  2739. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  2740. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  2741. child.SingleDoseUnit = childSingleDoseUnit
  2742. }
  2743. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  2744. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  2745. }
  2746. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  2747. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  2748. child.PrescribingNumberUnit = childPrescribingNumberUnit
  2749. }
  2750. child.DeliveryWay = advice.DeliveryWay
  2751. child.ExecutionFrequency = advice.ExecutionFrequency
  2752. advice.Children = append(advice.Children, &child)
  2753. }
  2754. }
  2755. }
  2756. temp_advice, _ := service.FindRemindAdvice(advice.UserOrgId, advice.AdviceName, advice.AdviceDesc, advice.TemplateId, advice.FrequencyType, patient, advice.RecordDate)
  2757. if temp_advice.ID == 0 {
  2758. advices = append(advices, &advice)
  2759. }
  2760. }
  2761. if len(advices) > 0 {
  2762. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  2763. if err != nil {
  2764. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  2765. return
  2766. }
  2767. c.ServeSuccessJSON(map[string]interface{}{
  2768. "msg": "ok",
  2769. "advices": list,
  2770. })
  2771. } else {
  2772. c.ServeSuccessJSON(map[string]interface{}{
  2773. "msg": "ok",
  2774. })
  2775. }
  2776. return
  2777. }
  2778. func (c *DialysisAPIController) UploadDryWeight() {
  2779. patient_id, _ := c.GetInt64("id")
  2780. dry_weight, _ := c.GetFloat("dry_weight")
  2781. doctor_id, _ := c.GetInt64("doctor_id")
  2782. remark := c.GetString("remark")
  2783. adminUserInfo := c.GetMobileAdminUserInfo()
  2784. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  2785. if err == gorm.ErrRecordNotFound {
  2786. dryWeight := &models.SgjPatientDryweight{
  2787. PatientId: patient_id,
  2788. DryWeight: dry_weight,
  2789. Remakes: remark,
  2790. Ctime: time.Now().Unix(),
  2791. Mtime: time.Now().Unix(),
  2792. Creator: doctor_id,
  2793. Status: 1,
  2794. UserOrgId: adminUserInfo.Org.Id,
  2795. AdjustedValue: "/",
  2796. UserId: adminUserInfo.AdminUser.Id,
  2797. }
  2798. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2799. if createErr == nil {
  2800. c.ServeSuccessJSON(map[string]interface{}{
  2801. "msg": "提交成功",
  2802. "weight": dryWeight,
  2803. })
  2804. }
  2805. } else {
  2806. dryWeight := &models.SgjPatientDryweight{
  2807. PatientId: patient_id,
  2808. DryWeight: dry_weight,
  2809. Remakes: remark,
  2810. Ctime: time.Now().Unix(),
  2811. Mtime: time.Now().Unix(),
  2812. Creator: doctor_id,
  2813. Status: 1,
  2814. UserOrgId: adminUserInfo.Org.Id,
  2815. AdjustedValue: "/",
  2816. UserId: adminUserInfo.AdminUser.Id,
  2817. }
  2818. var value float64
  2819. value = dry_weight - weightAdjust.DryWeight
  2820. if value < 0 {
  2821. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  2822. } else if value == 0 {
  2823. dryWeight.AdjustedValue = "/"
  2824. } else if value > 0 {
  2825. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  2826. }
  2827. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2828. if createErr == nil {
  2829. c.ServeSuccessJSON(map[string]interface{}{
  2830. "msg": "提交成功",
  2831. "weight": dryWeight,
  2832. })
  2833. }
  2834. }
  2835. }
  2836. func (c *DialysisAPIController) GetSolution() {
  2837. patient_id, _ := c.GetInt64("patient_id")
  2838. mode_id, _ := c.GetInt64("mode_id")
  2839. adminUserInfo := c.GetMobileAdminUserInfo()
  2840. solution, err := service.MobileGetDialysisSolutionByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2841. prescription, err := service.MobileGetLastDialysisPrescribeByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2842. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeId(adminUserInfo.Org.Id, mode_id)
  2843. if err != nil {
  2844. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2845. return
  2846. }
  2847. c.ServeSuccessJSON(map[string]interface{}{
  2848. "solution": solution,
  2849. "prescription": prescription,
  2850. "system_prescription": system_prescription,
  2851. })
  2852. }
  2853. func (c *DialysisAPIController) GetSchedule() {
  2854. schedual_type, _ := c.GetInt64("schedual_type")
  2855. adminUserInfo := c.GetMobileAdminUserInfo()
  2856. //timeLayout := "2006-01-02 15:04:05"
  2857. //
  2858. //date := time.Now().Format("2006-01-02") + " 00:00:00"
  2859. //loc, _ := time.LoadLocation("Local")
  2860. //theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  2861. //scheduleTime := theStartTime.Unix()
  2862. scheduleTime, _ := c.GetInt64("record_date")
  2863. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  2864. c.ServeSuccessJSON(map[string]interface{}{
  2865. "number": deviceNumber,
  2866. })
  2867. }
  2868. func (c *DialysisAPIController) GetPatientId() {
  2869. id, _ := c.GetInt64("id")
  2870. patientId, _ := service.GetPatientId(id)
  2871. //获取该患者的所有传染病
  2872. list, _ := service.GetPatientInfectious(id)
  2873. c.ServeSuccessJSON(map[string]interface{}{
  2874. "patient": patientId,
  2875. "infectioulist": list,
  2876. })
  2877. }
  2878. func (this *DialysisAPIController) GetDialysisSchedule() {
  2879. schedualDate := this.GetString("date")
  2880. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  2881. if parseDateErr != nil {
  2882. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2883. return
  2884. }
  2885. adminInfo := this.GetMobileAdminUserInfo()
  2886. orgID := adminInfo.Org.Id
  2887. redis := service.RedisClient()
  2888. defer redis.Close()
  2889. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  2890. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  2891. if len(scheduals) > 0 {
  2892. //缓存数据
  2893. scheduals_json, err := json.Marshal(scheduals)
  2894. if err == nil {
  2895. redis.Set(redis.Context(),key, scheduals_json, time.Second*30)
  2896. }
  2897. }
  2898. this.ServeSuccessJSON(map[string]interface{}{
  2899. "scheduals": scheduals,
  2900. })
  2901. }
  2902. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  2903. change_type, _ := this.GetInt64("type", 0)
  2904. record_date := this.GetString("record_time")
  2905. patient_id, _ := this.GetInt64("patient_id", 0)
  2906. timeLayout := "2006-01-02"
  2907. loc, _ := time.LoadLocation("Local")
  2908. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2909. record_time := theAdviceRecordTime.Unix()
  2910. adminUserInfo := this.GetMobileAdminUserInfo()
  2911. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  2912. if err == nil {
  2913. if len(advices) == 0 {
  2914. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  2915. return
  2916. } else {
  2917. this.ServeSuccessJSON(map[string]interface{}{
  2918. "advices": advices,
  2919. "schedule": sch,
  2920. })
  2921. return
  2922. }
  2923. } else {
  2924. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2925. return
  2926. }
  2927. }
  2928. func (c *DialysisAPIController) CreateConsumables() {
  2929. record_date := c.GetString("record_time")
  2930. patient_id, _ := c.GetInt64("patient_id", 0)
  2931. active, _ := c.GetInt64("active")
  2932. adminUser := c.GetMobileAdminUserInfo()
  2933. timeLayout := "2006-01-02"
  2934. loc, _ := time.LoadLocation("Local")
  2935. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2936. record_time := theRecordTime.Unix()
  2937. dataBody := make(map[string]interface{}, 0)
  2938. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2939. if err != nil {
  2940. utils.ErrorLog(err.Error())
  2941. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2942. return
  2943. }
  2944. var beforePrepares []*models.DialysisBeforePrepareGoods
  2945. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  2946. var dialysisBefor []*models.DialysisBeforePrepare
  2947. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2948. goods, _ := dataBody["goods"].([]interface{})
  2949. if len(goods) > 0 {
  2950. for _, item := range goods {
  2951. items := item.(map[string]interface{})
  2952. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2953. utils.ErrorLog("good_id")
  2954. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2955. return
  2956. }
  2957. good_id := int64(items["good_id"].(float64))
  2958. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2959. utils.ErrorLog("good_type_id")
  2960. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2961. return
  2962. }
  2963. good_type_id := int64(items["good_type_id"].(float64))
  2964. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2965. utils.ErrorLog("count")
  2966. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2967. return
  2968. }
  2969. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2970. commdity_code := items["commdity_code"].(string)
  2971. fmt.Println("commdity", commdity_code)
  2972. prepareGoods := &models.DialysisBeforePrepareGoods{
  2973. GoodTypeId: good_type_id,
  2974. GoodId: good_id,
  2975. Count: count,
  2976. }
  2977. beforePrepares = append(beforePrepares, prepareGoods)
  2978. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  2979. GoodTypeId: good_type_id,
  2980. GoodId: good_id,
  2981. Count: count,
  2982. }
  2983. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  2984. prepare := &models.DialysisBeforePrepare{
  2985. GoodTypeId: good_type_id,
  2986. GoodId: good_id,
  2987. Count: count,
  2988. PatientId: patient_id,
  2989. RecordDate: record_time,
  2990. UserOrgId: adminUser.Org.Id,
  2991. Status: 1,
  2992. Ctime: time.Now().Unix(),
  2993. Creater: adminUser.AdminUser.Id,
  2994. CommdityCode: commdity_code,
  2995. }
  2996. dialysisBefor = append(dialysisBefor, prepare)
  2997. }
  2998. }
  2999. //查询是否有库存
  3000. for _, item := range dialysisBefor {
  3001. warehouse, err := service.FindFirstWarehousingInfoByStock(item.GoodId, item.GoodTypeId)
  3002. fmt.Println("库存数量00000000000000000000", warehouse.StockCount, err)
  3003. if err == gorm.ErrRecordNotFound {
  3004. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3005. c.ServeSuccessJSON(map[string]interface{}{
  3006. "message": "1",
  3007. "good_name": goodObj.GoodName,
  3008. "specification_name": goodObj.SpecificationName,
  3009. })
  3010. return
  3011. }
  3012. if err != nil {
  3013. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3014. c.ServeSuccessJSON(map[string]interface{}{
  3015. "message": "1",
  3016. "good_name": goodObj.GoodName,
  3017. "specification_name": goodObj.SpecificationName,
  3018. })
  3019. return
  3020. }
  3021. }
  3022. fmt.Println("dialysisBefor9999999999999999999", dialysisBefor, active)
  3023. //新增
  3024. if active == 1 && len(goods) > 0 {
  3025. for _, item := range dialysisBefor {
  3026. dialyPrepareOne := models.DialysisBeforePrepare{
  3027. GoodTypeId: item.GoodTypeId,
  3028. GoodId: item.GoodId,
  3029. PatientId: item.PatientId,
  3030. RecordDate: item.RecordDate,
  3031. UserOrgId: item.UserOrgId,
  3032. Count: item.Count,
  3033. Ctime: time.Now().Unix(),
  3034. Creater: item.Creater,
  3035. CommdityCode: item.CommdityCode,
  3036. Status: 1,
  3037. }
  3038. //先清除再插入
  3039. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3040. err = service.CreateDialysisBeforePrepareOne(&dialyPrepareOne)
  3041. }
  3042. if err == nil {
  3043. c.ServeSuccessJSON(map[string]interface{}{
  3044. "msg": "保存成功",
  3045. "message": "2",
  3046. })
  3047. return
  3048. } else {
  3049. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3050. return
  3051. }
  3052. }
  3053. if len(beforePrepares) > 0 && active == 2 {
  3054. for _, item := range beforePrepares {
  3055. //1.查看该患者该耗材型号最后一次出库数量
  3056. goodInfo, _ := service.GetLastGoodListByPatientId(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3057. //判断当前出库数量和最后一次出库数量的大小
  3058. //如果当前出库数量小于或等于最后一次出库数量 正常出库后 需要退库操作
  3059. if item.Count <= goodInfo.Count {
  3060. //出库
  3061. err = ConsumablesDeliveryTotalSeven(adminUser.Org.Id, patient_id, record_time, beforePrepares, adminUser.AdminUser.Id, item.Count)
  3062. //查询今日出库数据
  3063. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3064. for _, it := range list {
  3065. prepare := models.DialysisBeforePrepare{
  3066. UserOrgId: it.OrgId,
  3067. PatientId: patient_id,
  3068. RecordDate: it.RecordTime,
  3069. GoodId: it.GoodId,
  3070. GoodTypeId: it.GoodTypeId,
  3071. Count: it.Count,
  3072. Ctime: time.Now().Unix(),
  3073. Creater: adminUser.AdminUser.Id,
  3074. Status: 1,
  3075. }
  3076. //删除准备表数据
  3077. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3078. service.CreateDialysisBeforePrepareOne(&prepare)
  3079. }
  3080. }
  3081. var last_total int64
  3082. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3083. if item.Count >= goodInfo.Count {
  3084. //查询当前批次当前耗材最后一条出库数据
  3085. lastOutInfo, _ := service.GetLastWarehouOutInfoByPatientId(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3086. //计算当前出库和最后一次出库数据相差数据
  3087. last_total = item.Count - lastOutInfo.Count
  3088. //查询该批次剩余库存
  3089. lastInfo, _ := service.GetLastStockOut(lastOutInfo.WarehouseInfotId)
  3090. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3091. if lastInfo.StockCount >= last_total {
  3092. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3093. //service.ConsumablesDeliveryTotalEight(adminInfo.Org.Id, patient_id, record_time, beforePrepares,adminInfo.AdminUser.Id,item.Count)
  3094. //查询今日出库数据
  3095. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3096. for _, it := range list {
  3097. prepare := models.DialysisBeforePrepare{
  3098. UserOrgId: it.OrgId,
  3099. PatientId: patient_id,
  3100. RecordDate: it.RecordTime,
  3101. GoodId: it.GoodId,
  3102. GoodTypeId: it.GoodTypeId,
  3103. Count: it.Count,
  3104. Ctime: time.Now().Unix(),
  3105. Creater: adminUser.AdminUser.Id,
  3106. Status: 1,
  3107. }
  3108. //删除准备表数据
  3109. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3110. service.CreateDialysisBeforePrepareOne(&prepare)
  3111. }
  3112. }
  3113. //如果库存不够,则出库到下一个批次
  3114. if lastInfo.StockCount < last_total {
  3115. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3116. //查询今日出库数据
  3117. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3118. for _, it := range list {
  3119. prepare := models.DialysisBeforePrepare{
  3120. UserOrgId: it.OrgId,
  3121. PatientId: patient_id,
  3122. RecordDate: it.RecordTime,
  3123. GoodId: it.GoodId,
  3124. GoodTypeId: it.GoodTypeId,
  3125. Count: it.Count,
  3126. Ctime: time.Now().Unix(),
  3127. Creater: adminUser.AdminUser.Id,
  3128. Status: 1,
  3129. }
  3130. //删除准备表数据
  3131. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3132. service.CreateDialysisBeforePrepareOne(&prepare)
  3133. }
  3134. if err != nil {
  3135. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3136. c.ServeSuccessJSON(map[string]interface{}{
  3137. "message": "1",
  3138. "good_name": goodObj.GoodName,
  3139. "specification_name": goodObj.SpecificationName,
  3140. })
  3141. return
  3142. }
  3143. }
  3144. }
  3145. if err != nil {
  3146. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3147. c.ServeSuccessJSON(map[string]interface{}{
  3148. "message": "1",
  3149. "good_name": goodObj.GoodName,
  3150. "specification_name": goodObj.SpecificationName,
  3151. })
  3152. return
  3153. }
  3154. }
  3155. //出库
  3156. //err = service.ConsumablesDeliveryTotal(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3157. //fmt.Println("err", err)
  3158. ////查询今日出库数据
  3159. //list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3160. //
  3161. //if len(list) == 0 {
  3162. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3163. // return
  3164. //}
  3165. //
  3166. //for _, item := range list {
  3167. // prepare := models.DialysisBeforePrepare{
  3168. // UserOrgId: item.OrgId,
  3169. // PatientId: patient_id,
  3170. // RecordDate: item.RecordTime,
  3171. // GoodId: item.GoodId,
  3172. // GoodTypeId: item.GoodTypeId,
  3173. // Count: item.Count,
  3174. // Ctime: time.Now().Unix(),
  3175. // Creater: adminUser.AdminUser.Id,
  3176. // Status: 1,
  3177. // }
  3178. // //删除准备表数据
  3179. // service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3180. // service.CreateDialysisBeforePrepareOne(&prepare)
  3181. //}
  3182. }
  3183. }
  3184. var errs error
  3185. if errs == nil {
  3186. c.ServeSuccessJSON(map[string]interface{}{
  3187. "msg": "提交成功",
  3188. "message": "2",
  3189. "good_name": "",
  3190. "specification_name": "",
  3191. })
  3192. return
  3193. } else {
  3194. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3195. return
  3196. }
  3197. }
  3198. func (c *DialysisAPIController) CreateStockOutInfo() {
  3199. patient_id, _ := c.GetInt64("patient_id", 0)
  3200. record_date := c.GetString("record_time")
  3201. if patient_id <= 0 {
  3202. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3203. return
  3204. }
  3205. adminInfo := c.GetMobileAdminUserInfo()
  3206. timeLayout := "2006-01-02"
  3207. loc, _ := time.LoadLocation("Local")
  3208. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3209. record_time := theRecordTime.Unix()
  3210. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3211. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3212. consumables = RemoveRepeatedGood(consumables)
  3213. if record.IsOpen == 1 {
  3214. //查询是否有库存
  3215. for _, item := range consumables {
  3216. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId)
  3217. if item.Count > warehouse.Count {
  3218. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3219. c.ServeSuccessJSON(map[string]interface{}{
  3220. "message": "1",
  3221. "good_name": goodObj.GoodName,
  3222. "specification_name": goodObj.SpecificationName,
  3223. })
  3224. return
  3225. }
  3226. }
  3227. //查询是否有出库单
  3228. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3229. if err == gorm.ErrRecordNotFound {
  3230. //没有记录,则创建出库单
  3231. timeStr := time.Now().Format("2006-01-02")
  3232. timeArr := strings.Split(timeStr, "-")
  3233. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3234. total = total + 1
  3235. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3236. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3237. number = number + total
  3238. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3239. creater := adminInfo.AdminUser.Id
  3240. warehouseOut := models.WarehouseOut{
  3241. WarehouseOutOrderNumber: warehousing_out_order,
  3242. OperationTime: time.Now().Unix(),
  3243. OrgId: adminInfo.Org.Id,
  3244. Creater: creater,
  3245. Ctime: time.Now().Unix(),
  3246. Status: 1,
  3247. WarehouseOutTime: record_time,
  3248. Dealer: 0,
  3249. Manufacturer: 0,
  3250. Type: 1,
  3251. IsSys: 1,
  3252. }
  3253. err := service.AddSigleWarehouseOut(&warehouseOut)
  3254. if err != nil {
  3255. utils.TraceLog("创建出库单失败 err = %v", err)
  3256. } else {
  3257. for _, item := range consumables {
  3258. //出库
  3259. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, item.Count)
  3260. }
  3261. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3262. if len(list) == 0 {
  3263. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3264. return
  3265. }
  3266. for _, item := range list {
  3267. prepare := models.DialysisBeforePrepare{
  3268. UserOrgId: adminInfo.Org.Id,
  3269. PatientId: patient_id,
  3270. RecordDate: record_time,
  3271. GoodId: item.GoodId,
  3272. GoodTypeId: item.GoodTypeId,
  3273. Count: item.Count,
  3274. Creater: adminInfo.AdminUser.Id,
  3275. Status: 1,
  3276. Ctime: time.Now().Unix(),
  3277. }
  3278. //清空准备表数据
  3279. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3280. service.CreateDialysisBeforePrepareOne(&prepare)
  3281. }
  3282. }
  3283. //
  3284. } else if err == nil {
  3285. for _, item := range consumables {
  3286. //出库
  3287. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &out, item.Count)
  3288. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3289. if len(list) == 0 {
  3290. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3291. return
  3292. }
  3293. for _, item := range list {
  3294. prepare := models.DialysisBeforePrepare{
  3295. UserOrgId: adminInfo.Org.Id,
  3296. PatientId: patient_id,
  3297. RecordDate: record_time,
  3298. GoodId: item.GoodId,
  3299. GoodTypeId: item.GoodTypeId,
  3300. Count: item.Count,
  3301. Creater: adminInfo.AdminUser.Id,
  3302. Status: 1,
  3303. Ctime: time.Now().Unix(),
  3304. }
  3305. //清空准备表数据
  3306. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3307. service.CreateDialysisBeforePrepareOne(&prepare)
  3308. }
  3309. }
  3310. }
  3311. c.ServeSuccessJSON(map[string]interface{}{
  3312. "msg": "提交成功",
  3313. "message": "2",
  3314. "good_name": "",
  3315. "specification_name": "",
  3316. })
  3317. return
  3318. } else {
  3319. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  3320. return
  3321. }
  3322. }
  3323. func (c *DialysisAPIController) EditConsumables() {
  3324. patient_id, _ := c.GetInt64("patient_id", 0)
  3325. record_date := c.GetString("record_time")
  3326. if patient_id <= 0 {
  3327. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3328. return
  3329. }
  3330. adminInfo := c.GetMobileAdminUserInfo()
  3331. timeLayout := "2006-01-02"
  3332. loc, _ := time.LoadLocation("Local")
  3333. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3334. record_time := theRecordTime.Unix()
  3335. dataBody := make(map[string]interface{}, 0)
  3336. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3337. if err != nil {
  3338. utils.ErrorLog(err.Error())
  3339. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3340. return
  3341. }
  3342. var beforePrepares []*models.DialysisBeforePrepareGoods
  3343. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3344. //判断是否开启自动出库
  3345. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3346. if record.IsOpen == 1 {
  3347. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3348. goods, _ := dataBody["goods"].([]interface{})
  3349. if len(goods) > 0 {
  3350. for _, item := range goods {
  3351. items := item.(map[string]interface{})
  3352. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3353. utils.ErrorLog("good_id")
  3354. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3355. return
  3356. }
  3357. good_id := int64(items["good_id"].(float64))
  3358. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3359. utils.ErrorLog("good_type_id")
  3360. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3361. return
  3362. }
  3363. good_type_id := int64(items["good_type_id"].(float64))
  3364. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3365. utils.ErrorLog("count")
  3366. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3367. return
  3368. }
  3369. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3370. commdity_code := items["commdity_code"].(string)
  3371. fmt.Println(commdity_code)
  3372. prepareGoods := &models.DialysisBeforePrepareGoods{
  3373. GoodTypeId: good_type_id,
  3374. GoodId: good_id,
  3375. Count: count,
  3376. }
  3377. beforePrepares = append(beforePrepares, prepareGoods)
  3378. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3379. GoodTypeId: good_type_id,
  3380. GoodId: good_id,
  3381. Count: count,
  3382. }
  3383. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3384. }
  3385. for _, item := range beforePrepares {
  3386. fmt.Println("23232323232323为什么99999999999999999999999999999999", item.GoodId)
  3387. //1.查看该患者该耗材型号最后一次出库数量
  3388. goodInfo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3389. //判断当前出库数量和最后一次出库数量的大小
  3390. //如果当前出库数量小于最后一次出库数量 正常出库后 需要退库操作
  3391. fmt.Println("当前出库数量", item.Count)
  3392. fmt.Println("最后一次出库数量", goodInfo.Count)
  3393. if item.Count < goodInfo.Count {
  3394. //出库
  3395. err = ConsumablesDeliveryTotalSeven(adminInfo.Org.Id, patient_id, record_time, beforePrepares, adminInfo.AdminUser.Id, item.Count)
  3396. break
  3397. }
  3398. var last_total int64
  3399. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3400. if item.Count > goodInfo.Count {
  3401. //计算当前出库和最后一次出库数据相差数据
  3402. last_total = item.Count - goodInfo.Count
  3403. //查询该批次剩余库存
  3404. lastInfo, _ := service.GetLastStockOut(goodInfo.WarehouseInfotId)
  3405. if lastInfo.StockCount == 0 {
  3406. //查询该耗材的总库存
  3407. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  3408. if wareinfo.StockCount == 0 {
  3409. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3410. c.ServeSuccessJSON(map[string]interface{}{
  3411. "message": "1",
  3412. "good_name": goodObj.GoodName,
  3413. "specification_name": goodObj.SpecificationName,
  3414. })
  3415. return
  3416. }
  3417. }
  3418. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3419. fmt.Println("剩余库存", lastInfo.StockCount)
  3420. fmt.Println("差", last_total)
  3421. if lastInfo.StockCount >= last_total {
  3422. err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3423. break
  3424. }
  3425. //如果库存不够,则出库到下一个批次
  3426. if lastInfo.StockCount < last_total {
  3427. err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3428. break
  3429. }
  3430. }
  3431. }
  3432. //查询今日出库数据
  3433. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3434. for _, it := range list {
  3435. prepare := models.DialysisBeforePrepare{
  3436. UserOrgId: it.OrgId,
  3437. PatientId: patient_id,
  3438. RecordDate: it.RecordTime,
  3439. GoodId: it.GoodId,
  3440. GoodTypeId: it.GoodTypeId,
  3441. Count: it.Count,
  3442. Ctime: time.Now().Unix(),
  3443. Creater: adminInfo.AdminUser.Id,
  3444. Status: 1,
  3445. }
  3446. //删除准备表数据
  3447. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, it.GoodId, it.GoodTypeId)
  3448. service.CreateDialysisBeforePrepareOne(&prepare)
  3449. if err != nil {
  3450. goodObj, _ := service.GetGoodInformationByGoodId(it.GoodId)
  3451. c.ServeSuccessJSON(map[string]interface{}{
  3452. "message": "2",
  3453. "good_name": goodObj.GoodName,
  3454. "specification_name": goodObj.SpecificationName,
  3455. })
  3456. return
  3457. }
  3458. }
  3459. }
  3460. }
  3461. //更新自动出库的地方
  3462. var errs error
  3463. if errs == nil {
  3464. c.ServeSuccessJSON(map[string]interface{}{
  3465. "msg": "修改成功",
  3466. "message": "2",
  3467. "good_name": "",
  3468. "specification_name": "",
  3469. })
  3470. return
  3471. } else {
  3472. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3473. return
  3474. }
  3475. }
  3476. }
  3477. func (c *DialysisAPIController) GetDialysisGoods() {
  3478. schedualDate := c.GetString("schedule_date")
  3479. schedule_type, _ := c.GetInt64("schedule_type")
  3480. partition_id, _ := c.GetInt64("partition_id")
  3481. page, _ := c.GetInt("page")
  3482. patient_id, _ := c.GetInt64("patient_id")
  3483. schedualEndDate := int64(0)
  3484. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3485. if parseDateErr != nil && len(schedualDate) != 0 {
  3486. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3487. return
  3488. }
  3489. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  3490. if parseDateErr != nil && len(schedualDate) != 0 {
  3491. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3492. return
  3493. }
  3494. schedualEndDate = endDate.Unix()
  3495. adminUser := c.GetMobileAdminUserInfo()
  3496. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  3497. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  3498. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  3499. //获取当天该病人的透析处方
  3500. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  3501. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3502. if err == gorm.ErrRecordNotFound {
  3503. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3504. if patient_id != 0 {
  3505. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3506. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3507. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3508. item.LastAutomaticReduceDetail = goodUser
  3509. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3510. item.Project = project
  3511. }
  3512. }
  3513. c.ServeSuccessJSON(map[string]interface{}{
  3514. "dialysis_goods": dialysisGoods,
  3515. "good_type": goodTypes,
  3516. "total": total,
  3517. "prescribe": prescribe,
  3518. "good_info": good_info,
  3519. })
  3520. return
  3521. } else if err == nil {
  3522. //获取当天排班的每个患者的库存使用情况
  3523. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3524. if patient_id != 0 {
  3525. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3526. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3527. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3528. item.Project = project
  3529. fmt.Println(goodUser)
  3530. fmt.Println(lastGoodUserDetial)
  3531. item.LastAutomaticReduceDetail = goodUser
  3532. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3533. }
  3534. }
  3535. if err == nil {
  3536. c.ServeSuccessJSON(map[string]interface{}{
  3537. "dialysis_goods": dialysisGoods,
  3538. "good_type": goodTypes,
  3539. "total": total,
  3540. "prescribe": prescribe,
  3541. "good_info": good_info,
  3542. "project": project,
  3543. })
  3544. return
  3545. } else {
  3546. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3547. return
  3548. }
  3549. } else if err != nil {
  3550. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3551. return
  3552. }
  3553. }
  3554. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  3555. start_time := c.GetString("start_time")
  3556. end_time := c.GetString("end_time")
  3557. timeLayout := "2006-01-02"
  3558. loc, _ := time.LoadLocation("Local")
  3559. var theStartTime int64
  3560. if len(start_time) > 0 {
  3561. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3562. if err != nil {
  3563. utils.ErrorLog(err.Error())
  3564. }
  3565. theStartTime = theTime.Unix()
  3566. }
  3567. var theEndtTime int64
  3568. if len(end_time) > 0 {
  3569. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3570. if err != nil {
  3571. utils.ErrorLog(err.Error())
  3572. }
  3573. theEndtTime = theTime.Unix()
  3574. }
  3575. adminUser := c.GetMobileAdminUserInfo()
  3576. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  3577. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  3578. if err == nil {
  3579. c.ServeSuccessJSON(map[string]interface{}{
  3580. "stock_out": outInfo,
  3581. "stockCount": stockCount,
  3582. })
  3583. return
  3584. } else {
  3585. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3586. return
  3587. }
  3588. }
  3589. func (c *DialysisAPIController) GetStockInGoodInfo() {
  3590. patient_id, _ := c.GetInt64("patient_id", 0)
  3591. record_time := c.GetString("record_time")
  3592. adminUser := c.GetMobileAdminUserInfo()
  3593. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  3594. if parseDateErr != nil && len(record_time) != 0 {
  3595. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3596. return
  3597. }
  3598. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  3599. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3600. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  3601. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  3602. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  3603. //获取今日患者的透析处方参数
  3604. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  3605. c.ServeSuccessJSON(map[string]interface{}{
  3606. "good_type": goodTypes,
  3607. "good_user": goodUser,
  3608. "good_info": good_info,
  3609. "last_good_user": lastGoodUserDetial,
  3610. "project": project,
  3611. "prescription": prescribe,
  3612. })
  3613. return
  3614. }
  3615. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  3616. patient_id, _ := c.GetInt64("patient_id", 0)
  3617. record_date := c.GetString("record_time")
  3618. timeLayout := "2006-01-02"
  3619. loc, _ := time.LoadLocation("Local")
  3620. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3621. record_time := theRecordTime.Unix()
  3622. adminInfo := c.GetMobileAdminUserInfo()
  3623. dataBody := make(map[string]interface{}, 0)
  3624. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3625. if err != nil {
  3626. utils.ErrorLog(err.Error())
  3627. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3628. return
  3629. }
  3630. var beforePrepares []*models.DialysisBeforePrepareGoods
  3631. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3632. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3633. goods, _ := dataBody["goods"].([]interface{})
  3634. if len(goods) > 0 {
  3635. for _, item := range goods {
  3636. items := item.(map[string]interface{})
  3637. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3638. utils.ErrorLog("good_id")
  3639. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3640. return
  3641. }
  3642. good_id := int64(items["good_id"].(float64))
  3643. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3644. utils.ErrorLog("good_type_id")
  3645. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3646. return
  3647. }
  3648. good_type_id := int64(items["good_type_id"].(float64))
  3649. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3650. utils.ErrorLog("count")
  3651. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3652. return
  3653. }
  3654. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3655. prepare := &models.DialysisBeforePrepareGoods{
  3656. GoodId: good_id,
  3657. GoodTypeId: good_type_id,
  3658. Count: count,
  3659. }
  3660. beforePrepares = append(beforePrepares, prepare)
  3661. newPrepare := &models.NewDialysisBeforePrepareGoods{
  3662. GoodId: good_id,
  3663. GoodTypeId: good_type_id,
  3664. Count: count,
  3665. }
  3666. newBeforePrepares = append(newBeforePrepares, newPrepare)
  3667. }
  3668. }
  3669. }
  3670. fmt.Println("前端数据9999999999999", beforePrepares)
  3671. //查询是否有库存
  3672. for _, item := range beforePrepares {
  3673. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId)
  3674. if item.Count > warehouse.Count {
  3675. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3676. c.ServeSuccessJSON(map[string]interface{}{
  3677. "message": "1",
  3678. "good_name": goodObj.GoodName,
  3679. "specification_name": goodObj.SpecificationName,
  3680. })
  3681. return
  3682. }
  3683. }
  3684. //出库逻辑
  3685. err = service.ConsumablesDeliveryTotal(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3686. if err != nil {
  3687. utils.ErrorLog(err.Error())
  3688. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3689. return
  3690. }
  3691. //查询当天出库的数据
  3692. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3693. for _, item := range list {
  3694. prepare := models.DialysisBeforePrepare{
  3695. UserOrgId: item.OrgId,
  3696. PatientId: item.PatientId,
  3697. RecordDate: item.RecordTime,
  3698. GoodId: item.GoodId,
  3699. GoodTypeId: item.GoodTypeId,
  3700. Count: item.Count,
  3701. Creater: adminInfo.AdminUser.Id,
  3702. Status: 1,
  3703. Ctime: time.Now().Unix(),
  3704. }
  3705. //清空准备表的数据
  3706. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3707. //插入准备表数据
  3708. service.CreateDialysisBeforePrepareOne(&prepare)
  3709. }
  3710. //更新自动出库的地方
  3711. var errs error
  3712. if errs == nil {
  3713. c.ServeSuccessJSON(map[string]interface{}{
  3714. "msg": "修改成功",
  3715. "message": "2",
  3716. "good_name": "",
  3717. "specification_name": "",
  3718. })
  3719. return
  3720. } else {
  3721. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3722. return
  3723. }
  3724. }
  3725. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3726. newArr = make([]*models.DialysisBeforePrepare, 0)
  3727. for i := 0; i < len(arr); i++ {
  3728. repeat := false
  3729. for j := i + 1; j < len(arr); j++ {
  3730. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  3731. repeat = true
  3732. break
  3733. }
  3734. }
  3735. if !repeat {
  3736. newArr = append(newArr, arr[i])
  3737. }
  3738. }
  3739. return
  3740. }
  3741. func (c *DialysisAPIController) GetAllDrug() {
  3742. patient_id, _ := c.GetInt64("patient_id", 0)
  3743. adminInfo := c.GetMobileAdminUserInfo()
  3744. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3745. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  3746. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  3747. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  3748. c.ServeSuccessJSON(map[string]interface{}{
  3749. "base_drug_config": drugStockConfig,
  3750. "private_drug_config": privateDrugConfig,
  3751. "base_drug_list": drugList,
  3752. "private_drug_list": privateDrugList,
  3753. })
  3754. }
  3755. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3756. newArr = make([]*models.DialysisBeforePrepare, 0)
  3757. for i := 0; i < len(arr); i++ {
  3758. repeat := false
  3759. for j := i + 1; j < len(arr); j++ {
  3760. if arr[i].GoodId == arr[j].GoodId {
  3761. repeat = true
  3762. break
  3763. }
  3764. }
  3765. if !repeat {
  3766. newArr = append(newArr, arr[i])
  3767. }
  3768. }
  3769. return
  3770. }
  3771. func (c *DialysisAPIController) GetDepartment() {
  3772. adminInfo := c.GetMobileAdminUserInfo()
  3773. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  3774. if err == nil {
  3775. c.ServeSuccessJSON(map[string]interface{}{
  3776. "departments": departments,
  3777. })
  3778. } else {
  3779. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3780. return
  3781. }
  3782. }
  3783. func (c *DialysisAPIController) GetMobilePrintStockGood() {
  3784. types, _ := c.GetInt("type", 0)
  3785. start_time := c.GetString("start_time")
  3786. end_time := c.GetString("end_time")
  3787. orgId := c.GetMobileAdminUserInfo().Org.Id
  3788. timeLayout := "2006-01-02"
  3789. loc, _ := time.LoadLocation("Local")
  3790. var startTime int64
  3791. if len(start_time) > 0 {
  3792. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3793. if err != nil {
  3794. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3795. return
  3796. }
  3797. startTime = theTime.Unix()
  3798. }
  3799. var endTime int64
  3800. if len(end_time) > 0 {
  3801. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3802. if err != nil {
  3803. utils.ErrorLog(err.Error())
  3804. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3805. return
  3806. }
  3807. endTime = theTime.Unix()
  3808. }
  3809. list, err := service.FindPrintStockGoodInfoByType(types, startTime, endTime, orgId)
  3810. stockTotal, err := service.GetOutStockTotalCountTwo(startTime, endTime, orgId)
  3811. if err != nil {
  3812. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3813. } else {
  3814. c.ServeSuccessJSON(map[string]interface{}{
  3815. "list": list,
  3816. "type": types,
  3817. "stockTotal": stockTotal,
  3818. })
  3819. }
  3820. }
  3821. func (c *DialysisAPIController) BatchDeleteMonitor() {
  3822. fmt.Println("jin2222245555555555")
  3823. ids := c.GetString("ids")
  3824. fmt.Println("dis22222222", ids)
  3825. idArray := strings.Split(ids, ",")
  3826. err := service.BatchDeleteMonitor(idArray)
  3827. fmt.Print("err", err)
  3828. c.ServeSuccessJSON(map[string]interface{}{
  3829. "msg": "批量删除成功",
  3830. })
  3831. return
  3832. }
  3833. func (c *DialysisAPIController) GetPatientDialysisRecordList() {
  3834. id, _ := c.GetInt64("id")
  3835. fmt.Println(id)
  3836. timeLayout := "2006-01-02"
  3837. loc, _ := time.LoadLocation("Local")
  3838. start_time := time.Now().Format("2006-01-02")
  3839. startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3840. fmt.Println("start_timestart_time", start_time)
  3841. nowTime := time.Now()
  3842. endTime := nowTime.AddDate(-1, 0, 0)
  3843. endTimes := endTime.Format("2006-01-02")
  3844. endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", endTimes+" 00:00:00", loc)
  3845. list, _ := service.GetPatientDialysisRecordList(id, endtime.Unix(), startime.Unix())
  3846. c.ServeSuccessJSON(map[string]interface{}{
  3847. "list": list,
  3848. })
  3849. return
  3850. }
  3851. func (c *DialysisAPIController) BathDeleteAdviceList() {
  3852. dataBody := make(map[string]interface{}, 0)
  3853. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3854. ids := c.GetString("ids")
  3855. fmt.Println("dis22222222", ids)
  3856. idArray := strings.Split(ids, ",")
  3857. origin, _ := c.GetInt64("origin")
  3858. if origin == 1 {
  3859. err = service.BatchDeleteAdvice(idArray)
  3860. fmt.Print("err", err)
  3861. c.ServeSuccessJSON(map[string]interface{}{
  3862. "msg": "批量删除成功",
  3863. })
  3864. return
  3865. }
  3866. if origin == 2 {
  3867. service.BatchDeleteHisAdvice(idArray)
  3868. }
  3869. }
  3870. func (c *DialysisAPIController) UpdateAutoReduceDetail() {
  3871. good_id, _ := c.GetInt64("good_id")
  3872. count, _ := c.GetInt64("count")
  3873. record_time, _ := c.GetInt64("record_time")
  3874. patient_id, _ := c.GetInt64("patient_id")
  3875. detail, _ := service.UpdateAutoReduceDetail(good_id, count, record_time, patient_id)
  3876. c.ServeSuccessJSON(map[string]interface{}{
  3877. "detail": detail,
  3878. })
  3879. return
  3880. }
  3881. func (c *DialysisAPIController) DeleteAutoReduceDetail() {
  3882. good_id, _ := c.GetInt64("good_id")
  3883. record_time, _ := c.GetInt64("record_time")
  3884. patient_id, _ := c.GetInt64("patient_id")
  3885. fmt.Println("0000000000000000", patient_id)
  3886. service.DeleteDialysisBeforOne(good_id, record_time, patient_id)
  3887. fmt.Println()
  3888. err := service.DeleteAutoReduceDetail(good_id, record_time, patient_id)
  3889. fmt.Print("err", err)
  3890. c.ServeSuccessJSON(map[string]interface{}{
  3891. "msg": "批量删除成功",
  3892. })
  3893. return
  3894. }
  3895. func (c *DialysisAPIController) BatchAdviceCheck() {
  3896. ids := c.GetString("ids")
  3897. idArray := strings.Split(ids, ",")
  3898. creator, _ := c.GetInt64("creator")
  3899. origin, _ := c.GetInt64("origin")
  3900. if origin == 1 {
  3901. err := service.BatchAdviceCheck(idArray, creator)
  3902. fmt.Println(err)
  3903. list, _ := service.GetAdviceExecutionById(idArray)
  3904. c.ServeSuccessJSON(map[string]interface{}{
  3905. "list": list,
  3906. })
  3907. return
  3908. }
  3909. if origin == 2 {
  3910. service.BatchHisAdviceCheck(idArray, creator)
  3911. list, _ := service.GetHisAdviceExecutionById(idArray)
  3912. c.ServeSuccessJSON(map[string]interface{}{
  3913. "list": list,
  3914. })
  3915. return
  3916. }
  3917. }
  3918. func (c *DialysisAPIController) BatchAdviceExecution() {
  3919. ids := c.GetString("ids")
  3920. idArray := strings.Split(ids, ",")
  3921. executionTime := c.GetString("execution_time")
  3922. creator, _ := c.GetInt64("creator")
  3923. timeLayout := "2006-01-02 15:04:05"
  3924. loc, _ := time.LoadLocation("Local")
  3925. theTime, _ := time.ParseInLocation(timeLayout, executionTime, loc)
  3926. orgin, _ := c.GetInt64("origin")
  3927. if orgin == 1 {
  3928. err := service.BatchAdviceExecution(idArray, creator, theTime.Unix())
  3929. list, _ := service.GetAdviceExecutionById(idArray)
  3930. fmt.Println(err)
  3931. c.ServeSuccessJSON(map[string]interface{}{
  3932. "list": list,
  3933. })
  3934. return
  3935. }
  3936. if orgin == 2 {
  3937. err := service.BatchHisAdviceExecution(idArray, creator, theTime.Unix())
  3938. list, _ := service.GetHisAdviceExecutionById(idArray)
  3939. fmt.Println(err)
  3940. c.ServeSuccessJSON(map[string]interface{}{
  3941. "list": list,
  3942. })
  3943. return
  3944. }
  3945. }
  3946. func (c *DialysisAPIController) UpdateStockGoods() {
  3947. good_id, _ := c.GetInt64("good_id")
  3948. record_time, _ := c.GetInt64("record_time")
  3949. patient_id, _ := c.GetInt64("patient_id")
  3950. count, _ := c.GetInt64("count")
  3951. err := service.UpdateStockGoods(good_id, record_time, patient_id, count)
  3952. fmt.Print("err", err)
  3953. c.ServeSuccessJSON(map[string]interface{}{
  3954. "msg": "更新成功",
  3955. })
  3956. return
  3957. }
  3958. //当前数据比上一次出库数据少
  3959. func ConsumablesDeliveryTotalSeven(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, creater int64, count int64) (err error) {
  3960. fmt.Println("w我的中国馆公共区发电房阿道夫安抚安抚安抚安抚安抚安抚阿道夫阿道夫阿凡达阿道夫a", count)
  3961. //查询该患者当天已经出库的耗材信息
  3962. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  3963. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  3964. for i := len(goods_yc) - 1; i >= 0; i-- {
  3965. goods_yc_temp := goods_yc[i]
  3966. for j := len(goods) - 1; j >= 0; j-- {
  3967. goods_temp := goods[j]
  3968. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  3969. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  3970. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  3971. if goods_yc_temp.Count == goods_temp.Count {
  3972. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  3973. goods = append(goods[:j], goods[j+1:]...)
  3974. break
  3975. }
  3976. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  3977. if goods_yc_temp.Count > goods_temp.Count {
  3978. temp_count := goods_yc_temp.Count - goods_temp.Count
  3979. goods_yc[i].Count = temp_count
  3980. goods = append(goods[:j], goods[j+1:]...)
  3981. break
  3982. }
  3983. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  3984. if goods_yc_temp.Count < goods_temp.Count {
  3985. temp_count := goods_temp.Count - goods_yc_temp.Count
  3986. //fmt.Println("988888888888888", temp_count)
  3987. goods[j].Count = temp_count
  3988. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  3989. //fmt.Println("888888888", goods_yc)
  3990. break
  3991. }
  3992. }
  3993. }
  3994. }
  3995. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  3996. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  3997. fmt.Println("goodsy999999999999", goods_yc)
  3998. //退库
  3999. if len(goods_yc) > 0 {
  4000. for _, good_yc := range goods_yc {
  4001. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  4002. ConsumablesDeliveryDeleteFour(orgID, record_time, good_yc, &out, patient_id, creater, count)
  4003. }
  4004. }
  4005. return nil
  4006. }
  4007. //耗材出库删除
  4008. func ConsumablesDeliveryDeleteFour(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  4009. fmt.Println("count2323223884584854854854u5454785487547845785478758487545475475487,count", count)
  4010. // 先根据相关信息查询当天该耗材的出库信息
  4011. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  4012. fmt.Println("errr232323232323232323232323232", err)
  4013. if err != nil {
  4014. return err
  4015. }
  4016. var delete_count int64 = 0
  4017. delete_count = warehouseOutInfos.Count - count
  4018. fmt.Println("delete_count2323232", delete_count)
  4019. // 在出库记录表里记录退库详情
  4020. warehouseOutInfo := &models.WarehouseOutInfo{
  4021. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4022. WarehouseOutId: warehouseOut.ID,
  4023. Status: 1,
  4024. Ctime: time.Now().Unix(),
  4025. OrgId: orgID,
  4026. Type: 1,
  4027. IsSys: 1,
  4028. SysRecordTime: record_time,
  4029. GoodTypeId: good_yc.GoodTypeId,
  4030. GoodId: good_yc.GoodId,
  4031. PatientId: good_yc.PatientId,
  4032. ConsumableType: 2,
  4033. }
  4034. warehouseOutInfo.Count = count
  4035. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4036. warehouseOutInfo.Price = stockInInfo.Price
  4037. warehouseOutInfo.Dealer = stockInInfo.Dealer
  4038. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  4039. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  4040. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  4041. warehouseOutInfo.Number = warehouseOutInfos.Number
  4042. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  4043. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  4044. //查找当天是否存在出库记录
  4045. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time)
  4046. fmt.Println("errcode2323223255556652324242424242424242424242424242242", errcod)
  4047. if errcod == gorm.ErrRecordNotFound {
  4048. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4049. //插入详情明细表
  4050. stockFlow := models.VmStockFlow{
  4051. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4052. WarehouseOutId: warehouseOut.ID,
  4053. GoodId: good_yc.GoodId,
  4054. Number: warehouseOutInfos.Number,
  4055. ProductDate: stockInInfo.ProductDate,
  4056. ExpireDate: stockInInfo.ExpiryDate,
  4057. Count: count,
  4058. Price: stockInInfo.Price,
  4059. Status: 1,
  4060. Ctime: time.Now().Unix(),
  4061. UserOrgId: good_yc.OrgId,
  4062. Manufacturer: stockInInfo.Manufacturer,
  4063. Dealer: stockInInfo.Dealer,
  4064. LicenseNumber: stockInInfo.LicenseNumber,
  4065. IsEdit: 2,
  4066. Creator: creater,
  4067. SystemTime: record_time,
  4068. ConsumableType: 3,
  4069. WarehousingDetailId: 0,
  4070. IsSys: 1,
  4071. UpdateCreator: creater,
  4072. PatientId: patient_id,
  4073. }
  4074. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4075. if errflow == gorm.ErrRecordNotFound {
  4076. //创建流水表
  4077. err := service.CreateStockFlowOne(stockFlow)
  4078. fmt.Println("h2h3h2323342i24i242i4u2i4242u42424", err)
  4079. } else if errflow == nil {
  4080. //插入详情明细表
  4081. stockFlow := models.VmStockFlow{
  4082. ID: exsit.ID,
  4083. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4084. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4085. WarehouseOutId: warehouseOut.ID,
  4086. GoodId: good_yc.GoodId,
  4087. Number: warehouseOutInfos.Number,
  4088. ProductDate: stockInInfo.ProductDate,
  4089. ExpireDate: stockInInfo.ExpiryDate,
  4090. Count: exsit.Count - delete_count,
  4091. Price: stockInInfo.Price,
  4092. Status: 1,
  4093. Ctime: time.Now().Unix(),
  4094. UserOrgId: good_yc.OrgId,
  4095. Manufacturer: stockInInfo.Manufacturer,
  4096. Dealer: stockInInfo.Dealer,
  4097. LicenseNumber: stockInInfo.LicenseNumber,
  4098. IsEdit: 2,
  4099. Creator: creater,
  4100. SystemTime: record_time,
  4101. ConsumableType: 3,
  4102. WarehousingDetailId: 0,
  4103. IsSys: 1,
  4104. UpdateCreator: creater,
  4105. PatientId: patient_id,
  4106. }
  4107. service.UpdatedStockFlow(stockFlow)
  4108. }
  4109. if errOne != nil {
  4110. return errOne
  4111. }
  4112. } else if errcod == nil {
  4113. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time)
  4114. //插入详情明细表
  4115. stockFlow := models.VmStockFlow{
  4116. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4117. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4118. WarehouseOutId: warehouseOut.ID,
  4119. GoodId: good_yc.GoodId,
  4120. Number: warehouseOutInfos.Number,
  4121. ProductDate: stockInInfo.ProductDate,
  4122. ExpireDate: stockInInfo.ExpiryDate,
  4123. Count: count,
  4124. Price: stockInInfo.Price,
  4125. Status: 1,
  4126. Ctime: time.Now().Unix(),
  4127. UserOrgId: good_yc.OrgId,
  4128. Manufacturer: stockInInfo.Manufacturer,
  4129. Dealer: stockInInfo.Dealer,
  4130. LicenseNumber: stockInInfo.LicenseNumber,
  4131. IsEdit: 2,
  4132. Creator: creater,
  4133. SystemTime: record_time,
  4134. ConsumableType: 3,
  4135. WarehousingDetailId: 0,
  4136. IsSys: 1,
  4137. UpdateCreator: creater,
  4138. PatientId: patient_id,
  4139. ReturnCount: delete_count,
  4140. }
  4141. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4142. if errflows == gorm.ErrRecordNotFound {
  4143. //创建流水表
  4144. service.CreateStockFlowOne(stockFlow)
  4145. } else if errflows == nil {
  4146. stockFlow := models.VmStockFlow{
  4147. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4148. ID: exsit.ID,
  4149. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4150. WarehouseOutId: warehouseOut.ID,
  4151. GoodId: good_yc.GoodId,
  4152. Number: warehouseOutInfos.Number,
  4153. ProductDate: stockInInfo.ProductDate,
  4154. ExpireDate: stockInInfo.ExpiryDate,
  4155. Count: exsit.Count - delete_count,
  4156. Price: stockInInfo.Price,
  4157. Status: 1,
  4158. Ctime: time.Now().Unix(),
  4159. UserOrgId: good_yc.OrgId,
  4160. Manufacturer: stockInInfo.Manufacturer,
  4161. Dealer: stockInInfo.Dealer,
  4162. LicenseNumber: stockInInfo.LicenseNumber,
  4163. IsEdit: 2,
  4164. Creator: creater,
  4165. SystemTime: record_time,
  4166. ConsumableType: 3,
  4167. WarehousingDetailId: 0,
  4168. IsSys: 1,
  4169. UpdateCreator: creater,
  4170. PatientId: patient_id,
  4171. ReturnCount: delete_count,
  4172. }
  4173. service.UpdatedStockFlow(stockFlow)
  4174. }
  4175. }
  4176. //更改自动出库的表格
  4177. details := models.BloodAutomaticReduceDetail{
  4178. WarehouseOutId: warehouseOutInfo.ID,
  4179. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  4180. PatientId: patient_id,
  4181. Ctime: time.Now().Unix(),
  4182. Mtime: time.Now().Unix(),
  4183. Status: 1,
  4184. RecordTime: record_time,
  4185. OrgId: orgID,
  4186. GoodId: good_yc.GoodId,
  4187. GoodTypeId: good_yc.GoodTypeId,
  4188. Count: count,
  4189. }
  4190. //查询当天耗材是否已经存在数据
  4191. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4192. if errcode == gorm.ErrRecordNotFound {
  4193. errTwo := service.CreateAutoReduceRecord(&details)
  4194. if errTwo != nil {
  4195. return errTwo
  4196. }
  4197. } else if errcode == nil {
  4198. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4199. service.CreateAutoReduceRecord(&details)
  4200. }
  4201. // 删除出库完成后,要增加对应批次的库存数量
  4202. fmt.Println("deletecount2323232323232323232323232323", delete_count)
  4203. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count)
  4204. if errThree != nil {
  4205. return errThree
  4206. }
  4207. if good_yc.Count == 0 {
  4208. return nil
  4209. } else {
  4210. return errors.New("退库和出库数据不匹配")
  4211. }
  4212. }
  4213. func ConsumablesDeliveryTotalSix(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, goodOne []*models.NewDialysisBeforePrepareGoods, creater int64) (err error) {
  4214. //查询该患者当天已经出库的耗材信息
  4215. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  4216. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  4217. for i := len(goods_yc) - 1; i >= 0; i-- {
  4218. goods_yc_temp := goods_yc[i]
  4219. for j := len(goods) - 1; j >= 0; j-- {
  4220. goods_temp := goods[j]
  4221. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  4222. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  4223. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  4224. if goods_yc_temp.Count == goods_temp.Count {
  4225. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4226. goods = append(goods[:j], goods[j+1:]...)
  4227. break
  4228. }
  4229. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  4230. if goods_yc_temp.Count > goods_temp.Count {
  4231. temp_count := goods_yc_temp.Count - goods_temp.Count
  4232. goods_yc[i].Count = temp_count
  4233. goods = append(goods[:j], goods[j+1:]...)
  4234. break
  4235. }
  4236. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  4237. if goods_yc_temp.Count < goods_temp.Count {
  4238. temp_count := goods_temp.Count - goods_yc_temp.Count
  4239. goods[j].Count = temp_count
  4240. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4241. break
  4242. }
  4243. }
  4244. }
  4245. }
  4246. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  4247. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  4248. fmt.Println("goods222222222222", goods)
  4249. fmt.Println("goodsy999999999999", goods_yc)
  4250. if len(goods) > 0 {
  4251. out, err := service.FindStockOutByIsSys(orgID, 1, record_time)
  4252. if err == gorm.ErrRecordNotFound {
  4253. //没有记录,则创建出库单
  4254. timeStr := time.Now().Format("2006-01-02")
  4255. timeArr := strings.Split(timeStr, "-")
  4256. total, _ := service.FindAllWarehouseOut(orgID)
  4257. total = total + 1
  4258. warehousing_out_order := strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4259. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4260. number = number + total
  4261. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4262. warehouseOut := models.WarehouseOut{
  4263. WarehouseOutOrderNumber: warehousing_out_order,
  4264. OperationTime: time.Now().Unix(),
  4265. OrgId: orgID,
  4266. Creater: creater,
  4267. Ctime: time.Now().Unix(),
  4268. Status: 1,
  4269. WarehouseOutTime: record_time,
  4270. Dealer: 0,
  4271. Manufacturer: 0,
  4272. Type: 1,
  4273. IsSys: 1,
  4274. }
  4275. err := service.AddSigleWarehouseOut(&warehouseOut)
  4276. if err != nil {
  4277. utils.TraceLog("创建出库单失败 err = %v", err)
  4278. return err
  4279. } else {
  4280. out = warehouseOut
  4281. }
  4282. }
  4283. for _, item := range goods {
  4284. var newCount int64 = 0
  4285. for _, it := range goodOne {
  4286. if item.GoodTypeId == it.GoodTypeId && item.GoodId == it.GoodId {
  4287. newCount = it.Count
  4288. }
  4289. }
  4290. prepare := models.DialysisBeforePrepare{
  4291. GoodTypeId: item.GoodTypeId,
  4292. GoodId: item.GoodId,
  4293. Count: item.Count,
  4294. }
  4295. fmt.Println("到这里了吗34344343434334343434", newCount)
  4296. service.ConsumablesDelivery(orgID, patient_id, record_time, &prepare, &out, newCount)
  4297. }
  4298. }
  4299. if len(goods_yc) > 0 {
  4300. for _, good_yc := range goods_yc {
  4301. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  4302. ConsumablesDeliveryDeleteThree(orgID, record_time, good_yc, &out)
  4303. }
  4304. }
  4305. return nil
  4306. }
  4307. //耗材出库删除
  4308. func ConsumablesDeliveryDeleteThree(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut) (err error) {
  4309. // 先根据相关信息查询当天该耗材的出库信息
  4310. warehouseOutInfos, err := service.FindStockOutInfoByStockOne(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time)
  4311. if err != nil {
  4312. return err
  4313. }
  4314. var delete_count int64 = 0
  4315. for _, ware := range warehouseOutInfos {
  4316. // 判断当前出库的数据和删除出库数量
  4317. if good_yc.Count <= ware.Count {
  4318. delete_count = good_yc.Count
  4319. } else {
  4320. delete_count = ware.Count
  4321. }
  4322. // 在出库记录表里记录退库详情
  4323. warehouseOutInfo := &models.WarehouseOutInfo{
  4324. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4325. WarehouseOutId: warehouseOut.ID,
  4326. Status: 1,
  4327. Ctime: time.Now().Unix(),
  4328. Remark: "",
  4329. OrgId: orgID,
  4330. Type: 1,
  4331. Manufacturer: 0,
  4332. Dealer: 0,
  4333. IsSys: 0,
  4334. SysRecordTime: record_time,
  4335. GoodTypeId: good_yc.GoodTypeId,
  4336. GoodId: good_yc.GoodId,
  4337. }
  4338. warehouseOutInfo.Count = delete_count
  4339. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4340. warehouseOutInfo.Price = stockInInfo.Price
  4341. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4342. if errOne != nil {
  4343. return errOne
  4344. }
  4345. //更改自动出库的表格
  4346. // 删除出库完成后,要增加对应批次的库存数量
  4347. fmt.Println("deletecount2323232323232323232323232323", delete_count)
  4348. errThree := service.UpDateWarehouseInfoByStockDelete(ware.WarehouseInfotId, delete_count)
  4349. if errThree != nil {
  4350. return errThree
  4351. }
  4352. }
  4353. if good_yc.Count == 0 {
  4354. return nil
  4355. } else {
  4356. return errors.New("退库和出库数据不匹配")
  4357. }
  4358. }