dialysis_api_controller.go 220KB

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