dialysis_api_controller.go 182KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022
  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. "XT_New/enums"
  12. "XT_New/models"
  13. "XT_New/service"
  14. "XT_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(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(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(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(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 || adminUserInfo.Org.Id == 10215 || adminUserInfo.Org.Id == 10233 || adminUserInfo.Org.Id == 10223 {
  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 == 10233 {
  1356. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume / 1000
  1357. }
  1358. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10060 {
  1359. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1360. }
  1361. if lastAssessmentAfterDislysis != nil {
  1362. tempassessmentAfterDislysis.BloodPressureType = lastAssessmentAfterDislysis.BloodPressureType
  1363. tempassessmentAfterDislysis.WeighingWay = lastAssessmentAfterDislysis.WeighingWay
  1364. tempassessmentAfterDislysis.Cruor = lastAssessmentAfterDislysis.Cruor
  1365. tempassessmentAfterDislysis.SymptomAfterDialysis = lastAssessmentAfterDislysis.SymptomAfterDialysis
  1366. tempassessmentAfterDislysis.InternalFistula = lastAssessmentAfterDislysis.InternalFistula
  1367. tempassessmentAfterDislysis.Catheter = lastAssessmentAfterDislysis.Catheter
  1368. tempassessmentAfterDislysis.Complication = lastAssessmentAfterDislysis.Complication
  1369. tempassessmentAfterDislysis.DialysisIntakes = lastAssessmentAfterDislysis.DialysisIntakes
  1370. tempassessmentAfterDislysis.DialysisIntakesFeed = lastAssessmentAfterDislysis.DialysisIntakesFeed
  1371. tempassessmentAfterDislysis.DialysisIntakesTransfusion = lastAssessmentAfterDislysis.DialysisIntakesTransfusion
  1372. tempassessmentAfterDislysis.DialysisIntakesBloodTransfusion = lastAssessmentAfterDislysis.DialysisIntakesBloodTransfusion
  1373. tempassessmentAfterDislysis.DialysisIntakesWashpipe = lastAssessmentAfterDislysis.DialysisIntakesWashpipe
  1374. tempassessmentAfterDislysis.BloodAccessPartId = lastAssessmentAfterDislysis.BloodAccessPartId
  1375. tempassessmentAfterDislysis.BloodAccessPartOperaId = lastAssessmentAfterDislysis.BloodAccessPartOperaId
  1376. tempassessmentAfterDislysis.PuncturePointOozingBlood = lastAssessmentAfterDislysis.PuncturePointOozingBlood
  1377. tempassessmentAfterDislysis.PuncturePointHaematoma = lastAssessmentAfterDislysis.PuncturePointHaematoma
  1378. tempassessmentAfterDislysis.InternalFistulaTremorAc = lastAssessmentAfterDislysis.InternalFistulaTremorAc
  1379. tempassessmentAfterDislysis.PatientGose = lastAssessmentAfterDislysis.PatientGose
  1380. tempassessmentAfterDislysis.InpatientDepartment = lastAssessmentAfterDislysis.InpatientDepartment
  1381. tempassessmentAfterDislysis.ObservationContent = lastAssessmentAfterDislysis.ObservationContent
  1382. tempassessmentAfterDislysis.ObservationContentOther = lastAssessmentAfterDislysis.ObservationContentOther
  1383. tempassessmentAfterDislysis.DryWeight = lastAssessmentAfterDislysis.DryWeight
  1384. tempassessmentAfterDislysis.DialysisProcess = lastAssessmentAfterDislysis.DialysisProcess
  1385. tempassessmentAfterDislysis.InAdvanceMinute = lastAssessmentAfterDislysis.InAdvanceMinute
  1386. tempassessmentAfterDislysis.InAdvanceReason = lastAssessmentAfterDislysis.InAdvanceReason
  1387. tempassessmentAfterDislysis.HemostasisMinute = lastAssessmentAfterDislysis.HemostasisMinute
  1388. tempassessmentAfterDislysis.HemostasisOpera = lastAssessmentAfterDislysis.HemostasisOpera
  1389. tempassessmentAfterDislysis.TremorNoise = lastAssessmentAfterDislysis.TremorNoise
  1390. tempassessmentAfterDislysis.DisequilibriumSyndrome = lastAssessmentAfterDislysis.DisequilibriumSyndrome
  1391. tempassessmentAfterDislysis.DisequilibriumSyndromeOption = lastAssessmentAfterDislysis.DisequilibriumSyndromeOption
  1392. tempassessmentAfterDislysis.ArterialTube = lastAssessmentAfterDislysis.ArterialTube
  1393. tempassessmentAfterDislysis.IntravenousTube = lastAssessmentAfterDislysis.IntravenousTube
  1394. tempassessmentAfterDislysis.Dialyzer = lastAssessmentAfterDislysis.Dialyzer
  1395. tempassessmentAfterDislysis.InAdvanceReasonOther = lastAssessmentAfterDislysis.InAdvanceReasonOther
  1396. tempassessmentAfterDislysis.IsEat = lastAssessmentAfterDislysis.IsEat
  1397. tempassessmentAfterDislysis.DialysisIntakesUnit = lastAssessmentAfterDislysis.DialysisIntakesUnit
  1398. tempassessmentAfterDislysis.CvcA = lastAssessmentAfterDislysis.CvcA
  1399. tempassessmentAfterDislysis.CvcV = lastAssessmentAfterDislysis.CvcV
  1400. tempassessmentAfterDislysis.Channel = lastAssessmentAfterDislysis.Channel
  1401. tempassessmentAfterDislysis.ReturnBlood = lastAssessmentAfterDislysis.ReturnBlood
  1402. tempassessmentAfterDislysis.RehydrationVolume = lastAssessmentAfterDislysis.RehydrationVolume
  1403. tempassessmentAfterDislysis.DialysisDuring = lastAssessmentAfterDislysis.DialysisDuring
  1404. tempassessmentAfterDislysis.StrokeVolume = lastAssessmentAfterDislysis.StrokeVolume
  1405. tempassessmentAfterDislysis.BloodFlow = lastAssessmentAfterDislysis.BloodFlow
  1406. tempassessmentAfterDislysis.SealingFluidDispose = lastAssessmentAfterDislysis.SealingFluidDispose
  1407. tempassessmentAfterDislysis.SealingFluidSpecial = lastAssessmentAfterDislysis.SealingFluidSpecial
  1408. }
  1409. err := service.UpdateAssessmentAfterDislysisRecord(&tempassessmentAfterDislysis)
  1410. if err != nil {
  1411. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1412. return
  1413. }
  1414. if dialysisOrder == nil {
  1415. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoStart)
  1416. return
  1417. }
  1418. if dialysisOrder.Stage == 2 {
  1419. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoEND)
  1420. return
  1421. }
  1422. if dialysisOrder.Stage == 1 {
  1423. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id)
  1424. //结束时候透析次数加1
  1425. service.UpdateSolutionByPatientId(id)
  1426. dialysisOrder.Stage = 2
  1427. dialysisOrder.FinishNurse = nurseID
  1428. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1429. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1430. dialysisOrder.EndTime = endDate.Unix()
  1431. go func() {
  1432. ssoDomain := beego.AppConfig.String("call_domain")
  1433. api := ssoDomain + "/index/downpatient"
  1434. values := make(url.Values)
  1435. values.Set("org_id", strconv.FormatInt(adminUserInfo.AdminUser.Id, 10))
  1436. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1437. values.Set("patient_id", strconv.FormatInt(id, 10))
  1438. http.PostForm(api, values)
  1439. }()
  1440. if err == nil {
  1441. c.ServeSuccessJSON(map[string]interface{}{
  1442. "dialysisOrder": dialysisOrder,
  1443. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1444. })
  1445. } else {
  1446. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1447. }
  1448. }
  1449. }
  1450. func (c *DialysisAPIController) GetAllZone() {
  1451. adminUserInfo := c.GetMobileAdminUserInfo()
  1452. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1453. if err == nil {
  1454. c.ServeSuccessJSON(map[string]interface{}{
  1455. "zone": zone,
  1456. })
  1457. }
  1458. }
  1459. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1460. adminUserInfo := c.GetMobileAdminUserInfo()
  1461. page, _ := c.GetInt64("page", 1)
  1462. limit, _ := c.GetInt64("limit", 10)
  1463. schedulType, _ := c.GetInt64("schedul_type", 0)
  1464. startTime, _ := c.GetInt64("schedul_time", 0)
  1465. partitionType, _ := c.GetInt64("partition_type", 0)
  1466. keywords := c.GetString("keywords")
  1467. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1468. if err == nil {
  1469. c.ServeSuccessJSON(map[string]interface{}{
  1470. "schedule": dialysisSchedule,
  1471. })
  1472. }
  1473. return
  1474. }
  1475. // /m/api/dialysis/start [post]
  1476. // @param patient_id:int
  1477. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1478. // @param nurse:int 上机护士
  1479. // @param bed:int 床位号
  1480. func (this *DialysisAPIController) StartDialysis() {
  1481. patientID, _ := this.GetInt64("patient_id")
  1482. recordDateStr := this.GetString("record_date")
  1483. nurseID, _ := this.GetInt64("nurse")
  1484. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1485. blood_drawing, _ := this.GetInt64("blood_drawing")
  1486. schedual_type, _ := this.GetInt64("schedual_type")
  1487. bedID, _ := this.GetInt64("bed")
  1488. start_time := this.GetString("start_time")
  1489. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1490. change_nurse, _ := this.GetInt64("change_nurse")
  1491. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1492. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1493. zone_id, _ := this.GetInt64("zone_id")
  1494. fmt.Println("zone23333232323232232332232323", zone_id)
  1495. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1496. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1497. return
  1498. }
  1499. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1500. if parseStartDateErr != nil {
  1501. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1502. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1503. return
  1504. }
  1505. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1506. if parseErr != nil {
  1507. this.ErrorLog("时间解析失败:%v", parseErr)
  1508. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1509. return
  1510. }
  1511. adminUserInfo := this.GetMobileAdminUserInfo()
  1512. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1513. if getPatientErr != nil {
  1514. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1515. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1516. return
  1517. } else if patient == nil {
  1518. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1519. return
  1520. }
  1521. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1522. if getNurseErr != nil {
  1523. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1524. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1525. return
  1526. } else if nurse == nil {
  1527. this.ErrorLog("护士不存在")
  1528. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1529. return
  1530. }
  1531. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1532. //if getNurseErr != nil {
  1533. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  1534. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1535. // return
  1536. //} else if nurse == nil {
  1537. // this.ErrorLog("护士不存在")
  1538. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1539. // return
  1540. //}
  1541. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1542. if getDeviceNumberErr != nil {
  1543. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1544. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1545. return
  1546. } else if deviceNumber == nil {
  1547. this.ErrorLog("床位号不存在")
  1548. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1549. return
  1550. }
  1551. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1552. if getRecordErr != nil {
  1553. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1554. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1555. return
  1556. } else if dialysisRecord != nil {
  1557. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1558. return
  1559. }
  1560. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1561. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1562. timeLayout := "2006-01-02 15:04:05"
  1563. loc, _ := time.LoadLocation("Local")
  1564. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1565. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1566. schedulestartTime := theStartTime.Unix()
  1567. scheduleendTime := theEndTime.Unix()
  1568. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1569. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1570. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1571. //查询该床位是否有人用了
  1572. order, order_err := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1573. if err == gorm.ErrRecordNotFound { //空床位
  1574. // 修改了床位逻辑
  1575. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1576. if daySchedule.ID > 0 {
  1577. daySchedule.PartitionId = deviceNumber.ZoneID
  1578. daySchedule.BedId = bedID
  1579. daySchedule.ScheduleType = schedual_type
  1580. daySchedule.UpdatedTime = time.Now().Unix()
  1581. err := service.UpdateSchedule(&daySchedule)
  1582. if err != nil {
  1583. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1584. return
  1585. }
  1586. }
  1587. } else if err == nil {
  1588. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1589. if order_err == nil {
  1590. if order.ID > 0 { //该机位被其他人占用了
  1591. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1592. return
  1593. } else {
  1594. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1595. if daySchedule.ID > 0 {
  1596. daySchedule.PartitionId = deviceNumber.ZoneID
  1597. daySchedule.BedId = bedID
  1598. daySchedule.ScheduleType = schedual_type
  1599. daySchedule.UpdatedTime = time.Now().Unix()
  1600. err := service.UpdateSchedule(&daySchedule)
  1601. if err != nil {
  1602. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1603. return
  1604. }
  1605. }
  1606. }
  1607. } else if order_err == gorm.ErrRecordNotFound { //该床位没被占用
  1608. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1609. if daySchedule.ID > 0 {
  1610. daySchedule.PartitionId = deviceNumber.ZoneID
  1611. daySchedule.BedId = bedID
  1612. daySchedule.ScheduleType = schedual_type
  1613. daySchedule.UpdatedTime = time.Now().Unix()
  1614. err := service.UpdateSchedule(&daySchedule)
  1615. if err != nil {
  1616. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1617. return
  1618. }
  1619. }
  1620. }
  1621. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1622. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1623. return
  1624. }
  1625. } else if err != nil {
  1626. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1627. return
  1628. }
  1629. dialysisRecord = &models.DialysisOrder{
  1630. DialysisDate: recordDate.Unix(),
  1631. UserOrgId: adminUserInfo.Org.Id,
  1632. PatientId: patientID,
  1633. Stage: 1,
  1634. BedID: bedID,
  1635. StartNurse: nurseID,
  1636. Status: 1,
  1637. StartTime: startDate.Unix(),
  1638. CreatedTime: time.Now().Unix(),
  1639. UpdatedTime: time.Now().Unix(),
  1640. PunctureNurse: puncture_nurse,
  1641. Creator: adminUserInfo.AdminUser.Id,
  1642. Modifier: adminUserInfo.AdminUser.Id,
  1643. SchedualType: schedual_type,
  1644. WashpipeNurse: washpipe_nurse,
  1645. ChangeNurse: change_nurse,
  1646. DifficultPunctureNurse: difficult_puncture_nurse,
  1647. NewFistulaNurse: new_fistula_nurse,
  1648. ZoneId: zone_id,
  1649. }
  1650. //查询该床位是否有人用了
  1651. _, errorscode := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1652. if errorscode == gorm.ErrRecordNotFound {
  1653. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  1654. if createErr != nil {
  1655. this.ErrorLog("上机失败:%v", createErr)
  1656. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1657. return
  1658. }
  1659. }
  1660. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1661. var tempdispose string
  1662. // 只针对中能建
  1663. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  1664. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  1665. }
  1666. var ultrafiltration_rate float64
  1667. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1668. //后期预增脱水量
  1669. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1670. fmt.Println(evaluation)
  1671. if prescription.ID > 0 {
  1672. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1673. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1674. if (template.TemplateId == 6 || template.TemplateId == 32) && adminUserInfo.Org.Id != 9671 { //adminUserInfo.Org.Id == 9538
  1675. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1676. }
  1677. //针对医师汇
  1678. if adminUserInfo.Org.Id == 10121 {
  1679. dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  1680. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  1681. }
  1682. //针对通道
  1683. if adminUserInfo.Org.Id == 10234 {
  1684. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration) / float64(totalMin) * 60 * 1000)
  1685. }
  1686. //针对监利大垸医院
  1687. if template.TemplateId == 41 {
  1688. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  1689. }
  1690. //针对肇庆三鹤血液透析中心
  1691. if template.TemplateId == 43 {
  1692. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  1693. fmt.Println("hhhh232332322323232332", ultrafiltration_rate)
  1694. }
  1695. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  1696. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1697. }
  1698. // 只针对方济医院
  1699. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  1700. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1701. ultrafiltration_rate = value
  1702. }
  1703. }
  1704. }
  1705. record := models.MonitoringRecord{
  1706. UserOrgId: adminUserInfo.Org.Id,
  1707. PatientId: patientID,
  1708. DialysisOrderId: dialysisRecord.ID,
  1709. MonitoringDate: schedulestartTime,
  1710. OperateTime: startDate.Unix(),
  1711. // MonitoringTime: recordTime,
  1712. MonitoringNurse: nurseID,
  1713. Dispose: tempdispose,
  1714. UltrafiltrationRate: ultrafiltration_rate,
  1715. UltrafiltrationVolume: 0,
  1716. Status: 1,
  1717. CreatedTime: time.Now().Unix(),
  1718. UpdatedTime: time.Now().Unix(),
  1719. }
  1720. //只针对广慈医院
  1721. if template.TemplateId == 26 || template.TemplateId == 25 || template.TemplateId == 28 || adminUserInfo.Org.Id == 9987 || adminUserInfo.Org.Id == 9526 || template.TemplateId == 32 {
  1722. // 查询病人是否有透前评估数据
  1723. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1724. //如果有数据就插入
  1725. if errcode == nil {
  1726. record.SystolicBloodPressure = befor.SystolicBloodPressure
  1727. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  1728. record.BreathingRate = befor.BreathingRate
  1729. record.PulseFrequency = befor.PulseFrequency
  1730. record.Temperature = befor.Temperature
  1731. }
  1732. }
  1733. // 如果当天有插入数据,则不再往透析纪录里插入数据
  1734. if newdialysisRecord.ID > 0 {
  1735. err := service.CreateMonitor(&record)
  1736. if err != nil {
  1737. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  1738. return
  1739. }
  1740. }
  1741. go func() {
  1742. ssoDomain := beego.AppConfig.String("call_domain")
  1743. api := ssoDomain + "/index/uppatient"
  1744. values := make(url.Values)
  1745. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  1746. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1747. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  1748. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  1749. http.PostForm(api, values)
  1750. }()
  1751. this.ServeSuccessJSON(map[string]interface{}{
  1752. "dialysis_order": newdialysisRecord,
  1753. "monitor": record,
  1754. })
  1755. }
  1756. func (c *DialysisAPIController) PostSolution() {
  1757. id, _ := c.GetInt64("patient", 0)
  1758. recordDateStr := c.GetString("record_date")
  1759. if id <= 0 {
  1760. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1761. return
  1762. }
  1763. adminUserInfo := c.GetMobileAdminUserInfo()
  1764. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1765. if patient.ID == 0 {
  1766. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1767. return
  1768. }
  1769. if len(recordDateStr) == 0 {
  1770. recordDateStr = time.Now().Format("2006-01-02")
  1771. }
  1772. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1773. if parseDateErr != nil {
  1774. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1775. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1776. return
  1777. }
  1778. mode_id, _ := c.GetInt64("mode_id", 0)
  1779. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1780. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1781. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1782. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1783. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1784. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1785. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1786. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1787. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1788. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1789. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1790. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1791. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1792. kalium, _ := c.GetFloat("kalium", 0)
  1793. sodium, _ := c.GetFloat("sodium", 0)
  1794. calcium, _ := c.GetFloat("calcium", 0)
  1795. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1796. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1797. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1798. glucose, _ := c.GetFloat("glucose", 0)
  1799. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1800. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1801. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1802. conductivity, _ := c.GetFloat("conductivity", 0)
  1803. remark := c.GetString("remark")
  1804. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1805. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1806. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1807. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1808. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1809. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1810. special_medicine_other := c.GetString("special_medicine_other")
  1811. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1812. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1813. blood_access, _ := c.GetInt64("blood_access", 0)
  1814. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1815. body_fluid_other := c.GetString("body_fluid_other")
  1816. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1817. niprocart, _ := c.GetInt64("niprocart", 0)
  1818. jms, _ := c.GetInt64("jms", 0)
  1819. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1820. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1821. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1822. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1823. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1824. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1825. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1826. injector, _ := c.GetInt64("injector", 0)
  1827. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1828. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1829. safe_package, _ := c.GetInt64("package", 0)
  1830. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1831. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1832. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1833. blood := c.GetString("blood")
  1834. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  1835. dialysis_irrigation := c.GetString("dialysis_irrigation")
  1836. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  1837. displace_speed := c.GetString("displace_speed")
  1838. illness, _ := c.GetInt64("illness")
  1839. amylaceum := c.GetString("amylaceum")
  1840. single_time := c.GetString("single_time")
  1841. single_water := c.GetString("single_water")
  1842. replacement_flow := c.GetString("replacement_flow")
  1843. plasma_separator := c.GetString("plasma_separator")
  1844. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  1845. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  1846. oxygen_flow := c.GetString("oxygen_flow")
  1847. oxygen_time := c.GetString("oxygen_time")
  1848. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  1849. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  1850. puncture_needle := c.GetString("puncture_needle")
  1851. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  1852. epo := c.GetString("epo")
  1853. epo_count, _ := c.GetFloat("epo_count", 0)
  1854. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  1855. if mode_id > 0 {
  1856. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1857. }
  1858. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1859. //
  1860. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1861. // if appRole.UserType == 3 {
  1862. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1863. // if getPermissionErr != nil {
  1864. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1865. // return
  1866. // } else if headNursePermission == nil {
  1867. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1868. // return
  1869. // }
  1870. // }
  1871. //}
  1872. prescription := models.DialysisPrescription{
  1873. UserOrgId: adminUserInfo.Org.Id,
  1874. PatientId: id,
  1875. RecordDate: recordDate.Unix(),
  1876. ModeId: mode_id,
  1877. DialysisDuration: dialysis_duration,
  1878. Dialyzer: dialyzer,
  1879. PerfusionApparatus: perfusion_apparatus,
  1880. BloodFlowVolume: blood_flow_volume,
  1881. DewaterAmount: dewater_amount,
  1882. DisplaceLiqui: displace_liqui,
  1883. ReplacementWay: replacement_way,
  1884. Anticoagulant: anticoagulant,
  1885. AnticoagulantShouji: anticoagulant_shouji,
  1886. AnticoagulantWeichi: anticoagulant_weichi,
  1887. AnticoagulantZongliang: anticoagulant_zongliang,
  1888. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1889. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1890. Kalium: kalium,
  1891. Sodium: sodium,
  1892. Calcium: calcium,
  1893. Bicarbonate: bicarbonate,
  1894. Glucose: glucose,
  1895. // DryWeight: dry_weight,
  1896. DialysateFlow: dialysate_flow,
  1897. DialysateTemperature: dialysate_temperature,
  1898. Conductivity: conductivity,
  1899. Remark: remark,
  1900. Status: 1,
  1901. CreatedTime: time.Now().Unix(),
  1902. UpdatedTime: time.Now().Unix(),
  1903. DialysisDurationMinute: dialysisDurationMinute,
  1904. DialysisDurationHour: dialysisDurationHour,
  1905. TargetUltrafiltration: targetUltrafiltration,
  1906. DialysateFormulation: dialysateFormulation,
  1907. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1908. BodyFluid: body_fluid,
  1909. SpecialMedicine: special_medicine,
  1910. SpecialMedicineOther: special_medicine_other,
  1911. DisplaceLiquiPart: displace_liqui_part,
  1912. DisplaceLiquiValue: displace_liqui_value,
  1913. BloodAccess: blood_access,
  1914. Ultrafiltration: ultrafiltration,
  1915. BodyFluidOther: body_fluid_other,
  1916. ReplacementTotal: replacement_total,
  1917. Niprocart: niprocart,
  1918. Jms: jms,
  1919. FistulaNeedleSet: fistula_needle_set,
  1920. FistulaNeedleSet16: fistula_needle_set_16,
  1921. Hemoperfusion: hemoperfusion,
  1922. DialyserSterilised: dialyser_sterilised,
  1923. Filtryzer: filtryzer,
  1924. TargetKtv: target_ktv,
  1925. Dialyzers: dialyzers,
  1926. Injector: injector,
  1927. Bloodlines: bloodlines,
  1928. TubingHemodialysis: tubing_hemodialysis,
  1929. Package: safe_package,
  1930. ALiquid: a_liquid,
  1931. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1932. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1933. Blood: blood,
  1934. DialysisDialyszers: dialysis_dialyszers,
  1935. DialysisIrrigation: dialysis_irrigation,
  1936. AntioxidantCommodityName: antioxidant_commodity_name,
  1937. DisplaceSpeed: displace_speed,
  1938. Illness: illness,
  1939. Amylaceum: amylaceum,
  1940. SingleWater: single_water,
  1941. SingleTime: single_time,
  1942. ReplacementFlow: replacement_flow,
  1943. PlasmaSeparator: plasma_separator,
  1944. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  1945. OxygenUptake: oxygen_uptake,
  1946. OxygenTime: oxygen_time,
  1947. OxygenFlow: oxygen_flow,
  1948. HemodialysisPipelines: hemodialysis_pipelines,
  1949. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  1950. PunctureNeedle: puncture_needle,
  1951. PunctureNeedleCount: puncture_needle_count,
  1952. Epo: epo,
  1953. EpoCount: epo_count,
  1954. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  1955. }
  1956. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1957. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1958. //
  1959. if appRole.UserType == 2 || appRole.UserType == 1 {
  1960. prescription_doctor = adminUserInfo.AdminUser.Id
  1961. prescription.PrescriptionDoctor = prescription_doctor
  1962. }
  1963. if dialysisPrescription.ID == 0 { //新增
  1964. prescription.Creater = adminUserInfo.AdminUser.Id
  1965. } else { //修改
  1966. if dialysisPrescription.Creater == 0 {
  1967. prescription.Creater = adminUserInfo.AdminUser.Id
  1968. } else {
  1969. prescription.Creater = dialysisPrescription.Creater
  1970. }
  1971. //if/**/
  1972. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1973. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  1974. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1975. // if getPermissionErr != nil {
  1976. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1977. // return
  1978. // } else if headNursePermission == nil {
  1979. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1980. // return
  1981. // }
  1982. //}
  1983. //prescription.Creater = dialysisPrescription.Creater
  1984. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1985. prescription.Modifier = adminUserInfo.AdminUser.Id
  1986. prescription.ID = dialysisPrescription.ID
  1987. }
  1988. solution := models.DialysisSolution{
  1989. RegistrarsId: adminUserInfo.AdminUser.Id,
  1990. UserOrgId: adminUserInfo.Org.Id,
  1991. Doctor: prescription_doctor,
  1992. PatientId: id,
  1993. ModeId: mode_id,
  1994. DialysisDuration: dialysis_duration,
  1995. PerfusionApparatus: perfusion_apparatus,
  1996. BloodFlowVolume: blood_flow_volume,
  1997. Dewater: dewater_amount,
  1998. DisplaceLiqui: displace_liqui,
  1999. ReplacementWay: replacement_way,
  2000. Anticoagulant: anticoagulant,
  2001. AnticoagulantShouji: anticoagulant_shouji,
  2002. AnticoagulantWeichi: anticoagulant_weichi,
  2003. AnticoagulantZongliang: anticoagulant_zongliang,
  2004. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  2005. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  2006. Kalium: kalium,
  2007. Sodium: sodium,
  2008. Calcium: calcium,
  2009. Bicarbonate: bicarbonate,
  2010. Glucose: glucose,
  2011. // DryWeight: dry_weight,
  2012. DialysateFlow: dialysate_flow,
  2013. DialysateTemperature: dialysate_temperature,
  2014. Conductivity: conductivity,
  2015. Remark: remark,
  2016. Status: 1,
  2017. CreatedTime: time.Now().Unix(),
  2018. UpdatedTime: time.Now().Unix(),
  2019. DialysisDurationMinute: dialysisDurationMinute,
  2020. DialysisDurationHour: dialysisDurationHour,
  2021. TargetUltrafiltration: targetUltrafiltration,
  2022. DialysateFormulation: dialysateFormulation,
  2023. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2024. BodyFluid: body_fluid,
  2025. SpecialMedicine: special_medicine,
  2026. SpecialMedicineOther: special_medicine_other,
  2027. DisplaceLiquiPart: displace_liqui_part,
  2028. DisplaceLiquiValue: displace_liqui_value,
  2029. BloodAccess: blood_access,
  2030. Ultrafiltration: ultrafiltration,
  2031. BodyFluidOther: body_fluid_other,
  2032. ReplacementTotal: replacement_total,
  2033. TargetKtv: target_ktv,
  2034. DialysisDialyszers: dialysis_dialyszers,
  2035. DialysisIrrigation: dialysis_irrigation,
  2036. HemodialysisPipelines: hemodialysis_pipelines,
  2037. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2038. PunctureNeedle: puncture_needle,
  2039. PunctureNeedleCount: puncture_needle_count,
  2040. Epo: epo,
  2041. EpoCount: epo_count,
  2042. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2043. }
  2044. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  2045. //查询最近透析准备表里是否存在 透析器 灌流器
  2046. //splitStr := strings.Split(dialysis_dialyszers, ",")
  2047. //
  2048. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  2049. //
  2050. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  2051. //if len(mation)>0{
  2052. // for _, item := range splitStr {
  2053. // for _,it := range mation{
  2054. // if(item == it.SpecificationName){
  2055. //
  2056. // //查询最近一次的透析器
  2057. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2058. //
  2059. // if errcode == gorm.ErrRecordNotFound{
  2060. // //插入数据
  2061. // prepare := models.DialysisBeforePrepare{
  2062. // UserOrgId: adminUserInfo.Org.Id,
  2063. // PatientId: id,
  2064. // RecordDate: recordDate.Unix(),
  2065. // GoodTypeId: it.GoodTypeId,
  2066. // GoodId: it.ID,
  2067. // Count: 1,
  2068. // Ctime: time.Now().Unix(),
  2069. // Creater: adminUserInfo.AdminUser.Id,
  2070. // Status:1,
  2071. //
  2072. // }
  2073. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2074. // fmt.Println("",errcode)
  2075. // }
  2076. // }
  2077. // }
  2078. //
  2079. // }
  2080. //
  2081. // for _, item := range splitIrrigation {
  2082. // for _,it := range mation{
  2083. // if(item == it.SpecificationName){
  2084. // //查询最近一次的透析器
  2085. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2086. // if errcode == gorm.ErrRecordNotFound{
  2087. // //插入数据
  2088. // prepare := models.DialysisBeforePrepare{
  2089. // UserOrgId: adminUserInfo.Org.Id,
  2090. // PatientId: id,
  2091. // RecordDate: recordDate.Unix(),
  2092. // GoodTypeId: it.GoodTypeId,
  2093. // GoodId: it.ID,
  2094. // Count: 1,
  2095. // Ctime: time.Now().Unix(),
  2096. // Creater: adminUserInfo.AdminUser.Id,
  2097. // Status:1,
  2098. //
  2099. // }
  2100. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2101. // fmt.Println(errcode)
  2102. // }
  2103. // }
  2104. // }
  2105. // }
  2106. //}
  2107. c.ServeSuccessJSON(map[string]interface{}{
  2108. "solution": &solution,
  2109. "prescription": &prescription,
  2110. })
  2111. }
  2112. func (c *DialysisAPIController) GetAcceptsAssessment() {
  2113. patient, _ := c.GetInt64("patient", 0)
  2114. adminUserInfo := c.GetMobileAdminUserInfo()
  2115. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  2116. c.ServeSuccessJSON(map[string]interface{}{
  2117. "receiveTreatmentAsses": receiveTreatmentAsses,
  2118. })
  2119. }
  2120. func (this *DialysisAPIController) PostSignInfo() {
  2121. patientID, _ := this.GetInt64("patient_id")
  2122. recordDateStr := this.GetString("date")
  2123. if patientID <= 0 {
  2124. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2125. return
  2126. }
  2127. if len(recordDateStr) == 0 {
  2128. recordDateStr = time.Now().Format("2006-01-02")
  2129. }
  2130. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2131. if parseDateErr != nil {
  2132. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2133. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2134. return
  2135. }
  2136. adminInfo := this.GetMobileAdminUserInfo()
  2137. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  2138. if err != nil {
  2139. this.ErrorLog("签名失败:%v", err)
  2140. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2141. return
  2142. }
  2143. this.ServeSuccessJSON(map[string]interface{}{
  2144. "doctor_id": adminInfo.AdminUser.Id,
  2145. })
  2146. }
  2147. func (this *DialysisAPIController) GetLastMonitorRecord() {
  2148. patientID, _ := this.GetInt64("patient_id")
  2149. adminInfo := this.GetMobileAdminUserInfo()
  2150. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  2151. this.ServeSuccessJSON(map[string]interface{}{
  2152. "monitor": record,
  2153. })
  2154. }
  2155. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  2156. thisTime := time.Now()
  2157. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  2158. timeLayout := "2006-01-02 15:04:05"
  2159. loc, _ := time.LoadLocation("Local")
  2160. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2161. theAssessmentDateTime := theStartTime.Unix()
  2162. patientID, _ := this.GetInt64("patient_id")
  2163. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  2164. adminInfo := this.GetMobileAdminUserInfo()
  2165. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2166. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2167. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  2168. var ultrafiltration_rate float64
  2169. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2170. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2171. fmt.Println(evaluation)
  2172. if prescription.ID > 0 {
  2173. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2174. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2175. if template.TemplateId == 6 && adminInfo.Org.Id != 9538 {
  2176. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2177. record.UltrafiltrationRate = ultrafiltration_rate
  2178. }
  2179. //if template.TemplateId == 6 && adminInfo.Org.Id ==9671{
  2180. // dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  2181. // ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  2182. // record.UltrafiltrationRate = ultrafiltration_rate
  2183. //}
  2184. if template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 {
  2185. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1)
  2186. record.UltrafiltrationRate = ultrafiltration_rate
  2187. }
  2188. if template.TemplateId == 20 || template.TemplateId == 22 {
  2189. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2190. record.UltrafiltrationRate = ultrafiltration_rate
  2191. }
  2192. // 只针对方济医院
  2193. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  2194. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2195. ultrafiltration_rate = value
  2196. record.UltrafiltrationRate = ultrafiltration_rate
  2197. }
  2198. if template.TemplateId == 41 {
  2199. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  2200. record.UltrafiltrationRate = ultrafiltration_rate
  2201. }
  2202. if template.TemplateId == 43 {
  2203. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2204. record.UltrafiltrationRate = ultrafiltration_rate
  2205. }
  2206. }
  2207. }
  2208. // record.UltrafiltrationRate = ultrafiltration_rate
  2209. record.UltrafiltrationVolume = 0
  2210. 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
  2211. if ultrafiltration_rate > 0 {
  2212. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  2213. record.UltrafiltrationVolume = value
  2214. }
  2215. }
  2216. if template.TemplateId == 6 || template.TemplateId == 20 || template.TemplateId == 22 || template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 || template.TemplateId == 41 || template.TemplateId == 43 { //adminInfo.Org.Id == 9538
  2217. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  2218. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2219. record.UltrafiltrationVolume = ultrafiltration_volume
  2220. }
  2221. }
  2222. this.ServeSuccessJSON(map[string]interface{}{
  2223. "monitor": record,
  2224. })
  2225. }
  2226. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  2227. record_id, _ := this.GetInt64("id")
  2228. nurseID, _ := this.GetInt64("nurse")
  2229. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  2230. bedID, _ := this.GetInt64("bed")
  2231. start_time := this.GetString("start_time")
  2232. schedual_type, _ := this.GetInt64("schedual_type")
  2233. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  2234. change_nurse, _ := this.GetInt64("change_nurse")
  2235. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  2236. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  2237. if record_id == 0 {
  2238. this.ErrorLog("id:%v", record_id)
  2239. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2240. return
  2241. }
  2242. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  2243. if parseStartDateErr != nil {
  2244. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  2245. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2246. return
  2247. }
  2248. adminUserInfo := this.GetMobileAdminUserInfo()
  2249. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2250. if getNurseErr != nil {
  2251. this.ErrorLog("获取护士失败:%v", getNurseErr)
  2252. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2253. return
  2254. } else if nurse == nil {
  2255. this.ErrorLog("护士不存在")
  2256. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2257. return
  2258. }
  2259. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  2260. //if getNurseErr != nil {
  2261. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  2262. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2263. // return
  2264. //} else if nurse == nil {
  2265. // this.ErrorLog("护士不存在")
  2266. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2267. // return
  2268. //}
  2269. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  2270. if getDeviceNumberErr != nil {
  2271. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  2272. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2273. return
  2274. } else if deviceNumber == nil {
  2275. this.ErrorLog("床位号不存在")
  2276. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2277. return
  2278. }
  2279. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  2280. //
  2281. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  2282. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2283. // if getPermissionErr != nil {
  2284. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2285. // return
  2286. // } else if headNursePermission == nil {
  2287. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2288. // return
  2289. // }
  2290. //}
  2291. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  2292. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  2293. timeLayout := "2006-01-02 15:04:05"
  2294. loc, _ := time.LoadLocation("Local")
  2295. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2296. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  2297. schedulestartTime := theStartTime.Unix()
  2298. scheduleendTime := theEndTime.Unix()
  2299. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  2300. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2301. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2302. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  2303. if err == gorm.ErrRecordNotFound { //空床位
  2304. // 修改了床位逻辑
  2305. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2306. if daySchedule.ID > 0 {
  2307. daySchedule.BedId = bedID
  2308. daySchedule.PartitionId = deviceNumber.ZoneID
  2309. daySchedule.ScheduleType = schedual_type
  2310. daySchedule.UpdatedTime = time.Now().Unix()
  2311. err := service.UpdateSchedule(&daySchedule)
  2312. if err != nil {
  2313. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2314. return
  2315. }
  2316. }
  2317. } else if err == nil {
  2318. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  2319. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2320. if daySchedule.ID > 0 {
  2321. daySchedule.BedId = bedID
  2322. daySchedule.PartitionId = deviceNumber.ZoneID
  2323. daySchedule.ScheduleType = schedual_type
  2324. daySchedule.UpdatedTime = time.Now().Unix()
  2325. err := service.UpdateSchedule(&daySchedule)
  2326. if err != nil {
  2327. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2328. return
  2329. }
  2330. }
  2331. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2332. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2333. return
  2334. }
  2335. } else if err != nil {
  2336. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2337. return
  2338. }
  2339. }
  2340. dialysisRecord := &models.DialysisOrder{
  2341. ID: record_id,
  2342. UserOrgId: adminUserInfo.Org.Id,
  2343. BedID: bedID,
  2344. StartNurse: nurseID,
  2345. StartTime: startDate.Unix(),
  2346. PunctureNurse: puncture_nurse,
  2347. Creator: adminUserInfo.AdminUser.Id,
  2348. Modifier: adminUserInfo.AdminUser.Id,
  2349. WashpipeNurse: washpipe_nurse,
  2350. SchedualType: schedual_type,
  2351. ChangeNurse: change_nurse,
  2352. DifficultPunctureNurse: difficult_puncture_nurse,
  2353. NewFistulaNurse: new_fistula_nurse,
  2354. }
  2355. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  2356. if updateErr != nil {
  2357. this.ErrorLog("修改上机失败:%v", updateErr)
  2358. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2359. return
  2360. }
  2361. if updateErr == nil {
  2362. if tempDialysisRecord.Stage == 2 {
  2363. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  2364. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2365. fmt.Println(value)
  2366. a, b := math.Modf(value)
  2367. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2368. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2369. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2370. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  2371. if updateAssessmentErr != nil {
  2372. utils.ErrorLog("%v", updateAssessmentErr)
  2373. }
  2374. }
  2375. }
  2376. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2377. this.ServeSuccessJSON(map[string]interface{}{
  2378. "dialysis_order": dialysisRecords,
  2379. })
  2380. }
  2381. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  2382. record_id, _ := c.GetInt64("id")
  2383. nurseID, _ := c.GetInt64("nurse")
  2384. end_time := c.GetString("end_time")
  2385. if record_id <= 0 || nurseID <= 0 {
  2386. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2387. return
  2388. }
  2389. adminUserInfo := c.GetMobileAdminUserInfo()
  2390. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2391. if getNurseErr != nil {
  2392. c.ErrorLog("获取护士失败:%v", getNurseErr)
  2393. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2394. return
  2395. } else if nurse == nil {
  2396. c.ErrorLog("护士不存在")
  2397. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2398. return
  2399. }
  2400. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  2401. if parseEndDateErr != nil {
  2402. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  2403. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2404. return
  2405. }
  2406. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2407. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2408. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2409. // if getPermissionErr != nil {
  2410. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2411. // return
  2412. // } else if headNursePermission == nil {
  2413. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2414. // return
  2415. // }
  2416. //}
  2417. dialysisRecord := &models.DialysisOrder{
  2418. ID: record_id,
  2419. UserOrgId: adminUserInfo.Org.Id,
  2420. EndTime: endDate.Unix(),
  2421. FinishNurse: nurseID,
  2422. FinishModifier: adminUserInfo.AdminUser.Id,
  2423. }
  2424. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  2425. if updateErr != nil {
  2426. c.ErrorLog("修改下机失败:%v", updateErr)
  2427. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2428. return
  2429. }
  2430. if updateErr == nil {
  2431. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  2432. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2433. a, b := math.Modf(value)
  2434. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2435. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2436. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2437. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  2438. if updateAssessmentErr != nil {
  2439. utils.ErrorLog("%v", updateAssessmentErr)
  2440. }
  2441. }
  2442. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2443. c.ServeSuccessJSON(map[string]interface{}{
  2444. "dialysis_order": dialysisRecords,
  2445. })
  2446. }
  2447. func (c *DialysisAPIController) GetLongAdvice() {
  2448. patient_id, _ := c.GetInt64("id")
  2449. adminUserInfo := c.GetMobileAdminUserInfo()
  2450. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  2451. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  2452. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  2453. c.ServeSuccessJSON(map[string]interface{}{
  2454. "status": "1",
  2455. })
  2456. return
  2457. } else { //开启推送提醒
  2458. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  2459. var advice_three []*models.DoctorAdvice
  2460. //groupNo := service.GetMaxLongAdviceGroupID(adminUserInfo.Org.Id, patient_id)
  2461. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id)
  2462. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id)
  2463. for _, advice := range advices {
  2464. if advice.FrequencyType == 3 {
  2465. t := time.Now()
  2466. week := int(t.Weekday())
  2467. fmt.Println(t.Weekday())
  2468. fmt.Println(week)
  2469. switch week {
  2470. case 1:
  2471. if strings.Index(advice.WeekDay, "周一") == -1 {
  2472. advice_three = append(advice_three, advice)
  2473. }
  2474. break
  2475. case 2:
  2476. if strings.Index(advice.WeekDay, "周二") == -1 {
  2477. advice_three = append(advice_three, advice)
  2478. }
  2479. break
  2480. case 3:
  2481. if strings.Index(advice.WeekDay, "周三") == -1 {
  2482. advice_three = append(advice_three, advice)
  2483. }
  2484. break
  2485. case 4:
  2486. if strings.Index(advice.WeekDay, "周四") == -1 {
  2487. advice_three = append(advice_three, advice)
  2488. }
  2489. break
  2490. case 5:
  2491. if strings.Index(advice.WeekDay, "周五") == -1 {
  2492. advice_three = append(advice_three, advice)
  2493. }
  2494. break
  2495. case 6:
  2496. if strings.Index(advice.WeekDay, "周六") == -1 {
  2497. advice_three = append(advice_three, advice)
  2498. }
  2499. break
  2500. case 0:
  2501. if strings.Index(advice.WeekDay, "周日") == -1 {
  2502. advice_three = append(advice_three, advice)
  2503. }
  2504. break
  2505. }
  2506. }
  2507. }
  2508. for _, advice := range advices_two {
  2509. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2510. now := p.Unix()
  2511. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2512. dayStr2 := "-" + dayStr
  2513. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2514. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2515. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2516. for _, ad := range advices {
  2517. advice_three = append(advice_three, ad)
  2518. }
  2519. }
  2520. if err == nil {
  2521. c.ServeSuccessJSON(map[string]interface{}{
  2522. "status": "2",
  2523. "advices": advices,
  2524. "advices_two": RemoveRepeatedElement(advice_three),
  2525. "is_open_remind": config.IsOpenRemind,
  2526. })
  2527. }
  2528. }
  2529. }
  2530. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  2531. newArr = make([]*models.DoctorAdvice, 0)
  2532. for i := 0; i < len(arr); i++ {
  2533. repeat := false
  2534. for j := i + 1; j < len(arr); j++ {
  2535. if arr[i].ID == arr[j].ID {
  2536. repeat = true
  2537. break
  2538. }
  2539. }
  2540. if !repeat {
  2541. newArr = append(newArr, arr[i])
  2542. }
  2543. }
  2544. return
  2545. }
  2546. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  2547. patient, _ := c.GetInt64("id", 0)
  2548. groupNo, _ := c.GetInt64("groupno", 0)
  2549. if patient <= 0 {
  2550. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2551. return
  2552. }
  2553. adminUserInfo := c.GetMobileAdminUserInfo()
  2554. dataBody := make(map[string]interface{}, 0)
  2555. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2556. if err != nil {
  2557. utils.ErrorLog(err.Error())
  2558. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2559. return
  2560. }
  2561. utils.ErrorLog("%v", dataBody)
  2562. timeLayout := "2006-01-02 15:04"
  2563. loc, _ := time.LoadLocation("Local")
  2564. timeLayout2 := "2006-01-02"
  2565. loc2, _ := time.LoadLocation("Local")
  2566. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  2567. utils.ErrorLog("advice_type")
  2568. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2569. return
  2570. }
  2571. adviceType := int64(2)
  2572. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  2573. utils.ErrorLog("advice_date")
  2574. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2575. return
  2576. }
  2577. adviceDate, _ := dataBody["advice_date"].(string)
  2578. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  2579. AdviceDate := theTime.Unix()
  2580. RecordDate := theTime.Unix()
  2581. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  2582. utils.ErrorLog("start_time")
  2583. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2584. return
  2585. }
  2586. startTime, _ := dataBody["start_time"].(string)
  2587. if len(startTime) == 0 {
  2588. utils.ErrorLog("len(start_time) == 0")
  2589. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2590. return
  2591. }
  2592. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  2593. if err != nil {
  2594. utils.ErrorLog(err.Error())
  2595. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2596. return
  2597. }
  2598. StartTime := theTime.Unix()
  2599. Remark := ""
  2600. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  2601. remark, _ := dataBody["remark"].(string)
  2602. Remark = remark
  2603. }
  2604. var advices []*models.GroupAdvice
  2605. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  2606. utils.ErrorLog("advices")
  2607. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2608. return
  2609. }
  2610. adviceNames := dataBody["advices"].([]interface{})
  2611. for _, adviceNameMap := range adviceNames {
  2612. adviceNameM := adviceNameMap.(map[string]interface{})
  2613. var advice models.GroupAdvice
  2614. advice.Remark = Remark
  2615. advice.AdviceType = adviceType
  2616. advice.StartTime = StartTime
  2617. advice.AdviceDate = AdviceDate
  2618. advice.RecordDate = RecordDate
  2619. advice.Status = 1
  2620. advice.CreatedTime = time.Now().Unix()
  2621. advice.UpdatedTime = time.Now().Unix()
  2622. advice.StopState = 2
  2623. advice.ExecutionState = 2
  2624. advice.UserOrgId = adminUserInfo.Org.Id
  2625. advice.PatientId = patient
  2626. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  2627. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  2628. utils.ErrorLog("advice_name")
  2629. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2630. return
  2631. }
  2632. adviceName, _ := adviceNameM["advice_name"].(string)
  2633. if len(adviceName) == 0 {
  2634. utils.ErrorLog("len(advice_name) == 0")
  2635. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2636. return
  2637. }
  2638. advice.AdviceName = adviceName
  2639. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  2640. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  2641. advice.DrugSpec = drugSpec
  2642. }
  2643. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  2644. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  2645. advice.AdviceDesc = adviceDesc
  2646. }
  2647. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  2648. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  2649. advice.DrugSpecUnit = drugSpecUnit
  2650. }
  2651. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  2652. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  2653. // advice.SingleDose = singleDose
  2654. //}
  2655. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  2656. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2657. advice.SingleDose = adviceNameM["single_dose"].(float64)
  2658. }
  2659. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  2660. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  2661. advice.SingleDoseUnit = singleDoseUnit
  2662. }
  2663. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  2664. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  2665. // advice.PrescribingNumber = prescribingNumber
  2666. //}
  2667. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  2668. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2669. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  2670. }
  2671. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  2672. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  2673. advice.PrescribingNumberUnit = prescribingNumberUnit
  2674. }
  2675. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  2676. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  2677. advice.DeliveryWay = deliveryWay
  2678. }
  2679. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  2680. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2681. advice.ExecutionFrequency = executionFrequency
  2682. }
  2683. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  2684. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  2685. advice.FrequencyType = frequency_type
  2686. }
  2687. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  2688. day_count := int64(adviceNameM["day_count"].(float64))
  2689. advice.DayCount = day_count
  2690. }
  2691. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  2692. week_day, _ := adviceNameM["week_day"].(string)
  2693. advice.WeekDay = week_day
  2694. }
  2695. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  2696. way := int64(adviceNameM["way"].(float64))
  2697. advice.Way = way
  2698. }
  2699. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  2700. drug_id := int64(adviceNameM["drug_id"].(float64))
  2701. advice.DrugId = drug_id
  2702. }
  2703. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  2704. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  2705. advice.DrugNameId = drug_name_id
  2706. }
  2707. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  2708. template_id, _ := adviceNameM["template_id"].(string)
  2709. advice.TemplateId = template_id
  2710. }
  2711. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  2712. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2713. advice.ExecutionFrequency = executionFrequency
  2714. }
  2715. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  2716. children := adviceNameM["child"].([]interface{})
  2717. if len(children) > 0 {
  2718. for _, childrenMap := range children {
  2719. childMap := childrenMap.(map[string]interface{})
  2720. var child models.GroupAdvice
  2721. child.Remark = Remark
  2722. child.AdviceType = adviceType
  2723. child.StartTime = StartTime
  2724. child.AdviceDate = AdviceDate
  2725. child.RecordDate = RecordDate
  2726. child.Status = 1
  2727. child.CreatedTime = time.Now().Unix()
  2728. child.UpdatedTime = time.Now().Unix()
  2729. child.StopState = 2
  2730. child.ExecutionState = 2
  2731. child.UserOrgId = adminUserInfo.Org.Id
  2732. child.PatientId = patient
  2733. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  2734. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  2735. utils.ErrorLog("child advice_name")
  2736. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2737. return
  2738. }
  2739. childAdviceName, _ := childMap["advice_name"].(string)
  2740. if len(childAdviceName) == 0 {
  2741. utils.ErrorLog("len(child advice_name) == 0")
  2742. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2743. return
  2744. }
  2745. child.AdviceName = childAdviceName
  2746. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  2747. childAdviceDesc, _ := childMap["advice_desc"].(string)
  2748. child.AdviceDesc = childAdviceDesc
  2749. }
  2750. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  2751. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  2752. child.DrugSpec = childDrugSpec
  2753. }
  2754. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  2755. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  2756. child.DrugSpecUnit = childDrugSpecUnit
  2757. }
  2758. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  2759. child.SingleDose = childMap["single_dose"].(float64)
  2760. }
  2761. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  2762. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  2763. child.SingleDoseUnit = childSingleDoseUnit
  2764. }
  2765. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  2766. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  2767. }
  2768. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  2769. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  2770. child.PrescribingNumberUnit = childPrescribingNumberUnit
  2771. }
  2772. child.DeliveryWay = advice.DeliveryWay
  2773. child.ExecutionFrequency = advice.ExecutionFrequency
  2774. advice.Children = append(advice.Children, &child)
  2775. }
  2776. }
  2777. }
  2778. temp_advice, _ := service.FindRemindAdvice(advice.UserOrgId, advice.AdviceName, advice.AdviceDesc, advice.TemplateId, advice.FrequencyType, patient, advice.RecordDate)
  2779. if temp_advice.ID == 0 {
  2780. advices = append(advices, &advice)
  2781. }
  2782. }
  2783. if len(advices) > 0 {
  2784. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  2785. if err != nil {
  2786. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  2787. return
  2788. }
  2789. c.ServeSuccessJSON(map[string]interface{}{
  2790. "msg": "ok",
  2791. "advices": list,
  2792. })
  2793. } else {
  2794. c.ServeSuccessJSON(map[string]interface{}{
  2795. "msg": "ok",
  2796. })
  2797. }
  2798. return
  2799. }
  2800. func (c *DialysisAPIController) UploadDryWeight() {
  2801. patient_id, _ := c.GetInt64("id")
  2802. dry_weight, _ := c.GetFloat("dry_weight")
  2803. doctor_id, _ := c.GetInt64("doctor_id")
  2804. remark := c.GetString("remark")
  2805. adminUserInfo := c.GetMobileAdminUserInfo()
  2806. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  2807. if err == gorm.ErrRecordNotFound {
  2808. dryWeight := &models.SgjPatientDryweight{
  2809. PatientId: patient_id,
  2810. DryWeight: dry_weight,
  2811. Remakes: remark,
  2812. Ctime: time.Now().Unix(),
  2813. Mtime: time.Now().Unix(),
  2814. Creator: doctor_id,
  2815. Status: 1,
  2816. UserOrgId: adminUserInfo.Org.Id,
  2817. AdjustedValue: "/",
  2818. UserId: adminUserInfo.AdminUser.Id,
  2819. }
  2820. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2821. if createErr == nil {
  2822. c.ServeSuccessJSON(map[string]interface{}{
  2823. "msg": "提交成功",
  2824. "weight": dryWeight,
  2825. })
  2826. }
  2827. } else {
  2828. dryWeight := &models.SgjPatientDryweight{
  2829. PatientId: patient_id,
  2830. DryWeight: dry_weight,
  2831. Remakes: remark,
  2832. Ctime: time.Now().Unix(),
  2833. Mtime: time.Now().Unix(),
  2834. Creator: doctor_id,
  2835. Status: 1,
  2836. UserOrgId: adminUserInfo.Org.Id,
  2837. AdjustedValue: "/",
  2838. UserId: adminUserInfo.AdminUser.Id,
  2839. }
  2840. var value float64
  2841. value = dry_weight - weightAdjust.DryWeight
  2842. if value < 0 {
  2843. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  2844. } else if value == 0 {
  2845. dryWeight.AdjustedValue = "/"
  2846. } else if value > 0 {
  2847. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  2848. }
  2849. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2850. if createErr == nil {
  2851. c.ServeSuccessJSON(map[string]interface{}{
  2852. "msg": "提交成功",
  2853. "weight": dryWeight,
  2854. })
  2855. }
  2856. }
  2857. }
  2858. func (c *DialysisAPIController) GetSolution() {
  2859. patient_id, _ := c.GetInt64("patient_id")
  2860. mode_id, _ := c.GetInt64("mode_id")
  2861. adminUserInfo := c.GetMobileAdminUserInfo()
  2862. solution, err := service.MobileGetDialysisSolutionByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2863. prescription, err := service.MobileGetLastDialysisPrescribeByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2864. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeId(adminUserInfo.Org.Id, mode_id)
  2865. if err != nil {
  2866. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2867. return
  2868. }
  2869. c.ServeSuccessJSON(map[string]interface{}{
  2870. "solution": solution,
  2871. "prescription": prescription,
  2872. "system_prescription": system_prescription,
  2873. })
  2874. }
  2875. func (c *DialysisAPIController) GetSchedule() {
  2876. schedual_type, _ := c.GetInt64("schedual_type")
  2877. adminUserInfo := c.GetMobileAdminUserInfo()
  2878. //timeLayout := "2006-01-02 15:04:05"
  2879. //
  2880. //date := time.Now().Format("2006-01-02") + " 00:00:00"
  2881. //loc, _ := time.LoadLocation("Local")
  2882. //theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  2883. //scheduleTime := theStartTime.Unix()
  2884. scheduleTime, _ := c.GetInt64("record_date")
  2885. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  2886. c.ServeSuccessJSON(map[string]interface{}{
  2887. "number": deviceNumber,
  2888. })
  2889. }
  2890. func (c *DialysisAPIController) GetPatientId() {
  2891. id, _ := c.GetInt64("id")
  2892. patientId, _ := service.GetPatientId(id)
  2893. //获取该患者的所有传染病
  2894. list, _ := service.GetPatientInfectious(id)
  2895. c.ServeSuccessJSON(map[string]interface{}{
  2896. "patient": patientId,
  2897. "infectioulist": list,
  2898. })
  2899. }
  2900. func (this *DialysisAPIController) GetDialysisSchedule() {
  2901. schedualDate := this.GetString("date")
  2902. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  2903. if parseDateErr != nil {
  2904. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2905. return
  2906. }
  2907. adminInfo := this.GetMobileAdminUserInfo()
  2908. orgID := adminInfo.Org.Id
  2909. redis := service.RedisClient()
  2910. defer redis.Close()
  2911. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  2912. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  2913. if len(scheduals) > 0 {
  2914. //缓存数据
  2915. scheduals_json, err := json.Marshal(scheduals)
  2916. if err == nil {
  2917. redis.Set(key, scheduals_json, time.Second*30)
  2918. }
  2919. }
  2920. this.ServeSuccessJSON(map[string]interface{}{
  2921. "scheduals": scheduals,
  2922. })
  2923. }
  2924. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  2925. change_type, _ := this.GetInt64("type", 0)
  2926. record_date := this.GetString("record_time")
  2927. patient_id, _ := this.GetInt64("patient_id", 0)
  2928. timeLayout := "2006-01-02"
  2929. loc, _ := time.LoadLocation("Local")
  2930. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2931. record_time := theAdviceRecordTime.Unix()
  2932. adminUserInfo := this.GetMobileAdminUserInfo()
  2933. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  2934. if err == nil {
  2935. if len(advices) == 0 {
  2936. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  2937. return
  2938. } else {
  2939. this.ServeSuccessJSON(map[string]interface{}{
  2940. "advices": advices,
  2941. "schedule": sch,
  2942. })
  2943. return
  2944. }
  2945. } else {
  2946. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2947. return
  2948. }
  2949. }
  2950. func (c *DialysisAPIController) CreateConsumables() {
  2951. record_date := c.GetString("record_time")
  2952. patient_id, _ := c.GetInt64("patient_id", 0)
  2953. active, _ := c.GetInt64("active")
  2954. adminUser := c.GetMobileAdminUserInfo()
  2955. timeLayout := "2006-01-02"
  2956. loc, _ := time.LoadLocation("Local")
  2957. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2958. record_time := theRecordTime.Unix()
  2959. dataBody := make(map[string]interface{}, 0)
  2960. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2961. if err != nil {
  2962. utils.ErrorLog(err.Error())
  2963. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2964. return
  2965. }
  2966. var beforePrepares []*models.DialysisBeforePrepareGoods
  2967. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  2968. var dialysisBefor []*models.DialysisBeforePrepare
  2969. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2970. goods, _ := dataBody["goods"].([]interface{})
  2971. if len(goods) > 0 {
  2972. for _, item := range goods {
  2973. items := item.(map[string]interface{})
  2974. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2975. utils.ErrorLog("good_id")
  2976. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2977. return
  2978. }
  2979. good_id := int64(items["good_id"].(float64))
  2980. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2981. utils.ErrorLog("good_type_id")
  2982. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2983. return
  2984. }
  2985. good_type_id := int64(items["good_type_id"].(float64))
  2986. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2987. utils.ErrorLog("count")
  2988. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2989. return
  2990. }
  2991. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2992. commdity_code := items["commdity_code"].(string)
  2993. fmt.Println("commdity", commdity_code)
  2994. prepareGoods := &models.DialysisBeforePrepareGoods{
  2995. GoodTypeId: good_type_id,
  2996. GoodId: good_id,
  2997. Count: count,
  2998. }
  2999. beforePrepares = append(beforePrepares, prepareGoods)
  3000. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3001. GoodTypeId: good_type_id,
  3002. GoodId: good_id,
  3003. Count: count,
  3004. }
  3005. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3006. prepare := &models.DialysisBeforePrepare{
  3007. GoodTypeId: good_type_id,
  3008. GoodId: good_id,
  3009. Count: count,
  3010. PatientId: patient_id,
  3011. RecordDate: record_time,
  3012. UserOrgId: adminUser.Org.Id,
  3013. Status: 1,
  3014. Ctime: time.Now().Unix(),
  3015. Creater: adminUser.AdminUser.Id,
  3016. CommdityCode: commdity_code,
  3017. }
  3018. dialysisBefor = append(dialysisBefor, prepare)
  3019. }
  3020. }
  3021. //查询是否有库存
  3022. for _, item := range dialysisBefor {
  3023. warehouse, err := service.FindFirstWarehousingInfoByStock(item.GoodId, item.GoodTypeId)
  3024. fmt.Println("库存数量00000000000000000000", warehouse.StockCount, err)
  3025. if err == gorm.ErrRecordNotFound {
  3026. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3027. c.ServeSuccessJSON(map[string]interface{}{
  3028. "message": "1",
  3029. "good_name": goodObj.GoodName,
  3030. "specification_name": goodObj.SpecificationName,
  3031. })
  3032. return
  3033. }
  3034. if err != nil {
  3035. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3036. c.ServeSuccessJSON(map[string]interface{}{
  3037. "message": "1",
  3038. "good_name": goodObj.GoodName,
  3039. "specification_name": goodObj.SpecificationName,
  3040. })
  3041. return
  3042. }
  3043. }
  3044. fmt.Println("dialysisBefor9999999999999999999", dialysisBefor, active)
  3045. //新增
  3046. if active == 1 && len(goods) > 0 {
  3047. for _, item := range dialysisBefor {
  3048. dialyPrepareOne := models.DialysisBeforePrepare{
  3049. GoodTypeId: item.GoodTypeId,
  3050. GoodId: item.GoodId,
  3051. PatientId: item.PatientId,
  3052. RecordDate: item.RecordDate,
  3053. UserOrgId: item.UserOrgId,
  3054. Count: item.Count,
  3055. Ctime: time.Now().Unix(),
  3056. Creater: item.Creater,
  3057. CommdityCode: item.CommdityCode,
  3058. Status: 1,
  3059. }
  3060. //先清除再插入
  3061. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3062. err = service.CreateDialysisBeforePrepareOne(&dialyPrepareOne)
  3063. }
  3064. if err == nil {
  3065. c.ServeSuccessJSON(map[string]interface{}{
  3066. "msg": "保存成功",
  3067. "message": "2",
  3068. })
  3069. return
  3070. } else {
  3071. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3072. return
  3073. }
  3074. }
  3075. if len(beforePrepares) > 0 && active == 2 {
  3076. for _, item := range beforePrepares {
  3077. //1.查看该患者该耗材型号最后一次出库数量
  3078. goodInfo, _ := service.GetLastGoodListByPatientId(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3079. //判断当前出库数量和最后一次出库数量的大小
  3080. //如果当前出库数量小于或等于最后一次出库数量 正常出库后 需要退库操作
  3081. if item.Count <= goodInfo.Count {
  3082. //出库
  3083. err = ConsumablesDeliveryTotalSeven(adminUser.Org.Id, patient_id, record_time, beforePrepares, adminUser.AdminUser.Id, item.Count)
  3084. //查询今日出库数据
  3085. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3086. for _, it := range list {
  3087. prepare := models.DialysisBeforePrepare{
  3088. UserOrgId: it.OrgId,
  3089. PatientId: patient_id,
  3090. RecordDate: it.RecordTime,
  3091. GoodId: it.GoodId,
  3092. GoodTypeId: it.GoodTypeId,
  3093. Count: it.Count,
  3094. Ctime: time.Now().Unix(),
  3095. Creater: adminUser.AdminUser.Id,
  3096. Status: 1,
  3097. }
  3098. //删除准备表数据
  3099. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3100. service.CreateDialysisBeforePrepareOne(&prepare)
  3101. }
  3102. }
  3103. var last_total int64
  3104. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3105. if item.Count >= goodInfo.Count {
  3106. //查询当前批次当前耗材最后一条出库数据
  3107. lastOutInfo, _ := service.GetLastWarehouOutInfoByPatientId(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3108. //计算当前出库和最后一次出库数据相差数据
  3109. last_total = item.Count - lastOutInfo.Count
  3110. //查询该批次剩余库存
  3111. lastInfo, _ := service.GetLastStockOut(lastOutInfo.WarehouseInfotId)
  3112. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3113. if lastInfo.StockCount >= last_total {
  3114. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3115. //service.ConsumablesDeliveryTotalEight(adminInfo.Org.Id, patient_id, record_time, beforePrepares,adminInfo.AdminUser.Id,item.Count)
  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. }
  3135. //如果库存不够,则出库到下一个批次
  3136. if lastInfo.StockCount < last_total {
  3137. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3138. //查询今日出库数据
  3139. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3140. for _, it := range list {
  3141. prepare := models.DialysisBeforePrepare{
  3142. UserOrgId: it.OrgId,
  3143. PatientId: patient_id,
  3144. RecordDate: it.RecordTime,
  3145. GoodId: it.GoodId,
  3146. GoodTypeId: it.GoodTypeId,
  3147. Count: it.Count,
  3148. Ctime: time.Now().Unix(),
  3149. Creater: adminUser.AdminUser.Id,
  3150. Status: 1,
  3151. }
  3152. //删除准备表数据
  3153. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3154. service.CreateDialysisBeforePrepareOne(&prepare)
  3155. }
  3156. if err != nil {
  3157. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3158. c.ServeSuccessJSON(map[string]interface{}{
  3159. "message": "1",
  3160. "good_name": goodObj.GoodName,
  3161. "specification_name": goodObj.SpecificationName,
  3162. })
  3163. return
  3164. }
  3165. }
  3166. }
  3167. if err != nil {
  3168. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3169. c.ServeSuccessJSON(map[string]interface{}{
  3170. "message": "1",
  3171. "good_name": goodObj.GoodName,
  3172. "specification_name": goodObj.SpecificationName,
  3173. })
  3174. return
  3175. }
  3176. }
  3177. }
  3178. }
  3179. var errs error
  3180. if errs == nil {
  3181. c.ServeSuccessJSON(map[string]interface{}{
  3182. "msg": "提交成功",
  3183. "message": "2",
  3184. "good_name": "",
  3185. "specification_name": "",
  3186. })
  3187. return
  3188. } else {
  3189. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3190. return
  3191. }
  3192. }
  3193. func (c *DialysisAPIController) CreateStockOutInfo() {
  3194. patient_id, _ := c.GetInt64("patient_id", 0)
  3195. record_date := c.GetString("record_time")
  3196. if patient_id <= 0 {
  3197. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3198. return
  3199. }
  3200. adminInfo := c.GetMobileAdminUserInfo()
  3201. timeLayout := "2006-01-02"
  3202. loc, _ := time.LoadLocation("Local")
  3203. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3204. record_time := theRecordTime.Unix()
  3205. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3206. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3207. consumables = RemoveRepeatedGood(consumables)
  3208. if record.IsOpen == 1 {
  3209. //查询是否有库存
  3210. for _, item := range consumables {
  3211. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId)
  3212. if item.Count > warehouse.Count {
  3213. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3214. c.ServeSuccessJSON(map[string]interface{}{
  3215. "message": "1",
  3216. "good_name": goodObj.GoodName,
  3217. "specification_name": goodObj.SpecificationName,
  3218. })
  3219. return
  3220. }
  3221. }
  3222. //查询是否有出库单
  3223. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3224. if err == gorm.ErrRecordNotFound {
  3225. //没有记录,则创建出库单
  3226. timeStr := time.Now().Format("2006-01-02")
  3227. timeArr := strings.Split(timeStr, "-")
  3228. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3229. total = total + 1
  3230. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3231. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3232. number = number + total
  3233. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3234. creater := adminInfo.AdminUser.Id
  3235. warehouseOut := models.WarehouseOut{
  3236. WarehouseOutOrderNumber: warehousing_out_order,
  3237. OperationTime: time.Now().Unix(),
  3238. OrgId: adminInfo.Org.Id,
  3239. Creater: creater,
  3240. Ctime: time.Now().Unix(),
  3241. Status: 1,
  3242. WarehouseOutTime: record_time,
  3243. Dealer: 0,
  3244. Manufacturer: 0,
  3245. Type: 1,
  3246. IsSys: 1,
  3247. }
  3248. err := service.AddSigleWarehouseOut(&warehouseOut)
  3249. if err != nil {
  3250. utils.TraceLog("创建出库单失败 err = %v", err)
  3251. } else {
  3252. for _, item := range consumables {
  3253. //出库
  3254. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, item.Count)
  3255. }
  3256. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3257. if len(list) == 0 {
  3258. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3259. return
  3260. }
  3261. for _, item := range list {
  3262. prepare := models.DialysisBeforePrepare{
  3263. UserOrgId: adminInfo.Org.Id,
  3264. PatientId: patient_id,
  3265. RecordDate: record_time,
  3266. GoodId: item.GoodId,
  3267. GoodTypeId: item.GoodTypeId,
  3268. Count: item.Count,
  3269. Creater: adminInfo.AdminUser.Id,
  3270. Status: 1,
  3271. Ctime: time.Now().Unix(),
  3272. }
  3273. //清空准备表数据
  3274. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3275. service.CreateDialysisBeforePrepareOne(&prepare)
  3276. }
  3277. }
  3278. //
  3279. } else if err == nil {
  3280. for _, item := range consumables {
  3281. //出库
  3282. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &out, item.Count)
  3283. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3284. if len(list) == 0 {
  3285. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3286. return
  3287. }
  3288. for _, item := range list {
  3289. prepare := models.DialysisBeforePrepare{
  3290. UserOrgId: adminInfo.Org.Id,
  3291. PatientId: patient_id,
  3292. RecordDate: record_time,
  3293. GoodId: item.GoodId,
  3294. GoodTypeId: item.GoodTypeId,
  3295. Count: item.Count,
  3296. Creater: adminInfo.AdminUser.Id,
  3297. Status: 1,
  3298. Ctime: time.Now().Unix(),
  3299. }
  3300. //清空准备表数据
  3301. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3302. service.CreateDialysisBeforePrepareOne(&prepare)
  3303. }
  3304. }
  3305. }
  3306. c.ServeSuccessJSON(map[string]interface{}{
  3307. "msg": "提交成功",
  3308. "message": "2",
  3309. "good_name": "",
  3310. "specification_name": "",
  3311. })
  3312. return
  3313. } else {
  3314. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  3315. return
  3316. }
  3317. }
  3318. func (c *DialysisAPIController) EditConsumables() {
  3319. patient_id, _ := c.GetInt64("patient_id", 0)
  3320. record_date := c.GetString("record_time")
  3321. if patient_id <= 0 {
  3322. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3323. return
  3324. }
  3325. adminInfo := c.GetMobileAdminUserInfo()
  3326. timeLayout := "2006-01-02"
  3327. loc, _ := time.LoadLocation("Local")
  3328. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3329. record_time := theRecordTime.Unix()
  3330. dataBody := make(map[string]interface{}, 0)
  3331. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3332. if err != nil {
  3333. utils.ErrorLog(err.Error())
  3334. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3335. return
  3336. }
  3337. var beforePrepares []*models.DialysisBeforePrepareGoods
  3338. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3339. //判断是否开启自动出库
  3340. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3341. if record.IsOpen == 1 {
  3342. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3343. goods, _ := dataBody["goods"].([]interface{})
  3344. if len(goods) > 0 {
  3345. for _, item := range goods {
  3346. items := item.(map[string]interface{})
  3347. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3348. utils.ErrorLog("good_id")
  3349. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3350. return
  3351. }
  3352. good_id := int64(items["good_id"].(float64))
  3353. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3354. utils.ErrorLog("good_type_id")
  3355. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3356. return
  3357. }
  3358. good_type_id := int64(items["good_type_id"].(float64))
  3359. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3360. utils.ErrorLog("count")
  3361. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3362. return
  3363. }
  3364. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3365. commdity_code := items["commdity_code"].(string)
  3366. fmt.Println(commdity_code)
  3367. prepareGoods := &models.DialysisBeforePrepareGoods{
  3368. GoodTypeId: good_type_id,
  3369. GoodId: good_id,
  3370. Count: count,
  3371. }
  3372. beforePrepares = append(beforePrepares, prepareGoods)
  3373. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3374. GoodTypeId: good_type_id,
  3375. GoodId: good_id,
  3376. Count: count,
  3377. }
  3378. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3379. }
  3380. for _, item := range beforePrepares {
  3381. //1.查看该患者该耗材型号最后一次出库数量
  3382. goodInfo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3383. //判断当前出库数量和最后一次出库数量的大小
  3384. //如果当前出库数量小于最后一次出库数量 正常出库后 需要退库操作
  3385. fmt.Println("当前出库数量", item.Count)
  3386. fmt.Println("最后一次出库数量", goodInfo.Count)
  3387. if item.Count < goodInfo.Count {
  3388. //出库
  3389. err = ConsumablesDeliveryTotalSeven(adminInfo.Org.Id, patient_id, record_time, beforePrepares, adminInfo.AdminUser.Id, item.Count)
  3390. break
  3391. }
  3392. var last_total int64
  3393. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3394. if item.Count > goodInfo.Count {
  3395. //计算当前出库和最后一次出库数据相差数据
  3396. last_total = item.Count - goodInfo.Count
  3397. //查询该批次剩余库存
  3398. lastInfo, _ := service.GetLastStockOut(goodInfo.WarehouseInfotId)
  3399. fmt.Println("剩余库存333333333333333", lastInfo)
  3400. if lastInfo.StockCount == 0 {
  3401. //查询该耗材的总库存
  3402. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  3403. if wareinfo.StockCount == 0 {
  3404. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3405. c.ServeSuccessJSON(map[string]interface{}{
  3406. "message": "1",
  3407. "good_name": goodObj.GoodName,
  3408. "specification_name": goodObj.SpecificationName,
  3409. })
  3410. return
  3411. }
  3412. }
  3413. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3414. fmt.Println("剩余库存", lastInfo.StockCount)
  3415. fmt.Println("差", last_total)
  3416. //查询该耗材的总库存
  3417. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  3418. // 如果库存差大于剩余库存则提示库存不足
  3419. if last_total > wareinfo.StockCount {
  3420. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3421. c.ServeSuccessJSON(map[string]interface{}{
  3422. "message": "1",
  3423. "good_name": goodObj.GoodName,
  3424. "specification_name": goodObj.SpecificationName,
  3425. })
  3426. return
  3427. } else {
  3428. err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3429. break
  3430. }
  3431. //if lastInfo.StockCount >= last_total {
  3432. // err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3433. // break
  3434. //}
  3435. //
  3436. ////如果库存不够,则出库到下一个批次
  3437. //if lastInfo.StockCount < last_total {
  3438. //
  3439. // err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3440. // break
  3441. //}
  3442. }
  3443. }
  3444. //查询今日出库数据
  3445. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3446. for _, it := range list {
  3447. prepare := models.DialysisBeforePrepare{
  3448. UserOrgId: it.OrgId,
  3449. PatientId: patient_id,
  3450. RecordDate: it.RecordTime,
  3451. GoodId: it.GoodId,
  3452. GoodTypeId: it.GoodTypeId,
  3453. Count: it.Count,
  3454. Ctime: time.Now().Unix(),
  3455. Creater: adminInfo.AdminUser.Id,
  3456. Status: 1,
  3457. }
  3458. //删除准备表数据
  3459. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, it.GoodId, it.GoodTypeId)
  3460. service.CreateDialysisBeforePrepareOne(&prepare)
  3461. if err != nil {
  3462. goodObj, _ := service.GetGoodInformationByGoodId(it.GoodId)
  3463. c.ServeSuccessJSON(map[string]interface{}{
  3464. "message": "2",
  3465. "good_name": goodObj.GoodName,
  3466. "specification_name": goodObj.SpecificationName,
  3467. })
  3468. return
  3469. }
  3470. }
  3471. }
  3472. }
  3473. //更新自动出库的地方
  3474. var errs error
  3475. if errs == nil {
  3476. c.ServeSuccessJSON(map[string]interface{}{
  3477. "msg": "修改成功",
  3478. "message": "2",
  3479. "good_name": "",
  3480. "specification_name": "",
  3481. })
  3482. return
  3483. } else {
  3484. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3485. return
  3486. }
  3487. }
  3488. }
  3489. func (c *DialysisAPIController) GetDialysisGoods() {
  3490. schedualDate := c.GetString("schedule_date")
  3491. schedule_type, _ := c.GetInt64("schedule_type")
  3492. partition_id, _ := c.GetInt64("partition_id")
  3493. page, _ := c.GetInt("page")
  3494. patient_id, _ := c.GetInt64("patient_id")
  3495. schedualEndDate := int64(0)
  3496. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3497. if parseDateErr != nil && len(schedualDate) != 0 {
  3498. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3499. return
  3500. }
  3501. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  3502. if parseDateErr != nil && len(schedualDate) != 0 {
  3503. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3504. return
  3505. }
  3506. schedualEndDate = endDate.Unix()
  3507. adminUser := c.GetMobileAdminUserInfo()
  3508. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  3509. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  3510. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  3511. //获取当天该病人的透析处方
  3512. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  3513. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3514. if err == gorm.ErrRecordNotFound {
  3515. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3516. if patient_id != 0 {
  3517. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3518. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3519. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3520. item.LastAutomaticReduceDetail = goodUser
  3521. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3522. item.Project = project
  3523. }
  3524. }
  3525. c.ServeSuccessJSON(map[string]interface{}{
  3526. "dialysis_goods": dialysisGoods,
  3527. "good_type": goodTypes,
  3528. "total": total,
  3529. "prescribe": prescribe,
  3530. "good_info": good_info,
  3531. })
  3532. return
  3533. } else if err == nil {
  3534. //获取当天排班的每个患者的库存使用情况
  3535. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3536. if patient_id != 0 {
  3537. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3538. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3539. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3540. item.Project = project
  3541. fmt.Println(goodUser)
  3542. fmt.Println(lastGoodUserDetial)
  3543. item.LastAutomaticReduceDetail = goodUser
  3544. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3545. }
  3546. }
  3547. if err == nil {
  3548. c.ServeSuccessJSON(map[string]interface{}{
  3549. "dialysis_goods": dialysisGoods,
  3550. "good_type": goodTypes,
  3551. "total": total,
  3552. "prescribe": prescribe,
  3553. "good_info": good_info,
  3554. "project": project,
  3555. })
  3556. return
  3557. } else {
  3558. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3559. return
  3560. }
  3561. } else if err != nil {
  3562. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3563. return
  3564. }
  3565. }
  3566. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  3567. start_time := c.GetString("start_time")
  3568. end_time := c.GetString("end_time")
  3569. timeLayout := "2006-01-02"
  3570. loc, _ := time.LoadLocation("Local")
  3571. var theStartTime int64
  3572. if len(start_time) > 0 {
  3573. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3574. if err != nil {
  3575. utils.ErrorLog(err.Error())
  3576. }
  3577. theStartTime = theTime.Unix()
  3578. }
  3579. var theEndtTime int64
  3580. if len(end_time) > 0 {
  3581. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3582. if err != nil {
  3583. utils.ErrorLog(err.Error())
  3584. }
  3585. theEndtTime = theTime.Unix()
  3586. }
  3587. adminUser := c.GetMobileAdminUserInfo()
  3588. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  3589. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  3590. if err == nil {
  3591. c.ServeSuccessJSON(map[string]interface{}{
  3592. "stock_out": outInfo,
  3593. "stockCount": stockCount,
  3594. })
  3595. return
  3596. } else {
  3597. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3598. return
  3599. }
  3600. }
  3601. func (c *DialysisAPIController) GetStockInGoodInfo() {
  3602. patient_id, _ := c.GetInt64("patient_id", 0)
  3603. record_time := c.GetString("record_time")
  3604. adminUser := c.GetMobileAdminUserInfo()
  3605. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  3606. if parseDateErr != nil && len(record_time) != 0 {
  3607. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3608. return
  3609. }
  3610. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  3611. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3612. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  3613. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  3614. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  3615. //获取今日患者的透析处方参数
  3616. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  3617. c.ServeSuccessJSON(map[string]interface{}{
  3618. "good_type": goodTypes,
  3619. "good_user": goodUser,
  3620. "good_info": good_info,
  3621. "last_good_user": lastGoodUserDetial,
  3622. "project": project,
  3623. "prescription": prescribe,
  3624. })
  3625. return
  3626. }
  3627. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  3628. patient_id, _ := c.GetInt64("patient_id", 0)
  3629. record_date := c.GetString("record_time")
  3630. timeLayout := "2006-01-02"
  3631. loc, _ := time.LoadLocation("Local")
  3632. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3633. record_time := theRecordTime.Unix()
  3634. adminInfo := c.GetMobileAdminUserInfo()
  3635. dataBody := make(map[string]interface{}, 0)
  3636. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3637. if err != nil {
  3638. utils.ErrorLog(err.Error())
  3639. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3640. return
  3641. }
  3642. var beforePrepares []*models.DialysisBeforePrepareGoods
  3643. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3644. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3645. goods, _ := dataBody["goods"].([]interface{})
  3646. if len(goods) > 0 {
  3647. for _, item := range goods {
  3648. items := item.(map[string]interface{})
  3649. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3650. utils.ErrorLog("good_id")
  3651. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3652. return
  3653. }
  3654. good_id := int64(items["good_id"].(float64))
  3655. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3656. utils.ErrorLog("good_type_id")
  3657. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3658. return
  3659. }
  3660. good_type_id := int64(items["good_type_id"].(float64))
  3661. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3662. utils.ErrorLog("count")
  3663. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3664. return
  3665. }
  3666. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3667. prepare := &models.DialysisBeforePrepareGoods{
  3668. GoodId: good_id,
  3669. GoodTypeId: good_type_id,
  3670. Count: count,
  3671. }
  3672. beforePrepares = append(beforePrepares, prepare)
  3673. newPrepare := &models.NewDialysisBeforePrepareGoods{
  3674. GoodId: good_id,
  3675. GoodTypeId: good_type_id,
  3676. Count: count,
  3677. }
  3678. newBeforePrepares = append(newBeforePrepares, newPrepare)
  3679. }
  3680. }
  3681. }
  3682. fmt.Println("前端数据9999999999999", beforePrepares)
  3683. //查询是否有库存
  3684. for _, item := range beforePrepares {
  3685. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId)
  3686. if item.Count > warehouse.Count {
  3687. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3688. c.ServeSuccessJSON(map[string]interface{}{
  3689. "message": "1",
  3690. "good_name": goodObj.GoodName,
  3691. "specification_name": goodObj.SpecificationName,
  3692. })
  3693. return
  3694. }
  3695. }
  3696. //出库逻辑
  3697. err = service.ConsumablesDeliveryTotal(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3698. if err != nil {
  3699. utils.ErrorLog(err.Error())
  3700. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3701. return
  3702. }
  3703. //查询当天出库的数据
  3704. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3705. for _, item := range list {
  3706. prepare := models.DialysisBeforePrepare{
  3707. UserOrgId: item.OrgId,
  3708. PatientId: item.PatientId,
  3709. RecordDate: item.RecordTime,
  3710. GoodId: item.GoodId,
  3711. GoodTypeId: item.GoodTypeId,
  3712. Count: item.Count,
  3713. Creater: adminInfo.AdminUser.Id,
  3714. Status: 1,
  3715. Ctime: time.Now().Unix(),
  3716. }
  3717. //清空准备表的数据
  3718. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3719. //插入准备表数据
  3720. service.CreateDialysisBeforePrepareOne(&prepare)
  3721. }
  3722. //更新自动出库的地方
  3723. var errs error
  3724. if errs == nil {
  3725. c.ServeSuccessJSON(map[string]interface{}{
  3726. "msg": "修改成功",
  3727. "message": "2",
  3728. "good_name": "",
  3729. "specification_name": "",
  3730. })
  3731. return
  3732. } else {
  3733. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3734. return
  3735. }
  3736. }
  3737. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3738. newArr = make([]*models.DialysisBeforePrepare, 0)
  3739. for i := 0; i < len(arr); i++ {
  3740. repeat := false
  3741. for j := i + 1; j < len(arr); j++ {
  3742. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  3743. repeat = true
  3744. break
  3745. }
  3746. }
  3747. if !repeat {
  3748. newArr = append(newArr, arr[i])
  3749. }
  3750. }
  3751. return
  3752. }
  3753. func (c *DialysisAPIController) GetAllDrug() {
  3754. patient_id, _ := c.GetInt64("patient_id", 0)
  3755. adminInfo := c.GetMobileAdminUserInfo()
  3756. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3757. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  3758. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  3759. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  3760. c.ServeSuccessJSON(map[string]interface{}{
  3761. "base_drug_config": drugStockConfig,
  3762. "private_drug_config": privateDrugConfig,
  3763. "base_drug_list": drugList,
  3764. "private_drug_list": privateDrugList,
  3765. })
  3766. }
  3767. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3768. newArr = make([]*models.DialysisBeforePrepare, 0)
  3769. for i := 0; i < len(arr); i++ {
  3770. repeat := false
  3771. for j := i + 1; j < len(arr); j++ {
  3772. if arr[i].GoodId == arr[j].GoodId {
  3773. repeat = true
  3774. break
  3775. }
  3776. }
  3777. if !repeat {
  3778. newArr = append(newArr, arr[i])
  3779. }
  3780. }
  3781. return
  3782. }
  3783. func (c *DialysisAPIController) GetDepartment() {
  3784. adminInfo := c.GetMobileAdminUserInfo()
  3785. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  3786. if err == nil {
  3787. c.ServeSuccessJSON(map[string]interface{}{
  3788. "departments": departments,
  3789. })
  3790. } else {
  3791. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3792. return
  3793. }
  3794. }
  3795. func (c *DialysisAPIController) GetMobilePrintStockGood() {
  3796. types, _ := c.GetInt("type", 0)
  3797. start_time := c.GetString("start_time")
  3798. end_time := c.GetString("end_time")
  3799. orgId := c.GetMobileAdminUserInfo().Org.Id
  3800. timeLayout := "2006-01-02"
  3801. loc, _ := time.LoadLocation("Local")
  3802. var startTime int64
  3803. if len(start_time) > 0 {
  3804. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3805. if err != nil {
  3806. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3807. return
  3808. }
  3809. startTime = theTime.Unix()
  3810. }
  3811. var endTime int64
  3812. if len(end_time) > 0 {
  3813. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3814. if err != nil {
  3815. utils.ErrorLog(err.Error())
  3816. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3817. return
  3818. }
  3819. endTime = theTime.Unix()
  3820. }
  3821. list, err := service.FindPrintStockGoodInfoByType(types, startTime, endTime, orgId)
  3822. stockTotal, err := service.GetOutStockTotalCountTwo(startTime, endTime, orgId)
  3823. if err != nil {
  3824. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3825. } else {
  3826. c.ServeSuccessJSON(map[string]interface{}{
  3827. "list": list,
  3828. "type": types,
  3829. "stockTotal": stockTotal,
  3830. })
  3831. }
  3832. }
  3833. func (c *DialysisAPIController) BatchDeleteMonitor() {
  3834. fmt.Println("jin2222245555555555")
  3835. ids := c.GetString("ids")
  3836. fmt.Println("dis22222222", ids)
  3837. idArray := strings.Split(ids, ",")
  3838. err := service.BatchDeleteMonitor(idArray)
  3839. fmt.Print("err", err)
  3840. c.ServeSuccessJSON(map[string]interface{}{
  3841. "msg": "批量删除成功",
  3842. })
  3843. return
  3844. }
  3845. func (c *DialysisAPIController) GetPatientDialysisRecordList() {
  3846. id, _ := c.GetInt64("id")
  3847. fmt.Println(id)
  3848. timeLayout := "2006-01-02"
  3849. loc, _ := time.LoadLocation("Local")
  3850. start_time := time.Now().Format("2006-01-02")
  3851. startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3852. fmt.Println("start_timestart_time", start_time)
  3853. nowTime := time.Now()
  3854. endTime := nowTime.AddDate(-1, 0, 0)
  3855. endTimes := endTime.Format("2006-01-02")
  3856. endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", endTimes+" 00:00:00", loc)
  3857. list, _ := service.GetPatientDialysisRecordList(id, endtime.Unix(), startime.Unix())
  3858. c.ServeSuccessJSON(map[string]interface{}{
  3859. "list": list,
  3860. })
  3861. return
  3862. }
  3863. func (c *DialysisAPIController) BathDeleteAdviceList() {
  3864. dataBody := make(map[string]interface{}, 0)
  3865. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3866. ids := c.GetString("ids")
  3867. fmt.Println("dis22222222", ids)
  3868. idArray := strings.Split(ids, ",")
  3869. origin, _ := c.GetInt64("origin")
  3870. if origin == 1 {
  3871. err = service.BatchDeleteAdvice(idArray)
  3872. fmt.Print("err", err)
  3873. c.ServeSuccessJSON(map[string]interface{}{
  3874. "msg": "批量删除成功",
  3875. })
  3876. return
  3877. }
  3878. if origin == 2 {
  3879. service.BatchDeleteHisAdvice(idArray)
  3880. }
  3881. }
  3882. func (c *DialysisAPIController) UpdateAutoReduceDetail() {
  3883. good_id, _ := c.GetInt64("good_id")
  3884. count, _ := c.GetInt64("count")
  3885. record_time, _ := c.GetInt64("record_time")
  3886. patient_id, _ := c.GetInt64("patient_id")
  3887. detail, _ := service.UpdateAutoReduceDetail(good_id, count, record_time, patient_id)
  3888. c.ServeSuccessJSON(map[string]interface{}{
  3889. "detail": detail,
  3890. })
  3891. return
  3892. }
  3893. func (c *DialysisAPIController) DeleteAutoReduceDetail() {
  3894. good_id, _ := c.GetInt64("good_id")
  3895. record_time, _ := c.GetInt64("record_time")
  3896. patient_id, _ := c.GetInt64("patient_id")
  3897. fmt.Println("0000000000000000", patient_id)
  3898. service.DeleteDialysisBeforOne(good_id, record_time, patient_id)
  3899. fmt.Println()
  3900. err := service.DeleteAutoReduceDetail(good_id, record_time, patient_id)
  3901. fmt.Print("err", err)
  3902. c.ServeSuccessJSON(map[string]interface{}{
  3903. "msg": "批量删除成功",
  3904. })
  3905. return
  3906. }
  3907. func (c *DialysisAPIController) BatchAdviceCheck() {
  3908. ids := c.GetString("ids")
  3909. idArray := strings.Split(ids, ",")
  3910. creator, _ := c.GetInt64("creator")
  3911. origin, _ := c.GetInt64("origin")
  3912. if origin == 1 {
  3913. err := service.BatchAdviceCheck(idArray, creator)
  3914. fmt.Println(err)
  3915. list, _ := service.GetAdviceExecutionById(idArray)
  3916. c.ServeSuccessJSON(map[string]interface{}{
  3917. "list": list,
  3918. })
  3919. return
  3920. }
  3921. if origin == 2 {
  3922. service.BatchHisAdviceCheck(idArray, creator)
  3923. list, _ := service.GetHisAdviceExecutionById(idArray)
  3924. c.ServeSuccessJSON(map[string]interface{}{
  3925. "list": list,
  3926. })
  3927. return
  3928. }
  3929. }
  3930. func (c *DialysisAPIController) BatchAdviceExecution() {
  3931. ids := c.GetString("ids")
  3932. idArray := strings.Split(ids, ",")
  3933. executionTime := c.GetString("execution_time")
  3934. creator, _ := c.GetInt64("creator")
  3935. timeLayout := "2006-01-02 15:04:05"
  3936. loc, _ := time.LoadLocation("Local")
  3937. theTime, _ := time.ParseInLocation(timeLayout, executionTime, loc)
  3938. orgin, _ := c.GetInt64("origin")
  3939. if orgin == 1 {
  3940. err := service.BatchAdviceExecution(idArray, creator, theTime.Unix())
  3941. list, _ := service.GetAdviceExecutionById(idArray)
  3942. fmt.Println(err)
  3943. c.ServeSuccessJSON(map[string]interface{}{
  3944. "list": list,
  3945. })
  3946. return
  3947. }
  3948. if orgin == 2 {
  3949. err := service.BatchHisAdviceExecution(idArray, creator, theTime.Unix())
  3950. list, _ := service.GetHisAdviceExecutionById(idArray)
  3951. fmt.Println(err)
  3952. c.ServeSuccessJSON(map[string]interface{}{
  3953. "list": list,
  3954. })
  3955. return
  3956. }
  3957. }
  3958. func (c *DialysisAPIController) UpdateStockGoods() {
  3959. good_id, _ := c.GetInt64("good_id")
  3960. record_time, _ := c.GetInt64("record_time")
  3961. patient_id, _ := c.GetInt64("patient_id")
  3962. count, _ := c.GetInt64("count")
  3963. err := service.UpdateStockGoods(good_id, record_time, patient_id, count)
  3964. fmt.Print("err", err)
  3965. c.ServeSuccessJSON(map[string]interface{}{
  3966. "msg": "更新成功",
  3967. })
  3968. return
  3969. }
  3970. //当前数据比上一次出库数据少
  3971. func ConsumablesDeliveryTotalSeven(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, creater int64, count int64) (err error) {
  3972. fmt.Println("w我的中国馆公共区发电房阿道夫安抚安抚安抚安抚安抚安抚阿道夫阿道夫阿凡达阿道夫a", count)
  3973. //查询该患者当天已经出库的耗材信息
  3974. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  3975. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  3976. for i := len(goods_yc) - 1; i >= 0; i-- {
  3977. goods_yc_temp := goods_yc[i]
  3978. for j := len(goods) - 1; j >= 0; j-- {
  3979. goods_temp := goods[j]
  3980. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  3981. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  3982. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  3983. if goods_yc_temp.Count == goods_temp.Count {
  3984. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  3985. goods = append(goods[:j], goods[j+1:]...)
  3986. break
  3987. }
  3988. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  3989. if goods_yc_temp.Count > goods_temp.Count {
  3990. temp_count := goods_yc_temp.Count - goods_temp.Count
  3991. goods_yc[i].Count = temp_count
  3992. goods = append(goods[:j], goods[j+1:]...)
  3993. break
  3994. }
  3995. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  3996. if goods_yc_temp.Count < goods_temp.Count {
  3997. temp_count := goods_temp.Count - goods_yc_temp.Count
  3998. //fmt.Println("988888888888888", temp_count)
  3999. goods[j].Count = temp_count
  4000. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4001. //fmt.Println("888888888", goods_yc)
  4002. break
  4003. }
  4004. }
  4005. }
  4006. }
  4007. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  4008. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  4009. fmt.Println("goodsy999999999999", goods_yc)
  4010. //退库
  4011. if len(goods_yc) > 0 {
  4012. for _, good_yc := range goods_yc {
  4013. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  4014. ConsumablesDeliveryDeleteFour(orgID, record_time, good_yc, &out, patient_id, creater, count)
  4015. }
  4016. }
  4017. return nil
  4018. }
  4019. //耗材出库删除
  4020. func ConsumablesDeliveryDeleteFour(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  4021. fmt.Println("count2323223884584854854854u5454785487547845785478758487545475475487,count", count)
  4022. // 先根据相关信息查询当天该耗材的出库信息
  4023. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  4024. fmt.Println("errr232323232323232323232323232", err)
  4025. if err != nil {
  4026. return err
  4027. }
  4028. var delete_count int64 = 0
  4029. delete_count = warehouseOutInfos.Count - count
  4030. fmt.Println("delete_count2323232", delete_count)
  4031. // 在出库记录表里记录退库详情
  4032. warehouseOutInfo := &models.WarehouseOutInfo{
  4033. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4034. WarehouseOutId: warehouseOut.ID,
  4035. Status: 1,
  4036. Ctime: time.Now().Unix(),
  4037. OrgId: orgID,
  4038. Type: 1,
  4039. IsSys: 1,
  4040. SysRecordTime: record_time,
  4041. GoodTypeId: good_yc.GoodTypeId,
  4042. GoodId: good_yc.GoodId,
  4043. PatientId: good_yc.PatientId,
  4044. ConsumableType: 2,
  4045. }
  4046. warehouseOutInfo.Count = count
  4047. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4048. warehouseOutInfo.Price = stockInInfo.Price
  4049. warehouseOutInfo.Dealer = stockInInfo.Dealer
  4050. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  4051. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  4052. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  4053. warehouseOutInfo.Number = warehouseOutInfos.Number
  4054. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  4055. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  4056. //查找当天是否存在出库记录
  4057. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time)
  4058. fmt.Println("errcode2323223255556652324242424242424242424242424242242", errcod)
  4059. if errcod == gorm.ErrRecordNotFound {
  4060. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4061. //插入详情明细表
  4062. stockFlow := models.VmStockFlow{
  4063. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4064. WarehouseOutId: warehouseOut.ID,
  4065. GoodId: good_yc.GoodId,
  4066. Number: warehouseOutInfos.Number,
  4067. ProductDate: stockInInfo.ProductDate,
  4068. ExpireDate: stockInInfo.ExpiryDate,
  4069. Count: count,
  4070. Price: stockInInfo.Price,
  4071. Status: 1,
  4072. Ctime: time.Now().Unix(),
  4073. UserOrgId: good_yc.OrgId,
  4074. Manufacturer: stockInInfo.Manufacturer,
  4075. Dealer: stockInInfo.Dealer,
  4076. LicenseNumber: stockInInfo.LicenseNumber,
  4077. IsEdit: 2,
  4078. Creator: creater,
  4079. SystemTime: record_time,
  4080. ConsumableType: 3,
  4081. WarehousingDetailId: 0,
  4082. IsSys: 1,
  4083. UpdateCreator: creater,
  4084. PatientId: patient_id,
  4085. }
  4086. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4087. if errflow == gorm.ErrRecordNotFound {
  4088. //创建流水表
  4089. err := service.CreateStockFlowOne(stockFlow)
  4090. fmt.Println("h2h3h2323342i24i242i4u2i4242u42424", err)
  4091. } else if errflow == nil {
  4092. //插入详情明细表
  4093. stockFlow := models.VmStockFlow{
  4094. ID: exsit.ID,
  4095. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4096. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4097. WarehouseOutId: warehouseOut.ID,
  4098. GoodId: good_yc.GoodId,
  4099. Number: warehouseOutInfos.Number,
  4100. ProductDate: stockInInfo.ProductDate,
  4101. ExpireDate: stockInInfo.ExpiryDate,
  4102. Count: exsit.Count - delete_count,
  4103. Price: stockInInfo.Price,
  4104. Status: 1,
  4105. Ctime: time.Now().Unix(),
  4106. UserOrgId: good_yc.OrgId,
  4107. Manufacturer: stockInInfo.Manufacturer,
  4108. Dealer: stockInInfo.Dealer,
  4109. LicenseNumber: stockInInfo.LicenseNumber,
  4110. IsEdit: 2,
  4111. Creator: creater,
  4112. SystemTime: record_time,
  4113. ConsumableType: 3,
  4114. WarehousingDetailId: 0,
  4115. IsSys: 1,
  4116. UpdateCreator: creater,
  4117. PatientId: patient_id,
  4118. }
  4119. service.UpdatedStockFlow(stockFlow)
  4120. }
  4121. if errOne != nil {
  4122. return errOne
  4123. }
  4124. } else if errcod == nil {
  4125. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time)
  4126. //插入详情明细表
  4127. stockFlow := models.VmStockFlow{
  4128. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4129. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4130. WarehouseOutId: warehouseOut.ID,
  4131. GoodId: good_yc.GoodId,
  4132. Number: warehouseOutInfos.Number,
  4133. ProductDate: stockInInfo.ProductDate,
  4134. ExpireDate: stockInInfo.ExpiryDate,
  4135. Count: count,
  4136. Price: stockInInfo.Price,
  4137. Status: 1,
  4138. Ctime: time.Now().Unix(),
  4139. UserOrgId: good_yc.OrgId,
  4140. Manufacturer: stockInInfo.Manufacturer,
  4141. Dealer: stockInInfo.Dealer,
  4142. LicenseNumber: stockInInfo.LicenseNumber,
  4143. IsEdit: 2,
  4144. Creator: creater,
  4145. SystemTime: record_time,
  4146. ConsumableType: 3,
  4147. WarehousingDetailId: 0,
  4148. IsSys: 1,
  4149. UpdateCreator: creater,
  4150. PatientId: patient_id,
  4151. ReturnCount: delete_count,
  4152. }
  4153. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4154. if errflows == gorm.ErrRecordNotFound {
  4155. //创建流水表
  4156. service.CreateStockFlowOne(stockFlow)
  4157. } else if errflows == nil {
  4158. stockFlow := models.VmStockFlow{
  4159. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4160. ID: exsit.ID,
  4161. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4162. WarehouseOutId: warehouseOut.ID,
  4163. GoodId: good_yc.GoodId,
  4164. Number: warehouseOutInfos.Number,
  4165. ProductDate: stockInInfo.ProductDate,
  4166. ExpireDate: stockInInfo.ExpiryDate,
  4167. Count: exsit.Count - delete_count,
  4168. Price: stockInInfo.Price,
  4169. Status: 1,
  4170. Ctime: time.Now().Unix(),
  4171. UserOrgId: good_yc.OrgId,
  4172. Manufacturer: stockInInfo.Manufacturer,
  4173. Dealer: stockInInfo.Dealer,
  4174. LicenseNumber: stockInInfo.LicenseNumber,
  4175. IsEdit: 2,
  4176. Creator: creater,
  4177. SystemTime: record_time,
  4178. ConsumableType: 3,
  4179. WarehousingDetailId: 0,
  4180. IsSys: 1,
  4181. UpdateCreator: creater,
  4182. PatientId: patient_id,
  4183. ReturnCount: delete_count,
  4184. }
  4185. service.UpdatedStockFlow(stockFlow)
  4186. }
  4187. }
  4188. //更改自动出库的表格
  4189. details := models.BloodAutomaticReduceDetail{
  4190. WarehouseOutId: warehouseOutInfo.ID,
  4191. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  4192. PatientId: patient_id,
  4193. Ctime: time.Now().Unix(),
  4194. Mtime: time.Now().Unix(),
  4195. Status: 1,
  4196. RecordTime: record_time,
  4197. OrgId: orgID,
  4198. GoodId: good_yc.GoodId,
  4199. GoodTypeId: good_yc.GoodTypeId,
  4200. Count: count,
  4201. }
  4202. //查询当天耗材是否已经存在数据
  4203. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4204. if errcode == gorm.ErrRecordNotFound {
  4205. errTwo := service.CreateAutoReduceRecord(&details)
  4206. if errTwo != nil {
  4207. return errTwo
  4208. }
  4209. } else if errcode == nil {
  4210. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4211. service.CreateAutoReduceRecord(&details)
  4212. }
  4213. // 删除出库完成后,要增加对应批次的库存数量
  4214. fmt.Println("deletecount2323232323232323232323232323", delete_count)
  4215. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count)
  4216. if errThree != nil {
  4217. return errThree
  4218. }
  4219. if good_yc.Count == 0 {
  4220. return nil
  4221. } else {
  4222. return errors.New("退库和出库数据不匹配")
  4223. }
  4224. }
  4225. func ConsumablesDeliveryTotalSix(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, goodOne []*models.NewDialysisBeforePrepareGoods, creater int64) (err error) {
  4226. //查询该患者当天已经出库的耗材信息
  4227. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  4228. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  4229. for i := len(goods_yc) - 1; i >= 0; i-- {
  4230. goods_yc_temp := goods_yc[i]
  4231. for j := len(goods) - 1; j >= 0; j-- {
  4232. goods_temp := goods[j]
  4233. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  4234. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  4235. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  4236. if goods_yc_temp.Count == goods_temp.Count {
  4237. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4238. goods = append(goods[:j], goods[j+1:]...)
  4239. break
  4240. }
  4241. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  4242. if goods_yc_temp.Count > goods_temp.Count {
  4243. temp_count := goods_yc_temp.Count - goods_temp.Count
  4244. goods_yc[i].Count = temp_count
  4245. goods = append(goods[:j], goods[j+1:]...)
  4246. break
  4247. }
  4248. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  4249. if goods_yc_temp.Count < goods_temp.Count {
  4250. temp_count := goods_temp.Count - goods_yc_temp.Count
  4251. goods[j].Count = temp_count
  4252. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4253. break
  4254. }
  4255. }
  4256. }
  4257. }
  4258. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  4259. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  4260. fmt.Println("goods222222222222", goods)
  4261. fmt.Println("goodsy999999999999", goods_yc)
  4262. if len(goods) > 0 {
  4263. out, err := service.FindStockOutByIsSys(orgID, 1, record_time)
  4264. if err == gorm.ErrRecordNotFound {
  4265. //没有记录,则创建出库单
  4266. timeStr := time.Now().Format("2006-01-02")
  4267. timeArr := strings.Split(timeStr, "-")
  4268. total, _ := service.FindAllWarehouseOut(orgID)
  4269. total = total + 1
  4270. warehousing_out_order := strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4271. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4272. number = number + total
  4273. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4274. warehouseOut := models.WarehouseOut{
  4275. WarehouseOutOrderNumber: warehousing_out_order,
  4276. OperationTime: time.Now().Unix(),
  4277. OrgId: orgID,
  4278. Creater: creater,
  4279. Ctime: time.Now().Unix(),
  4280. Status: 1,
  4281. WarehouseOutTime: record_time,
  4282. Dealer: 0,
  4283. Manufacturer: 0,
  4284. Type: 1,
  4285. IsSys: 1,
  4286. }
  4287. err := service.AddSigleWarehouseOut(&warehouseOut)
  4288. if err != nil {
  4289. utils.TraceLog("创建出库单失败 err = %v", err)
  4290. return err
  4291. } else {
  4292. out = warehouseOut
  4293. }
  4294. }
  4295. for _, item := range goods {
  4296. var newCount int64 = 0
  4297. for _, it := range goodOne {
  4298. if item.GoodTypeId == it.GoodTypeId && item.GoodId == it.GoodId {
  4299. newCount = it.Count
  4300. }
  4301. }
  4302. prepare := models.DialysisBeforePrepare{
  4303. GoodTypeId: item.GoodTypeId,
  4304. GoodId: item.GoodId,
  4305. Count: item.Count,
  4306. }
  4307. fmt.Println("到这里了吗34344343434334343434", newCount)
  4308. service.ConsumablesDelivery(orgID, patient_id, record_time, &prepare, &out, newCount)
  4309. }
  4310. }
  4311. if len(goods_yc) > 0 {
  4312. for _, good_yc := range goods_yc {
  4313. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  4314. ConsumablesDeliveryDeleteThree(orgID, record_time, good_yc, &out)
  4315. }
  4316. }
  4317. return nil
  4318. }
  4319. //耗材出库删除
  4320. func ConsumablesDeliveryDeleteThree(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut) (err error) {
  4321. // 先根据相关信息查询当天该耗材的出库信息
  4322. warehouseOutInfos, err := service.FindStockOutInfoByStockOne(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time)
  4323. if err != nil {
  4324. return err
  4325. }
  4326. var delete_count int64 = 0
  4327. for _, ware := range warehouseOutInfos {
  4328. // 判断当前出库的数据和删除出库数量
  4329. if good_yc.Count <= ware.Count {
  4330. delete_count = good_yc.Count
  4331. } else {
  4332. delete_count = ware.Count
  4333. }
  4334. // 在出库记录表里记录退库详情
  4335. warehouseOutInfo := &models.WarehouseOutInfo{
  4336. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4337. WarehouseOutId: warehouseOut.ID,
  4338. Status: 1,
  4339. Ctime: time.Now().Unix(),
  4340. Remark: "",
  4341. OrgId: orgID,
  4342. Type: 1,
  4343. Manufacturer: 0,
  4344. Dealer: 0,
  4345. IsSys: 0,
  4346. SysRecordTime: record_time,
  4347. GoodTypeId: good_yc.GoodTypeId,
  4348. GoodId: good_yc.GoodId,
  4349. }
  4350. warehouseOutInfo.Count = delete_count
  4351. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4352. warehouseOutInfo.Price = stockInInfo.Price
  4353. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4354. if errOne != nil {
  4355. return errOne
  4356. }
  4357. //更改自动出库的表格
  4358. // 删除出库完成后,要增加对应批次的库存数量
  4359. fmt.Println("deletecount2323232323232323232323232323", delete_count)
  4360. errThree := service.UpDateWarehouseInfoByStockDelete(ware.WarehouseInfotId, delete_count)
  4361. if errThree != nil {
  4362. return errThree
  4363. }
  4364. }
  4365. if good_yc.Count == 0 {
  4366. return nil
  4367. } else {
  4368. return errors.New("退库和出库数据不匹配")
  4369. }
  4370. }
  4371. func (this *DialysisAPIController) GetMobileScheduleList() {
  4372. limit, _ := this.GetInt64("limit")
  4373. page, _ := this.GetInt64("page")
  4374. type_options_visible, _ := this.GetInt64("type_options_visible")
  4375. sch_type_options_visible, _ := this.GetInt64("sch_type_options_visible")
  4376. zone_options_visible, _ := this.GetInt64("zone_options_visible")
  4377. fmt.Println(limit, page, type_options_visible, sch_type_options_visible, zone_options_visible)
  4378. }