dialysis_api_controller.go 284KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662
  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. dobulecheck, _ := service.GetAllDobuleCheckList(orgID, date.Unix())
  94. hisAdvices, _ := service.GetAllHisAdvicesByList(orgID, date.Unix())
  95. for key, item := range scheduals {
  96. // 获取患者信息
  97. for _, patient := range patients {
  98. if item.PatientId == patient.ID {
  99. scheduals[key].SchedualPatient = patient
  100. break
  101. }
  102. }
  103. // 床位信息
  104. for _, device := range devices {
  105. if item.BedId == device.ID {
  106. scheduals[key].DeviceNumber = device
  107. break
  108. }
  109. }
  110. // 医嘱信息
  111. scheduals[key].Advices = make([]models.VMDoctorAdviceForList, 0)
  112. for _, advice := range advices {
  113. if item.PatientId == advice.PatientId {
  114. scheduals[key].Advices = append(scheduals[key].Advices, advice)
  115. }
  116. }
  117. // 医嘱信息
  118. scheduals[key].HisAdvices = make([]service.VMHisDoctorAdviceInfo, 0)
  119. for _, hisAdvice := range hisAdvices {
  120. if item.PatientId == hisAdvice.PatientId {
  121. scheduals[key].HisAdvices = append(scheduals[key].HisAdvices, hisAdvice)
  122. }
  123. }
  124. // 医嘱信息
  125. for _, prescription := range prescriptions {
  126. if item.PatientId == prescription.PatientId {
  127. scheduals[key].Prescription = prescription
  128. break
  129. }
  130. }
  131. // 透前评估
  132. for _, assessmentBefore := range assessmentBefores {
  133. if item.PatientId == assessmentBefore.PatientId {
  134. scheduals[key].AssessmentBeforeDislysis = assessmentBefore
  135. break
  136. }
  137. }
  138. // 透析上下机
  139. for _, dialysisOrder := range dialysisOrders {
  140. if item.PatientId == dialysisOrder.PatientId {
  141. scheduals[key].DialysisOrder = dialysisOrder
  142. break
  143. }
  144. }
  145. // 治疗小节
  146. for _, afterDislysis := range AssessmentAfterDislysis {
  147. if item.PatientId == afterDislysis.PatientId {
  148. scheduals[key].AssessmentAfterDislysis = afterDislysis
  149. break
  150. }
  151. }
  152. // 透后评估
  153. for _, treatmentSummary := range treatmentSummarys {
  154. if item.PatientId == treatmentSummary.PatientId {
  155. scheduals[key].TreatmentSummary = treatmentSummary
  156. break
  157. }
  158. }
  159. for _, check := range dobulecheck {
  160. if item.PatientId == check.PatientId {
  161. scheduals[key].DoubleCheck = check
  162. break
  163. }
  164. }
  165. }
  166. //缓存数据
  167. scheduals_json, err := json.Marshal(&scheduals)
  168. if err == nil {
  169. redis.Set(key, scheduals_json, time.Second*60)
  170. }
  171. }
  172. //获取今日所有的处方开的耗材
  173. _, configs := service.FindXTHisProjectByOrgId(orgID)
  174. project := make([]*models.HisPrescriptionProjectTwo, 0)
  175. if configs.ID > 0 && configs.IsOpen == 1 {
  176. project, _ = service.GetAllHisProjectPrescription(orgID, date.Unix())
  177. }
  178. //list, _ := service.GetZoneCountList(orgID, date.Unix())
  179. this.ServeSuccessJSON(map[string]interface{}{
  180. "scheduals": scheduals,
  181. "project": project,
  182. })
  183. }
  184. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  185. var dat []map[string]interface{}
  186. if err := json.Unmarshal([]byte(scheduals_json_str), &dat); err == nil {
  187. } else {
  188. }
  189. //获取今日所有的处方开的耗材
  190. _, configs := service.FindXTHisProjectByOrgId(orgID)
  191. project := make([]*models.HisPrescriptionProjectTwo, 0)
  192. if configs.ID > 0 && configs.IsOpen == 1 {
  193. project, _ = service.GetAllHisProjectPrescription(orgID, date.Unix())
  194. }
  195. this.ServeSuccessJSON(map[string]interface{}{
  196. "scheduals": dat,
  197. "redis": "true",
  198. "date": schedualDate,
  199. "project": project,
  200. })
  201. }
  202. }
  203. // /m/api/waiting_scheduals [get]
  204. // @param date:string
  205. func (this *DialysisAPIController) WaitingScheduals() {
  206. schedualDate := this.GetString("date")
  207. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  208. if parseDateErr != nil && len(schedualDate) != 0 {
  209. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  210. return
  211. }
  212. adminInfo := this.GetMobileAdminUserInfo()
  213. orgID := adminInfo.Org.Id
  214. redis := service.RedisClient()
  215. defer redis.Close()
  216. // cur_date := time.Now().Format("2006-01-02")
  217. key := "wait_scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  218. wait_scheduals, _ := redis.Get(key).Result()
  219. if len(wait_scheduals) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  220. scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  221. if err != nil {
  222. this.ErrorLog("获取排班信息失败:%v", err)
  223. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  224. } else {
  225. returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  226. for _, s := range scheduals {
  227. returnScheduals = append(returnScheduals, s)
  228. }
  229. if len(returnScheduals) > 0 {
  230. //缓存数据
  231. wait_scheduals_json, err := json.Marshal(scheduals)
  232. if err == nil {
  233. redis.Set(key, wait_scheduals_json, time.Second*30)
  234. }
  235. }
  236. this.ServeSuccessJSON(map[string]interface{}{
  237. "scheduals": scheduals,
  238. })
  239. }
  240. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  241. var dat []map[string]interface{}
  242. if err := json.Unmarshal([]byte(wait_scheduals), &dat); err == nil {
  243. } else {
  244. }
  245. this.ServeSuccessJSON(map[string]interface{}{
  246. "scheduals": dat,
  247. "redis": "true",
  248. "date": schedualDate,
  249. })
  250. }
  251. }
  252. //else{
  253. // fmt.Println("33333333")
  254. //
  255. // scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  256. // if err != nil {
  257. // this.ErrorLog("获取排班信息失败:%v", err)
  258. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  259. // } else {
  260. // returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  261. // for _, s := range scheduals {
  262. //
  263. // returnScheduals = append(returnScheduals, s)
  264. // }
  265. //
  266. // this.ServeSuccessJSON(map[string]interface{}{
  267. // "scheduals": returnScheduals,
  268. // })
  269. // }
  270. //
  271. // }
  272. //if err == nil{
  273. //
  274. //
  275. //
  276. //
  277. //
  278. //}else{
  279. //}
  280. // /m/api/dialysis/record [get]
  281. // @param patient_id:int
  282. // @param date:string (yyyy-MM-dd)
  283. func (this *DialysisAPIController) DialysisRecord() {
  284. patientID, _ := this.GetInt64("patient_id")
  285. recordDateStr := this.GetString("date")
  286. if patientID <= 0 {
  287. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  288. return
  289. }
  290. if len(recordDateStr) == 0 {
  291. recordDateStr = time.Now().Format("2006-01-02")
  292. }
  293. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  294. if parseDateErr != nil {
  295. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  296. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  297. return
  298. }
  299. adminInfo := this.GetMobileAdminUserInfo()
  300. ch := make(chan struct{})
  301. count := 24 // count 表示活动的协程个数
  302. var patient models.Patients
  303. var receiverTreatmentAccess *models.ReceiveTreatmentAsses
  304. var predialysisEvaluation *models.PredialysisEvaluation
  305. var lastPredialysisEvaluation *models.PredialysisEvaluation
  306. var doctorAdvices []*models.DoctorAdvice
  307. var dialysisOrder *models.DialysisOrder
  308. var doubleCheck *models.DoubleCheck
  309. var monitorRecords []*models.MonitoringRecord
  310. var lastMonitorRecord *models.MonitoringRecord
  311. var assessmentAfterDislysis *models.AssessmentAfterDislysis
  312. var lastAssessmentAfterDislysis *models.AssessmentAfterDislysis
  313. var treatmentSummary *models.TreatmentSummary
  314. var dialysisPrescribe *models.DialysisPrescription
  315. var dialysisSolution *models.DialysisSolution
  316. var lastDialysisPrescribe *models.DialysisPrescription
  317. var systemDialysisPrescribe *models.SystemPrescription
  318. var is_project_open_config models.XtHisProjectConfig
  319. var projects []*models.HisPrescriptionProject
  320. var stockType []*models.GoodsTypeOne
  321. var prepare []*models.XtDialysisBeforePrepare
  322. var lastAssessment models.XtPatientVascularAccess
  323. var lastDryWeightDislysis *models.SgjPatientDryweight
  324. var gobalConfig models.GobalConfig
  325. var operators []*models.SgjUserAdminRoles
  326. // 先走redis,没有走数据库
  327. schedual, _ := service.MobileGetSchedualDetailOne(adminInfo.Org.Id, patientID, date.Unix())
  328. go func() {
  329. patient, _ = service.FindPatientByIdWithDiseases(adminInfo.Org.Id, patientID)
  330. ch <- struct{}{}
  331. }()
  332. go func() {
  333. receiverTreatmentAccess, _ = service.MobileGetReceiverTreatmentAccessRecord(adminInfo.Org.Id, patientID, date.Unix())
  334. ch <- struct{}{}
  335. }()
  336. go func() {
  337. predialysisEvaluation, _ = service.MobileGetPredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  338. ch <- struct{}{}
  339. }()
  340. go func() {
  341. lastPredialysisEvaluation, _ = service.MobileGetLastTimePredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  342. ch <- struct{}{}
  343. }()
  344. go func() {
  345. doctorAdvices, _ = service.MobileGetDoctorAdvicesByGroups(adminInfo.Org.Id, patientID, date.Unix())
  346. ch <- struct{}{}
  347. }()
  348. go func() {
  349. dialysisOrder, _ = service.MobileGetSchedualDialysisRecord(adminInfo.Org.Id, patientID, date.Unix())
  350. ch <- struct{}{}
  351. }()
  352. go func() {
  353. doubleCheck, _ = service.MobileGetDoubleCheck(adminInfo.Org.Id, patientID, date.Unix())
  354. ch <- struct{}{}
  355. }()
  356. go func() {
  357. monitorRecords, _ = service.MobileGetMonitorRecords(adminInfo.Org.Id, patientID, date.Unix())
  358. ch <- struct{}{}
  359. }()
  360. go func() {
  361. lastMonitorRecord, _ = service.MobileGetLastMonitorRecord(adminInfo.Org.Id, patientID, date.Unix())
  362. ch <- struct{}{}
  363. }()
  364. go func() {
  365. assessmentAfterDislysis, _ = service.MobileGetAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  366. ch <- struct{}{}
  367. }()
  368. go func() {
  369. lastAssessmentAfterDislysis, _ = service.MobileGetLastTimeAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  370. ch <- struct{}{}
  371. }()
  372. go func() {
  373. treatmentSummary, _ = service.MobileGetTreatmentSummary(adminInfo.Org.Id, patientID, date.Unix())
  374. ch <- struct{}{}
  375. }()
  376. go func() {
  377. dialysisPrescribe, _ = service.MobileGetDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, date.Unix(), schedual.ModeId)
  378. ch <- struct{}{}
  379. }()
  380. go func() {
  381. dialysisSolution, _ = service.MobileGetDialysisSolutionByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  382. ch <- struct{}{}
  383. }()
  384. go func() {
  385. lastDialysisPrescribe, _ = service.MobileGetLastDialysisPrescribeByModeIdSix(adminInfo.Org.Id, patientID, schedual.ModeId)
  386. ch <- struct{}{}
  387. }()
  388. go func() {
  389. systemDialysisPrescribe, _ = service.MobileGetSystemDialysisPrescribeByModeId(adminInfo.Org.Id, schedual.ModeId)
  390. ch <- struct{}{}
  391. }()
  392. go func() {
  393. // 先走redis,没有走数据库
  394. _, is_project_open_config = service.FindXTHisProjectByOrgId(adminInfo.Org.Id)
  395. ch <- struct{}{}
  396. }()
  397. go func() {
  398. // 先走redis,没有走数据库
  399. projects, _ = service.GetHisPrescriptionProjects(adminInfo.Org.Id, patientID, date.Unix())
  400. ch <- struct{}{}
  401. }()
  402. go func() {
  403. // // 先走redis,没有走数据库
  404. stockType, _ = service.GetStockType(adminInfo.Org.Id)
  405. ch <- struct{}{}
  406. }()
  407. go func() {
  408. // 先走redis,没有走数据库
  409. prepare, _ = service.GetDialyStockOut(adminInfo.Org.Id, date.Unix(), patientID)
  410. ch <- struct{}{}
  411. }()
  412. go func() {
  413. // //获取最后一次血管通路
  414. // 先走redis,没有走数据库
  415. lastAssessment, _ = service.GetLastPassWayAssessment(adminInfo.Org.Id, patientID)
  416. ch <- struct{}{}
  417. }()
  418. go func() {
  419. // 先走redis,没有走数据库
  420. lastDryWeightDislysis, _ = service.MobileGetLastDryWeight(adminInfo.Org.Id, patientID)
  421. ch <- struct{}{}
  422. }()
  423. go func() {
  424. // 先走redis,没有走数据库
  425. _, gobalConfig = service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  426. ch <- struct{}{}
  427. }()
  428. go func() {
  429. // 先走redis,没有走数据库
  430. operators, _ = service.GetAllStarfEs(adminInfo.Org.Id)
  431. ch <- struct{}{}
  432. }()
  433. for range ch {
  434. // 每次从ch中接收数据,表明一个活动的协程结束
  435. count--
  436. // 当所有活动的协程都结束时,关闭管道
  437. if count == 0 {
  438. close(ch)
  439. }
  440. }
  441. prescribeOne, _ := service.MobileGetDialysisPrescribeByModeIdOne(adminInfo.Org.Id, patientID, date.Unix())
  442. _, is_open_config := service.FindXTHisRecordByOrgId(adminInfo.Org.Id)
  443. _, is_project_open_config = service.FindXTHisProjectByOrgId(adminInfo.Org.Id)
  444. projects, _ = service.GetHisPrescriptionProjects(adminInfo.Org.Id, patientID, date.Unix())
  445. temp_team_projects, _ := service.GetHisPrescriptionTeamProjects(adminInfo.Org.Id, patientID, date.Unix())
  446. prescriptionConfig, _ := service.FindPrescriptionConfigById(adminInfo.Org.Id)
  447. var team_projects []*models.HisPrescriptionProject
  448. //var index int64 = 0
  449. for _, item := range temp_team_projects {
  450. //组套里面非检验项目的
  451. if item.HisProject.CostClassify != 3 {
  452. projects = append(projects, item)
  453. }
  454. //组套里面检验项目的
  455. if item.HisProject.CostClassify == 3 {
  456. team_projects = append(team_projects, item)
  457. }
  458. }
  459. team_projects = RemoveRepeatedCheckRecod(team_projects)
  460. stockType, _ = service.GetStockType(adminInfo.Org.Id)
  461. prepare, _ = service.GetDialyStockOut(adminInfo.Org.Id, date.Unix(), patientID)
  462. prescribeOne, _ = service.MobileGetDialysisPrescribeByModeIdOne(adminInfo.Org.Id, patientID, date.Unix())
  463. var his_advices []*models.HisDoctorAdviceInfo
  464. if is_open_config.IsOpen == 1 {
  465. // 先走redis,没有走数据库
  466. his_advices, _ = service.GetAllHisDoctorAdvice(adminInfo.Org.Id, patientID, date.Unix())
  467. }
  468. is_advice_open, _ := service.FindAdviceSettingById(adminInfo.Org.Id)
  469. if is_advice_open.IsAdviceOpen == 1 {
  470. his_advices, _ = service.GetAllHisDoctorAdvice(adminInfo.Org.Id, patientID, date.Unix())
  471. }
  472. lastOrder, _ := service.GetLastDilysisOrder(adminInfo.Org.Id, patientID, date.Unix())
  473. returnData := map[string]interface{}{
  474. "patient": patient,
  475. "schedual": schedual,
  476. "prescription": dialysisPrescribe,
  477. "solution": dialysisSolution,
  478. "last_prescription": lastDialysisPrescribe,
  479. "receiver_treatment_access": receiverTreatmentAccess,
  480. "predialysis_evaluation": predialysisEvaluation,
  481. "doctor_advices": doctorAdvices,
  482. "double_check": doubleCheck,
  483. "assessment_after_dislysis": assessmentAfterDislysis,
  484. "treatment_summary": treatmentSummary,
  485. "monitor_records": monitorRecords,
  486. "dialysis_order": dialysisOrder,
  487. "operators": operators,
  488. "last_predialysis_evaluation": lastPredialysisEvaluation,
  489. "last_assessment_after_dislysis": lastAssessmentAfterDislysis,
  490. "last_monitor_record": lastMonitorRecord,
  491. "config": gobalConfig,
  492. "dry_weight": lastDryWeightDislysis,
  493. "system_prescription": systemDialysisPrescribe,
  494. "his_advices": his_advices,
  495. "is_open_config": is_open_config,
  496. "stockType": stockType,
  497. "prepare": prepare,
  498. "lastAssessment": lastAssessment,
  499. "prescribeOne": prescribeOne,
  500. "is_project_open_config": is_project_open_config,
  501. "project": projects,
  502. "team_projects": team_projects,
  503. "is_advice_open": is_advice_open,
  504. "prescription_open": prescriptionConfig.IsOpen,
  505. "lastOrder": lastOrder,
  506. }
  507. this.ServeSuccessJSON(returnData)
  508. }
  509. func (c *DialysisAPIController) GetDialysisGlobalConfig() {
  510. adminInfo := c.GetMobileAdminUserInfo()
  511. adminUsers, _ := service.GetAllAdminUsers(adminInfo.Org.Id, adminInfo.App.Id)
  512. devices, _ := service.GetValidDevicesBy(adminInfo.Org.Id, 0, 0)
  513. device_numbers, _ := service.GetAllValidDeviceNumbers(adminInfo.Org.Id)
  514. returnData := map[string]interface{}{
  515. "admin_users": adminUsers,
  516. "devices": devices,
  517. "device_numbers": device_numbers,
  518. }
  519. c.ServeSuccessJSON(returnData)
  520. }
  521. func (c *DialysisAPIController) PostAtreatmentInfo() {
  522. id, _ := c.GetInt64("patient", 0)
  523. recordDateStr := c.GetString("record_date")
  524. propagandaAndEducationContent := c.GetString("propagandaAndEducationContent")
  525. summaryContent := c.GetString("summaryContent")
  526. changeMedicalNurseId, _ := c.GetInt64("changeMedicalNurse", 0)
  527. treatNurseId, _ := c.GetInt64("treatNurse", 0)
  528. checkStaffId, _ := c.GetInt64("checkStaff", 0)
  529. deboardNurseId, _ := c.GetInt64("deboardNurse", 0)
  530. treatDoctor, _ := c.GetInt64("treatDoctor", 0)
  531. nursingRecord := c.GetString("nursing_record")
  532. fmt.Println("护理记录", nursingRecord)
  533. specialRecord := c.GetString("special_record")
  534. fmt.Println("特殊记录", specialRecord)
  535. adminUserInfo := c.GetMobileAdminUserInfo()
  536. changeMedicalNurseId = adminUserInfo.AdminUser.Id
  537. checkStaffId = adminUserInfo.AdminUser.Id
  538. deboardNurseId = adminUserInfo.AdminUser.Id
  539. treatDoctor = adminUserInfo.AdminUser.Id
  540. if id <= 0 {
  541. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  542. return
  543. }
  544. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  545. if patient.ID == 0 {
  546. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  547. return
  548. }
  549. if len(recordDateStr) == 0 {
  550. recordDateStr = time.Now().Format("2006-01-02")
  551. }
  552. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  553. if parseDateErr != nil {
  554. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  555. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  556. return
  557. }
  558. summary := models.TreatmentSummary{
  559. UserOrgId: adminUserInfo.Org.Id,
  560. PatientId: id,
  561. AssessmentDate: recordDate.Unix(),
  562. Mission: propagandaAndEducationContent,
  563. DialysisSummary: summaryContent,
  564. SjNurse: changeMedicalNurseId,
  565. ZlNurse: treatNurseId,
  566. HdNurse: checkStaffId,
  567. XjNurse: deboardNurseId,
  568. ZlDoctor: treatDoctor,
  569. CreatedTime: time.Now().Unix(),
  570. Status: 1,
  571. NursingRecord: nursingRecord,
  572. SpecialRecord: specialRecord,
  573. }
  574. _, treatmentSummary := service.FindTreatmentSummaryByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  575. if treatmentSummary.ID == 0 { //新增
  576. summary.Creater = adminUserInfo.AdminUser.Id
  577. service.AddSigleSummaryRecord(&summary)
  578. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summary"
  579. redis := service.RedisClient()
  580. //清空key 值
  581. redis.Set(key, "", time.Second)
  582. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summarys_list_all"
  583. redis.Set(keyOne, "", time.Second)
  584. keyThree := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  585. redis.Set(keyThree, "", time.Second)
  586. defer redis.Close()
  587. c.ServeSuccessJSON(map[string]interface{}{
  588. "summary": summary,
  589. })
  590. } else { //修改
  591. summary.Creater = treatmentSummary.Creater
  592. summary.CreatedTime = treatmentSummary.CreatedTime
  593. summary.Modifier = adminUserInfo.AdminUser.Id
  594. summary.ID = treatmentSummary.ID
  595. service.UpdateSummeRecord(&summary)
  596. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summary"
  597. redis := service.RedisClient()
  598. //清空key 值
  599. redis.Set(key, "", time.Second)
  600. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":treatment_summarys_list_all"
  601. redis.Set(keyOne, "", time.Second)
  602. keyThree := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  603. redis.Set(keyThree, "", time.Second)
  604. defer redis.Close()
  605. c.ServeSuccessJSON(map[string]interface{}{
  606. "summary": summary,
  607. })
  608. }
  609. }
  610. func (c *DialysisAPIController) PostDoubleCheck() {
  611. id, _ := c.GetInt64("patient", 0)
  612. recordDateStr := c.GetString("record_date")
  613. checkTimeStr := c.GetString("check_time")
  614. firstCheckTimeStr := c.GetString("first_check_time")
  615. creater, _ := c.GetInt64("creater", 0)
  616. modifier, _ := c.GetInt64("modifier", 0)
  617. dialysis_item_check, _ := c.GetInt64("dialysis_item_check", 0)
  618. dialysis_parameter_check, _ := c.GetInt64("dialysis_parameter_check", 0)
  619. vascular_access_verification, _ := c.GetInt64("vascular_access_verification", 0)
  620. pipeline_connection_check, _ := c.GetInt64("pipeline_connection_check", 0)
  621. dialysis_item_desc := c.GetString("dialysis_item_desc")
  622. dialysis_parameter_desc := c.GetString("dialysis_parameter_desc")
  623. vascular_access_desc := c.GetString("vascular_access_desc")
  624. pipeline_connection_desc := c.GetString("pipeline_connection_desc")
  625. collator, _ := c.GetInt64("collator", 0)
  626. employee_number := c.GetString("employee_number")
  627. if id <= 0 {
  628. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  629. return
  630. }
  631. adminUserInfo := c.GetMobileAdminUserInfo()
  632. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  633. if patient.ID == 0 {
  634. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  635. return
  636. }
  637. if len(recordDateStr) == 0 {
  638. recordDateStr = time.Now().Format("2006-01-02")
  639. }
  640. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  641. if parseDateErr != nil {
  642. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  643. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  644. return
  645. }
  646. var checkDate int64
  647. if len(checkTimeStr) == 0 {
  648. checkDate = 0
  649. } else {
  650. checkDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", checkTimeStr)
  651. checkDate = checkDateUnix.Unix()
  652. }
  653. var firstCheckDate int64
  654. if len(firstCheckTimeStr) == 0 {
  655. firstCheckDate = 0
  656. } else {
  657. firstCheckDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", firstCheckTimeStr)
  658. firstCheckDate = firstCheckDateUnix.Unix()
  659. }
  660. if adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 9675 || adminUserInfo.Org.Id == 10340 {
  661. list, _ := service.GetRoleList(adminUserInfo.Org.Id, modifier)
  662. _, check := service.FindDoubleCheckByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  663. if check.ID == 0 {
  664. if employee_number != list.JobNumber {
  665. c.ServeSuccessJSON(map[string]interface{}{
  666. "doubleCheck": check,
  667. "msg": "2",
  668. })
  669. return
  670. }
  671. }
  672. if check.ID > 0 {
  673. if employee_number != list.JobNumber {
  674. c.ServeSuccessJSON(map[string]interface{}{
  675. "doubleCheck": check,
  676. "msg": "2",
  677. })
  678. return
  679. }
  680. }
  681. }
  682. doubleCheck := models.DoubleCheck{
  683. UserOrgId: adminUserInfo.Org.Id,
  684. PatientId: id,
  685. DialysisItemCheck: dialysis_item_check,
  686. DialysisParameterCheck: dialysis_parameter_check,
  687. VascularAccessVerification: vascular_access_verification,
  688. PipelineConnectionCheck: pipeline_connection_check,
  689. DialysisItemDesc: dialysis_item_desc,
  690. DialysisParameterDesc: dialysis_parameter_desc,
  691. VascularAccessDesc: vascular_access_desc,
  692. PipelineConnectionDesc: pipeline_connection_desc,
  693. Collator: collator,
  694. Status: 1,
  695. CreatedTime: time.Now().Unix(),
  696. CheckDate: recordDate.Unix(),
  697. UpdatedTime: time.Now().Unix(),
  698. EmployeeNumber: employee_number,
  699. }
  700. _, check := service.FindDoubleCheckByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  701. if check.ID == 0 { //新增
  702. doubleCheck.FirstCheckTime = firstCheckDate
  703. doubleCheck.CheckTime = checkDate
  704. doubleCheck.Creater = creater
  705. doubleCheck.Modifier = modifier
  706. err := service.AddSigleDoubleCheck(&doubleCheck)
  707. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":double_check"
  708. redis := service.RedisClient()
  709. defer redis.Close()
  710. //清空key 值
  711. redis.Set(key, "", time.Second)
  712. if err == nil {
  713. c.ServeSuccessJSON(map[string]interface{}{
  714. "doubleCheck": &doubleCheck,
  715. })
  716. }
  717. } else { //修改
  718. doubleCheck.FirstCheckTime = firstCheckDate
  719. doubleCheck.CheckTime = checkDate
  720. doubleCheck.Creater = creater
  721. doubleCheck.Modifier = modifier
  722. doubleCheck.CreatedTime = check.CreatedTime
  723. doubleCheck.ID = check.ID
  724. doubleCheck.EmployeeNumber = employee_number
  725. err := service.UpdateDoubleCheck(&doubleCheck)
  726. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":double_check"
  727. redis := service.RedisClient()
  728. defer redis.Close()
  729. //清空key 值
  730. redis.Set(key, "", time.Second)
  731. if err == nil {
  732. c.ServeSuccessJSON(map[string]interface{}{
  733. "doubleCheck": &doubleCheck,
  734. "msg": "1",
  735. })
  736. }
  737. }
  738. }
  739. func (c *DialysisAPIController) PostAcceptsAssessment() {
  740. id, _ := c.GetInt64("patient", 0)
  741. recordDateStr := c.GetString("record_date")
  742. way, _ := c.GetInt64("way", 0)
  743. consciousness, _ := c.GetInt64("consciousness", 0)
  744. appetite, _ := c.GetInt64("appetite", 0)
  745. condition, _ := c.GetInt64("condition", 0)
  746. posture, _ := c.GetInt64("posture")
  747. sick_condition, _ := c.GetInt64("sick_condition", 0)
  748. danger_level, _ := c.GetInt64("danger_level", 0)
  749. intake, _ := c.GetInt64("intake", 0)
  750. nutrition, _ := c.GetInt64("nutrition", 0)
  751. psychological_assessment, _ := c.GetInt64("psychological_assessment", 0)
  752. psychological_assessment_other := c.GetString("psychological_assessment_other")
  753. score := c.GetString("score")
  754. sick_condition_other := c.GetString("sick_condition_other")
  755. //precaution, _ := c.GetInt64("precaution", 0)
  756. precaution := c.GetString("precaution")
  757. precaution_other := c.GetString("precaution_other")
  758. psychological_other := c.GetString("psychological_other")
  759. admission_number := c.GetString("admission_number")
  760. tumble, _ := c.GetInt64("tumble")
  761. diacrisis := c.GetString("diacrisis")
  762. his_department := c.GetString("his_department")
  763. his_bed := c.GetString("his_bed")
  764. if id <= 0 {
  765. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  766. return
  767. }
  768. adminUserInfo := c.GetMobileAdminUserInfo()
  769. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  770. if patient.ID == 0 {
  771. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  772. return
  773. }
  774. //now := time.Now()
  775. //year, month, day := now.Date()
  776. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  777. //todayTimeStamp := today_time.Unix()
  778. if len(recordDateStr) == 0 {
  779. recordDateStr = time.Now().Format("2006-01-02")
  780. }
  781. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  782. if parseDateErr != nil {
  783. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  784. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  785. return
  786. }
  787. _, receiveTreatment := service.FindReceiveTreatmentAssesByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  788. receiveTreatmentAsses := models.ReceiveTreatmentAsses{
  789. UserOrgId: adminUserInfo.Org.Id,
  790. PatientId: id,
  791. RecordDate: recordDate.Unix(),
  792. Way: way,
  793. Consciousness: consciousness,
  794. Appetite: appetite,
  795. Condition: condition,
  796. SickCondition: sick_condition,
  797. DangerLevel: danger_level,
  798. Intake: intake,
  799. Nutrition: nutrition,
  800. PsychologicalAssessment: psychological_assessment,
  801. PsychologicalAssessmentOther: psychological_assessment_other,
  802. SickConditionOther: sick_condition_other,
  803. Posture: posture,
  804. CreatedTime: time.Now().Unix(),
  805. UpdateTime: time.Now().Unix(),
  806. Status: 1,
  807. Score: score,
  808. Precaution: precaution,
  809. PrecautionOther: precaution_other,
  810. PsychologicalOther: psychological_other,
  811. AdmissionNumber: admission_number,
  812. Tumble: tumble,
  813. Diacrisis: diacrisis,
  814. HisBed: his_bed,
  815. HisDepartment: his_department,
  816. }
  817. if receiveTreatment.ID == 0 { //新增
  818. receiveTreatmentAsses.Creater = adminUserInfo.AdminUser.Id
  819. err := service.AddSigleReceiveTreatmentAssesRecord(&receiveTreatmentAsses)
  820. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":receive_treatment_asses"
  821. redis := service.RedisClient()
  822. defer redis.Close()
  823. //清空key 值
  824. redis.Set(key, "", time.Second)
  825. if err == nil {
  826. c.ServeSuccessJSON(map[string]interface{}{
  827. "receiveTreatmentAsses": receiveTreatmentAsses,
  828. })
  829. }
  830. } else { //修改
  831. //if receiveTreatment.Creater != adminUserInfo.AdminUser.Id {
  832. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  833. // if getPermissionErr != nil {
  834. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  835. // return
  836. // } else if headNursePermission == nil {
  837. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  838. // return
  839. // }
  840. //}
  841. receiveTreatmentAsses.Creater = receiveTreatment.Creater
  842. receiveTreatmentAsses.CreatedTime = receiveTreatment.CreatedTime
  843. receiveTreatmentAsses.Modifier = adminUserInfo.AdminUser.Id
  844. receiveTreatmentAsses.ID = receiveTreatment.ID
  845. err := service.UpadateReceiveTreatmentAsses(&receiveTreatmentAsses)
  846. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":receive_treatment_asses"
  847. redis := service.RedisClient()
  848. defer redis.Close()
  849. //清空key 值
  850. redis.Set(key, "", time.Second)
  851. if err == nil {
  852. c.ServeSuccessJSON(map[string]interface{}{
  853. "receiveTreatmentAsses": receiveTreatmentAsses,
  854. })
  855. }
  856. }
  857. }
  858. func (c *DialysisAPIController) PostAssessmentAfterDislysis() {
  859. id, _ := c.GetInt64("patient", 0)
  860. recordDateStr := c.GetString("record_date")
  861. weightAfter, _ := c.GetFloat("weight_after", 0)
  862. additionalWeight, _ := c.GetFloat("additional_weight", 0)
  863. weightReduce, _ := c.GetFloat("weight_loss", 0)
  864. temperature, _ := c.GetFloat("temperature", 0)
  865. pulse_frequency, _ := c.GetFloat("pulse_frequency", 0)
  866. breathing_rate := c.GetString("breathing_rate")
  867. systolic_blood_pressure, _ := c.GetFloat("systolic_blood_pressure", 0)
  868. diastolic_blood_pressure, _ := c.GetFloat("diastolic_blood_pressure", 0)
  869. actual_ultrafiltration, _ := c.GetFloat("actual_ultrafiltration", 0)
  870. actual_displacement, _ := c.GetFloat("actual_displacement", 0)
  871. actualtreatHour, _ := c.GetInt64("actual_treatment_hour", 0)
  872. actualtreatmin, _ := c.GetInt64("actual_treatment_minute", 0)
  873. cruor := c.GetString("cruor")
  874. symptomsAfterDialysi := c.GetString("symptom_after_dialysis")
  875. internalFistula := c.GetString("internal_fistula")
  876. catheter := c.GetString("catheter")
  877. complications := c.GetString("complication")
  878. remark := c.GetString("remark")
  879. //dialysateVolume, _ := c.GetInt64("dialysis_intakes", 0)
  880. dialysis_intakes := c.GetString("dialysis_intakes")
  881. dialysateVolume, _ := strconv.ParseFloat(dialysis_intakes, 64)
  882. fmt.Println("dialysateVolumewode 23323233223232wode", dialysateVolume)
  883. dialysis_intakes_unit, _ := c.GetInt64("dialysis_intakes_unit", 0)
  884. blood_access_part_id, _ := c.GetInt64("blood_access_part_id", 0)
  885. blood_access_part_opera_id, _ := c.GetInt64("blood_access_part_opera_id", 0)
  886. puncturePointOozingBlood, _ := c.GetInt64("puncture_point_oozing_blood", 0)
  887. puncturePointHaematoma, _ := c.GetInt64("puncture_point_haematoma", 0)
  888. internalFistulaTremorAc, _ := c.GetInt64("internal_fistula_tremor_ac", 0)
  889. patientGose, _ := c.GetInt64("patient_gose", 0)
  890. inpatientDepartment := c.GetString("inpatient_department")
  891. observationContent := c.GetString("observation_content")
  892. observationContentOther := c.GetString("observation_content_other")
  893. dialysis_process, _ := c.GetInt64("dialysis_process", 0)
  894. in_advance_minute, _ := c.GetFloat("in_advance_minute", 0)
  895. in_advance_reason := c.GetString("in_advance_reason")
  896. hemostasis_minute, _ := c.GetInt64("hemostasis_minute", 0)
  897. hemostasis_opera, _ := c.GetInt64("hemostasis_opera", 0)
  898. tremor_noise, _ := c.GetInt64("tremor_noise", 0)
  899. disequilibrium_syndrome, _ := c.GetInt64("disequilibrium_syndrome", 0)
  900. disequilibrium_syndrome_option := c.GetString("disequilibrium_syndrome_option")
  901. arterial_tube, _ := c.GetInt64("arterial_tube", 0)
  902. intravenous_tube, _ := c.GetInt64("intravenous_tube", 0)
  903. dialyzer, _ := c.GetInt64("dialyzer", 0)
  904. in_advance_reason_other := c.GetString("in_advance_reason_other")
  905. is_eat, _ := c.GetInt64("is_eat", 0)
  906. cvc_a, _ := c.GetFloat("cvc_a", 0)
  907. cvc_v, _ := c.GetFloat("cvc_v", 0)
  908. channels, _ := c.GetInt64("channel", 0)
  909. return_blood, _ := c.GetInt64("return_blood", 0)
  910. rehydration_volume, _ := c.GetInt64("rehydration_volume", 0)
  911. dialysis_during, _ := c.GetInt64("dialysis_during", 0)
  912. stroke_volume, _ := c.GetInt64("stroke_volume", 0)
  913. blood_flow, _ := c.GetInt64("blood_flow", 0)
  914. //sealing_fluid_dispose, _ := c.GetInt64("sealing_fluid_dispose", 0)
  915. sealing_fluid_dispose := c.GetString("sealing_fluid_dispose")
  916. sealing_fluid_special := c.GetString("sealing_fluid_special")
  917. dosage_of_anticoagulants, _ := c.GetFloat("dosage_of_anticoagulants")
  918. supine_systolic_blood_pressure := c.GetString("supine_systolic_blood_pressure")
  919. setting_pressure := c.GetString("setting_pressure")
  920. supine_diastolic_blood_pressure := c.GetString("supine_diastolic_blood_pressure")
  921. diastolic_pressure := c.GetString("diastolic_pressure")
  922. other_complication := c.GetString("other_complication")
  923. ktv := c.GetString("ktv")
  924. urr := c.GetString("urr")
  925. hypertenison, _ := c.GetInt64("hypertenison")
  926. hypopiesia, _ := c.GetInt64("hypopiesia")
  927. leave_office_method, _ := c.GetInt64("leave_office_method")
  928. lapse, _ := c.GetInt64("lapse")
  929. consciousness, _ := c.GetInt64("consciousness")
  930. fallrisk, _ := c.GetInt64("fallrisk")
  931. machine_run := c.GetString("machine_run")
  932. after_urea := c.GetString("after_urea")
  933. pip_coagulation := c.GetString("pip_coagulation")
  934. accumulated_blood_volume := c.GetString("accumulated_blood_volume")
  935. if id <= 0 {
  936. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  937. return
  938. }
  939. adminUserInfo := c.GetMobileAdminUserInfo()
  940. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  941. if patient.ID == 0 {
  942. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  943. return
  944. }
  945. if len(recordDateStr) == 0 {
  946. recordDateStr = time.Now().Format("2006-01-02")
  947. }
  948. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  949. if parseDateErr != nil {
  950. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  951. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  952. return
  953. }
  954. //now := time.Now()
  955. //year, month, day := now.Date()
  956. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  957. //todayTimeStamp := today_time.Unix()
  958. //_, evaluation := service.FindPredialysisEvaluationByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  959. assessmentAfterDislysis := models.AssessmentAfterDislysis{
  960. UserOrgId: adminUserInfo.Org.Id,
  961. PatientId: id,
  962. AssessmentDate: recordDate.Unix(),
  963. Temperature: temperature,
  964. PulseFrequency: pulse_frequency,
  965. BreathingRate: breathing_rate,
  966. SystolicBloodPressure: systolic_blood_pressure,
  967. DiastolicBloodPressure: diastolic_blood_pressure,
  968. ActualUltrafiltration: actual_ultrafiltration,
  969. ActualDisplacement: actual_displacement,
  970. ActualTreatmentHour: actualtreatHour,
  971. ActualTreatmentMinute: actualtreatmin,
  972. WeightAfter: weightAfter,
  973. AdditionalWeight: additionalWeight,
  974. WeightLoss: weightReduce,
  975. Cruor: cruor,
  976. SymptomAfterDialysis: symptomsAfterDialysi,
  977. InternalFistula: internalFistula,
  978. Catheter: catheter,
  979. Complication: complications,
  980. DialysisIntakes: dialysateVolume,
  981. CreatedTime: time.Now().Unix(),
  982. UpdatedTime: time.Now().Unix(),
  983. Status: 1,
  984. Remark: remark,
  985. BloodAccessPartId: blood_access_part_id,
  986. BloodAccessPartOperaId: blood_access_part_opera_id,
  987. DialysisIntakesUnit: dialysis_intakes_unit,
  988. PuncturePointOozingBlood: puncturePointOozingBlood,
  989. PuncturePointHaematoma: puncturePointHaematoma,
  990. InternalFistulaTremorAc: internalFistulaTremorAc,
  991. PatientGose: patientGose,
  992. InpatientDepartment: inpatientDepartment,
  993. ObservationContent: observationContent,
  994. ObservationContentOther: observationContentOther,
  995. DialysisProcess: dialysis_process,
  996. InAdvanceMinute: in_advance_minute,
  997. InAdvanceReason: in_advance_reason,
  998. HemostasisMinute: hemostasis_minute,
  999. HemostasisOpera: hemostasis_opera,
  1000. TremorNoise: tremor_noise,
  1001. DisequilibriumSyndrome: disequilibrium_syndrome,
  1002. DisequilibriumSyndromeOption: disequilibrium_syndrome_option,
  1003. ArterialTube: arterial_tube,
  1004. IntravenousTube: intravenous_tube,
  1005. Dialyzer: dialyzer,
  1006. InAdvanceReasonOther: in_advance_reason_other,
  1007. IsEat: is_eat,
  1008. CvcA: cvc_a,
  1009. CvcV: cvc_v,
  1010. Channel: channels,
  1011. ReturnBlood: return_blood,
  1012. RehydrationVolume: rehydration_volume,
  1013. DialysisDuring: dialysis_during,
  1014. StrokeVolume: stroke_volume,
  1015. BloodFlow: blood_flow,
  1016. SealingFluidDispose: sealing_fluid_dispose,
  1017. SealingFluidSpecial: sealing_fluid_special,
  1018. DosageOfAnticoagulants: dosage_of_anticoagulants,
  1019. SupineDiastolicBloodPressure: supine_diastolic_blood_pressure,
  1020. SupineSystolicBloodPressure: supine_systolic_blood_pressure,
  1021. SettingPressure: setting_pressure,
  1022. DiastolicPressure: diastolic_pressure,
  1023. OtherComplication: other_complication,
  1024. Ktv: ktv,
  1025. Urr: urr,
  1026. Hypopiesia: hypopiesia,
  1027. Hypertenison: hypertenison,
  1028. Lapse: lapse,
  1029. LeaveOfficeMethod: leave_office_method,
  1030. Consciousness: consciousness,
  1031. Fallrisk: fallrisk,
  1032. MachineRun: machine_run,
  1033. AfterUrea: after_urea,
  1034. PipCoagulation: pip_coagulation,
  1035. AccumulatedBloodVolume: accumulated_blood_volume,
  1036. }
  1037. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1038. _, assessmentAfter := service.FindAssessmentAfterDislysisByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1039. if assessmentAfter.ID == 0 { //新增
  1040. if appRole.UserType == 2 || appRole.UserType == 1 {
  1041. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  1042. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  1043. } else {
  1044. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  1045. }
  1046. err := service.AddSigleAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  1047. redis := service.RedisClient()
  1048. keyTwo := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1049. redis.Set(keyTwo, "", time.Second)
  1050. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis"
  1051. //清空key 值
  1052. redis.Set(key, "", time.Second)
  1053. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_list_all"
  1054. redis.Set(keyOne, "", time.Second)
  1055. defer redis.Close()
  1056. if err == nil {
  1057. c.ServeSuccessJSON(map[string]interface{}{
  1058. "assessmentAfterDislysis": assessmentAfterDislysis,
  1059. })
  1060. }
  1061. } else { //修改
  1062. if appRole.UserType == 2 || appRole.UserType == 1 {
  1063. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  1064. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  1065. } else {
  1066. assessmentAfterDislysis.Modifier = adminUserInfo.AdminUser.Id
  1067. if assessmentAfterDislysis.Creater == 0 {
  1068. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  1069. }
  1070. }
  1071. assessmentAfterDislysis.CreatedTime = assessmentAfter.CreatedTime
  1072. assessmentAfterDislysis.ID = assessmentAfter.ID
  1073. err := service.UpdateAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  1074. redis := service.RedisClient()
  1075. keyTwo := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1076. redis.Set(keyTwo, "", time.Second)
  1077. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis"
  1078. //清空key 值
  1079. redis.Set(key, "", time.Second)
  1080. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_list_all"
  1081. redis.Set(keyOne, "", time.Second)
  1082. fmt.Println("err233332323232232323", err)
  1083. if err == nil {
  1084. c.ServeSuccessJSON(map[string]interface{}{
  1085. "assessmentAfterDislysis": assessmentAfterDislysis,
  1086. })
  1087. }
  1088. }
  1089. }
  1090. func (c *DialysisAPIController) PostDialysisPrescription() {
  1091. id, _ := c.GetInt64("patient", 0)
  1092. recordDateStr := c.GetString("record_date")
  1093. if id <= 0 {
  1094. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1095. return
  1096. }
  1097. adminUserInfo := c.GetMobileAdminUserInfo()
  1098. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1099. if patient.ID == 0 {
  1100. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1101. return
  1102. }
  1103. if len(recordDateStr) == 0 {
  1104. recordDateStr = time.Now().Format("2006-01-02")
  1105. }
  1106. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1107. if parseDateErr != nil {
  1108. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1109. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1110. return
  1111. }
  1112. mode_id, _ := c.GetInt64("mode_id", 0)
  1113. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1114. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1115. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1116. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1117. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1118. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1119. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1120. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1121. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1122. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1123. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1124. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1125. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1126. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1127. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1128. kalium, _ := c.GetFloat("kalium", 0)
  1129. sodium, _ := c.GetFloat("sodium", 0)
  1130. calcium, _ := c.GetFloat("calcium", 0)
  1131. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1132. glucose, _ := c.GetFloat("glucose", 0)
  1133. // prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1134. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1135. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1136. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1137. conductivity, _ := c.GetFloat("conductivity", 0)
  1138. remark := c.GetString("remark")
  1139. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1140. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1141. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1142. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1143. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1144. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1145. special_medicine_other := c.GetString("special_medicine_other")
  1146. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1147. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1148. blood_access, _ := c.GetInt64("blood_access", 0)
  1149. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1150. body_fluid_other := c.GetString("body_fluid_other")
  1151. niprocart, _ := c.GetInt64("niprocart", 0)
  1152. jms, _ := c.GetInt64("jms", 0)
  1153. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1154. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1155. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1156. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1157. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1158. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1159. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1160. injector, _ := c.GetInt64("injector", 0)
  1161. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1162. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1163. safe_package, _ := c.GetInt64("package", 0)
  1164. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1165. pre_impulse, parseDateErr := c.GetFloat("pre_impulse", 0)
  1166. fmt.Println("预冲量", pre_impulse)
  1167. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1168. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1169. blood := c.GetString("blood")
  1170. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  1171. dialysis_irrigation := c.GetString("dialysis_irrigation")
  1172. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  1173. displace_speed := c.GetString("displace_speed")
  1174. illness, _ := c.GetInt64("illness")
  1175. amylaceum := c.GetString("amylaceum")
  1176. single_time := c.GetString("single_time")
  1177. single_water := c.GetString("single_water")
  1178. replacement_flow := c.GetString("replacement_flow")
  1179. plasma_separator := c.GetString("plasma_separator")
  1180. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  1181. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  1182. oxygen_flow := c.GetString("oxygen_flow")
  1183. oxygen_time := c.GetString("oxygen_time")
  1184. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  1185. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  1186. puncture_needle := c.GetString("puncture_needle")
  1187. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  1188. epo := c.GetString("epo")
  1189. epo_count, _ := c.GetFloat("epo_count", 0)
  1190. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  1191. admin_user_id, _ := c.GetInt64("admin_user_id")
  1192. is_water := c.GetString("is_water")
  1193. var is_war int64
  1194. if is_water == "是" {
  1195. is_war = 1
  1196. }
  1197. if is_water == "否" {
  1198. is_war = 2
  1199. }
  1200. if is_water == "请选择" {
  1201. is_war = 0
  1202. }
  1203. drhy_water := c.GetString("drhy_water")
  1204. dry_water_hour := c.GetString("dry_water_hour")
  1205. water_machine := c.GetString("water_machine")
  1206. add_amount, _ := c.GetFloat("add_amount")
  1207. reduce_amount, _ := c.GetFloat("reduce_amount")
  1208. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1209. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1210. //
  1211. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1212. // if appRole.UserType == 3 {
  1213. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1214. // if getPermissionErr != nil {
  1215. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1216. // return
  1217. // } else if headNursePermission == nil {
  1218. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1219. // return
  1220. // }
  1221. // }
  1222. //}
  1223. //TODO 需要根据角色去判断
  1224. prescription := models.DialysisPrescription{
  1225. UserOrgId: adminUserInfo.Org.Id,
  1226. PatientId: id,
  1227. RecordDate: recordDate.Unix(),
  1228. ModeId: mode_id,
  1229. DialysisDuration: dialysis_duration,
  1230. Dialyzer: dialyzer,
  1231. PerfusionApparatus: perfusion_apparatus,
  1232. BloodFlowVolume: blood_flow_volume,
  1233. DewaterAmount: dewater_amount,
  1234. DisplaceLiqui: displace_liqui,
  1235. ReplacementWay: replacement_way,
  1236. Anticoagulant: anticoagulant,
  1237. AnticoagulantShouji: anticoagulant_shouji,
  1238. AnticoagulantWeichi: anticoagulant_weichi,
  1239. AnticoagulantZongliang: anticoagulant_zongliang,
  1240. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1241. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1242. Kalium: kalium,
  1243. Sodium: sodium,
  1244. Calcium: calcium,
  1245. Bicarbonate: bicarbonate,
  1246. Glucose: glucose,
  1247. // DryWeight: dry_weight,
  1248. DialysateFlow: dialysate_flow,
  1249. DialysateTemperature: dialysate_temperature,
  1250. // PrescriptionDoctor: prescription_doctor,
  1251. ReplacementTotal: replacement_total,
  1252. Conductivity: conductivity,
  1253. Remark: remark,
  1254. Status: 1,
  1255. CreatedTime: time.Now().Unix(),
  1256. UpdatedTime: time.Now().Unix(),
  1257. DialysisDurationMinute: dialysisDurationMinute,
  1258. DialysisDurationHour: dialysisDurationHour,
  1259. TargetUltrafiltration: targetUltrafiltration,
  1260. DialysateFormulation: dialysateFormulation,
  1261. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1262. BodyFluid: body_fluid,
  1263. SpecialMedicine: special_medicine,
  1264. SpecialMedicineOther: special_medicine_other,
  1265. DisplaceLiquiPart: displace_liqui_part,
  1266. DisplaceLiquiValue: displace_liqui_value,
  1267. BloodAccess: blood_access,
  1268. Ultrafiltration: ultrafiltration,
  1269. BodyFluidOther: body_fluid_other,
  1270. Niprocart: niprocart,
  1271. Jms: jms,
  1272. FistulaNeedleSet: fistula_needle_set,
  1273. FistulaNeedleSet16: fistula_needle_set_16,
  1274. Hemoperfusion: hemoperfusion,
  1275. DialyserSterilised: dialyser_sterilised,
  1276. Filtryzer: filtryzer,
  1277. Dialyzers: dialyzers,
  1278. Injector: injector,
  1279. Bloodlines: bloodlines,
  1280. TubingHemodialysis: tubing_hemodialysis,
  1281. Package: safe_package,
  1282. ALiquid: a_liquid,
  1283. TargetKtv: target_ktv,
  1284. PreImpulse: pre_impulse,
  1285. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1286. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1287. Blood: blood,
  1288. DialysisDialyszers: dialysis_dialyszers,
  1289. DialysisIrrigation: dialysis_irrigation,
  1290. AntioxidantCommodityName: antioxidant_commodity_name,
  1291. DisplaceSpeed: displace_speed,
  1292. Illness: illness,
  1293. Amylaceum: amylaceum,
  1294. SingleTime: single_time,
  1295. SingleWater: single_water,
  1296. ReplacementFlow: replacement_flow,
  1297. PlasmaSeparator: plasma_separator,
  1298. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  1299. OxygenUptake: oxygen_uptake,
  1300. OxygenFlow: oxygen_flow,
  1301. OxygenTime: oxygen_time,
  1302. HemodialysisPipelines: hemodialysis_pipelines,
  1303. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  1304. PunctureNeedle: puncture_needle,
  1305. PunctureNeedleCount: puncture_needle_count,
  1306. Epo: epo,
  1307. EpoCount: epo_count,
  1308. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  1309. AdminUserId: admin_user_id,
  1310. IsWater: is_war,
  1311. DrhyWater: drhy_water,
  1312. DryWaterHour: dry_water_hour,
  1313. WaterMachine: water_machine,
  1314. AddAmount: add_amount,
  1315. ReduceAmount: reduce_amount,
  1316. }
  1317. //查询最近透析准备表里是否存在 透析器 灌流器
  1318. //
  1319. //splitStr := strings.Split(dialysis_dialyszers, ",")
  1320. //
  1321. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  1322. //
  1323. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  1324. //if len(mation)>0{
  1325. // for _, item := range splitStr {
  1326. // for _,it := range mation{
  1327. // if(item == it.SpecificationName){
  1328. //
  1329. // //查询最近一次的透析器
  1330. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1331. //
  1332. // if errcode == gorm.ErrRecordNotFound{
  1333. // //插入数据
  1334. // prepare := models.DialysisBeforePrepare{
  1335. // UserOrgId: adminUserInfo.Org.Id,
  1336. // PatientId: id,
  1337. // RecordDate: recordDate.Unix(),
  1338. // GoodTypeId: it.GoodTypeId,
  1339. // GoodId: it.ID,
  1340. // Count: 1,
  1341. // Ctime: time.Now().Unix(),
  1342. // Creater: adminUserInfo.AdminUser.Id,
  1343. // Status:1,
  1344. //
  1345. // }
  1346. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1347. // fmt.Println("",errcode)
  1348. // }
  1349. // }
  1350. // }
  1351. //
  1352. // }
  1353. //
  1354. // for _, item := range splitIrrigation {
  1355. // for _,it := range mation{
  1356. // if(item == it.SpecificationName){
  1357. // //查询最近一次的透析器
  1358. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1359. // if errcode == gorm.ErrRecordNotFound{
  1360. // //插入数据
  1361. // prepare := models.DialysisBeforePrepare{
  1362. // UserOrgId: adminUserInfo.Org.Id,
  1363. // PatientId: id,
  1364. // RecordDate: recordDate.Unix(),
  1365. // GoodTypeId: it.GoodTypeId,
  1366. // GoodId: it.ID,
  1367. // Count: 1,
  1368. // Ctime: time.Now().Unix(),
  1369. // Creater: adminUserInfo.AdminUser.Id,
  1370. // Status:1,
  1371. //
  1372. // }
  1373. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1374. // fmt.Println(errcode)
  1375. // }
  1376. // }
  1377. // }
  1378. // }
  1379. //}
  1380. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1381. if dialysisPrescription.ID == 0 { //新增
  1382. if appRole.UserType == 2 || appRole.UserType == 1 {
  1383. prescription.PrescriptionDoctor = adminUserInfo.AdminUser.Id
  1384. }
  1385. prescription.Creater = adminUserInfo.AdminUser.Id
  1386. //针对河间咸得
  1387. if adminUserInfo.Org.Id == 10164 || adminUserInfo.Org.Id == 10090 || adminUserInfo.Org.Id == 3877 {
  1388. if prescription.ModeId != 2 && prescription.ModeId != 5 && prescription.ModeId != 12 {
  1389. prescription.DisplaceLiquiPart = 0
  1390. prescription.DisplaceLiquiValue = 0
  1391. }
  1392. }
  1393. err := service.AddSigleRecord(&prescription)
  1394. //获取key,清空redis
  1395. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe"
  1396. redis := service.RedisClient()
  1397. //清空key 值
  1398. redis.Set(key, "", time.Second)
  1399. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1400. //清空key 值
  1401. redis.Set(keyOne, "", time.Second)
  1402. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_solution"
  1403. //清空key 值
  1404. redis.Set(keyTwo, "", time.Second)
  1405. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  1406. redis.Set(keySix, "", time.Second)
  1407. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  1408. redis.Set(keySeven, "", time.Second)
  1409. if err == nil {
  1410. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1411. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe_by_mode"
  1412. //清空key 值
  1413. redis.Set(keyThree, "", time.Second)
  1414. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":system_dialysis_prescribe"
  1415. //清空key 值
  1416. redis.Set(keyFour, "", time.Second)
  1417. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":schedual_detail"
  1418. redis.Set(keyFive, "", time.Second)
  1419. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  1420. redis.Set(keySix, "", time.Second)
  1421. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  1422. redis.Set(keySeven, "", time.Second)
  1423. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1424. //清空key 值
  1425. redis.Set(keyOne, "", time.Second)
  1426. if updateErr != nil {
  1427. utils.ErrorLog("%v", updateErr)
  1428. }
  1429. defer redis.Close()
  1430. c.ServeSuccessJSON(map[string]interface{}{
  1431. "prescription": prescription,
  1432. })
  1433. }
  1434. } else { //修改
  1435. //if mode_id > 0 {
  1436. // service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1437. //}
  1438. //if template.TemplateId == 1 {
  1439. // if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater != 0 {
  1440. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1441. // if getPermissionErr != nil {
  1442. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1443. // return
  1444. // } else if headNursePermission == nil {
  1445. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1446. // return
  1447. // }
  1448. // }
  1449. //}
  1450. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1451. prescription.Modifier = adminUserInfo.AdminUser.Id
  1452. if appRole.UserType == 2 || appRole.UserType == 1 {
  1453. prescription_doctor := adminUserInfo.AdminUser.Id
  1454. prescription.PrescriptionDoctor = prescription_doctor
  1455. } else {
  1456. prescription.PrescriptionDoctor = dialysisPrescription.PrescriptionDoctor
  1457. }
  1458. if dialysisPrescription.Creater == 0 { //体重称
  1459. prescription.Creater = adminUserInfo.AdminUser.Id
  1460. } else {
  1461. prescription.Creater = dialysisPrescription.Creater
  1462. }
  1463. prescription.ID = dialysisPrescription.ID
  1464. err := service.UpDateDialysisPrescription(&prescription)
  1465. //获取key,清空redis
  1466. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe"
  1467. redis := service.RedisClient()
  1468. //清空key 值
  1469. redis.Set(key, "", time.Second)
  1470. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1471. //清空key 值
  1472. redis.Set(keyOne, "", time.Second)
  1473. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  1474. redis.Set(keySix, "", time.Second)
  1475. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  1476. redis.Set(keySeven, "", time.Second)
  1477. if err == nil {
  1478. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1479. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  1480. //清空key 值
  1481. redis.Set(keyOne, "", time.Second)
  1482. defer redis.Close()
  1483. if updateErr != nil {
  1484. utils.ErrorLog("%v", updateErr)
  1485. }
  1486. c.ServeSuccessJSON(map[string]interface{}{
  1487. "prescription": prescription,
  1488. })
  1489. }
  1490. }
  1491. }
  1492. func (c *DialysisAPIController) Finish() {
  1493. id, _ := c.GetInt64("patient", 0)
  1494. recordDateStr := c.GetString("record_date")
  1495. nurseID, _ := c.GetInt64("nurse")
  1496. end_time := c.GetString("end_time")
  1497. puncture_point_haematoma, _ := c.GetInt64("puncture_point_haematoma")
  1498. internal_fistula := c.GetString("blood_access_internal_fistula")
  1499. catheter := c.GetString("catheter")
  1500. cruor := c.GetString("cruor")
  1501. mission := c.GetString("mission")
  1502. if id <= 0 || nurseID <= 0 {
  1503. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1504. return
  1505. }
  1506. adminUserInfo := c.GetMobileAdminUserInfo()
  1507. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1508. if patient.ID == 0 {
  1509. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1510. return
  1511. }
  1512. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1513. if getNurseErr != nil {
  1514. c.ErrorLog("获取护士失败:%v", getNurseErr)
  1515. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1516. return
  1517. } else if nurse == nil {
  1518. c.ErrorLog("护士不存在")
  1519. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1520. return
  1521. }
  1522. if len(recordDateStr) == 0 {
  1523. recordDateStr = time.Now().Format("2006-01-02")
  1524. }
  1525. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1526. if parseDateErr != nil {
  1527. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1528. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1529. return
  1530. }
  1531. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  1532. if parseEndDateErr != nil {
  1533. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  1534. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1535. return
  1536. }
  1537. //now := time.Now()
  1538. //year, month, day := now.Date()
  1539. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  1540. //todayTimeStamp := today_time.Unix()
  1541. // 获取当天的第一条透析纪录
  1542. fmonitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecordFirst(adminUserInfo.Org.Id, id, recordDate.Unix())
  1543. if getMonitorRecordsErr != nil {
  1544. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1545. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1546. return
  1547. }
  1548. // 获取当前的最后一条透析纪录
  1549. endmonitorRecords, getMonitorRecordsErr := service.MobileGetLastMonitorRecordOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1550. if getMonitorRecordsErr != nil {
  1551. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1552. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1553. return
  1554. }
  1555. fmt.Println(endmonitorRecords.UltrafiltrationVolume)
  1556. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysisOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1557. if getAADErr != nil {
  1558. c.ErrorLog("获取透后评估失败:%v", getAADErr)
  1559. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1560. return
  1561. }
  1562. lastAssessmentAfterDislysis, _ := service.MobileGetLastTimeAssessmentAfterDislysisOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1563. _, dialysisOrder := service.FindDialysisRecordById(adminUserInfo.Org.Id, id, recordDate.Unix())
  1564. var tempassessmentAfterDislysis models.AssessmentAfterDislysis
  1565. if assessmentAfterDislysis != nil {
  1566. tempassessmentAfterDislysis = *assessmentAfterDislysis
  1567. tempassessmentAfterDislysis.UpdatedTime = time.Now().Unix()
  1568. } else {
  1569. tempassessmentAfterDislysis.CreatedTime = time.Now().Unix()
  1570. tempassessmentAfterDislysis.AssessmentDate = recordDate.Unix()
  1571. tempassessmentAfterDislysis.Status = 1
  1572. tempassessmentAfterDislysis.PatientId = id
  1573. tempassessmentAfterDislysis.UserOrgId = adminUserInfo.Org.Id
  1574. }
  1575. //长沙南雅
  1576. if adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 9675 || adminUserInfo.Org.Id == 10340 {
  1577. //获取最后一条透析处方数据
  1578. prescription, _ := service.GetLastDialysisPrescriptionByPatientIdTwo(adminUserInfo.Org.Id, id, recordDate.Unix())
  1579. evaluation, _ := service.MobileGetPredialysisEvaluationTwo(adminUserInfo.Org.Id, id, recordDate.Unix())
  1580. tempassessmentAfterDislysis.WeightAfter = evaluation.WeightBefore - prescription.TargetUltrafiltration/1000
  1581. }
  1582. if dialysisOrder.Stage == 1 {
  1583. temp_time := (float64(endDate.Unix()) - float64(dialysisOrder.StartTime)) / 3600
  1584. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  1585. fmt.Println(value)
  1586. a, b := math.Modf(value)
  1587. c, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  1588. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  1589. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", c*60), 10, 64)
  1590. tempassessmentAfterDislysis.ActualTreatmentHour = hour
  1591. tempassessmentAfterDislysis.ActualTreatmentMinute = minute
  1592. }
  1593. if fmonitorRecords.ID > 0 && endmonitorRecords.ID > 0 {
  1594. //var num1 int64
  1595. //num1 = endmonitorRecords.OperateTime - fmonitorRecords.OperateTime
  1596. //fmt.Println(num1)
  1597. //sub := float64(num1 / 3600)
  1598. //fmt.Println(sub)
  1599. //tempassessmentAfterDislysis.ActualTreatmentHour = int64(math.Floor(sub))
  1600. //sub2 := float64(((endmonitorRecords.OperateTime - fmonitorRecords.OperateTime) % 3600) / 60)
  1601. //tempassessmentAfterDislysis.ActualTreatmentMinute = int64(math.Floor(sub2))
  1602. tempassessmentAfterDislysis.Temperature = endmonitorRecords.Temperature
  1603. tempassessmentAfterDislysis.PulseFrequency = endmonitorRecords.PulseFrequency
  1604. tempassessmentAfterDislysis.BreathingRate = endmonitorRecords.BreathingRate
  1605. tempassessmentAfterDislysis.SystolicBloodPressure = endmonitorRecords.SystolicBloodPressure
  1606. tempassessmentAfterDislysis.DiastolicBloodPressure = endmonitorRecords.DiastolicBloodPressure
  1607. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1608. tempassessmentAfterDislysis.ActualDisplacement = endmonitorRecords.DisplacementQuantity
  1609. }
  1610. 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 || adminUserInfo.Org.Id == 10414 || adminUserInfo.Org.Id == 10430 || adminUserInfo.Org.Id == 10432 || adminUserInfo.Org.Id == 10223 {
  1611. evaluation, _ := service.MobileGetPredialysisEvaluationOne(adminUserInfo.Org.Id, id, recordDate.Unix())
  1612. if evaluation.SystolicBloodPressure == 0 {
  1613. evaluation.SystolicBloodPressure = fmonitorRecords.SystolicBloodPressure
  1614. pre := models.PredialysisEvaluation{
  1615. SystolicBloodPressure: evaluation.SystolicBloodPressure,
  1616. }
  1617. fmt.Println("prew", pre)
  1618. getNurseErr := service.UpdatePredialysisEvaluation(&pre, evaluation.ID)
  1619. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1620. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1621. redis := service.RedisClient()
  1622. redis.Set(key, "", time.Second)
  1623. redis.Set(keyOne, "", time.Second)
  1624. defer redis.Close()
  1625. fmt.Println(getNurseErr)
  1626. }
  1627. if evaluation.DiastolicBloodPressure == 0 {
  1628. evaluation.DiastolicBloodPressure = fmonitorRecords.DiastolicBloodPressure
  1629. pres := models.PredialysisEvaluation{
  1630. DiastolicBloodPressure: evaluation.DiastolicBloodPressure,
  1631. }
  1632. getNurseErr := service.UpdatePredialysisEvaluationTwo(&pres, evaluation.ID)
  1633. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1634. redis := service.RedisClient()
  1635. redis.Set(key, "", time.Second)
  1636. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1637. redis.Set(keyOne, "", time.Second)
  1638. defer redis.Close()
  1639. fmt.Println(getNurseErr)
  1640. }
  1641. if evaluation.PulseFrequency == 0 {
  1642. evaluation.PulseFrequency = fmonitorRecords.PulseFrequency
  1643. press := models.PredialysisEvaluation{
  1644. PulseFrequency: evaluation.PulseFrequency,
  1645. }
  1646. getNurseErr := service.UpdatePredialysisEvaluationThree(&press, evaluation.ID)
  1647. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1648. redis := service.RedisClient()
  1649. redis.Set(key, "", time.Second)
  1650. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1651. redis.Set(keyOne, "", time.Second)
  1652. defer redis.Close()
  1653. fmt.Println(getNurseErr)
  1654. }
  1655. if evaluation.Temperature == 0 {
  1656. evaluation.Temperature = fmonitorRecords.Temperature
  1657. press := models.PredialysisEvaluation{
  1658. Temperature: evaluation.Temperature,
  1659. }
  1660. getNurseErr := service.UpdatePredialysisEvaluationFour(&press, evaluation.ID)
  1661. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_before_dislysis"
  1662. redis := service.RedisClient()
  1663. redis.Set(key, "", time.Second)
  1664. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_befores_list_all"
  1665. redis.Set(keyOne, "", time.Second)
  1666. defer redis.Close()
  1667. fmt.Println(getNurseErr)
  1668. }
  1669. }
  1670. if adminUserInfo.Org.Id == 9583 {
  1671. //获取透析处方的最后一条数据
  1672. diaPrescription, diaerr := service.GetLastDialysisPrescriptionByPatientId(adminUserInfo.Org.Id, id, recordDate.Unix())
  1673. if diaerr != nil {
  1674. c.ErrorLog("获取透析处方失败:%v", diaerr)
  1675. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1676. return
  1677. }
  1678. if diaPrescription.ID > 0 && adminUserInfo.Org.Id == 9583 {
  1679. tempassessmentAfterDislysis.ActualUltrafiltration = diaPrescription.TargetUltrafiltration
  1680. }
  1681. }
  1682. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10101 {
  1683. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume / 1000
  1684. }
  1685. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10233 {
  1686. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume / 1000
  1687. }
  1688. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10060 {
  1689. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1690. }
  1691. if lastAssessmentAfterDislysis != nil {
  1692. tempassessmentAfterDislysis.BloodPressureType = lastAssessmentAfterDislysis.BloodPressureType
  1693. tempassessmentAfterDislysis.WeighingWay = lastAssessmentAfterDislysis.WeighingWay
  1694. tempassessmentAfterDislysis.Cruor = lastAssessmentAfterDislysis.Cruor
  1695. tempassessmentAfterDislysis.SymptomAfterDialysis = lastAssessmentAfterDislysis.SymptomAfterDialysis
  1696. tempassessmentAfterDislysis.InternalFistula = lastAssessmentAfterDislysis.InternalFistula
  1697. tempassessmentAfterDislysis.Catheter = lastAssessmentAfterDislysis.Catheter
  1698. tempassessmentAfterDislysis.Complication = lastAssessmentAfterDislysis.Complication
  1699. tempassessmentAfterDislysis.DialysisIntakes = lastAssessmentAfterDislysis.DialysisIntakes
  1700. tempassessmentAfterDislysis.DialysisIntakesFeed = lastAssessmentAfterDislysis.DialysisIntakesFeed
  1701. tempassessmentAfterDislysis.DialysisIntakesTransfusion = lastAssessmentAfterDislysis.DialysisIntakesTransfusion
  1702. tempassessmentAfterDislysis.DialysisIntakesBloodTransfusion = lastAssessmentAfterDislysis.DialysisIntakesBloodTransfusion
  1703. tempassessmentAfterDislysis.DialysisIntakesWashpipe = lastAssessmentAfterDislysis.DialysisIntakesWashpipe
  1704. tempassessmentAfterDislysis.BloodAccessPartId = lastAssessmentAfterDislysis.BloodAccessPartId
  1705. tempassessmentAfterDislysis.BloodAccessPartOperaId = lastAssessmentAfterDislysis.BloodAccessPartOperaId
  1706. tempassessmentAfterDislysis.PuncturePointOozingBlood = lastAssessmentAfterDislysis.PuncturePointOozingBlood
  1707. tempassessmentAfterDislysis.PuncturePointHaematoma = lastAssessmentAfterDislysis.PuncturePointHaematoma
  1708. tempassessmentAfterDislysis.InternalFistulaTremorAc = lastAssessmentAfterDislysis.InternalFistulaTremorAc
  1709. tempassessmentAfterDislysis.PatientGose = lastAssessmentAfterDislysis.PatientGose
  1710. tempassessmentAfterDislysis.InpatientDepartment = lastAssessmentAfterDislysis.InpatientDepartment
  1711. tempassessmentAfterDislysis.ObservationContent = lastAssessmentAfterDislysis.ObservationContent
  1712. tempassessmentAfterDislysis.ObservationContentOther = lastAssessmentAfterDislysis.ObservationContentOther
  1713. tempassessmentAfterDislysis.DryWeight = lastAssessmentAfterDislysis.DryWeight
  1714. tempassessmentAfterDislysis.DialysisProcess = lastAssessmentAfterDislysis.DialysisProcess
  1715. tempassessmentAfterDislysis.InAdvanceMinute = lastAssessmentAfterDislysis.InAdvanceMinute
  1716. tempassessmentAfterDislysis.InAdvanceReason = lastAssessmentAfterDislysis.InAdvanceReason
  1717. tempassessmentAfterDislysis.HemostasisMinute = lastAssessmentAfterDislysis.HemostasisMinute
  1718. tempassessmentAfterDislysis.HemostasisOpera = lastAssessmentAfterDislysis.HemostasisOpera
  1719. tempassessmentAfterDislysis.TremorNoise = lastAssessmentAfterDislysis.TremorNoise
  1720. tempassessmentAfterDislysis.DisequilibriumSyndrome = lastAssessmentAfterDislysis.DisequilibriumSyndrome
  1721. tempassessmentAfterDislysis.DisequilibriumSyndromeOption = lastAssessmentAfterDislysis.DisequilibriumSyndromeOption
  1722. tempassessmentAfterDislysis.ArterialTube = lastAssessmentAfterDislysis.ArterialTube
  1723. tempassessmentAfterDislysis.IntravenousTube = lastAssessmentAfterDislysis.IntravenousTube
  1724. tempassessmentAfterDislysis.Dialyzer = lastAssessmentAfterDislysis.Dialyzer
  1725. tempassessmentAfterDislysis.InAdvanceReasonOther = lastAssessmentAfterDislysis.InAdvanceReasonOther
  1726. tempassessmentAfterDislysis.IsEat = lastAssessmentAfterDislysis.IsEat
  1727. tempassessmentAfterDislysis.DialysisIntakesUnit = lastAssessmentAfterDislysis.DialysisIntakesUnit
  1728. tempassessmentAfterDislysis.CvcA = lastAssessmentAfterDislysis.CvcA
  1729. tempassessmentAfterDislysis.CvcV = lastAssessmentAfterDislysis.CvcV
  1730. tempassessmentAfterDislysis.Channel = lastAssessmentAfterDislysis.Channel
  1731. tempassessmentAfterDislysis.ReturnBlood = lastAssessmentAfterDislysis.ReturnBlood
  1732. tempassessmentAfterDislysis.RehydrationVolume = lastAssessmentAfterDislysis.RehydrationVolume
  1733. tempassessmentAfterDislysis.DialysisDuring = lastAssessmentAfterDislysis.DialysisDuring
  1734. tempassessmentAfterDislysis.StrokeVolume = lastAssessmentAfterDislysis.StrokeVolume
  1735. tempassessmentAfterDislysis.BloodFlow = lastAssessmentAfterDislysis.BloodFlow
  1736. tempassessmentAfterDislysis.SealingFluidDispose = lastAssessmentAfterDislysis.SealingFluidDispose
  1737. tempassessmentAfterDislysis.SealingFluidSpecial = lastAssessmentAfterDislysis.SealingFluidSpecial
  1738. }
  1739. err := service.UpdateAssessmentAfterDislysisRecord(&tempassessmentAfterDislysis)
  1740. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis"
  1741. redis := service.RedisClient()
  1742. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_list_all"
  1743. redis.Set(keyOne, "", time.Second)
  1744. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":assessment_after_dislysis_last"
  1745. redis.Set(keyTwo, "", time.Second)
  1746. defer redis.Close()
  1747. //清空key 值
  1748. redis.Set(key, "", time.Second)
  1749. if err != nil {
  1750. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1751. return
  1752. }
  1753. if dialysisOrder == nil {
  1754. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoStart)
  1755. return
  1756. }
  1757. if dialysisOrder.Stage == 2 {
  1758. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoEND)
  1759. return
  1760. }
  1761. if dialysisOrder.Stage == 1 {
  1762. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id, puncture_point_haematoma, internal_fistula, catheter, cruor, mission)
  1763. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_order"
  1764. redis := service.RedisClient()
  1765. defer redis.Close()
  1766. //清空key 值
  1767. redis.Set(key, "", time.Second)
  1768. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_orders_list_all"
  1769. redis.Set(keyOne, "", time.Second)
  1770. //结束时候透析次数加1
  1771. service.UpdateSolutionByPatientId(id)
  1772. dialysisOrder.Stage = 2
  1773. dialysisOrder.FinishNurse = nurseID
  1774. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1775. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1776. dialysisOrder.EndTime = endDate.Unix()
  1777. go func() {
  1778. ssoDomain := beego.AppConfig.String("call_domain")
  1779. api := ssoDomain + "/index/downpatient"
  1780. values := make(url.Values)
  1781. values.Set("org_id", strconv.FormatInt(adminUserInfo.AdminUser.Id, 10))
  1782. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1783. values.Set("patient_id", strconv.FormatInt(id, 10))
  1784. http.PostForm(api, values)
  1785. }()
  1786. if err == nil {
  1787. c.ServeSuccessJSON(map[string]interface{}{
  1788. "dialysisOrder": dialysisOrder,
  1789. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1790. })
  1791. } else {
  1792. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1793. }
  1794. }
  1795. }
  1796. func (c *DialysisAPIController) GetAllZone() {
  1797. adminUserInfo := c.GetMobileAdminUserInfo()
  1798. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1799. if err == nil {
  1800. c.ServeSuccessJSON(map[string]interface{}{
  1801. "zone": zone,
  1802. })
  1803. }
  1804. }
  1805. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1806. adminUserInfo := c.GetMobileAdminUserInfo()
  1807. page, _ := c.GetInt64("page", 1)
  1808. limit, _ := c.GetInt64("limit", 10)
  1809. schedulType, _ := c.GetInt64("schedul_type", 0)
  1810. startTime, _ := c.GetInt64("schedul_time", 0)
  1811. partitionType, _ := c.GetInt64("partition_type", 0)
  1812. keywords := c.GetString("keywords")
  1813. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1814. if err == nil {
  1815. c.ServeSuccessJSON(map[string]interface{}{
  1816. "schedule": dialysisSchedule,
  1817. })
  1818. }
  1819. return
  1820. }
  1821. // /m/api/dialysis/start [post]
  1822. // @param patient_id:int
  1823. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1824. // @param nurse:int 上机护士
  1825. // @param bed:int 床位号
  1826. func (this *DialysisAPIController) StartDialysis() {
  1827. patientID, _ := this.GetInt64("patient_id")
  1828. recordDateStr := this.GetString("record_date")
  1829. nurseID, _ := this.GetInt64("nurse")
  1830. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1831. blood_drawing, _ := this.GetInt64("blood_drawing")
  1832. schedual_type, _ := this.GetInt64("schedual_type")
  1833. bedID, _ := this.GetInt64("bed")
  1834. start_time := this.GetString("start_time")
  1835. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1836. change_nurse, _ := this.GetInt64("change_nurse")
  1837. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1838. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1839. quality_nurse_id, _ := this.GetInt64("quality_nurse_id")
  1840. puncture_needle := this.GetString("puncture_needle")
  1841. puncture_way := this.GetString("puncture_way")
  1842. dialysis_dialyszers := this.GetString("dialysis_dialyszers")
  1843. dialysis_irrigation := this.GetString("dialysis_irrigation")
  1844. blood_access_id, _ := this.GetInt64("blood_access_id")
  1845. zone_id, _ := this.GetInt64("zone_id")
  1846. elecsign := this.GetString("url")
  1847. nuclein_date_str := this.GetString("nuclein_date_str")
  1848. schedule_remark := this.GetString("schedule_remark")
  1849. order_remark := this.GetString("order_remark")
  1850. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1851. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1852. return
  1853. }
  1854. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1855. if parseStartDateErr != nil {
  1856. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1857. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1858. return
  1859. }
  1860. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1861. if parseErr != nil {
  1862. this.ErrorLog("时间解析失败:%v", parseErr)
  1863. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1864. return
  1865. }
  1866. adminUserInfo := this.GetMobileAdminUserInfo()
  1867. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1868. if getPatientErr != nil {
  1869. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1870. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1871. return
  1872. } else if patient == nil {
  1873. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1874. return
  1875. }
  1876. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1877. if getNurseErr != nil {
  1878. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1879. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1880. return
  1881. } else if nurse == nil {
  1882. this.ErrorLog("护士不存在")
  1883. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1884. return
  1885. }
  1886. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1887. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1888. if getDeviceNumberErr != nil {
  1889. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1890. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1891. return
  1892. } else if deviceNumber == nil {
  1893. this.ErrorLog("床位号不存在")
  1894. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1895. return
  1896. }
  1897. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1898. if getRecordErr != nil {
  1899. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1900. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1901. return
  1902. } else if dialysisRecord != nil {
  1903. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1904. return
  1905. }
  1906. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1907. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1908. timeLayout := "2006-01-02 15:04:05"
  1909. loc, _ := time.LoadLocation("Local")
  1910. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1911. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1912. schedulestartTime := theStartTime.Unix()
  1913. scheduleendTime := theEndTime.Unix()
  1914. var theNucleinDate int64
  1915. timeLayoutOne := "2006-01-02"
  1916. if len(nuclein_date_str) > 0 {
  1917. theTime, err := time.ParseInLocation(timeLayoutOne+" 15:04:05", nuclein_date_str+" 00:00:00", loc)
  1918. if err != nil {
  1919. utils.ErrorLog(err.Error())
  1920. }
  1921. theNucleinDate = theTime.Unix()
  1922. }
  1923. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1924. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1925. //sch, _ := service.GetSourceSch(adminUserInfo.Org.Id, patientID, scheduleendTime)
  1926. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1927. //查询该床位是否有人用了
  1928. order, _ := service.GetDialysisOrderByBedIdTwo(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1929. if err == gorm.ErrRecordNotFound { //空床位
  1930. // 修改了床位逻辑
  1931. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1932. if daySchedule.ID > 0 {
  1933. daySchedule.PartitionId = deviceNumber.ZoneID
  1934. daySchedule.BedId = bedID
  1935. daySchedule.ScheduleType = schedual_type
  1936. daySchedule.UpdatedTime = time.Now().Unix()
  1937. xtSchedule := models.Schedule{
  1938. PartitionId: deviceNumber.ZoneID,
  1939. BedId: bedID,
  1940. ScheduleType: schedual_type,
  1941. UpdatedTime: time.Now().Unix(),
  1942. }
  1943. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  1944. if err != nil {
  1945. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1946. return
  1947. }
  1948. }
  1949. } else if err == nil {
  1950. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1951. if order.ID > 0 { //该机位被其他人占用了
  1952. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1953. return
  1954. } else { //2022-11-04 更变需求,如果改床位有排班,但是没上机,则进行互换床位操作
  1955. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1956. if daySchedule.ID > 0 {
  1957. //daySchedule.PartitionId = deviceNumber.ZoneID
  1958. //daySchedule.BedId = bedID
  1959. //daySchedule.ScheduleType = schedual_type
  1960. //daySchedule.UpdatedTime = time.Now().Unix()
  1961. //err := service.UpdateSchedule(&daySchedule)
  1962. //xtSchedule := models.Schedule{
  1963. // PartitionId: deviceNumber.ZoneID,
  1964. // BedId: bedID,
  1965. // ScheduleType: schedual_type,
  1966. // UpdatedTime: time.Now().Unix(),
  1967. //}
  1968. //err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  1969. service.UpdateScheduleTwo(daySchedule, schedule)
  1970. }
  1971. }
  1972. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1973. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1974. return
  1975. }
  1976. //else if order.ID == 0 { //该床位没被占用
  1977. // daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1978. // if daySchedule.ID > 0 {
  1979. // //daySchedule.PartitionId = deviceNumber.ZoneID
  1980. // //daySchedule.BedId = bedID
  1981. // //daySchedule.ScheduleType = schedual_type
  1982. // //daySchedule.UpdatedTime = time.Now().Unix()
  1983. // //err := service.UpdateSchedule(&daySchedule)
  1984. // xtSchedule := models.Schedule{
  1985. // PartitionId: deviceNumber.ZoneID,
  1986. // BedId: bedID,
  1987. // ScheduleType: schedual_type,
  1988. // UpdatedTime: time.Now().Unix(),
  1989. // }
  1990. // err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  1991. // if err != nil {
  1992. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1993. // return
  1994. // }
  1995. // }
  1996. //}
  1997. //}
  1998. } else if err != nil {
  1999. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2000. return
  2001. }
  2002. dialysisRecord = &models.DialysisOrder{
  2003. DialysisDate: recordDate.Unix(),
  2004. UserOrgId: adminUserInfo.Org.Id,
  2005. PatientId: patientID,
  2006. Stage: 1,
  2007. BedID: bedID,
  2008. StartNurse: nurseID,
  2009. Status: 1,
  2010. StartTime: startDate.Unix(),
  2011. CreatedTime: time.Now().Unix(),
  2012. UpdatedTime: time.Now().Unix(),
  2013. PunctureNurse: puncture_nurse,
  2014. Creator: adminUserInfo.AdminUser.Id,
  2015. Modifier: adminUserInfo.AdminUser.Id,
  2016. SchedualType: schedual_type,
  2017. WashpipeNurse: washpipe_nurse,
  2018. ChangeNurse: change_nurse,
  2019. DifficultPunctureNurse: difficult_puncture_nurse,
  2020. NewFistulaNurse: new_fistula_nurse,
  2021. ZoneId: zone_id,
  2022. QualityNurseId: quality_nurse_id,
  2023. PunctureNeedle: puncture_needle,
  2024. PunctureWay: puncture_way,
  2025. DialysisIrrigation: dialysis_irrigation,
  2026. DialysisDialyszers: dialysis_dialyszers,
  2027. BloodAccessId: blood_access_id,
  2028. Url: elecsign,
  2029. NucleinDate: theNucleinDate,
  2030. ScheduleRemark: schedule_remark,
  2031. OrderRemark: order_remark,
  2032. }
  2033. //查询该床位是否有人用了
  2034. _, errorscode := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2035. if errorscode == gorm.ErrRecordNotFound {
  2036. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  2037. service.UpdateMobilePatient(adminUserInfo.Org.Id, patientID, schedule_remark)
  2038. redis := service.RedisClient()
  2039. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patientID, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_order"
  2040. redis.Set(key, "", time.Second)
  2041. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_orders_list_all"
  2042. //清空key 值
  2043. redis.Set(keyOne, "", time.Second)
  2044. keyTwo := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  2045. //清空key 值
  2046. redis.Set(keyTwo, "", time.Second)
  2047. if createErr != nil {
  2048. this.ErrorLog("上机失败:%v", createErr)
  2049. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2050. return
  2051. }
  2052. }
  2053. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2054. var tempdispose string
  2055. // 只针对中能建
  2056. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  2057. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  2058. }
  2059. if blood_drawing > 0 && adminUserInfo.Org.Id == 10318 {
  2060. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  2061. }
  2062. var ultrafiltration_rate float64
  2063. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  2064. //后期预增脱水量
  2065. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  2066. if prescription.ID > 0 {
  2067. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2068. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2069. if (template.TemplateId == 6 || template.TemplateId == 32) && adminUserInfo.Org.Id != 9671 { //adminUserInfo.Org.Id == 9538
  2070. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2071. }
  2072. //针对医师汇
  2073. if adminUserInfo.Org.Id == 10121 {
  2074. dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  2075. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  2076. }
  2077. //针对通道
  2078. if adminUserInfo.Org.Id == 10234 {
  2079. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration) / float64(totalMin) * 60 * 1000)
  2080. }
  2081. //针对监利大垸医院
  2082. if template.TemplateId == 41 {
  2083. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  2084. }
  2085. //针对肇庆三鹤血液透析中心
  2086. if template.TemplateId == 43 || adminUserInfo.Org.Id == 10432 {
  2087. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2088. }
  2089. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  2090. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2091. }
  2092. // 只针对方济医院
  2093. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  2094. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2095. ultrafiltration_rate = value
  2096. }
  2097. }
  2098. }
  2099. record := models.MonitoringRecord{
  2100. UserOrgId: adminUserInfo.Org.Id,
  2101. PatientId: patientID,
  2102. DialysisOrderId: dialysisRecord.ID,
  2103. MonitoringDate: schedulestartTime,
  2104. OperateTime: startDate.Unix(),
  2105. // MonitoringTime: recordTime,
  2106. MonitoringNurse: nurseID,
  2107. Dispose: tempdispose,
  2108. UltrafiltrationRate: ultrafiltration_rate,
  2109. UltrafiltrationVolume: 0,
  2110. Status: 1,
  2111. CreatedTime: time.Now().Unix(),
  2112. UpdatedTime: time.Now().Unix(),
  2113. }
  2114. //只针对广慈医院
  2115. 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 || adminUserInfo.Org.Id == 10432 {
  2116. // 查询病人是否有透前评估数据
  2117. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2118. //如果有数据就插入
  2119. if errcode == nil {
  2120. record.SystolicBloodPressure = befor.SystolicBloodPressure
  2121. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  2122. record.BreathingRate = befor.BreathingRate
  2123. record.PulseFrequency = befor.PulseFrequency
  2124. record.Temperature = befor.Temperature
  2125. }
  2126. }
  2127. // 如果当天有插入数据,则不再往透析纪录里插入数据
  2128. if newdialysisRecord.ID > 0 {
  2129. if adminUserInfo.Org.Id == 10340 || adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 9675 {
  2130. record.Temperature = 36.5
  2131. record.ArterialPressure = -100
  2132. record.DialysateTemperature = 36.5
  2133. record.Conductivity = 14
  2134. record.BreathingRate = "20"
  2135. record.VenousPressure = 80
  2136. record.TransmembranePressure = 60
  2137. }
  2138. //针对兰溪人民医院的需求
  2139. if adminUserInfo.Org.Id == 10430 || adminUserInfo.Org.Id == 9671 {
  2140. befor, _ := service.GetAssessmentBeforThrity(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  2141. record.SystolicBloodPressure = befor.SystolicBloodPressure
  2142. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  2143. record.Temperature = befor.Temperature
  2144. record.PulseFrequency = befor.PulseFrequency
  2145. record.BreathingRate = befor.BreathingRate
  2146. }
  2147. err := service.CreateMonitor(&record)
  2148. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patientID, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":monitor_records"
  2149. redis := service.RedisClient()
  2150. //清空key 值
  2151. redis.Set(key, "", time.Second)
  2152. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":monitor_record_list_all"
  2153. redis.Set(keyOne, "", time.Second)
  2154. defer redis.Close()
  2155. if err != nil {
  2156. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  2157. return
  2158. }
  2159. }
  2160. go func() {
  2161. ssoDomain := beego.AppConfig.String("call_domain")
  2162. api := ssoDomain + "/index/uppatient"
  2163. values := make(url.Values)
  2164. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  2165. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  2166. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  2167. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  2168. http.PostForm(api, values)
  2169. }()
  2170. this.ServeSuccessJSON(map[string]interface{}{
  2171. "dialysis_order": newdialysisRecord,
  2172. "monitor": record,
  2173. })
  2174. return
  2175. }
  2176. func (c *DialysisAPIController) PostSolution() {
  2177. id, _ := c.GetInt64("patient", 0)
  2178. recordDateStr := c.GetString("record_date")
  2179. if id <= 0 {
  2180. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2181. return
  2182. }
  2183. adminUserInfo := c.GetMobileAdminUserInfo()
  2184. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  2185. if patient.ID == 0 {
  2186. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  2187. return
  2188. }
  2189. if len(recordDateStr) == 0 {
  2190. recordDateStr = time.Now().Format("2006-01-02")
  2191. }
  2192. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2193. if parseDateErr != nil {
  2194. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2195. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2196. return
  2197. }
  2198. mode_id, _ := c.GetInt64("mode_id", 0)
  2199. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  2200. dialyzer, _ := c.GetInt64("dialyzer", 0)
  2201. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  2202. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  2203. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  2204. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  2205. replacement_way, _ := c.GetInt64("replacement_way", 0)
  2206. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  2207. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  2208. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  2209. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  2210. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  2211. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  2212. kalium, _ := c.GetFloat("kalium", 0)
  2213. sodium, _ := c.GetFloat("sodium", 0)
  2214. calcium, _ := c.GetFloat("calcium", 0)
  2215. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  2216. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  2217. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  2218. glucose, _ := c.GetFloat("glucose", 0)
  2219. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  2220. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  2221. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  2222. conductivity, _ := c.GetFloat("conductivity", 0)
  2223. remark := c.GetString("remark")
  2224. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  2225. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  2226. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  2227. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  2228. body_fluid, _ := c.GetInt64("body_fluid", 0)
  2229. special_medicine, _ := c.GetInt64("special_medicine", 0)
  2230. special_medicine_other := c.GetString("special_medicine_other")
  2231. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  2232. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  2233. blood_access, _ := c.GetInt64("blood_access", 0)
  2234. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  2235. body_fluid_other := c.GetString("body_fluid_other")
  2236. replacement_total, _ := c.GetFloat("replacement_total", 0)
  2237. niprocart, _ := c.GetInt64("niprocart", 0)
  2238. jms, _ := c.GetInt64("jms", 0)
  2239. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  2240. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  2241. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  2242. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  2243. filtryzer, _ := c.GetInt64("filtryzer", 0)
  2244. target_ktv, _ := c.GetFloat("target_ktv", 0)
  2245. dialyzers, _ := c.GetInt64("dialyzers", 0)
  2246. injector, _ := c.GetInt64("injector", 0)
  2247. bloodlines, _ := c.GetInt64("bloodlines", 0)
  2248. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  2249. safe_package, _ := c.GetInt64("package", 0)
  2250. a_liquid, _ := c.GetInt64("a_liquid", 0)
  2251. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  2252. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  2253. blood := c.GetString("blood")
  2254. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  2255. dialysis_irrigation := c.GetString("dialysis_irrigation")
  2256. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  2257. displace_speed := c.GetString("displace_speed")
  2258. illness, _ := c.GetInt64("illness")
  2259. amylaceum := c.GetString("amylaceum")
  2260. single_time := c.GetString("single_time")
  2261. single_water := c.GetString("single_water")
  2262. replacement_flow := c.GetString("replacement_flow")
  2263. plasma_separator := c.GetString("plasma_separator")
  2264. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  2265. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  2266. oxygen_flow := c.GetString("oxygen_flow")
  2267. oxygen_time := c.GetString("oxygen_time")
  2268. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  2269. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  2270. puncture_needle := c.GetString("puncture_needle")
  2271. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  2272. epo := c.GetString("epo")
  2273. epo_count, _ := c.GetFloat("epo_count", 0)
  2274. max_ultrafiltration_rate, _ := c.GetFloat("max_ultrafiltration_rate")
  2275. pre_impulse := c.GetString("pre_impulse")
  2276. impulse, _ := strconv.ParseFloat(pre_impulse, 64)
  2277. admin_user_id, _ := c.GetInt64("admin_user_id")
  2278. is_water := c.GetString("is_water")
  2279. add_amount, _ := c.GetFloat("add_amount")
  2280. reduce_amount, _ := c.GetFloat("reduce_amount")
  2281. var is_war int64
  2282. if is_water == "是" {
  2283. is_war = 1
  2284. }
  2285. if is_water == "否" {
  2286. is_war = 2
  2287. }
  2288. if is_water == "请选择" {
  2289. is_war = 0
  2290. }
  2291. drhy_water := c.GetString("drhy_water")
  2292. dry_water_hour := c.GetString("dry_water_hour")
  2293. water_machine := c.GetString("water_machine")
  2294. if mode_id > 0 {
  2295. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  2296. }
  2297. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  2298. //
  2299. //if template.TemplateId == 2 || template.TemplateId == 6 {
  2300. // if appRole.UserType == 3 {
  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. //}
  2311. prescription := models.DialysisPrescription{
  2312. UserOrgId: adminUserInfo.Org.Id,
  2313. PatientId: id,
  2314. RecordDate: recordDate.Unix(),
  2315. ModeId: mode_id,
  2316. DialysisDuration: dialysis_duration,
  2317. Dialyzer: dialyzer,
  2318. PerfusionApparatus: perfusion_apparatus,
  2319. BloodFlowVolume: blood_flow_volume,
  2320. DewaterAmount: dewater_amount,
  2321. DisplaceLiqui: displace_liqui,
  2322. ReplacementWay: replacement_way,
  2323. Anticoagulant: anticoagulant,
  2324. AnticoagulantShouji: anticoagulant_shouji,
  2325. AnticoagulantWeichi: anticoagulant_weichi,
  2326. AnticoagulantZongliang: anticoagulant_zongliang,
  2327. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  2328. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  2329. Kalium: kalium,
  2330. Sodium: sodium,
  2331. Calcium: calcium,
  2332. Bicarbonate: bicarbonate,
  2333. Glucose: glucose,
  2334. // DryWeight: dry_weight,
  2335. DialysateFlow: dialysate_flow,
  2336. DialysateTemperature: dialysate_temperature,
  2337. Conductivity: conductivity,
  2338. Remark: remark,
  2339. Status: 1,
  2340. CreatedTime: time.Now().Unix(),
  2341. UpdatedTime: time.Now().Unix(),
  2342. DialysisDurationMinute: dialysisDurationMinute,
  2343. DialysisDurationHour: dialysisDurationHour,
  2344. TargetUltrafiltration: targetUltrafiltration,
  2345. DialysateFormulation: dialysateFormulation,
  2346. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2347. BodyFluid: body_fluid,
  2348. SpecialMedicine: special_medicine,
  2349. SpecialMedicineOther: special_medicine_other,
  2350. DisplaceLiquiPart: displace_liqui_part,
  2351. DisplaceLiquiValue: displace_liqui_value,
  2352. BloodAccess: blood_access,
  2353. Ultrafiltration: ultrafiltration,
  2354. BodyFluidOther: body_fluid_other,
  2355. ReplacementTotal: replacement_total,
  2356. Niprocart: niprocart,
  2357. Jms: jms,
  2358. FistulaNeedleSet: fistula_needle_set,
  2359. FistulaNeedleSet16: fistula_needle_set_16,
  2360. Hemoperfusion: hemoperfusion,
  2361. DialyserSterilised: dialyser_sterilised,
  2362. Filtryzer: filtryzer,
  2363. TargetKtv: target_ktv,
  2364. Dialyzers: dialyzers,
  2365. Injector: injector,
  2366. Bloodlines: bloodlines,
  2367. TubingHemodialysis: tubing_hemodialysis,
  2368. Package: safe_package,
  2369. ALiquid: a_liquid,
  2370. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  2371. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  2372. Blood: blood,
  2373. DialysisDialyszers: dialysis_dialyszers,
  2374. DialysisIrrigation: dialysis_irrigation,
  2375. AntioxidantCommodityName: antioxidant_commodity_name,
  2376. DisplaceSpeed: displace_speed,
  2377. Illness: illness,
  2378. Amylaceum: amylaceum,
  2379. SingleWater: single_water,
  2380. SingleTime: single_time,
  2381. ReplacementFlow: replacement_flow,
  2382. PlasmaSeparator: plasma_separator,
  2383. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  2384. OxygenUptake: oxygen_uptake,
  2385. OxygenTime: oxygen_time,
  2386. OxygenFlow: oxygen_flow,
  2387. HemodialysisPipelines: hemodialysis_pipelines,
  2388. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2389. PunctureNeedle: puncture_needle,
  2390. PunctureNeedleCount: puncture_needle_count,
  2391. Epo: epo,
  2392. EpoCount: epo_count,
  2393. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2394. PreImpulse: impulse,
  2395. AdminUserId: admin_user_id,
  2396. IsWater: is_war,
  2397. DrhyWater: drhy_water,
  2398. DryWaterHour: dry_water_hour,
  2399. WaterMachine: water_machine,
  2400. AddAmount: add_amount,
  2401. ReduceAmount: reduce_amount,
  2402. }
  2403. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  2404. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  2405. //
  2406. if appRole.UserType == 2 || appRole.UserType == 1 {
  2407. prescription_doctor = adminUserInfo.AdminUser.Id
  2408. prescription.PrescriptionDoctor = prescription_doctor
  2409. }
  2410. if dialysisPrescription.ID == 0 { //新增
  2411. prescription.Creater = adminUserInfo.AdminUser.Id
  2412. } else { //修改
  2413. if dialysisPrescription.Creater == 0 {
  2414. prescription.Creater = adminUserInfo.AdminUser.Id
  2415. } else {
  2416. prescription.Creater = dialysisPrescription.Creater
  2417. }
  2418. //if/**/
  2419. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  2420. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  2421. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2422. // if getPermissionErr != nil {
  2423. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2424. // return
  2425. // } else if headNursePermission == nil {
  2426. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2427. // return
  2428. // }
  2429. //}
  2430. //prescription.Creater = dialysisPrescription.Creater
  2431. prescription.CreatedTime = dialysisPrescription.CreatedTime
  2432. prescription.Modifier = adminUserInfo.AdminUser.Id
  2433. prescription.ID = dialysisPrescription.ID
  2434. }
  2435. solution := models.DialysisSolution{
  2436. RegistrarsId: adminUserInfo.AdminUser.Id,
  2437. UserOrgId: adminUserInfo.Org.Id,
  2438. Doctor: prescription_doctor,
  2439. PatientId: id,
  2440. ModeId: mode_id,
  2441. DialysisDuration: dialysis_duration,
  2442. PerfusionApparatus: perfusion_apparatus,
  2443. BloodFlowVolume: blood_flow_volume,
  2444. Dewater: dewater_amount,
  2445. DisplaceLiqui: displace_liqui,
  2446. ReplacementWay: replacement_way,
  2447. Anticoagulant: anticoagulant,
  2448. AnticoagulantShouji: anticoagulant_shouji,
  2449. AnticoagulantWeichi: anticoagulant_weichi,
  2450. AnticoagulantZongliang: anticoagulant_zongliang,
  2451. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  2452. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  2453. Kalium: kalium,
  2454. Sodium: sodium,
  2455. Calcium: calcium,
  2456. Bicarbonate: bicarbonate,
  2457. Glucose: glucose,
  2458. // DryWeight: dry_weight,
  2459. DialysateFlow: dialysate_flow,
  2460. DialysateTemperature: dialysate_temperature,
  2461. Conductivity: conductivity,
  2462. Remark: remark,
  2463. Status: 1,
  2464. CreatedTime: time.Now().Unix(),
  2465. UpdatedTime: time.Now().Unix(),
  2466. DialysisDurationMinute: dialysisDurationMinute,
  2467. DialysisDurationHour: dialysisDurationHour,
  2468. TargetUltrafiltration: targetUltrafiltration,
  2469. DialysateFormulation: dialysateFormulation,
  2470. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  2471. BodyFluid: body_fluid,
  2472. SpecialMedicine: special_medicine,
  2473. SpecialMedicineOther: special_medicine_other,
  2474. DisplaceLiquiPart: displace_liqui_part,
  2475. DisplaceLiquiValue: displace_liqui_value,
  2476. BloodAccess: blood_access,
  2477. Ultrafiltration: ultrafiltration,
  2478. BodyFluidOther: body_fluid_other,
  2479. ReplacementTotal: replacement_total,
  2480. TargetKtv: target_ktv,
  2481. DialysisDialyszers: dialysis_dialyszers,
  2482. DialysisIrrigation: dialysis_irrigation,
  2483. HemodialysisPipelines: hemodialysis_pipelines,
  2484. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2485. PunctureNeedle: puncture_needle,
  2486. PunctureNeedleCount: puncture_needle_count,
  2487. Epo: epo,
  2488. EpoCount: epo_count,
  2489. MaxUltrafiltrationRate: max_ultrafiltration_rate,
  2490. PreImpulse: impulse,
  2491. SolutionStatus: 1,
  2492. }
  2493. //针对河间咸的
  2494. if adminUserInfo.Org.Id == 10090 || adminUserInfo.Org.Id == 10164 || adminUserInfo.Org.Id == 3877 {
  2495. if solution.ModeId != 2 && solution.ModeId != 5 && solution.ModeId != 12 {
  2496. solution.DisplaceLiquiPart = 0
  2497. solution.DisplaceLiquiValue = 0
  2498. }
  2499. if prescription.ModeId != 2 && prescription.ModeId != 5 && prescription.ModeId != 12 {
  2500. prescription.DisplaceLiquiPart = 0
  2501. prescription.DisplaceLiquiValue = 0
  2502. }
  2503. }
  2504. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  2505. //获取最新1条
  2506. dialysisSolution, _ := service.GetLastPatientDialysisSolution(id, adminUserInfo.Org.Id)
  2507. //更新状态
  2508. service.UpdateDialysisSolutionStatusTwo(dialysisSolution.ID, dialysisSolution.ModeId, dialysisSolution.UserOrgId, dialysisSolution.PatientId)
  2509. //获取key,清空redis
  2510. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_prescribe"
  2511. redis := service.RedisClient()
  2512. defer redis.Close()
  2513. //清空key 值
  2514. redis.Set(key, "", time.Second)
  2515. //清空长期医嘱的key
  2516. soulution_key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(mode_id, 10) + ":dialysis_solution"
  2517. redis.Set(soulution_key, "", time.Second)
  2518. //查询最近透析准备表里是否存在 透析器 灌流器
  2519. keyOne := "scheduals_" + recordDateStr + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  2520. redis.Set(keyOne, "", time.Second)
  2521. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":schedual_detail"
  2522. redis.Set(keyTwo, "", time.Second)
  2523. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":prescriptions_list_all"
  2524. redis.Set(keyThree, "", time.Second)
  2525. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(id, 10) + ":" + strconv.FormatInt(recordDate.Unix(), 10) + ":dialysis_prescribe_by_mode"
  2526. redis.Set(keyFour, "", time.Second)
  2527. //splitStr := strings.Split(dialysis_dialyszers, ",")
  2528. //
  2529. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  2530. //
  2531. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  2532. //if len(mation)>0{
  2533. // for _, item := range splitStr {
  2534. // for _,it := range mation{
  2535. // if(item == it.SpecificationName){
  2536. //
  2537. // //查询最近一次的透析器
  2538. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2539. //
  2540. // if errcode == gorm.ErrRecordNotFound{
  2541. // //插入数据
  2542. // prepare := models.DialysisBeforePrepare{
  2543. // UserOrgId: adminUserInfo.Org.Id,
  2544. // PatientId: id,
  2545. // RecordDate: recordDate.Unix(),
  2546. // GoodTypeId: it.GoodTypeId,
  2547. // GoodId: it.ID,
  2548. // Count: 1,
  2549. // Ctime: time.Now().Unix(),
  2550. // Creater: adminUserInfo.AdminUser.Id,
  2551. // Status:1,
  2552. //
  2553. // }
  2554. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2555. // fmt.Println("",errcode)
  2556. // }
  2557. // }
  2558. // }
  2559. //
  2560. // }
  2561. //
  2562. // for _, item := range splitIrrigation {
  2563. // for _,it := range mation{
  2564. // if(item == it.SpecificationName){
  2565. // //查询最近一次的透析器
  2566. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2567. // if errcode == gorm.ErrRecordNotFound{
  2568. // //插入数据
  2569. // prepare := models.DialysisBeforePrepare{
  2570. // UserOrgId: adminUserInfo.Org.Id,
  2571. // PatientId: id,
  2572. // RecordDate: recordDate.Unix(),
  2573. // GoodTypeId: it.GoodTypeId,
  2574. // GoodId: it.ID,
  2575. // Count: 1,
  2576. // Ctime: time.Now().Unix(),
  2577. // Creater: adminUserInfo.AdminUser.Id,
  2578. // Status:1,
  2579. //
  2580. // }
  2581. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2582. // fmt.Println(errcode)
  2583. // }
  2584. // }
  2585. // }
  2586. // }
  2587. //}
  2588. c.ServeSuccessJSON(map[string]interface{}{
  2589. "solution": &solution,
  2590. "prescription": &prescription,
  2591. })
  2592. }
  2593. func (c *DialysisAPIController) GetAcceptsAssessment() {
  2594. patient, _ := c.GetInt64("patient", 0)
  2595. adminUserInfo := c.GetMobileAdminUserInfo()
  2596. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  2597. c.ServeSuccessJSON(map[string]interface{}{
  2598. "receiveTreatmentAsses": receiveTreatmentAsses,
  2599. })
  2600. }
  2601. func (this *DialysisAPIController) PostSignInfo() {
  2602. patientID, _ := this.GetInt64("patient_id")
  2603. recordDateStr := this.GetString("date")
  2604. if patientID <= 0 {
  2605. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2606. return
  2607. }
  2608. if len(recordDateStr) == 0 {
  2609. recordDateStr = time.Now().Format("2006-01-02")
  2610. }
  2611. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2612. if parseDateErr != nil {
  2613. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2614. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2615. return
  2616. }
  2617. adminInfo := this.GetMobileAdminUserInfo()
  2618. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  2619. if err != nil {
  2620. this.ErrorLog("签名失败:%v", err)
  2621. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2622. return
  2623. }
  2624. this.ServeSuccessJSON(map[string]interface{}{
  2625. "doctor_id": adminInfo.AdminUser.Id,
  2626. })
  2627. }
  2628. func (this *DialysisAPIController) GetLastMonitorRecord() {
  2629. patientID, _ := this.GetInt64("patient_id")
  2630. adminInfo := this.GetMobileAdminUserInfo()
  2631. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  2632. this.ServeSuccessJSON(map[string]interface{}{
  2633. "monitor": record,
  2634. })
  2635. }
  2636. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  2637. thisTime := time.Now()
  2638. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  2639. timeLayout := "2006-01-02 15:04:05"
  2640. loc, _ := time.LoadLocation("Local")
  2641. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2642. theAssessmentDateTime := theStartTime.Unix()
  2643. patientID, _ := this.GetInt64("patient_id")
  2644. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  2645. adminInfo := this.GetMobileAdminUserInfo()
  2646. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2647. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2648. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  2649. var ultrafiltration_rate float64
  2650. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2651. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2652. fmt.Println(evaluation)
  2653. if prescription.ID > 0 {
  2654. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2655. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2656. if template.TemplateId == 6 && adminInfo.Org.Id != 9538 {
  2657. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2658. record.UltrafiltrationRate = ultrafiltration_rate
  2659. }
  2660. if template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 {
  2661. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1)
  2662. record.UltrafiltrationRate = ultrafiltration_rate
  2663. }
  2664. if template.TemplateId == 20 || template.TemplateId == 22 {
  2665. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2666. record.UltrafiltrationRate = ultrafiltration_rate
  2667. }
  2668. // 只针对方济医院
  2669. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  2670. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2671. ultrafiltration_rate = value
  2672. record.UltrafiltrationRate = ultrafiltration_rate
  2673. }
  2674. if template.TemplateId == 41 || template.TemplateId == 47 {
  2675. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin) * 1000)
  2676. record.UltrafiltrationRate = ultrafiltration_rate
  2677. }
  2678. if template.TemplateId == 43 {
  2679. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2680. record.UltrafiltrationRate = ultrafiltration_rate
  2681. }
  2682. if template.TemplateId == 46 || template.TemplateId == 54 {
  2683. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2684. record.UltrafiltrationRate = ultrafiltration_rate
  2685. }
  2686. if adminInfo.Org.Id == 10395 || adminInfo.Org.Id == 10138 || adminInfo.Org.Id == 10278 || adminInfo.Org.Id == 10340 || adminInfo.Org.Id == 10432 {
  2687. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / 1000 / float64(totalMin) * 1000)
  2688. record.UltrafiltrationRate = ultrafiltration_rate
  2689. }
  2690. //if template.TemplateId == 47 {
  2691. // ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration * 60 / float64(totalMin))
  2692. // record.UltrafiltrationRate = ultrafiltration_rate
  2693. //}
  2694. }
  2695. }
  2696. // record.UltrafiltrationRate = ultrafiltration_rate
  2697. record.UltrafiltrationVolume = 0
  2698. 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
  2699. if ultrafiltration_rate > 0 {
  2700. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  2701. record.UltrafiltrationVolume = value
  2702. }
  2703. }
  2704. 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
  2705. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  2706. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2707. record.UltrafiltrationVolume = ultrafiltration_volume
  2708. }
  2709. }
  2710. if adminInfo.Org.Id == 10395 || adminInfo.Org.Id == 10138 || adminInfo.Org.Id == 10278 || adminInfo.Org.Id == 10340 || adminInfo.Org.Id == 10432 {
  2711. if ultrafiltration_rate > 0 {
  2712. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2713. record.UltrafiltrationVolume = ultrafiltration_volume
  2714. }
  2715. }
  2716. if template.TemplateId == 47 || template.TemplateId == 54 {
  2717. record.DisplacementQuantity = record.DisplacementQuantity + record.DisplacementQuantity
  2718. }
  2719. this.ServeSuccessJSON(map[string]interface{}{
  2720. "monitor": record,
  2721. })
  2722. }
  2723. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  2724. record_id, _ := this.GetInt64("id")
  2725. nurseID, _ := this.GetInt64("nurse")
  2726. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  2727. bedID, _ := this.GetInt64("bed")
  2728. start_time := this.GetString("start_time")
  2729. schedual_type, _ := this.GetInt64("schedual_type")
  2730. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  2731. change_nurse, _ := this.GetInt64("change_nurse")
  2732. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  2733. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  2734. quality_nurse_id, _ := this.GetInt64("quality_nurse_id")
  2735. patient_id, _ := this.GetInt64("patient_id")
  2736. record_date, _ := this.GetInt64("record_date")
  2737. puncture_needle := this.GetString("puncture_needle")
  2738. puncture_way := this.GetString("puncture_way")
  2739. dialysis_dialyszers := this.GetString("dialysis_dialyszers")
  2740. dialysis_irrigation := this.GetString("dialysis_irrigation")
  2741. blood_access_id, _ := this.GetInt64("blood_access_id")
  2742. nuclein_date_str := this.GetString("nuclein_date_str")
  2743. order_remark := this.GetString("order_remark")
  2744. schedule_remark := this.GetString("schedule_remark")
  2745. if record_id == 0 {
  2746. this.ErrorLog("id:%v", record_id)
  2747. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2748. return
  2749. }
  2750. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  2751. if parseStartDateErr != nil {
  2752. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  2753. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2754. return
  2755. }
  2756. adminUserInfo := this.GetMobileAdminUserInfo()
  2757. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2758. if getNurseErr != nil {
  2759. this.ErrorLog("获取护士失败:%v", getNurseErr)
  2760. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2761. return
  2762. } else if nurse == nil {
  2763. this.ErrorLog("护士不存在")
  2764. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2765. return
  2766. }
  2767. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  2768. //if getNurseErr != nil {
  2769. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  2770. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2771. // return
  2772. //} else if nurse == nil {
  2773. // this.ErrorLog("护士不存在")
  2774. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2775. // return
  2776. //}
  2777. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  2778. if getDeviceNumberErr != nil {
  2779. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  2780. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2781. return
  2782. } else if deviceNumber == nil {
  2783. this.ErrorLog("床位号不存在")
  2784. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2785. return
  2786. }
  2787. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  2788. //
  2789. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  2790. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2791. // if getPermissionErr != nil {
  2792. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2793. // return
  2794. // } else if headNursePermission == nil {
  2795. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2796. // return
  2797. // }
  2798. //}
  2799. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  2800. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  2801. timeLayout := "2006-01-02 15:04:05"
  2802. loc, _ := time.LoadLocation("Local")
  2803. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2804. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  2805. schedulestartTime := theStartTime.Unix()
  2806. scheduleendTime := theEndTime.Unix()
  2807. var theNucleinDate int64
  2808. timeLayoutOne := "2006-01-02"
  2809. if len(nuclein_date_str) > 0 {
  2810. theTime, err := time.ParseInLocation(timeLayoutOne+" 15:04:05", nuclein_date_str+" 00:00:00", loc)
  2811. if err != nil {
  2812. utils.ErrorLog(err.Error())
  2813. }
  2814. theNucleinDate = theTime.Unix()
  2815. }
  2816. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  2817. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2818. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2819. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  2820. if err == gorm.ErrRecordNotFound { //空床位
  2821. // 修改了床位逻辑
  2822. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2823. if daySchedule.ID > 0 {
  2824. //daySchedule.BedId = bedID
  2825. //daySchedule.PartitionId = deviceNumber.ZoneID
  2826. //daySchedule.ScheduleType = schedual_type
  2827. //daySchedule.UpdatedTime = time.Now().Unix()
  2828. //err := service.UpdateSchedule(&daySchedule)
  2829. xtSchedule := models.Schedule{
  2830. PartitionId: deviceNumber.ZoneID,
  2831. BedId: bedID,
  2832. ScheduleType: schedual_type,
  2833. UpdatedTime: time.Now().Unix(),
  2834. }
  2835. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2836. if err != nil {
  2837. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2838. return
  2839. }
  2840. }
  2841. } else if err == nil {
  2842. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  2843. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2844. if daySchedule.ID > 0 {
  2845. //daySchedule.BedId = bedID
  2846. //daySchedule.PartitionId = deviceNumber.ZoneID
  2847. //
  2848. //daySchedule.ScheduleType = schedual_type
  2849. //daySchedule.UpdatedTime = time.Now().Unix()
  2850. //err := service.UpdateSchedule(&daySchedule)
  2851. xtSchedule := models.Schedule{
  2852. PartitionId: deviceNumber.ZoneID,
  2853. BedId: bedID,
  2854. ScheduleType: schedual_type,
  2855. UpdatedTime: time.Now().Unix(),
  2856. }
  2857. err := service.UpdateScheduleOne(daySchedule.ID, xtSchedule)
  2858. if err != nil {
  2859. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2860. return
  2861. }
  2862. }
  2863. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2864. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2865. return
  2866. }
  2867. } else if err != nil {
  2868. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2869. return
  2870. }
  2871. }
  2872. dialysisRecord := &models.DialysisOrder{
  2873. ID: record_id,
  2874. UserOrgId: adminUserInfo.Org.Id,
  2875. BedID: bedID,
  2876. StartNurse: nurseID,
  2877. StartTime: startDate.Unix(),
  2878. PunctureNurse: puncture_nurse,
  2879. Creator: adminUserInfo.AdminUser.Id,
  2880. Modifier: adminUserInfo.AdminUser.Id,
  2881. WashpipeNurse: washpipe_nurse,
  2882. SchedualType: schedual_type,
  2883. ChangeNurse: change_nurse,
  2884. DifficultPunctureNurse: difficult_puncture_nurse,
  2885. NewFistulaNurse: new_fistula_nurse,
  2886. QualityNurseId: quality_nurse_id,
  2887. PunctureNeedle: puncture_needle,
  2888. PunctureWay: puncture_way,
  2889. DialysisDialyszers: dialysis_dialyszers,
  2890. DialysisIrrigation: dialysis_irrigation,
  2891. BloodAccessId: blood_access_id,
  2892. NucleinDate: theNucleinDate,
  2893. OrderRemark: order_remark,
  2894. ScheduleRemark: schedule_remark,
  2895. }
  2896. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  2897. order, _ := service.GetLastPatientOrder(record_id)
  2898. service.UpdateMobilePatient(adminUserInfo.Org.Id, order.PatientId, schedule_remark)
  2899. redis := service.RedisClient()
  2900. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_order"
  2901. redis.Set(key, "", time.Second)
  2902. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_orders_list_all"
  2903. //清空key 值
  2904. redis.Set(keyOne, "", time.Second)
  2905. scheduleDateStartOne := startDate.Format("2006-01-02")
  2906. keyTwo := "scheduals_" + scheduleDateStartOne + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  2907. redis.Set(keyTwo, "", time.Second)
  2908. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":doctor_advices"
  2909. redis.Set(keyThree, "", time.Second)
  2910. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":monitor_records"
  2911. redis.Set(keyFour, "", time.Second)
  2912. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  2913. redis.Set(keyFive, "", time.Second)
  2914. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":his_doctor_advice"
  2915. redis.Set(keySix, "", time.Second)
  2916. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":device_list_all"
  2917. redis.Set(keySeven, "", time.Second)
  2918. if updateErr != nil {
  2919. this.ErrorLog("修改上机失败:%v", updateErr)
  2920. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2921. return
  2922. }
  2923. if updateErr == nil {
  2924. if tempDialysisRecord.Stage == 2 {
  2925. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  2926. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2927. fmt.Println(value)
  2928. a, b := math.Modf(value)
  2929. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2930. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2931. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2932. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  2933. redis := service.RedisClient()
  2934. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":assessment_after_dislysis_list_all"
  2935. redis.Set(key, "", time.Second)
  2936. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecord.PatientId, 10) + ":" + strconv.FormatInt(record_date, 10) + ":assessment_after_dislysis"
  2937. redis.Set(keyOne, "", time.Second)
  2938. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":dialysis_orders_list_all"
  2939. //清空key 值
  2940. redis.Set(keySix, "", time.Second)
  2941. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(record_date, 10) + ":monitor_records"
  2942. redis.Set(keySeven, "", time.Second)
  2943. redis.Close()
  2944. if updateAssessmentErr != nil {
  2945. utils.ErrorLog("%v", updateAssessmentErr)
  2946. }
  2947. }
  2948. }
  2949. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2950. this.ServeSuccessJSON(map[string]interface{}{
  2951. "dialysis_order": dialysisRecords,
  2952. })
  2953. }
  2954. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  2955. record_id, _ := c.GetInt64("id")
  2956. nurseID, _ := c.GetInt64("nurse")
  2957. end_time := c.GetString("end_time")
  2958. puncture_point_haematoma, _ := c.GetInt64("puncture_point_haematoma")
  2959. blood_access_internal_fistula := c.GetString("blood_access_internal_fistula")
  2960. catheter := c.GetString("catheter")
  2961. cruor := c.GetString("cruor")
  2962. mission := c.GetString("mission")
  2963. if record_id <= 0 || nurseID <= 0 {
  2964. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2965. return
  2966. }
  2967. adminUserInfo := c.GetMobileAdminUserInfo()
  2968. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2969. if getNurseErr != nil {
  2970. c.ErrorLog("获取护士失败:%v", getNurseErr)
  2971. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2972. return
  2973. } else if nurse == nil {
  2974. c.ErrorLog("护士不存在")
  2975. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2976. return
  2977. }
  2978. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  2979. if parseEndDateErr != nil {
  2980. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  2981. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2982. return
  2983. }
  2984. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2985. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2986. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2987. // if getPermissionErr != nil {
  2988. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2989. // return
  2990. // } else if headNursePermission == nil {
  2991. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2992. // return
  2993. // }
  2994. //}
  2995. dialysisRecord := &models.DialysisOrder{
  2996. ID: record_id,
  2997. UserOrgId: adminUserInfo.Org.Id,
  2998. EndTime: endDate.Unix(),
  2999. FinishNurse: nurseID,
  3000. FinishModifier: adminUserInfo.AdminUser.Id,
  3001. PuncturePointHaematoma: puncture_point_haematoma,
  3002. BloodAccessInternalFistula: blood_access_internal_fistula,
  3003. Catheter: catheter,
  3004. Cruor: cruor,
  3005. Mission: mission,
  3006. }
  3007. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  3008. redis := service.RedisClient()
  3009. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_order"
  3010. //清空key 值
  3011. redis.Set(key, "", time.Second)
  3012. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_orders_list_all"
  3013. //清空key 值
  3014. redis.Set(keyOne, "", time.Second)
  3015. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":monitor_records"
  3016. redis.Set(keySeven, "", time.Second)
  3017. redis.Close()
  3018. if updateErr != nil {
  3019. c.ErrorLog("修改下机失败:%v", updateErr)
  3020. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3021. return
  3022. }
  3023. if updateErr == nil {
  3024. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  3025. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  3026. a, b := math.Modf(value)
  3027. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  3028. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  3029. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  3030. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  3031. redis := service.RedisClient()
  3032. keyTen := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis"
  3033. redis.Set(keyTen, "", time.Second)
  3034. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis_last"
  3035. redis.Set(keyTwo, "", time.Second)
  3036. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":assessment_after_dislysis_list_all"
  3037. redis.Set(key, "", time.Second)
  3038. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":dialysis_orders_list_all"
  3039. redis.Set(keyThree, "", time.Second)
  3040. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(tempDialysisRecords.PatientId, 10) + ":" + strconv.FormatInt(tempDialysisRecords.DialysisDate, 10) + ":monitor_records"
  3041. redis.Set(keySeven, "", time.Second)
  3042. defer redis.Close()
  3043. if updateAssessmentErr != nil {
  3044. utils.ErrorLog("%v", updateAssessmentErr)
  3045. }
  3046. }
  3047. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  3048. c.ServeSuccessJSON(map[string]interface{}{
  3049. "dialysis_order": dialysisRecords,
  3050. })
  3051. }
  3052. func (c *DialysisAPIController) GetLongAdvice() {
  3053. patient_id, _ := c.GetInt64("id")
  3054. adminUserInfo := c.GetMobileAdminUserInfo()
  3055. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  3056. _, hisConfig := service.FindXTHisRecordByOrgId(adminUserInfo.Org.Id)
  3057. is_advice_open, _ := service.FindAdviceSettingById(adminUserInfo.Org.Id)
  3058. prescription_open, _ := service.FindPrescriptionConfigById(adminUserInfo.Org.Id)
  3059. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  3060. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  3061. c.ServeSuccessJSON(map[string]interface{}{
  3062. "status": "1",
  3063. })
  3064. return
  3065. } else { //开启推送提醒
  3066. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  3067. var advice_three []*models.DoctorAdvice
  3068. recordDateStr := time.Now().Format("2006-01-02")
  3069. recordDate, _ := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  3070. nowtime := recordDate.Unix()
  3071. //advices, err := service.GetLastLongAdviceByGroupNoOne(adminUserInfo.Org.Id, patient_id,nowtime)
  3072. //fmt.Println("advices232333232323323233232333223233232322332",advices)
  3073. //advices_two, err := service.GetLastLongAdviceByGroupNoFour(adminUserInfo.Org.Id, patient_id,nowtime)
  3074. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id, nowtime)
  3075. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id, nowtime)
  3076. for _, advice := range advices {
  3077. if advice.FrequencyType == 3 {
  3078. t := time.Now()
  3079. week := int(t.Weekday())
  3080. fmt.Println(t.Weekday())
  3081. fmt.Println(week)
  3082. switch week {
  3083. case 1:
  3084. if strings.Index(advice.WeekDay, "周一") == -1 {
  3085. advice_three = append(advice_three, advice)
  3086. }
  3087. break
  3088. case 2:
  3089. if strings.Index(advice.WeekDay, "周二") == -1 {
  3090. advice_three = append(advice_three, advice)
  3091. }
  3092. break
  3093. case 3:
  3094. if strings.Index(advice.WeekDay, "周三") == -1 {
  3095. advice_three = append(advice_three, advice)
  3096. }
  3097. break
  3098. case 4:
  3099. if strings.Index(advice.WeekDay, "周四") == -1 {
  3100. advice_three = append(advice_three, advice)
  3101. }
  3102. break
  3103. case 5:
  3104. if strings.Index(advice.WeekDay, "周五") == -1 {
  3105. advice_three = append(advice_three, advice)
  3106. }
  3107. break
  3108. case 6:
  3109. if strings.Index(advice.WeekDay, "周六") == -1 {
  3110. advice_three = append(advice_three, advice)
  3111. }
  3112. break
  3113. case 0:
  3114. if strings.Index(advice.WeekDay, "周日") == -1 {
  3115. advice_three = append(advice_three, advice)
  3116. }
  3117. break
  3118. }
  3119. }
  3120. }
  3121. for _, advice := range advices_two {
  3122. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  3123. now := p.Unix()
  3124. dayStr := strconv.FormatInt(advice.DayCount, 10)
  3125. dayStr2 := "-" + dayStr
  3126. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  3127. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  3128. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  3129. for _, ad := range advices {
  3130. advice_three = append(advice_three, ad)
  3131. }
  3132. }
  3133. if err == nil {
  3134. c.ServeSuccessJSON(map[string]interface{}{
  3135. "status": "2",
  3136. "advices": advices,
  3137. "advices_two": RemoveRepeatedElement(advice_three),
  3138. "is_open_remind": config.IsOpenRemind,
  3139. "his_config_open": hisConfig.IsOpen,
  3140. "is_advice_open": is_advice_open.IsAdviceOpen,
  3141. "prescription_open": prescription_open.IsOpen,
  3142. })
  3143. }
  3144. }
  3145. }
  3146. func (c *DialysisAPIController) GetLongAdviceOne() {
  3147. patient_id, _ := c.GetInt64("id")
  3148. startTime := c.GetString("schedule_date")
  3149. timeLayout := "2006-01-02"
  3150. loc, _ := time.LoadLocation("Local")
  3151. var theStartTime int64
  3152. if len(startTime) > 0 {
  3153. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", startTime+" 00:00:00", loc)
  3154. if err != nil {
  3155. utils.ErrorLog(err.Error())
  3156. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3157. return
  3158. }
  3159. theStartTime = theTime.Unix()
  3160. }
  3161. adminUserInfo := c.GetMobileAdminUserInfo()
  3162. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  3163. _, hisConfig := service.FindXTHisRecordByOrgId(adminUserInfo.Org.Id)
  3164. is_advice_open, _ := service.FindAdviceSettingById(adminUserInfo.Org.Id)
  3165. prescription_open, _ := service.FindPrescriptionConfigById(adminUserInfo.Org.Id)
  3166. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  3167. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  3168. c.ServeSuccessJSON(map[string]interface{}{
  3169. "status": "1",
  3170. })
  3171. return
  3172. } else { //开启推送提醒
  3173. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  3174. var advice_three []*models.DoctorAdvice
  3175. fmt.Println("theStartTime23434343433434433443434343434334", theStartTime)
  3176. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id, theStartTime)
  3177. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id, theStartTime)
  3178. for _, advice := range advices {
  3179. if advice.FrequencyType == 3 {
  3180. t := time.Now()
  3181. week := int(t.Weekday())
  3182. fmt.Println(t.Weekday())
  3183. fmt.Println(week)
  3184. switch week {
  3185. case 1:
  3186. if strings.Index(advice.WeekDay, "周一") == -1 {
  3187. advice_three = append(advice_three, advice)
  3188. }
  3189. break
  3190. case 2:
  3191. if strings.Index(advice.WeekDay, "周二") == -1 {
  3192. advice_three = append(advice_three, advice)
  3193. }
  3194. break
  3195. case 3:
  3196. if strings.Index(advice.WeekDay, "周三") == -1 {
  3197. advice_three = append(advice_three, advice)
  3198. }
  3199. break
  3200. case 4:
  3201. if strings.Index(advice.WeekDay, "周四") == -1 {
  3202. advice_three = append(advice_three, advice)
  3203. }
  3204. break
  3205. case 5:
  3206. if strings.Index(advice.WeekDay, "周五") == -1 {
  3207. advice_three = append(advice_three, advice)
  3208. }
  3209. break
  3210. case 6:
  3211. if strings.Index(advice.WeekDay, "周六") == -1 {
  3212. advice_three = append(advice_three, advice)
  3213. }
  3214. break
  3215. case 0:
  3216. if strings.Index(advice.WeekDay, "周日") == -1 {
  3217. advice_three = append(advice_three, advice)
  3218. }
  3219. break
  3220. }
  3221. }
  3222. }
  3223. for _, advice := range advices_two {
  3224. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  3225. now := p.Unix()
  3226. dayStr := strconv.FormatInt(advice.DayCount, 10)
  3227. dayStr2 := "-" + dayStr
  3228. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  3229. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  3230. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  3231. for _, ad := range advices {
  3232. advice_three = append(advice_three, ad)
  3233. }
  3234. }
  3235. if err == nil {
  3236. c.ServeSuccessJSON(map[string]interface{}{
  3237. "status": "2",
  3238. "advices": advices,
  3239. "advices_two": RemoveRepeatedElement(advice_three),
  3240. "is_open_remind": config.IsOpenRemind,
  3241. "his_config_open": hisConfig.IsOpen,
  3242. "is_advice_open": is_advice_open.IsAdviceOpen,
  3243. "prescription_open": prescription_open.IsOpen,
  3244. })
  3245. }
  3246. }
  3247. }
  3248. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  3249. newArr = make([]*models.DoctorAdvice, 0)
  3250. for i := 0; i < len(arr); i++ {
  3251. repeat := false
  3252. for j := i + 1; j < len(arr); j++ {
  3253. if arr[i].ID == arr[j].ID {
  3254. repeat = true
  3255. break
  3256. }
  3257. }
  3258. if !repeat {
  3259. newArr = append(newArr, arr[i])
  3260. }
  3261. }
  3262. return
  3263. }
  3264. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  3265. patient, _ := c.GetInt64("id", 0)
  3266. groupNo, _ := c.GetInt64("groupno", 0)
  3267. if patient <= 0 {
  3268. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3269. return
  3270. }
  3271. adminUserInfo := c.GetMobileAdminUserInfo()
  3272. dataBody := make(map[string]interface{}, 0)
  3273. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3274. if err != nil {
  3275. utils.ErrorLog(err.Error())
  3276. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3277. return
  3278. }
  3279. utils.ErrorLog("%v", dataBody)
  3280. timeLayout := "2006-01-02 15:04"
  3281. loc, _ := time.LoadLocation("Local")
  3282. timeLayout2 := "2006-01-02"
  3283. loc2, _ := time.LoadLocation("Local")
  3284. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  3285. utils.ErrorLog("advice_type")
  3286. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3287. return
  3288. }
  3289. adviceType := int64(2)
  3290. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  3291. utils.ErrorLog("advice_date")
  3292. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3293. return
  3294. }
  3295. adviceDate, _ := dataBody["advice_date"].(string)
  3296. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  3297. AdviceDate := theTime.Unix()
  3298. RecordDate := theTime.Unix()
  3299. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  3300. utils.ErrorLog("start_time")
  3301. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3302. return
  3303. }
  3304. startTime, _ := dataBody["start_time"].(string)
  3305. if len(startTime) == 0 {
  3306. utils.ErrorLog("len(start_time) == 0")
  3307. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3308. return
  3309. }
  3310. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  3311. if err != nil {
  3312. utils.ErrorLog(err.Error())
  3313. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3314. return
  3315. }
  3316. StartTime := theTime.Unix()
  3317. Remark := ""
  3318. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  3319. remark, _ := dataBody["remark"].(string)
  3320. Remark = remark
  3321. }
  3322. var advices []*models.GroupAdvice
  3323. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  3324. utils.ErrorLog("advices")
  3325. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3326. return
  3327. }
  3328. adviceNames := dataBody["advices"].([]interface{})
  3329. for _, adviceNameMap := range adviceNames {
  3330. adviceNameM := adviceNameMap.(map[string]interface{})
  3331. var advice models.GroupAdvice
  3332. advice.Remark = Remark
  3333. advice.AdviceType = adviceType
  3334. advice.StartTime = StartTime
  3335. advice.AdviceDate = AdviceDate
  3336. advice.RecordDate = RecordDate
  3337. advice.Status = 1
  3338. advice.CreatedTime = time.Now().Unix()
  3339. advice.UpdatedTime = time.Now().Unix()
  3340. advice.StopState = 2
  3341. advice.ExecutionState = 2
  3342. advice.UserOrgId = adminUserInfo.Org.Id
  3343. advice.PatientId = patient
  3344. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  3345. advice.IsSettle = 2
  3346. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  3347. utils.ErrorLog("advice_name")
  3348. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3349. return
  3350. }
  3351. adviceName, _ := adviceNameM["advice_name"].(string)
  3352. if len(adviceName) == 0 {
  3353. utils.ErrorLog("len(advice_name) == 0")
  3354. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3355. return
  3356. }
  3357. advice.AdviceName = adviceName
  3358. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  3359. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  3360. advice.DrugSpec = drugSpec
  3361. }
  3362. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  3363. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  3364. advice.AdviceDesc = adviceDesc
  3365. }
  3366. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  3367. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  3368. advice.DrugSpecUnit = drugSpecUnit
  3369. }
  3370. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  3371. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  3372. // advice.SingleDose = singleDose
  3373. //}
  3374. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  3375. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3376. advice.SingleDose = adviceNameM["single_dose"].(float64)
  3377. }
  3378. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  3379. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  3380. advice.SingleDoseUnit = singleDoseUnit
  3381. }
  3382. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  3383. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  3384. // advice.PrescribingNumber = prescribingNumber
  3385. //}
  3386. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  3387. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3388. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  3389. }
  3390. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  3391. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  3392. advice.PrescribingNumberUnit = prescribingNumberUnit
  3393. }
  3394. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  3395. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  3396. advice.DeliveryWay = deliveryWay
  3397. }
  3398. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  3399. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3400. advice.ExecutionFrequency = executionFrequency
  3401. }
  3402. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  3403. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  3404. advice.FrequencyType = frequency_type
  3405. }
  3406. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  3407. day_count := int64(adviceNameM["day_count"].(float64))
  3408. advice.DayCount = day_count
  3409. }
  3410. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  3411. week_day, _ := adviceNameM["week_day"].(string)
  3412. advice.WeekDay = week_day
  3413. }
  3414. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  3415. way := int64(adviceNameM["way"].(float64))
  3416. advice.Way = way
  3417. }
  3418. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  3419. drug_id := int64(adviceNameM["drug_id"].(float64))
  3420. advice.DrugId = drug_id
  3421. }
  3422. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  3423. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  3424. advice.DrugNameId = drug_name_id
  3425. }
  3426. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  3427. template_id, _ := adviceNameM["template_id"].(string)
  3428. advice.TemplateId = template_id
  3429. }
  3430. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  3431. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3432. advice.ExecutionFrequency = executionFrequency
  3433. }
  3434. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  3435. children := adviceNameM["child"].([]interface{})
  3436. if len(children) > 0 {
  3437. for _, childrenMap := range children {
  3438. childMap := childrenMap.(map[string]interface{})
  3439. var child models.GroupAdvice
  3440. child.Remark = Remark
  3441. child.AdviceType = adviceType
  3442. child.StartTime = StartTime
  3443. child.AdviceDate = AdviceDate
  3444. child.RecordDate = RecordDate
  3445. child.Status = 1
  3446. child.CreatedTime = time.Now().Unix()
  3447. child.UpdatedTime = time.Now().Unix()
  3448. child.StopState = 2
  3449. child.ExecutionState = 2
  3450. child.UserOrgId = adminUserInfo.Org.Id
  3451. child.PatientId = patient
  3452. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  3453. child.IsSettle = 1
  3454. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  3455. utils.ErrorLog("child advice_name")
  3456. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3457. return
  3458. }
  3459. childAdviceName, _ := childMap["advice_name"].(string)
  3460. if len(childAdviceName) == 0 {
  3461. utils.ErrorLog("len(child advice_name) == 0")
  3462. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3463. return
  3464. }
  3465. child.AdviceName = childAdviceName
  3466. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  3467. childAdviceDesc, _ := childMap["advice_desc"].(string)
  3468. child.AdviceDesc = childAdviceDesc
  3469. }
  3470. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  3471. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  3472. child.DrugSpec = childDrugSpec
  3473. }
  3474. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  3475. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  3476. child.DrugSpecUnit = childDrugSpecUnit
  3477. }
  3478. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  3479. child.SingleDose = childMap["single_dose"].(float64)
  3480. }
  3481. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  3482. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  3483. child.SingleDoseUnit = childSingleDoseUnit
  3484. }
  3485. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  3486. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  3487. }
  3488. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  3489. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  3490. child.PrescribingNumberUnit = childPrescribingNumberUnit
  3491. }
  3492. child.DeliveryWay = advice.DeliveryWay
  3493. child.ExecutionFrequency = advice.ExecutionFrequency
  3494. advice.Children = append(advice.Children, &child)
  3495. }
  3496. }
  3497. }
  3498. temp_advice, _ := service.FindRemindAdvice(advice.UserOrgId, advice.AdviceName, advice.AdviceDesc, advice.TemplateId, advice.FrequencyType, patient, advice.RecordDate)
  3499. if temp_advice.ID == 0 {
  3500. advices = append(advices, &advice)
  3501. }
  3502. }
  3503. if len(advices) > 0 {
  3504. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  3505. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient, 10) + ":" + strconv.FormatInt(RecordDate, 10) + ":doctor_advices"
  3506. redis := service.RedisClient()
  3507. //清空key 值
  3508. redis.Set(key, "", time.Second)
  3509. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(AdviceDate, 10) + ":advice_list_all"
  3510. redis.Set(keyOne, "", time.Second)
  3511. keyThree := "scheduals_" + adviceDate + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  3512. defer redis.Close()
  3513. redis.Set(keyThree, "", time.Second)
  3514. if err != nil {
  3515. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  3516. return
  3517. }
  3518. c.ServeSuccessJSON(map[string]interface{}{
  3519. "msg": "ok",
  3520. "advices": list,
  3521. })
  3522. } else {
  3523. c.ServeSuccessJSON(map[string]interface{}{
  3524. "msg": "ok",
  3525. })
  3526. }
  3527. return
  3528. }
  3529. func (c *DialysisAPIController) UploadDryWeight() {
  3530. patient_id, _ := c.GetInt64("id")
  3531. dry_weight, _ := c.GetFloat("dry_weight")
  3532. doctor_id, _ := c.GetInt64("doctor_id")
  3533. remark := c.GetString("remark")
  3534. adminUserInfo := c.GetMobileAdminUserInfo()
  3535. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  3536. if err == gorm.ErrRecordNotFound {
  3537. dryWeight := &models.SgjPatientDryweight{
  3538. PatientId: patient_id,
  3539. DryWeight: dry_weight,
  3540. Remakes: remark,
  3541. Ctime: time.Now().Unix(),
  3542. Mtime: time.Now().Unix(),
  3543. Creator: doctor_id,
  3544. Status: 1,
  3545. UserOrgId: adminUserInfo.Org.Id,
  3546. AdjustedValue: "/",
  3547. UserId: adminUserInfo.AdminUser.Id,
  3548. }
  3549. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3550. redis := service.RedisClient()
  3551. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":assessment_befores_list_all"
  3552. redis.Set(keyOne, "", time.Second)
  3553. loc, _ := time.LoadLocation("Local")
  3554. nowTime := time.Now()
  3555. nowDay := nowTime.Format("2006-01-02")
  3556. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3557. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3558. redis.Set(key, "", time.Second)
  3559. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3560. redis.Set(keyTwo, "", time.Second)
  3561. redis.Close()
  3562. if createErr == nil {
  3563. c.ServeSuccessJSON(map[string]interface{}{
  3564. "msg": "提交成功",
  3565. "weight": dryWeight,
  3566. })
  3567. }
  3568. } else {
  3569. dryWeight := &models.SgjPatientDryweight{
  3570. PatientId: patient_id,
  3571. DryWeight: dry_weight,
  3572. Remakes: remark,
  3573. Ctime: time.Now().Unix(),
  3574. Mtime: time.Now().Unix(),
  3575. Creator: doctor_id,
  3576. Status: 1,
  3577. UserOrgId: adminUserInfo.Org.Id,
  3578. AdjustedValue: "/",
  3579. UserId: adminUserInfo.AdminUser.Id,
  3580. }
  3581. var value float64
  3582. value = dry_weight - weightAdjust.DryWeight
  3583. if value < 0 {
  3584. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  3585. } else if value == 0 {
  3586. dryWeight.AdjustedValue = "/"
  3587. } else if value > 0 {
  3588. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  3589. }
  3590. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3591. redis := service.RedisClient()
  3592. loc, _ := time.LoadLocation("Local")
  3593. nowTime := time.Now()
  3594. nowDay := nowTime.Format("2006-01-02")
  3595. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3596. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_befores_list_all"
  3597. redis.Set(keyOne, "", time.Second)
  3598. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3599. redis.Set(key, "", time.Second)
  3600. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3601. redis.Set(keyTwo, "", time.Second)
  3602. redis.Close()
  3603. if createErr == nil {
  3604. c.ServeSuccessJSON(map[string]interface{}{
  3605. "msg": "提交成功",
  3606. "weight": dryWeight,
  3607. })
  3608. }
  3609. }
  3610. }
  3611. func (c *DialysisAPIController) GetSolution() {
  3612. patient_id, _ := c.GetInt64("patient_id")
  3613. mode_id, _ := c.GetInt64("mode_id")
  3614. adminUserInfo := c.GetMobileAdminUserInfo()
  3615. solution, err := service.MobileGetDialysisSolutionByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3616. prescription, err := service.MobileGetLastDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3617. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, mode_id)
  3618. dialysisPrescription, _ := service.MobileGetLastDialysisPrescription(patient_id, adminUserInfo.Org.Id)
  3619. if err != nil {
  3620. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3621. return
  3622. }
  3623. c.ServeSuccessJSON(map[string]interface{}{
  3624. "solution": solution,
  3625. "prescription": prescription,
  3626. "system_prescription": system_prescription,
  3627. "dialysisPrescription": dialysisPrescription,
  3628. })
  3629. }
  3630. func (c *DialysisAPIController) GetSchedule() {
  3631. schedual_type, _ := c.GetInt64("schedual_type")
  3632. adminUserInfo := c.GetMobileAdminUserInfo()
  3633. scheduleTime, _ := c.GetInt64("record_date")
  3634. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  3635. list, _ := service.GetAllBedNumberSeven(adminUserInfo.Org.Id)
  3636. c.ServeSuccessJSON(map[string]interface{}{
  3637. "number": deviceNumber,
  3638. "list": list,
  3639. })
  3640. }
  3641. func (c *DialysisAPIController) GetPatientId() {
  3642. id, _ := c.GetInt64("id")
  3643. //orgid := c.GetMobileAdminUserInfo().Org.Id
  3644. patientId, _ := service.GetPatientId(id)
  3645. //获取该患者的所有传染病
  3646. list, _ := service.GetPatientInfectious(id)
  3647. c.ServeSuccessJSON(map[string]interface{}{
  3648. "patient": patientId,
  3649. "infectioulist": list,
  3650. })
  3651. }
  3652. func (this *DialysisAPIController) GetDialysisSchedule() {
  3653. schedualDate := this.GetString("date")
  3654. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3655. if parseDateErr != nil {
  3656. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3657. return
  3658. }
  3659. adminInfo := this.GetMobileAdminUserInfo()
  3660. orgID := adminInfo.Org.Id
  3661. redis := service.RedisClient()
  3662. defer redis.Close()
  3663. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  3664. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  3665. if len(scheduals) > 0 {
  3666. //缓存数据
  3667. scheduals_json, err := json.Marshal(scheduals)
  3668. if err == nil {
  3669. redis.Set(key, scheduals_json, time.Second*30)
  3670. }
  3671. }
  3672. this.ServeSuccessJSON(map[string]interface{}{
  3673. "scheduals": scheduals,
  3674. })
  3675. }
  3676. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  3677. change_type, _ := this.GetInt64("type", 0)
  3678. record_date := this.GetString("record_time")
  3679. patient_id, _ := this.GetInt64("patient_id", 0)
  3680. timeLayout := "2006-01-02"
  3681. loc, _ := time.LoadLocation("Local")
  3682. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3683. record_time := theAdviceRecordTime.Unix()
  3684. adminUserInfo := this.GetMobileAdminUserInfo()
  3685. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  3686. if err == nil {
  3687. if len(advices) == 0 {
  3688. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  3689. return
  3690. } else {
  3691. this.ServeSuccessJSON(map[string]interface{}{
  3692. "advices": advices,
  3693. "schedule": sch,
  3694. })
  3695. return
  3696. }
  3697. } else {
  3698. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3699. return
  3700. }
  3701. }
  3702. func (c *DialysisAPIController) CreateConsumables() {
  3703. record_date := c.GetString("record_time")
  3704. patient_id, _ := c.GetInt64("patient_id", 0)
  3705. active, _ := c.GetInt64("active")
  3706. adminUser := c.GetMobileAdminUserInfo()
  3707. timeLayout := "2006-01-02"
  3708. loc, _ := time.LoadLocation("Local")
  3709. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3710. record_time := theRecordTime.Unix()
  3711. dataBody := make(map[string]interface{}, 0)
  3712. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3713. if err != nil {
  3714. utils.ErrorLog(err.Error())
  3715. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3716. return
  3717. }
  3718. houseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3719. var beforePrepares []*models.DialysisBeforePrepareGoods
  3720. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3721. var dialysisBefor []*models.DialysisBeforePrepare
  3722. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3723. goods, _ := dataBody["goods"].([]interface{})
  3724. if len(goods) > 0 {
  3725. for _, item := range goods {
  3726. items := item.(map[string]interface{})
  3727. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3728. utils.ErrorLog("good_id")
  3729. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3730. return
  3731. }
  3732. good_id := int64(items["good_id"].(float64))
  3733. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3734. utils.ErrorLog("good_type_id")
  3735. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3736. return
  3737. }
  3738. good_type_id := int64(items["good_type_id"].(float64))
  3739. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3740. utils.ErrorLog("count")
  3741. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3742. return
  3743. }
  3744. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3745. commdity_code := items["commdity_code"].(string)
  3746. fmt.Println("commdity", commdity_code)
  3747. prepareGoods := &models.DialysisBeforePrepareGoods{
  3748. GoodTypeId: good_type_id,
  3749. GoodId: good_id,
  3750. Count: count,
  3751. StorehouseId: houseConfig.StorehouseOutInfo,
  3752. }
  3753. beforePrepares = append(beforePrepares, prepareGoods)
  3754. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3755. GoodTypeId: good_type_id,
  3756. GoodId: good_id,
  3757. Count: count,
  3758. StorehouseId: houseConfig.StorehouseOutInfo,
  3759. }
  3760. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3761. prepare := &models.DialysisBeforePrepare{
  3762. GoodTypeId: good_type_id,
  3763. GoodId: good_id,
  3764. Count: count,
  3765. PatientId: patient_id,
  3766. RecordDate: record_time,
  3767. UserOrgId: adminUser.Org.Id,
  3768. Status: 1,
  3769. Ctime: time.Now().Unix(),
  3770. Creater: adminUser.AdminUser.Id,
  3771. CommdityCode: commdity_code,
  3772. StorehouseId: houseConfig.StorehouseOutInfo,
  3773. }
  3774. dialysisBefor = append(dialysisBefor, prepare)
  3775. }
  3776. }
  3777. //查询是否有库存
  3778. for _, item := range dialysisBefor {
  3779. _, err := service.FindFirstWarehousingInfoByStock(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  3780. if err == gorm.ErrRecordNotFound {
  3781. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3782. c.ServeSuccessJSON(map[string]interface{}{
  3783. "message": "1",
  3784. "good_name": goodObj.GoodName,
  3785. "specification_name": goodObj.SpecificationName,
  3786. })
  3787. return
  3788. }
  3789. if err != nil {
  3790. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3791. c.ServeSuccessJSON(map[string]interface{}{
  3792. "message": "1",
  3793. "good_name": goodObj.GoodName,
  3794. "specification_name": goodObj.SpecificationName,
  3795. })
  3796. return
  3797. }
  3798. }
  3799. //新增
  3800. if active == 1 && len(goods) > 0 {
  3801. for _, item := range dialysisBefor {
  3802. dialyPrepareOne := models.DialysisBeforePrepare{
  3803. GoodTypeId: item.GoodTypeId,
  3804. GoodId: item.GoodId,
  3805. PatientId: item.PatientId,
  3806. RecordDate: item.RecordDate,
  3807. UserOrgId: item.UserOrgId,
  3808. Count: item.Count,
  3809. Ctime: time.Now().Unix(),
  3810. Creater: item.Creater,
  3811. CommdityCode: item.CommdityCode,
  3812. Status: 1,
  3813. StorehouseId: houseConfig.StorehouseOutInfo,
  3814. }
  3815. //先清除再插入
  3816. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3817. err = service.CreateDialysisBeforePrepareOne(&dialyPrepareOne)
  3818. //查询默认仓库
  3819. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3820. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3821. var total_count int64
  3822. for _, it := range stockList {
  3823. total_count += it.StockCount
  3824. }
  3825. //基础库插入数据
  3826. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3827. //更新库存
  3828. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  3829. var flush_count int64
  3830. for _, it := range goodList {
  3831. flush_count += it.StockCount
  3832. }
  3833. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  3834. }
  3835. if err == nil {
  3836. c.ServeSuccessJSON(map[string]interface{}{
  3837. "msg": "保存成功",
  3838. "message": "2",
  3839. })
  3840. return
  3841. } else {
  3842. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3843. return
  3844. }
  3845. }
  3846. if len(beforePrepares) > 0 && active == 2 {
  3847. for _, item := range beforePrepares {
  3848. //1.查看该患者该耗材型号最后一次出库数量
  3849. goodInfo, _ := service.GetLastGoodListByPatientId(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3850. //判断当前出库数量和最后一次出库数量的大小
  3851. //如果当前出库数量小于或等于最后一次出库数量 正常出库后 需要退库操作
  3852. if item.Count <= goodInfo.Count {
  3853. //退库
  3854. err = ConsumablesDeliveryTotalSeven(adminUser.Org.Id, patient_id, record_time, beforePrepares, adminUser.AdminUser.Id, item.Count)
  3855. //查询今日出库数据
  3856. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3857. for _, it := range list {
  3858. prepare := models.DialysisBeforePrepare{
  3859. UserOrgId: it.OrgId,
  3860. PatientId: patient_id,
  3861. RecordDate: it.RecordTime,
  3862. GoodId: it.GoodId,
  3863. GoodTypeId: it.GoodTypeId,
  3864. Count: it.Count,
  3865. Ctime: time.Now().Unix(),
  3866. Creater: adminUser.AdminUser.Id,
  3867. Status: 1,
  3868. StorehouseId: houseConfig.StorehouseOutInfo,
  3869. }
  3870. //删除准备表数据
  3871. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3872. service.CreateDialysisBeforePrepareOne(&prepare)
  3873. }
  3874. }
  3875. var last_total int64
  3876. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3877. if item.Count >= goodInfo.Count {
  3878. //查询当前批次当前耗材最后一条出库数据
  3879. lastOutInfo, _ := service.GetLastWarehouOutInfoByPatientId(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3880. //计算当前出库和最后一次出库数据相差数据
  3881. last_total = item.Count - lastOutInfo.Count
  3882. //查询该批次剩余库存
  3883. lastInfo, _ := service.GetLastStockOut(lastOutInfo.WarehouseInfotId)
  3884. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3885. if lastInfo.StockCount >= last_total {
  3886. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3887. //查询今日出库数据
  3888. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3889. for _, it := range list {
  3890. prepare := models.DialysisBeforePrepare{
  3891. UserOrgId: it.OrgId,
  3892. PatientId: patient_id,
  3893. RecordDate: it.RecordTime,
  3894. GoodId: it.GoodId,
  3895. GoodTypeId: it.GoodTypeId,
  3896. Count: it.Count,
  3897. Ctime: time.Now().Unix(),
  3898. Creater: adminUser.AdminUser.Id,
  3899. Status: 1,
  3900. StorehouseId: houseConfig.StorehouseOutInfo,
  3901. }
  3902. //删除准备表数据
  3903. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3904. service.CreateDialysisBeforePrepareOne(&prepare)
  3905. //查询默认仓库
  3906. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3907. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3908. var total_count int64
  3909. for _, it := range stockList {
  3910. total_count += it.StockCount
  3911. }
  3912. //基础库插入数据
  3913. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3914. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  3915. var flush_count int64
  3916. for _, it := range goodList {
  3917. flush_count += it.StockCount
  3918. }
  3919. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  3920. }
  3921. }
  3922. //如果库存不够,则出库到下一个批次
  3923. if lastInfo.StockCount < last_total {
  3924. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3925. //查询今日出库数据
  3926. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3927. for _, it := range list {
  3928. prepare := models.DialysisBeforePrepare{
  3929. UserOrgId: it.OrgId,
  3930. PatientId: patient_id,
  3931. RecordDate: it.RecordTime,
  3932. GoodId: it.GoodId,
  3933. GoodTypeId: it.GoodTypeId,
  3934. Count: it.Count,
  3935. Ctime: time.Now().Unix(),
  3936. Creater: adminUser.AdminUser.Id,
  3937. Status: 1,
  3938. StorehouseId: houseConfig.StorehouseOutInfo,
  3939. }
  3940. //删除准备表数据
  3941. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3942. service.CreateDialysisBeforePrepareOne(&prepare)
  3943. //查询默认仓库
  3944. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3945. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3946. var total_count int64
  3947. for _, it := range stockList {
  3948. total_count += it.StockCount
  3949. }
  3950. //基础库插入数据
  3951. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3952. goodList, _ := service.GetSumGoodList(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  3953. var flush_count int64
  3954. for _, it := range goodList {
  3955. flush_count += it.StockCount
  3956. }
  3957. service.UpdateSumGood(adminUser.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  3958. }
  3959. if err != nil {
  3960. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3961. c.ServeSuccessJSON(map[string]interface{}{
  3962. "message": "1",
  3963. "good_name": goodObj.GoodName,
  3964. "specification_name": goodObj.SpecificationName,
  3965. })
  3966. return
  3967. }
  3968. }
  3969. }
  3970. if err != nil {
  3971. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3972. c.ServeSuccessJSON(map[string]interface{}{
  3973. "message": "1",
  3974. "good_name": goodObj.GoodName,
  3975. "specification_name": goodObj.SpecificationName,
  3976. })
  3977. return
  3978. }
  3979. }
  3980. }
  3981. }
  3982. var errs error
  3983. if errs == nil {
  3984. c.ServeSuccessJSON(map[string]interface{}{
  3985. "msg": "提交成功",
  3986. "message": "2",
  3987. "good_name": "",
  3988. "specification_name": "",
  3989. })
  3990. return
  3991. } else {
  3992. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3993. return
  3994. }
  3995. }
  3996. func (c *DialysisAPIController) CreateStockOutInfo() {
  3997. patient_id, _ := c.GetInt64("patient_id", 0)
  3998. record_date := c.GetString("record_time")
  3999. if patient_id <= 0 {
  4000. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4001. return
  4002. }
  4003. adminInfo := c.GetMobileAdminUserInfo()
  4004. creator := c.GetMobileAdminUserInfo().AdminUser.Id
  4005. timeLayout := "2006-01-02"
  4006. loc, _ := time.LoadLocation("Local")
  4007. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  4008. record_time := theRecordTime.Unix()
  4009. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  4010. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  4011. //去重
  4012. consumables = RemoveRepeatedGood(consumables)
  4013. if record.IsOpen == 1 {
  4014. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4015. //查询是否有库存
  4016. for _, item := range consumables {
  4017. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  4018. if item.Count > warehouse.Count {
  4019. goodErrcode := models.XtGoodErrcode{
  4020. UserOrgId: item.UserOrgId,
  4021. Errcode: "自动出库库存不足",
  4022. GoodId: item.GoodId,
  4023. Status: 1,
  4024. Ctime: time.Now().Unix(),
  4025. Mtime: 0,
  4026. Count: 0,
  4027. StockCount: 0,
  4028. Creater: creator,
  4029. BatchNumberId: warehouse.ID,
  4030. WarehouseOutId: 0,
  4031. }
  4032. service.CreateGoodErrcode(goodErrcode)
  4033. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4034. c.ServeSuccessJSON(map[string]interface{}{
  4035. "message": "1",
  4036. "good_name": goodObj.GoodName,
  4037. "specification_name": goodObj.SpecificationName,
  4038. })
  4039. return
  4040. }
  4041. }
  4042. //查询是否有出库单
  4043. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  4044. if err == gorm.ErrRecordNotFound {
  4045. //没有记录,则创建出库单
  4046. timeStr := time.Now().Format("2006-01-02")
  4047. timeArr := strings.Split(timeStr, "-")
  4048. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  4049. total = total + 1
  4050. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4051. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4052. number = number + total
  4053. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4054. creater := adminInfo.AdminUser.Id
  4055. warehouseOut := models.WarehouseOut{
  4056. WarehouseOutOrderNumber: warehousing_out_order,
  4057. OperationTime: time.Now().Unix(),
  4058. OrgId: adminInfo.Org.Id,
  4059. Creater: creater,
  4060. Ctime: time.Now().Unix(),
  4061. Status: 1,
  4062. WarehouseOutTime: record_time,
  4063. Dealer: 0,
  4064. Manufacturer: 0,
  4065. Type: 1,
  4066. IsSys: 1,
  4067. StorehouseId: houseConfig.StorehouseOutInfo,
  4068. IsCheck: 1,
  4069. }
  4070. err := service.AddSigleWarehouseOut(&warehouseOut)
  4071. if err != nil {
  4072. goodErrcode := models.XtGoodErrcode{
  4073. UserOrgId: adminInfo.Org.Id,
  4074. Errcode: "创建出库单失败",
  4075. GoodId: 0,
  4076. Status: 1,
  4077. Ctime: time.Now().Unix(),
  4078. Mtime: 0,
  4079. Count: 0,
  4080. StockCount: 0,
  4081. Creater: creator,
  4082. BatchNumberId: 0,
  4083. WarehouseOutId: 0,
  4084. }
  4085. service.CreateGoodErrcode(goodErrcode)
  4086. utils.TraceLog("创建出库单失败 err = %v", err)
  4087. } else {
  4088. for _, item := range consumables {
  4089. //出库
  4090. err := service.ConsumablesGoodDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, item.Count)
  4091. if err == nil {
  4092. goodErrcode := models.XtGoodErrcode{
  4093. UserOrgId: adminInfo.Org.Id,
  4094. Errcode: "自动出库接口报错",
  4095. GoodId: 0,
  4096. Status: 1,
  4097. Ctime: time.Now().Unix(),
  4098. Mtime: 0,
  4099. Count: 0,
  4100. StockCount: 0,
  4101. Creater: creator,
  4102. BatchNumberId: 0,
  4103. WarehouseOutId: 0,
  4104. }
  4105. service.CreateGoodErrcode(goodErrcode)
  4106. utils.TraceLog("创建出库单失败 err = %v", err)
  4107. }
  4108. //查询
  4109. //出库数量相加
  4110. errs := service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, item.UserOrgId, item.GoodId)
  4111. if errs != nil {
  4112. goodErrcode := models.XtGoodErrcode{
  4113. UserOrgId: item.UserOrgId,
  4114. Errcode: "创建剩余库存字段报错",
  4115. GoodId: item.GoodId,
  4116. Status: 1,
  4117. Ctime: time.Now().Unix(),
  4118. Mtime: 0,
  4119. Count: 0,
  4120. StockCount: 0,
  4121. Creater: creater,
  4122. BatchNumberId: 0,
  4123. WarehouseOutId: 0,
  4124. }
  4125. service.CreateGoodErrcode(goodErrcode)
  4126. }
  4127. }
  4128. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4129. if len(list) == 0 {
  4130. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4131. return
  4132. }
  4133. for _, item := range list {
  4134. prepare := models.DialysisBeforePrepare{
  4135. UserOrgId: adminInfo.Org.Id,
  4136. PatientId: patient_id,
  4137. RecordDate: record_time,
  4138. GoodId: item.GoodId,
  4139. GoodTypeId: item.GoodTypeId,
  4140. Count: item.Count,
  4141. Creater: adminInfo.AdminUser.Id,
  4142. Status: 1,
  4143. Ctime: time.Now().Unix(),
  4144. StorehouseId: houseConfig.StorehouseOutInfo,
  4145. }
  4146. //清空准备表数据
  4147. err := service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4148. if err != nil {
  4149. goodErrcode := models.XtGoodErrcode{
  4150. UserOrgId: item.OrgId,
  4151. Errcode: "自动出库清空准备表数据报错",
  4152. GoodId: item.GoodId,
  4153. Status: 1,
  4154. Ctime: time.Now().Unix(),
  4155. Mtime: 0,
  4156. Count: 0,
  4157. StockCount: 0,
  4158. Creater: creater,
  4159. BatchNumberId: 0,
  4160. WarehouseOutId: 0,
  4161. }
  4162. service.CreateGoodErrcode(goodErrcode)
  4163. }
  4164. errs := service.CreateDialysisBeforePrepareOne(&prepare)
  4165. if errs != nil {
  4166. goodErrcode := models.XtGoodErrcode{
  4167. UserOrgId: item.OrgId,
  4168. Errcode: "自动出库创建准备表数据报错",
  4169. GoodId: item.GoodId,
  4170. Status: 1,
  4171. Ctime: time.Now().Unix(),
  4172. Mtime: 0,
  4173. Count: 0,
  4174. StockCount: 0,
  4175. Creater: creater,
  4176. BatchNumberId: 0,
  4177. WarehouseOutId: 0,
  4178. }
  4179. service.CreateGoodErrcode(goodErrcode)
  4180. }
  4181. //查询默认仓库
  4182. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4183. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4184. var total_count int64
  4185. for _, it := range stockList {
  4186. total_count += it.StockCount
  4187. }
  4188. //基础库插入数据
  4189. errcodes := service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4190. if errcodes != nil {
  4191. goodErrcode := models.XtGoodErrcode{
  4192. UserOrgId: item.OrgId,
  4193. Errcode: "自动出库基础库插入数据",
  4194. GoodId: item.GoodId,
  4195. Status: 1,
  4196. Ctime: time.Now().Unix(),
  4197. Mtime: 0,
  4198. Count: 0,
  4199. StockCount: 0,
  4200. Creater: creater,
  4201. BatchNumberId: 0,
  4202. WarehouseOutId: 0,
  4203. }
  4204. service.CreateGoodErrcode(goodErrcode)
  4205. }
  4206. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4207. var flush_count int64
  4208. for _, it := range goodList {
  4209. flush_count += it.StockCount
  4210. }
  4211. errsss := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4212. if errsss != nil {
  4213. goodErrcode := models.XtGoodErrcode{
  4214. UserOrgId: item.OrgId,
  4215. Errcode: "自动出库剩余库存更新数据",
  4216. GoodId: item.GoodId,
  4217. Status: 1,
  4218. Ctime: time.Now().Unix(),
  4219. Mtime: 0,
  4220. Count: 0,
  4221. StockCount: 0,
  4222. Creater: creater,
  4223. BatchNumberId: 0,
  4224. WarehouseOutId: 0,
  4225. }
  4226. service.CreateGoodErrcode(goodErrcode)
  4227. }
  4228. }
  4229. }
  4230. //
  4231. } else if err == nil {
  4232. for _, item := range consumables {
  4233. //出库
  4234. err := service.ConsumablesGoodDelivery(item.UserOrgId, patient_id, record_time, item, &out, item.Count)
  4235. if err != nil {
  4236. goodErrcode := models.XtGoodErrcode{
  4237. UserOrgId: adminInfo.Org.Id,
  4238. Errcode: "自动出库接口报错",
  4239. GoodId: 0,
  4240. Status: 1,
  4241. Ctime: time.Now().Unix(),
  4242. Mtime: 0,
  4243. Count: 0,
  4244. StockCount: 0,
  4245. Creater: creator,
  4246. BatchNumberId: 0,
  4247. WarehouseOutId: 0,
  4248. }
  4249. service.CreateGoodErrcode(goodErrcode)
  4250. }
  4251. //出库数量相加
  4252. errss := service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, item.UserOrgId, item.GoodId)
  4253. if errss != nil {
  4254. goodErrcode := models.XtGoodErrcode{
  4255. UserOrgId: item.UserOrgId,
  4256. Errcode: "创建剩余库存字段报错",
  4257. GoodId: item.GoodId,
  4258. Status: 1,
  4259. Ctime: time.Now().Unix(),
  4260. Mtime: time.Now().Unix(),
  4261. Count: 0,
  4262. StockCount: 0,
  4263. Creater: item.Creater,
  4264. BatchNumberId: 0,
  4265. WarehouseOutId: 0,
  4266. }
  4267. service.CreateGoodErrcode(goodErrcode)
  4268. }
  4269. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4270. if len(list) == 0 {
  4271. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4272. return
  4273. }
  4274. for _, item := range list {
  4275. prepare := models.DialysisBeforePrepare{
  4276. UserOrgId: adminInfo.Org.Id,
  4277. PatientId: patient_id,
  4278. RecordDate: record_time,
  4279. GoodId: item.GoodId,
  4280. GoodTypeId: item.GoodTypeId,
  4281. Count: item.Count,
  4282. Creater: adminInfo.AdminUser.Id,
  4283. Status: 1,
  4284. Ctime: time.Now().Unix(),
  4285. StorehouseId: houseConfig.StorehouseOutInfo,
  4286. }
  4287. //清空准备表数据
  4288. errs := service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4289. if errs != nil {
  4290. goodErrcode := models.XtGoodErrcode{
  4291. UserOrgId: adminInfo.Org.Id,
  4292. Errcode: "自动出库清空准备表数据报错",
  4293. GoodId: 0,
  4294. Status: 1,
  4295. Ctime: time.Now().Unix(),
  4296. Mtime: 0,
  4297. Count: 0,
  4298. StockCount: 0,
  4299. Creater: creator,
  4300. BatchNumberId: 0,
  4301. WarehouseOutId: 0,
  4302. }
  4303. service.CreateGoodErrcode(goodErrcode)
  4304. }
  4305. errcodes := service.CreateDialysisBeforePrepareOne(&prepare)
  4306. if errcodes != nil {
  4307. goodErrcode := models.XtGoodErrcode{
  4308. UserOrgId: adminInfo.Org.Id,
  4309. Errcode: "自动出库创建准备表数据报错",
  4310. GoodId: 0,
  4311. Status: 1,
  4312. Ctime: time.Now().Unix(),
  4313. Mtime: 0,
  4314. Count: 0,
  4315. StockCount: 0,
  4316. Creater: creator,
  4317. BatchNumberId: 0,
  4318. WarehouseOutId: 0,
  4319. }
  4320. service.CreateGoodErrcode(goodErrcode)
  4321. }
  4322. //查询默认仓库
  4323. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4324. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4325. var total_count int64
  4326. for _, it := range stockList {
  4327. total_count += it.StockCount
  4328. }
  4329. //基础库插入数据
  4330. errcodes = service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4331. if errcodes != nil {
  4332. goodErrcode := models.XtGoodErrcode{
  4333. UserOrgId: adminInfo.Org.Id,
  4334. Errcode: "自动出库基础库插入数据报错",
  4335. GoodId: 0,
  4336. Status: 1,
  4337. Ctime: time.Now().Unix(),
  4338. Mtime: 0,
  4339. Count: 0,
  4340. StockCount: 0,
  4341. Creater: creator,
  4342. BatchNumberId: 0,
  4343. WarehouseOutId: 0,
  4344. }
  4345. service.CreateGoodErrcode(goodErrcode)
  4346. }
  4347. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4348. var flush_count int64
  4349. for _, it := range goodList {
  4350. flush_count += it.StockCount
  4351. }
  4352. errss := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4353. creater := c.GetMobileAdminUserInfo().AdminUser.Id
  4354. if errss != nil {
  4355. goodErrcode := models.XtGoodErrcode{
  4356. UserOrgId: item.OrgId,
  4357. Errcode: "自动出库剩余库存更新数据",
  4358. GoodId: item.GoodId,
  4359. Status: 1,
  4360. Ctime: time.Now().Unix(),
  4361. Mtime: 0,
  4362. Count: 0,
  4363. StockCount: 0,
  4364. Creater: creater,
  4365. BatchNumberId: 0,
  4366. WarehouseOutId: 0,
  4367. }
  4368. service.CreateGoodErrcode(goodErrcode)
  4369. }
  4370. }
  4371. }
  4372. }
  4373. c.ServeSuccessJSON(map[string]interface{}{
  4374. "msg": "提交成功",
  4375. "message": "2",
  4376. "good_name": "",
  4377. "specification_name": "",
  4378. })
  4379. return
  4380. } else {
  4381. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  4382. return
  4383. }
  4384. }
  4385. func (c *DialysisAPIController) EditConsumables() {
  4386. patient_id, _ := c.GetInt64("patient_id", 0)
  4387. record_date := c.GetString("record_time")
  4388. if patient_id <= 0 {
  4389. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4390. return
  4391. }
  4392. adminInfo := c.GetMobileAdminUserInfo()
  4393. timeLayout := "2006-01-02"
  4394. loc, _ := time.LoadLocation("Local")
  4395. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  4396. record_time := theRecordTime.Unix()
  4397. dataBody := make(map[string]interface{}, 0)
  4398. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  4399. if err != nil {
  4400. utils.ErrorLog(err.Error())
  4401. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4402. return
  4403. }
  4404. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4405. var beforePrepares []*models.DialysisBeforePrepareGoods
  4406. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  4407. var cancelbefor []*models.DialysisBeforePrepareGoods
  4408. var outbefor []*models.DialysisBeforePrepareGoods
  4409. //判断是否开启自动出库
  4410. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  4411. if record.IsOpen == 1 {
  4412. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  4413. goods, _ := dataBody["goods"].([]interface{})
  4414. if len(goods) > 0 {
  4415. for _, item := range goods {
  4416. items := item.(map[string]interface{})
  4417. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  4418. utils.ErrorLog("good_id")
  4419. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4420. return
  4421. }
  4422. good_id := int64(items["good_id"].(float64))
  4423. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  4424. utils.ErrorLog("good_type_id")
  4425. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4426. return
  4427. }
  4428. good_type_id := int64(items["good_type_id"].(float64))
  4429. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  4430. utils.ErrorLog("count")
  4431. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4432. return
  4433. }
  4434. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  4435. commdity_code := items["commdity_code"].(string)
  4436. fmt.Println(commdity_code)
  4437. prepareGoods := &models.DialysisBeforePrepareGoods{
  4438. GoodTypeId: good_type_id,
  4439. GoodId: good_id,
  4440. Count: count,
  4441. StorehouseId: houseConfig.StorehouseOutInfo,
  4442. }
  4443. beforePrepares = append(beforePrepares, prepareGoods)
  4444. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  4445. GoodTypeId: good_type_id,
  4446. GoodId: good_id,
  4447. Count: count,
  4448. StorehouseId: houseConfig.StorehouseOutInfo,
  4449. }
  4450. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  4451. }
  4452. for _, item := range beforePrepares {
  4453. //1.查看该患者该耗材型号最后一次出库数量
  4454. goodInfo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4455. //判断当前出库数量和最后一次出库数量的大小
  4456. //如果当前出库数量小于最后一次出库数量 正常出库后 需要退库操作
  4457. if item.Count < goodInfo.Count {
  4458. cancelbefor = append(cancelbefor, item)
  4459. }
  4460. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  4461. if item.Count > goodInfo.Count {
  4462. outbefor = append(outbefor, item)
  4463. }
  4464. //处理编辑耗材新增不了的问题
  4465. if goodInfo.Count == item.Count {
  4466. lastCount, _ := service.GetAutoGoodLastCount(item.GoodId, item.Count, record_time, patient_id)
  4467. service.UpdateLastAutoCount(lastCount.ID, item.Count)
  4468. }
  4469. }
  4470. fmt.Println("退库长度", len(cancelbefor))
  4471. fmt.Println("出库长度", len(outbefor))
  4472. //退库
  4473. for _, item := range cancelbefor {
  4474. warehouseOut, _ := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  4475. creater := adminInfo.AdminUser.Id
  4476. //退库
  4477. //err = ConsumablesDeliveryTotalSeven(adminInfo.Org.Id, patient_id, record_time, cancelbefor, adminInfo.AdminUser.Id, item.Count)
  4478. //查询该患者当天已经出库的耗材信息
  4479. warehouseOutInfos, _ := service.FindStockOutInfoByStockTwo(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, record_time, patient_id)
  4480. var delete_count int64 = 0
  4481. delete_count = warehouseOutInfos.Count - item.Count
  4482. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4483. // 在出库记录表里记录退库详情
  4484. warehouseOutInfo := &models.WarehouseOutInfo{
  4485. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4486. WarehouseOutId: warehouseOut.ID,
  4487. Status: 1,
  4488. Ctime: time.Now().Unix(),
  4489. OrgId: adminInfo.Org.Id,
  4490. Type: 1,
  4491. IsSys: 1,
  4492. SysRecordTime: record_time,
  4493. GoodTypeId: item.GoodTypeId,
  4494. GoodId: item.GoodId,
  4495. PatientId: patient_id,
  4496. ConsumableType: 2,
  4497. StorehouseId: houseConfig.StorehouseOutInfo,
  4498. IsCheck: 1,
  4499. }
  4500. warehouseOutInfo.Count = item.Count
  4501. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  4502. warehouseOutInfo.Price = stockInInfo.Price
  4503. warehouseOutInfo.Dealer = stockInInfo.Dealer
  4504. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  4505. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  4506. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  4507. warehouseOutInfo.Number = warehouseOutInfos.Number
  4508. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  4509. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  4510. //查找当天是否存在出库记录
  4511. _, errcod := service.GetWarehouseOutInfoIsExistOne(item.GoodId, patient_id, record_time, 0)
  4512. if errcod == gorm.ErrRecordNotFound {
  4513. service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4514. //插入详情明细表
  4515. stockFlow := models.VmStockFlow{
  4516. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4517. WarehouseOutId: warehouseOut.ID,
  4518. GoodId: item.GoodId,
  4519. Number: warehouseOutInfos.Number,
  4520. ProductDate: stockInInfo.ProductDate,
  4521. ExpireDate: stockInInfo.ExpiryDate,
  4522. Count: item.Count,
  4523. Price: stockInInfo.Price,
  4524. Status: 1,
  4525. Ctime: time.Now().Unix(),
  4526. UserOrgId: adminInfo.Org.Id,
  4527. Manufacturer: stockInInfo.Manufacturer,
  4528. Dealer: stockInInfo.Dealer,
  4529. LicenseNumber: stockInInfo.LicenseNumber,
  4530. IsEdit: 2,
  4531. Creator: creater,
  4532. SystemTime: record_time,
  4533. ConsumableType: 3,
  4534. WarehousingDetailId: 0,
  4535. IsSys: 1,
  4536. UpdateCreator: creater,
  4537. PatientId: patient_id,
  4538. StorehouseId: houseConfig.StorehouseOutInfo,
  4539. }
  4540. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, item.GoodId)
  4541. if errflow == gorm.ErrRecordNotFound {
  4542. //创建流水表
  4543. err := service.CreateStockFlowOne(stockFlow)
  4544. fmt.Println("err", err)
  4545. } else if errflow == nil {
  4546. //插入详情明细表
  4547. stockFlow := models.VmStockFlow{
  4548. ID: exsit.ID,
  4549. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4550. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4551. WarehouseOutId: warehouseOut.ID,
  4552. GoodId: item.GoodId,
  4553. Number: warehouseOutInfos.Number,
  4554. ProductDate: stockInInfo.ProductDate,
  4555. ExpireDate: stockInInfo.ExpiryDate,
  4556. Count: exsit.Count - delete_count,
  4557. Price: stockInInfo.Price,
  4558. Status: 1,
  4559. Ctime: time.Now().Unix(),
  4560. UserOrgId: adminInfo.Org.Id,
  4561. Manufacturer: stockInInfo.Manufacturer,
  4562. Dealer: stockInInfo.Dealer,
  4563. LicenseNumber: stockInInfo.LicenseNumber,
  4564. IsEdit: 2,
  4565. Creator: creater,
  4566. SystemTime: record_time,
  4567. ConsumableType: 3,
  4568. WarehousingDetailId: 0,
  4569. IsSys: 1,
  4570. UpdateCreator: creater,
  4571. PatientId: patient_id,
  4572. StorehouseId: houseConfig.StorehouseOutInfo,
  4573. }
  4574. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, item.GoodId)
  4575. }
  4576. } else if errcod == nil {
  4577. service.UpdatedWarehouseOutInfo(warehouseOutInfo, item.GoodId, patient_id, record_time, 0)
  4578. //插入详情明细表
  4579. stockFlow := models.VmStockFlow{
  4580. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4581. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4582. WarehouseOutId: warehouseOut.ID,
  4583. GoodId: item.GoodId,
  4584. Number: warehouseOutInfos.Number,
  4585. ProductDate: stockInInfo.ProductDate,
  4586. ExpireDate: stockInInfo.ExpiryDate,
  4587. Count: item.Count,
  4588. Price: stockInInfo.Price,
  4589. Status: 1,
  4590. Ctime: time.Now().Unix(),
  4591. UserOrgId: adminInfo.Org.Id,
  4592. Manufacturer: stockInInfo.Manufacturer,
  4593. Dealer: stockInInfo.Dealer,
  4594. LicenseNumber: stockInInfo.LicenseNumber,
  4595. IsEdit: 2,
  4596. Creator: creater,
  4597. SystemTime: record_time,
  4598. ConsumableType: 3,
  4599. WarehousingDetailId: 0,
  4600. IsSys: 1,
  4601. UpdateCreator: creater,
  4602. PatientId: patient_id,
  4603. ReturnCount: delete_count,
  4604. StorehouseId: houseConfig.StorehouseOutInfo,
  4605. }
  4606. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, item.GoodId)
  4607. if errflows == gorm.ErrRecordNotFound {
  4608. //创建流水表
  4609. service.CreateStockFlowOne(stockFlow)
  4610. } else if errflows == nil {
  4611. stockFlow := models.VmStockFlow{
  4612. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4613. ID: exsit.ID,
  4614. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4615. WarehouseOutId: warehouseOut.ID,
  4616. GoodId: item.GoodId,
  4617. Number: warehouseOutInfos.Number,
  4618. ProductDate: stockInInfo.ProductDate,
  4619. ExpireDate: stockInInfo.ExpiryDate,
  4620. Count: exsit.Count - delete_count,
  4621. Price: stockInInfo.Price,
  4622. Status: 1,
  4623. Ctime: time.Now().Unix(),
  4624. UserOrgId: adminInfo.Org.Id,
  4625. Manufacturer: stockInInfo.Manufacturer,
  4626. Dealer: stockInInfo.Dealer,
  4627. LicenseNumber: stockInInfo.LicenseNumber,
  4628. IsEdit: 2,
  4629. Creator: creater,
  4630. SystemTime: record_time,
  4631. ConsumableType: 3,
  4632. WarehousingDetailId: 0,
  4633. IsSys: 1,
  4634. UpdateCreator: creater,
  4635. PatientId: patient_id,
  4636. ReturnCount: delete_count,
  4637. StorehouseId: houseConfig.StorehouseOutInfo,
  4638. }
  4639. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, item.GoodId)
  4640. }
  4641. }
  4642. //更改自动出库的表格
  4643. details := models.BloodAutomaticReduceDetail{
  4644. WarehouseOutId: warehouseOutInfo.ID,
  4645. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  4646. PatientId: patient_id,
  4647. Ctime: time.Now().Unix(),
  4648. Mtime: time.Now().Unix(),
  4649. Status: 1,
  4650. RecordTime: record_time,
  4651. OrgId: adminInfo.Org.Id,
  4652. GoodId: item.GoodId,
  4653. GoodTypeId: item.GoodTypeId,
  4654. Count: item.Count,
  4655. StorehouseId: houseConfig.StorehouseOutInfo,
  4656. }
  4657. //查询当天耗材是否已经存在数据
  4658. _, errcode := service.GetAutoMaticReduceDetail(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4659. if errcode == gorm.ErrRecordNotFound {
  4660. service.CreateAutoReduceRecord(&details)
  4661. } else if errcode == nil {
  4662. service.DeleteAutoRedeceDetailTwo(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4663. service.CreateAutoReduceRecord(&details)
  4664. }
  4665. service.ModifyGoodAddInformation(item.GoodId, delete_count, adminInfo.Org.Id)
  4666. //增加出库库存数量
  4667. service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, adminInfo.Org.Id, item.GoodId)
  4668. errOne := service.UpDateWarehouStockFlowByStockDelete(warehouseOutInfos.WarehouseInfotId, record_time, item.GoodId, delete_count, patient_id)
  4669. fmt.Println("errOne", errOne)
  4670. // 删除出库完成后,要增加对应批次的库存数量
  4671. service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, item.GoodId)
  4672. //查询默认仓库
  4673. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4674. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4675. var total_count int64
  4676. for _, it := range stockList {
  4677. total_count += it.StockCount
  4678. }
  4679. //基础库插入数据
  4680. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4681. //更新剩余库存
  4682. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4683. var flush_count int64
  4684. for _, it := range goodList {
  4685. flush_count += it.StockCount
  4686. }
  4687. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4688. }
  4689. //出库
  4690. for _, item := range outbefor {
  4691. fmt.Println("出库ID", item.GoodId)
  4692. var last_total int64
  4693. //1.查看该患者该耗材型号最后一次出库数量
  4694. goodInfoOne, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4695. //计算当前出库和最后一次出库数据相差数据
  4696. last_total = item.Count - goodInfoOne.Count
  4697. //查询该批次剩余库存
  4698. lastInfo, _ := service.GetLastStockOut(goodInfoOne.WarehouseInfotId)
  4699. if lastInfo.StockCount == 0 {
  4700. //查询该耗材的总库存
  4701. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  4702. if wareinfo.StockCount == 0 {
  4703. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4704. c.ServeSuccessJSON(map[string]interface{}{
  4705. "message": "1",
  4706. "good_name": goodObj.GoodName,
  4707. "specification_name": goodObj.SpecificationName,
  4708. })
  4709. return
  4710. }
  4711. }
  4712. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  4713. //查询该耗材的总库存
  4714. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  4715. // 如果库存差大于剩余库存则提示库存不足
  4716. if last_total > wareinfo.StockCount {
  4717. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4718. c.ServeSuccessJSON(map[string]interface{}{
  4719. "message": "1",
  4720. "good_name": goodObj.GoodName,
  4721. "specification_name": goodObj.SpecificationName,
  4722. })
  4723. return
  4724. } else {
  4725. fmt.Println("出库2o2o2o2o2oo2o2o2o2o2o2o", item.GoodId)
  4726. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  4727. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4728. if err == gorm.ErrRecordNotFound {
  4729. //没有记录,则创建出库单
  4730. timeStr := time.Now().Format("2006-01-02")
  4731. timeArr := strings.Split(timeStr, "-")
  4732. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  4733. total = total + 1
  4734. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4735. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4736. number = number + total
  4737. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4738. warehouseOut := models.WarehouseOut{
  4739. WarehouseOutOrderNumber: warehousing_out_order,
  4740. OperationTime: time.Now().Unix(),
  4741. OrgId: adminInfo.Org.Id,
  4742. Creater: adminInfo.AdminUser.Id,
  4743. Ctime: time.Now().Unix(),
  4744. Status: 1,
  4745. WarehouseOutTime: record_time,
  4746. Dealer: 0,
  4747. Manufacturer: 0,
  4748. Type: 1,
  4749. IsSys: 1,
  4750. StorehouseId: houseConfig.StorehouseOutInfo,
  4751. IsCheck: 1,
  4752. }
  4753. service.AddSigleWarehouseOut(&warehouseOut)
  4754. }
  4755. //出库
  4756. //err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, outbefor, newBeforePrepares, adminInfo.AdminUser.Id)
  4757. //houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4758. //1.查看该患者该耗材型号最后一次出库数量
  4759. goodInfoTwo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  4760. fmt.Println("count2323323222323wi", item.Count)
  4761. prepare := models.DialysisBeforePrepare{
  4762. UserOrgId: adminInfo.Org.Id,
  4763. PatientId: patient_id,
  4764. RecordDate: record_time,
  4765. GoodId: item.GoodId,
  4766. GoodTypeId: item.GoodTypeId,
  4767. Count: item.Count - goodInfoTwo.Count,
  4768. Ctime: time.Now().Unix(),
  4769. Mtime: 0,
  4770. Creater: adminInfo.AdminUser.Id,
  4771. Modifier: adminInfo.AdminUser.Id,
  4772. Status: 1,
  4773. CommdityCode: "",
  4774. NewCount: 0,
  4775. ProjectId: 0,
  4776. StorehouseId: houseConfig.StorehouseOutInfo,
  4777. }
  4778. fmt.Println("prepare", prepare.Count)
  4779. fmt.Println("count", item.Count)
  4780. service.ConsumablesGoodDelivery(adminInfo.Org.Id, patient_id, record_time, &prepare, &out, item.Count)
  4781. //增加出库数量
  4782. service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, prepare.Count, adminInfo.Org.Id, item.GoodId)
  4783. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4784. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4785. var total_count int64
  4786. for _, it := range stockList {
  4787. total_count += it.StockCount
  4788. }
  4789. //基础库插入数据
  4790. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4791. //剩余库存
  4792. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  4793. var flush_count int64
  4794. for _, it := range goodList {
  4795. flush_count += it.StockCount
  4796. }
  4797. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  4798. }
  4799. }
  4800. //查询今日出库数据
  4801. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4802. for _, it := range list {
  4803. prepare := models.DialysisBeforePrepare{
  4804. UserOrgId: it.OrgId,
  4805. PatientId: patient_id,
  4806. RecordDate: it.RecordTime,
  4807. GoodId: it.GoodId,
  4808. GoodTypeId: it.GoodTypeId,
  4809. Count: it.Count,
  4810. Ctime: time.Now().Unix(),
  4811. Creater: adminInfo.AdminUser.Id,
  4812. Status: 1,
  4813. StorehouseId: houseConfig.StorehouseOutInfo,
  4814. }
  4815. //删除准备表数据
  4816. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, it.GoodId, it.GoodTypeId)
  4817. service.CreateDialysisBeforePrepareOne(&prepare)
  4818. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4819. stockList, _ := service.GetStockCountByGoodId(it.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4820. var total_count int64
  4821. for _, it := range stockList {
  4822. total_count += it.StockCount
  4823. }
  4824. //基础库插入数据
  4825. service.UpdateGoodInfoReduceSumCount(it.GoodId, total_count, adminInfo.Org.Id)
  4826. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, it.GoodId)
  4827. var flush_count int64
  4828. for _, it := range goodList {
  4829. flush_count += it.StockCount
  4830. }
  4831. service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, it.GoodId, flush_count)
  4832. //if err != nil {
  4833. // goodObj, _ := service.GetGoodInformationByGoodId(it.GoodId)
  4834. // c.ServeSuccessJSON(map[string]interface{}{
  4835. // "message": "2",
  4836. // "good_name": goodObj.GoodName,
  4837. // "specification_name": goodObj.SpecificationName,
  4838. // })
  4839. // return
  4840. //}
  4841. }
  4842. }
  4843. }
  4844. //更新自动出库的地方
  4845. var errs error
  4846. if errs == nil {
  4847. c.ServeSuccessJSON(map[string]interface{}{
  4848. "msg": "修改成功",
  4849. "message": "2",
  4850. "good_name": "",
  4851. "specification_name": "",
  4852. })
  4853. return
  4854. } else {
  4855. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4856. return
  4857. }
  4858. }
  4859. }
  4860. func (c *DialysisAPIController) GetDialysisGoods() {
  4861. schedualDate := c.GetString("schedule_date")
  4862. schedule_type, _ := c.GetInt64("schedule_type")
  4863. partition_id, _ := c.GetInt64("partition_id")
  4864. page, _ := c.GetInt("page")
  4865. patient_id, _ := c.GetInt64("patient_id")
  4866. schedualEndDate := int64(0)
  4867. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  4868. if parseDateErr != nil && len(schedualDate) != 0 {
  4869. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4870. return
  4871. }
  4872. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  4873. if parseDateErr != nil && len(schedualDate) != 0 {
  4874. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4875. return
  4876. }
  4877. schedualEndDate = endDate.Unix()
  4878. adminUser := c.GetMobileAdminUserInfo()
  4879. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  4880. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  4881. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  4882. _, config := service.FindXTHisRecordByOrgId(adminUser.Org.Id)
  4883. //获取当天该病人的透析处方
  4884. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  4885. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  4886. if err == gorm.ErrRecordNotFound {
  4887. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  4888. warehouseOutList, _ := service.GetAllWarehouseOutSumList(patient_id, adminUser.Org.Id, date.Unix())
  4889. if patient_id != 0 {
  4890. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  4891. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  4892. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  4893. //获取患者总的出库数据
  4894. item.LastAutomaticReduceDetail = goodUser
  4895. item.LastDialysisBeforePrepare = lastGoodUserDetial
  4896. item.Project = project
  4897. }
  4898. }
  4899. c.ServeSuccessJSON(map[string]interface{}{
  4900. "dialysis_goods": dialysisGoods,
  4901. "good_type": goodTypes,
  4902. "total": total,
  4903. "prescribe": prescribe,
  4904. "good_info": good_info,
  4905. "warehouseOutList": warehouseOutList,
  4906. "config": config,
  4907. })
  4908. return
  4909. } else if err == nil {
  4910. //获取当天排班的每个患者的库存使用情况
  4911. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  4912. //获取患者总的出库数据
  4913. warehouseOutList, _ := service.GetAllWarehouseOutSumList(patient_id, adminUser.Org.Id, date.Unix())
  4914. if patient_id != 0 {
  4915. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  4916. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  4917. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  4918. item.Project = project
  4919. item.LastAutomaticReduceDetail = goodUser
  4920. item.LastDialysisBeforePrepare = lastGoodUserDetial
  4921. }
  4922. }
  4923. if err == nil {
  4924. c.ServeSuccessJSON(map[string]interface{}{
  4925. "dialysis_goods": dialysisGoods,
  4926. "good_type": goodTypes,
  4927. "total": total,
  4928. "prescribe": prescribe,
  4929. "good_info": good_info,
  4930. "project": project,
  4931. "warehouseOutList": warehouseOutList,
  4932. "config": config,
  4933. })
  4934. return
  4935. } else {
  4936. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4937. return
  4938. }
  4939. } else if err != nil {
  4940. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4941. return
  4942. }
  4943. }
  4944. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  4945. start_time := c.GetString("start_time")
  4946. end_time := c.GetString("end_time")
  4947. timeLayout := "2006-01-02"
  4948. loc, _ := time.LoadLocation("Local")
  4949. var theStartTime int64
  4950. if len(start_time) > 0 {
  4951. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  4952. if err != nil {
  4953. utils.ErrorLog(err.Error())
  4954. }
  4955. theStartTime = theTime.Unix()
  4956. }
  4957. var theEndtTime int64
  4958. if len(end_time) > 0 {
  4959. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  4960. if err != nil {
  4961. utils.ErrorLog(err.Error())
  4962. }
  4963. theEndtTime = theTime.Unix()
  4964. }
  4965. adminUser := c.GetMobileAdminUserInfo()
  4966. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  4967. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  4968. if err == nil {
  4969. c.ServeSuccessJSON(map[string]interface{}{
  4970. "stock_out": outInfo,
  4971. "stockCount": stockCount,
  4972. })
  4973. return
  4974. } else {
  4975. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4976. return
  4977. }
  4978. }
  4979. func (c *DialysisAPIController) GetStockInGoodInfo() {
  4980. patient_id, _ := c.GetInt64("patient_id", 0)
  4981. record_time := c.GetString("record_time")
  4982. adminUser := c.GetMobileAdminUserInfo()
  4983. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  4984. if parseDateErr != nil && len(record_time) != 0 {
  4985. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4986. return
  4987. }
  4988. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  4989. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  4990. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  4991. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  4992. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  4993. //获取今日患者的透析处方参数
  4994. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  4995. outInfo, _ := service.GetGoodWarehouseOutInfo(adminUser.Org.Id, patient_id, date.Unix())
  4996. _, configs := service.FindXTHisRecordByOrgId(adminUser.Org.Id)
  4997. c.ServeSuccessJSON(map[string]interface{}{
  4998. "good_type": goodTypes,
  4999. "good_user": goodUser,
  5000. "good_info": good_info,
  5001. "last_good_user": lastGoodUserDetial,
  5002. "project": project,
  5003. "prescription": prescribe,
  5004. "outInfo": outInfo,
  5005. "configs": configs,
  5006. })
  5007. return
  5008. }
  5009. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  5010. patient_id, _ := c.GetInt64("patient_id", 0)
  5011. record_date := c.GetString("record_time")
  5012. timeLayout := "2006-01-02"
  5013. loc, _ := time.LoadLocation("Local")
  5014. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  5015. record_time := theRecordTime.Unix()
  5016. adminInfo := c.GetMobileAdminUserInfo()
  5017. dataBody := make(map[string]interface{}, 0)
  5018. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  5019. if err != nil {
  5020. utils.ErrorLog(err.Error())
  5021. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5022. return
  5023. }
  5024. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  5025. var beforePrepares []*models.DialysisBeforePrepareGoods
  5026. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  5027. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  5028. goods, _ := dataBody["goods"].([]interface{})
  5029. if len(goods) > 0 {
  5030. for _, item := range goods {
  5031. items := item.(map[string]interface{})
  5032. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  5033. utils.ErrorLog("good_id")
  5034. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5035. return
  5036. }
  5037. good_id := int64(items["good_id"].(float64))
  5038. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  5039. utils.ErrorLog("good_type_id")
  5040. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5041. return
  5042. }
  5043. good_type_id := int64(items["good_type_id"].(float64))
  5044. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  5045. utils.ErrorLog("count")
  5046. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5047. return
  5048. }
  5049. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  5050. if items["project_id"] == nil || reflect.TypeOf(items["project_id"]).String() != "float64" {
  5051. utils.ErrorLog("project_id")
  5052. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5053. return
  5054. }
  5055. project_id := int64(items["project_id"].(float64))
  5056. prepare := &models.DialysisBeforePrepareGoods{
  5057. GoodId: good_id,
  5058. GoodTypeId: good_type_id,
  5059. Count: count,
  5060. ProjectId: project_id,
  5061. StorehouseId: houseConfig.StorehouseOutInfo,
  5062. }
  5063. beforePrepares = append(beforePrepares, prepare)
  5064. newPrepare := &models.NewDialysisBeforePrepareGoods{
  5065. GoodId: good_id,
  5066. GoodTypeId: good_type_id,
  5067. Count: count,
  5068. ProjectId: project_id,
  5069. StorehouseId: houseConfig.StorehouseOutInfo,
  5070. }
  5071. newBeforePrepares = append(newBeforePrepares, newPrepare)
  5072. }
  5073. }
  5074. }
  5075. //查询是否有库存
  5076. for _, item := range beforePrepares {
  5077. storeConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  5078. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, storeConfig.StorehouseOutInfo)
  5079. if item.Count > warehouse.Count {
  5080. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  5081. c.ServeSuccessJSON(map[string]interface{}{
  5082. "message": "1",
  5083. "good_name": goodObj.GoodName,
  5084. "specification_name": goodObj.SpecificationName,
  5085. })
  5086. return
  5087. }
  5088. }
  5089. //出库逻辑
  5090. err = service.ConsumablesDeliveryTotal(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  5091. if err != nil {
  5092. utils.ErrorLog(err.Error())
  5093. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5094. return
  5095. }
  5096. //查询当天出库的数据
  5097. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  5098. for _, item := range list {
  5099. prepare := models.DialysisBeforePrepare{
  5100. UserOrgId: item.OrgId,
  5101. PatientId: item.PatientId,
  5102. RecordDate: item.RecordTime,
  5103. GoodId: item.GoodId,
  5104. GoodTypeId: item.GoodTypeId,
  5105. Count: item.Count,
  5106. Creater: adminInfo.AdminUser.Id,
  5107. Status: 1,
  5108. Ctime: time.Now().Unix(),
  5109. ProjectId: item.ProjectId,
  5110. StorehouseId: houseConfig.StorehouseOutInfo,
  5111. }
  5112. //清空准备表的数据
  5113. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  5114. //插入准备表数据
  5115. service.CreateDialysisBeforePrepareOne(&prepare)
  5116. //查询默认仓库
  5117. //查询默认仓库
  5118. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  5119. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  5120. var total_count int64
  5121. for _, it := range stockList {
  5122. total_count += it.StockCount
  5123. }
  5124. //基础库插入数据
  5125. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  5126. ////更新剩余库存
  5127. goodList, _ := service.GetSumGoodList(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId)
  5128. var flush_count int64
  5129. for _, it := range goodList {
  5130. flush_count += it.StockCount
  5131. }
  5132. errs := service.UpdateSumGood(adminInfo.Org.Id, storeHouseConfig.StorehouseOutInfo, item.GoodId, flush_count)
  5133. if errs != nil {
  5134. goodErrcode := models.XtGoodErrcode{
  5135. UserOrgId: item.OrgId,
  5136. Errcode: "手动出库更新剩余出库失败",
  5137. GoodId: item.GoodId,
  5138. Status: 1,
  5139. Ctime: time.Now().Unix(),
  5140. Mtime: 0,
  5141. Count: 0,
  5142. StockCount: 0,
  5143. Creater: adminInfo.AdminUser.Id,
  5144. BatchNumberId: 0,
  5145. WarehouseOutId: 0,
  5146. }
  5147. service.CreateGoodErrcode(goodErrcode)
  5148. }
  5149. }
  5150. //更新自动出库的地方
  5151. var errs error
  5152. if errs == nil {
  5153. c.ServeSuccessJSON(map[string]interface{}{
  5154. "msg": "修改成功",
  5155. "message": "2",
  5156. "good_name": "",
  5157. "specification_name": "",
  5158. })
  5159. return
  5160. } else {
  5161. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5162. return
  5163. }
  5164. }
  5165. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  5166. newArr = make([]*models.DialysisBeforePrepare, 0)
  5167. for i := 0; i < len(arr); i++ {
  5168. repeat := false
  5169. for j := i + 1; j < len(arr); j++ {
  5170. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  5171. repeat = true
  5172. break
  5173. }
  5174. }
  5175. if !repeat {
  5176. newArr = append(newArr, arr[i])
  5177. }
  5178. }
  5179. return
  5180. }
  5181. func (c *DialysisAPIController) GetAllDrug() {
  5182. patient_id, _ := c.GetInt64("patient_id", 0)
  5183. adminInfo := c.GetMobileAdminUserInfo()
  5184. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  5185. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  5186. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  5187. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  5188. c.ServeSuccessJSON(map[string]interface{}{
  5189. "base_drug_config": drugStockConfig,
  5190. "private_drug_config": privateDrugConfig,
  5191. "base_drug_list": drugList,
  5192. "private_drug_list": privateDrugList,
  5193. })
  5194. }
  5195. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  5196. newArr = make([]*models.DialysisBeforePrepare, 0)
  5197. for i := 0; i < len(arr); i++ {
  5198. repeat := false
  5199. for j := i + 1; j < len(arr); j++ {
  5200. if arr[i].GoodId == arr[j].GoodId {
  5201. repeat = true
  5202. break
  5203. }
  5204. }
  5205. if !repeat {
  5206. newArr = append(newArr, arr[i])
  5207. }
  5208. }
  5209. return
  5210. }
  5211. func (c *DialysisAPIController) GetDepartment() {
  5212. adminInfo := c.GetMobileAdminUserInfo()
  5213. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  5214. if err == nil {
  5215. c.ServeSuccessJSON(map[string]interface{}{
  5216. "departments": departments,
  5217. })
  5218. } else {
  5219. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  5220. return
  5221. }
  5222. }
  5223. func (c *DialysisAPIController) GetMobilePrintStockGood() {
  5224. types, _ := c.GetInt("type", 0)
  5225. start_time := c.GetString("start_time")
  5226. end_time := c.GetString("end_time")
  5227. orgId := c.GetMobileAdminUserInfo().Org.Id
  5228. timeLayout := "2006-01-02"
  5229. loc, _ := time.LoadLocation("Local")
  5230. var startTime int64
  5231. if len(start_time) > 0 {
  5232. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  5233. if err != nil {
  5234. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5235. return
  5236. }
  5237. startTime = theTime.Unix()
  5238. }
  5239. var endTime int64
  5240. if len(end_time) > 0 {
  5241. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  5242. if err != nil {
  5243. utils.ErrorLog(err.Error())
  5244. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  5245. return
  5246. }
  5247. endTime = theTime.Unix()
  5248. }
  5249. list, err := service.FindPrintStockGoodInfoByType(types, startTime, endTime, orgId)
  5250. stockTotal, err := service.GetOutStockTotalCountTwo(startTime, endTime, orgId)
  5251. if err != nil {
  5252. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  5253. } else {
  5254. c.ServeSuccessJSON(map[string]interface{}{
  5255. "list": list,
  5256. "type": types,
  5257. "stockTotal": stockTotal,
  5258. })
  5259. }
  5260. }
  5261. func (c *DialysisAPIController) BatchDeleteMonitor() {
  5262. ids := c.GetString("ids")
  5263. //patient_id, _ := c.GetInt64("patient_id")
  5264. //monitoring_date, _ := c.GetInt64("monitoring_date")
  5265. idArray := strings.Split(ids, ",")
  5266. err := service.BatchDeleteMonitor(idArray)
  5267. fmt.Print("err", err)
  5268. //orgid := c.GetMobileAdminUserInfo().Org.Id
  5269. //redis := service.RedisClient()
  5270. //key := strconv.FormatInt(orgid, 10) + ":" + ":monitor_record_list_all"
  5271. //redis.Set(key, "", time.Second)
  5272. //keyOne := strconv.FormatInt(orgid, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(monitoring_date, 10) + ":monitor_records"
  5273. //redis.Set(keyOne, "", time.Second)
  5274. //fmt.Println("keyo呢32332322332332232332",keyOne)
  5275. //redis.Close()
  5276. c.ServeSuccessJSON(map[string]interface{}{
  5277. "msg": "批量删除成功",
  5278. })
  5279. return
  5280. }
  5281. func (c *DialysisAPIController) GetPatientDialysisRecordList() {
  5282. id, _ := c.GetInt64("id")
  5283. timeLayout := "2006-01-02"
  5284. loc, _ := time.LoadLocation("Local")
  5285. start_time := time.Now().Format("2006-01-02")
  5286. startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  5287. nowTime := time.Now()
  5288. endTime := nowTime.AddDate(-2, 0, 0)
  5289. endTimes := endTime.Format("2006-01-02")
  5290. endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", endTimes+" 00:00:00", loc)
  5291. list, _ := service.GetPatientDialysisRecordList(id, endtime.Unix(), startime.Unix())
  5292. fmt.Println("endtime232332322332322323232332", endTime.Unix())
  5293. c.ServeSuccessJSON(map[string]interface{}{
  5294. "list": list,
  5295. })
  5296. return
  5297. }
  5298. func (c *DialysisAPIController) BathDeleteAdviceList() {
  5299. dataBody := make(map[string]interface{}, 0)
  5300. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  5301. ids := c.GetString("ids")
  5302. idArray := strings.Split(ids, ",")
  5303. origin, _ := c.GetInt64("origin")
  5304. if origin == 1 {
  5305. err = service.BatchDeleteAdvice(idArray)
  5306. fmt.Print("err", err)
  5307. c.ServeSuccessJSON(map[string]interface{}{
  5308. "msg": "批量删除成功",
  5309. })
  5310. return
  5311. }
  5312. if origin == 2 {
  5313. service.BatchDeleteHisAdvice(idArray)
  5314. }
  5315. }
  5316. func (c *DialysisAPIController) UpdateAutoReduceDetail() {
  5317. good_id, _ := c.GetInt64("good_id")
  5318. count, _ := c.GetInt64("count")
  5319. record_time, _ := c.GetInt64("record_time")
  5320. patient_id, _ := c.GetInt64("patient_id")
  5321. detail, _ := service.UpdateAutoReduceDetail(good_id, count, record_time, patient_id)
  5322. c.ServeSuccessJSON(map[string]interface{}{
  5323. "detail": detail,
  5324. })
  5325. return
  5326. }
  5327. func (c *DialysisAPIController) DeleteAutoReduceDetail() {
  5328. good_id, _ := c.GetInt64("good_id")
  5329. record_time, _ := c.GetInt64("record_time")
  5330. patient_id, _ := c.GetInt64("patient_id")
  5331. service.DeleteDialysisBeforOne(good_id, record_time, patient_id)
  5332. err := service.DeleteAutoReduceDetail(good_id, record_time, patient_id)
  5333. fmt.Print("err", err)
  5334. c.ServeSuccessJSON(map[string]interface{}{
  5335. "msg": "批量删除成功",
  5336. })
  5337. return
  5338. }
  5339. func (c *DialysisAPIController) BatchAdviceCheck() {
  5340. ids := c.GetString("ids")
  5341. idArray := strings.Split(ids, ",")
  5342. creator, _ := c.GetInt64("creator")
  5343. origin, _ := c.GetInt64("origin")
  5344. if origin == 1 {
  5345. err := service.BatchAdviceCheck(idArray, creator)
  5346. fmt.Println(err)
  5347. list, _ := service.GetAdviceExecutionById(idArray)
  5348. c.ServeSuccessJSON(map[string]interface{}{
  5349. "list": list,
  5350. })
  5351. return
  5352. }
  5353. if origin == 2 {
  5354. service.BatchHisAdviceCheck(idArray, creator)
  5355. list, _ := service.GetHisAdviceExecutionById(idArray)
  5356. c.ServeSuccessJSON(map[string]interface{}{
  5357. "list": list,
  5358. })
  5359. return
  5360. }
  5361. }
  5362. func (c *DialysisAPIController) BatchAdviceExecution() {
  5363. ids := c.GetString("ids")
  5364. idArray := strings.Split(ids, ",")
  5365. executionTime := c.GetString("execution_time")
  5366. creator, _ := c.GetInt64("creator")
  5367. timeLayout := "2006-01-02 15:04:05"
  5368. loc, _ := time.LoadLocation("Local")
  5369. theTime, _ := time.ParseInLocation(timeLayout, executionTime, loc)
  5370. orgin, _ := c.GetInt64("origin")
  5371. if orgin == 1 {
  5372. err := service.BatchAdviceExecution(idArray, creator, theTime.Unix())
  5373. list, _ := service.GetAdviceExecutionById(idArray)
  5374. fmt.Println(err)
  5375. c.ServeSuccessJSON(map[string]interface{}{
  5376. "list": list,
  5377. })
  5378. return
  5379. }
  5380. if orgin == 2 {
  5381. err := service.BatchHisAdviceExecution(idArray, creator, theTime.Unix())
  5382. list, _ := service.GetHisAdviceExecutionById(idArray)
  5383. fmt.Println(err)
  5384. c.ServeSuccessJSON(map[string]interface{}{
  5385. "list": list,
  5386. })
  5387. return
  5388. }
  5389. }
  5390. func (c *DialysisAPIController) UpdateStockGoods() {
  5391. good_id, _ := c.GetInt64("good_id")
  5392. record_time, _ := c.GetInt64("record_time")
  5393. patient_id, _ := c.GetInt64("patient_id")
  5394. count, _ := c.GetInt64("count")
  5395. err := service.UpdateStockGoods(good_id, record_time, patient_id, count)
  5396. fmt.Print("err", err)
  5397. c.ServeSuccessJSON(map[string]interface{}{
  5398. "msg": "更新成功",
  5399. })
  5400. return
  5401. }
  5402. //当前数据比上一次出库数据少
  5403. func ConsumablesDeliveryTotalSeven(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, creater int64, count int64) (err error) {
  5404. //查询该患者当天已经出库的耗材信息
  5405. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  5406. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  5407. for i := len(goods_yc) - 1; i >= 0; i-- {
  5408. goods_yc_temp := goods_yc[i]
  5409. for j := len(goods) - 1; j >= 0; j-- {
  5410. goods_temp := goods[j]
  5411. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  5412. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  5413. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  5414. if goods_yc_temp.Count == goods_temp.Count {
  5415. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5416. goods = append(goods[:j], goods[j+1:]...)
  5417. break
  5418. }
  5419. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  5420. if goods_yc_temp.Count > goods_temp.Count {
  5421. temp_count := goods_yc_temp.Count - goods_temp.Count
  5422. goods_yc[i].Count = temp_count
  5423. goods = append(goods[:j], goods[j+1:]...)
  5424. break
  5425. }
  5426. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  5427. if goods_yc_temp.Count < goods_temp.Count {
  5428. temp_count := goods_temp.Count - goods_yc_temp.Count
  5429. goods[j].Count = temp_count
  5430. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5431. break
  5432. }
  5433. }
  5434. }
  5435. }
  5436. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  5437. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  5438. //退库
  5439. if len(goods_yc) > 0 {
  5440. for _, good_yc := range goods_yc {
  5441. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  5442. ConsumablesDeliveryDeleteNew(orgID, record_time, good_yc, &out, patient_id, creater, count)
  5443. }
  5444. }
  5445. return nil
  5446. }
  5447. //耗材出库删除
  5448. func ConsumablesDeliveryDeleteFour(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  5449. // 先根据相关信息查询当天该耗材的出库信息
  5450. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  5451. if err != nil {
  5452. return err
  5453. }
  5454. var delete_count int64 = 0
  5455. delete_count = warehouseOutInfos.Count - count
  5456. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5457. // 在出库记录表里记录退库详情
  5458. warehouseOutInfo := &models.WarehouseOutInfo{
  5459. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5460. WarehouseOutId: warehouseOut.ID,
  5461. Status: 1,
  5462. Ctime: time.Now().Unix(),
  5463. OrgId: orgID,
  5464. Type: 1,
  5465. IsSys: 1,
  5466. SysRecordTime: record_time,
  5467. GoodTypeId: good_yc.GoodTypeId,
  5468. GoodId: good_yc.GoodId,
  5469. PatientId: good_yc.PatientId,
  5470. ConsumableType: 2,
  5471. StorehouseId: houseConfig.StorehouseOutInfo,
  5472. IsCheck: 1,
  5473. }
  5474. warehouseOutInfo.Count = count
  5475. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5476. warehouseOutInfo.Price = stockInInfo.Price
  5477. warehouseOutInfo.Dealer = stockInInfo.Dealer
  5478. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  5479. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  5480. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  5481. warehouseOutInfo.Number = warehouseOutInfos.Number
  5482. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  5483. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  5484. //查找当天是否存在出库记录
  5485. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5486. if errcod == gorm.ErrRecordNotFound {
  5487. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5488. //插入详情明细表
  5489. stockFlow := models.VmStockFlow{
  5490. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5491. WarehouseOutId: warehouseOut.ID,
  5492. GoodId: good_yc.GoodId,
  5493. Number: warehouseOutInfos.Number,
  5494. ProductDate: stockInInfo.ProductDate,
  5495. ExpireDate: stockInInfo.ExpiryDate,
  5496. Count: count,
  5497. Price: stockInInfo.Price,
  5498. Status: 1,
  5499. Ctime: time.Now().Unix(),
  5500. UserOrgId: good_yc.OrgId,
  5501. Manufacturer: stockInInfo.Manufacturer,
  5502. Dealer: stockInInfo.Dealer,
  5503. LicenseNumber: stockInInfo.LicenseNumber,
  5504. IsEdit: 2,
  5505. Creator: creater,
  5506. SystemTime: record_time,
  5507. ConsumableType: 3,
  5508. WarehousingDetailId: 0,
  5509. IsSys: 1,
  5510. UpdateCreator: creater,
  5511. PatientId: patient_id,
  5512. StorehouseId: houseConfig.StorehouseOutInfo,
  5513. }
  5514. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  5515. if errflow == gorm.ErrRecordNotFound {
  5516. //创建流水表
  5517. err := service.CreateStockFlowOne(stockFlow)
  5518. fmt.Println("err", err)
  5519. } else if errflow == nil {
  5520. //插入详情明细表
  5521. stockFlow := models.VmStockFlow{
  5522. ID: exsit.ID,
  5523. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5524. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5525. WarehouseOutId: warehouseOut.ID,
  5526. GoodId: good_yc.GoodId,
  5527. Number: warehouseOutInfos.Number,
  5528. ProductDate: stockInInfo.ProductDate,
  5529. ExpireDate: stockInInfo.ExpiryDate,
  5530. Count: exsit.Count - delete_count,
  5531. Price: stockInInfo.Price,
  5532. Status: 1,
  5533. Ctime: time.Now().Unix(),
  5534. UserOrgId: good_yc.OrgId,
  5535. Manufacturer: stockInInfo.Manufacturer,
  5536. Dealer: stockInInfo.Dealer,
  5537. LicenseNumber: stockInInfo.LicenseNumber,
  5538. IsEdit: 2,
  5539. Creator: creater,
  5540. SystemTime: record_time,
  5541. ConsumableType: 3,
  5542. WarehousingDetailId: 0,
  5543. IsSys: 1,
  5544. UpdateCreator: creater,
  5545. PatientId: patient_id,
  5546. StorehouseId: houseConfig.StorehouseOutInfo,
  5547. }
  5548. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  5549. }
  5550. if errOne != nil {
  5551. return errOne
  5552. }
  5553. } else if errcod == nil {
  5554. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5555. //插入详情明细表
  5556. stockFlow := models.VmStockFlow{
  5557. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5558. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5559. WarehouseOutId: warehouseOut.ID,
  5560. GoodId: good_yc.GoodId,
  5561. Number: warehouseOutInfos.Number,
  5562. ProductDate: stockInInfo.ProductDate,
  5563. ExpireDate: stockInInfo.ExpiryDate,
  5564. Count: count,
  5565. Price: stockInInfo.Price,
  5566. Status: 1,
  5567. Ctime: time.Now().Unix(),
  5568. UserOrgId: good_yc.OrgId,
  5569. Manufacturer: stockInInfo.Manufacturer,
  5570. Dealer: stockInInfo.Dealer,
  5571. LicenseNumber: stockInInfo.LicenseNumber,
  5572. IsEdit: 2,
  5573. Creator: creater,
  5574. SystemTime: record_time,
  5575. ConsumableType: 3,
  5576. WarehousingDetailId: 0,
  5577. IsSys: 1,
  5578. UpdateCreator: creater,
  5579. PatientId: patient_id,
  5580. ReturnCount: delete_count,
  5581. StorehouseId: houseConfig.StorehouseOutInfo,
  5582. }
  5583. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  5584. if errflows == gorm.ErrRecordNotFound {
  5585. //创建流水表
  5586. service.CreateStockFlowOne(stockFlow)
  5587. } else if errflows == nil {
  5588. stockFlow := models.VmStockFlow{
  5589. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  5590. ID: exsit.ID,
  5591. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5592. WarehouseOutId: warehouseOut.ID,
  5593. GoodId: good_yc.GoodId,
  5594. Number: warehouseOutInfos.Number,
  5595. ProductDate: stockInInfo.ProductDate,
  5596. ExpireDate: stockInInfo.ExpiryDate,
  5597. Count: exsit.Count - delete_count,
  5598. Price: stockInInfo.Price,
  5599. Status: 1,
  5600. Ctime: time.Now().Unix(),
  5601. UserOrgId: good_yc.OrgId,
  5602. Manufacturer: stockInInfo.Manufacturer,
  5603. Dealer: stockInInfo.Dealer,
  5604. LicenseNumber: stockInInfo.LicenseNumber,
  5605. IsEdit: 2,
  5606. Creator: creater,
  5607. SystemTime: record_time,
  5608. ConsumableType: 3,
  5609. WarehousingDetailId: 0,
  5610. IsSys: 1,
  5611. UpdateCreator: creater,
  5612. PatientId: patient_id,
  5613. ReturnCount: delete_count,
  5614. StorehouseId: houseConfig.StorehouseOutInfo,
  5615. }
  5616. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  5617. }
  5618. }
  5619. //更改自动出库的表格
  5620. details := models.BloodAutomaticReduceDetail{
  5621. WarehouseOutId: warehouseOutInfo.ID,
  5622. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  5623. PatientId: patient_id,
  5624. Ctime: time.Now().Unix(),
  5625. Mtime: time.Now().Unix(),
  5626. Status: 1,
  5627. RecordTime: record_time,
  5628. OrgId: orgID,
  5629. GoodId: good_yc.GoodId,
  5630. GoodTypeId: good_yc.GoodTypeId,
  5631. Count: count,
  5632. StorehouseId: houseConfig.StorehouseOutInfo,
  5633. }
  5634. //查询当天耗材是否已经存在数据
  5635. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5636. if errcode == gorm.ErrRecordNotFound {
  5637. errTwo := service.CreateAutoReduceRecord(&details)
  5638. if errTwo != nil {
  5639. return errTwo
  5640. }
  5641. } else if errcode == nil {
  5642. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  5643. service.CreateAutoReduceRecord(&details)
  5644. }
  5645. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5646. //增加出库库存数量
  5647. service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, good_yc.OrgId, good_yc.GoodId)
  5648. errOne := service.UpDateWarehouStockFlowByStockDelete(warehouseOutInfos.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  5649. fmt.Println("errOne", errOne)
  5650. // 删除出库完成后,要增加对应批次的库存数量
  5651. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, good_yc.GoodId)
  5652. if errThree != nil {
  5653. return errThree
  5654. }
  5655. if good_yc.Count == 0 {
  5656. return nil
  5657. } else {
  5658. return errors.New("退库和出库数据不匹配")
  5659. }
  5660. }
  5661. func ConsumablesDeliveryTotalSix(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, goodOne []*models.NewDialysisBeforePrepareGoods, creater int64) (err error) {
  5662. //查询该患者当天已经出库的耗材信息
  5663. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  5664. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  5665. for i := len(goods_yc) - 1; i >= 0; i-- {
  5666. goods_yc_temp := goods_yc[i]
  5667. for j := len(goods) - 1; j >= 0; j-- {
  5668. goods_temp := goods[j]
  5669. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  5670. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  5671. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  5672. if goods_yc_temp.Count == goods_temp.Count {
  5673. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5674. goods = append(goods[:j], goods[j+1:]...)
  5675. break
  5676. }
  5677. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  5678. if goods_yc_temp.Count > goods_temp.Count {
  5679. temp_count := goods_yc_temp.Count - goods_temp.Count
  5680. goods_yc[i].Count = temp_count
  5681. goods = append(goods[:j], goods[j+1:]...)
  5682. break
  5683. }
  5684. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  5685. if goods_yc_temp.Count < goods_temp.Count {
  5686. temp_count := goods_temp.Count - goods_yc_temp.Count
  5687. goods[j].Count = temp_count
  5688. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  5689. break
  5690. }
  5691. }
  5692. }
  5693. }
  5694. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  5695. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  5696. fmt.Println("剩余需要出库的", len(goods))
  5697. if len(goods) > 0 {
  5698. out, err := service.FindStockOutByIsSys(orgID, 1, record_time)
  5699. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5700. if err == gorm.ErrRecordNotFound {
  5701. //没有记录,则创建出库单
  5702. timeStr := time.Now().Format("2006-01-02")
  5703. timeArr := strings.Split(timeStr, "-")
  5704. total, _ := service.FindAllWarehouseOut(orgID)
  5705. total = total + 1
  5706. warehousing_out_order := strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  5707. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  5708. number = number + total
  5709. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  5710. warehouseOut := models.WarehouseOut{
  5711. WarehouseOutOrderNumber: warehousing_out_order,
  5712. OperationTime: time.Now().Unix(),
  5713. OrgId: orgID,
  5714. Creater: creater,
  5715. Ctime: time.Now().Unix(),
  5716. Status: 1,
  5717. WarehouseOutTime: record_time,
  5718. Dealer: 0,
  5719. Manufacturer: 0,
  5720. Type: 1,
  5721. IsSys: 1,
  5722. StorehouseId: houseConfig.StorehouseOutInfo,
  5723. IsCheck: 1,
  5724. }
  5725. err := service.AddSigleWarehouseOut(&warehouseOut)
  5726. if err != nil {
  5727. utils.TraceLog("创建出库单失败 err = %v", err)
  5728. return err
  5729. } else {
  5730. out = warehouseOut
  5731. }
  5732. }
  5733. for _, item := range goods {
  5734. var newCount int64 = 0
  5735. for _, it := range goodOne {
  5736. if item.GoodTypeId == it.GoodTypeId && item.GoodId == it.GoodId {
  5737. newCount = it.Count
  5738. }
  5739. }
  5740. prepare := models.DialysisBeforePrepare{
  5741. GoodTypeId: item.GoodTypeId,
  5742. GoodId: item.GoodId,
  5743. Count: item.Count,
  5744. StorehouseId: houseConfig.StorehouseOutInfo,
  5745. }
  5746. service.ConsumablesGoodDelivery(orgID, patient_id, record_time, &prepare, &out, newCount)
  5747. //增加出库数量
  5748. service.ModifyGoodSumCount(houseConfig.StorehouseOutInfo, item.Count, orgID, item.GoodId)
  5749. }
  5750. }
  5751. if len(goods_yc) > 0 {
  5752. for _, good_yc := range goods_yc {
  5753. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  5754. ConsumablesDeliveryDeleteThree(orgID, record_time, good_yc, &out)
  5755. }
  5756. }
  5757. return nil
  5758. }
  5759. //耗材出库删除
  5760. func ConsumablesDeliveryDeleteThree(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut) (err error) {
  5761. // 先根据相关信息查询当天该耗材的出库信息
  5762. warehouseOutInfos, err := service.FindStockOutInfoByStockOne(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time)
  5763. if err != nil {
  5764. return err
  5765. }
  5766. var delete_count int64 = 0
  5767. for _, ware := range warehouseOutInfos {
  5768. // 判断当前出库的数据和删除出库数量
  5769. if good_yc.Count <= ware.Count {
  5770. delete_count = good_yc.Count
  5771. } else {
  5772. delete_count = ware.Count
  5773. }
  5774. warehouseOutInfo := &models.WarehouseOutInfo{
  5775. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5776. WarehouseOutId: warehouseOut.ID,
  5777. Status: 1,
  5778. Ctime: time.Now().Unix(),
  5779. Remark: "",
  5780. OrgId: orgID,
  5781. Type: 1,
  5782. Manufacturer: 0,
  5783. Dealer: 0,
  5784. IsSys: 0,
  5785. SysRecordTime: record_time,
  5786. GoodTypeId: good_yc.GoodTypeId,
  5787. GoodId: good_yc.GoodId,
  5788. StorehouseId: warehouseOut.StorehouseId,
  5789. IsCheck: 1,
  5790. }
  5791. warehouseOutInfo.Count = delete_count
  5792. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5793. warehouseOutInfo.Price = stockInInfo.Price
  5794. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5795. if errOne != nil {
  5796. return errOne
  5797. }
  5798. // 删除出库完成后,要改变流水库存(有疑问)
  5799. errOne = service.UpDateWarehouStockFlowByStockDelete(ware.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  5800. fmt.Println("errOne", errOne)
  5801. errThree := service.UpDateWarehouseInfoByStockDelete(ware.WarehouseInfotId, delete_count, good_yc.PatientId, record_time, good_yc.GoodId)
  5802. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5803. //扣减出库数量
  5804. service.ModifyReduceGoodSumCount(warehouseOut.StorehouseId, good_yc.Count, good_yc.OrgId, good_yc.GoodId)
  5805. if errThree != nil {
  5806. return errThree
  5807. }
  5808. }
  5809. if good_yc.Count == 0 {
  5810. return nil
  5811. } else {
  5812. return errors.New("退库和出库数据不匹配")
  5813. }
  5814. }
  5815. func (this *DialysisAPIController) GetMobileScheduleList() {
  5816. limit, _ := this.GetInt64("limit")
  5817. page, _ := this.GetInt64("page")
  5818. type_options_visible, _ := this.GetInt64("type_options_visible")
  5819. sch_type_options_visible, _ := this.GetInt64("sch_type_options_visible")
  5820. zone_options_visible, _ := this.GetInt64("zone_options_visible")
  5821. fmt.Println(limit, page, type_options_visible, sch_type_options_visible, zone_options_visible)
  5822. }
  5823. func RemoveRepeatedCheckRecod(arr []*models.HisPrescriptionProject) (newArr []*models.HisPrescriptionProject) {
  5824. newArr = make([]*models.HisPrescriptionProject, 0)
  5825. for i := 0; i < len(arr); i++ {
  5826. repeat := false
  5827. for j := i + 1; j < len(arr); j++ {
  5828. if arr[i].TeamId == arr[j].TeamId {
  5829. repeat = true
  5830. break
  5831. }
  5832. }
  5833. if !repeat {
  5834. newArr = append(newArr, arr[i])
  5835. }
  5836. }
  5837. return
  5838. }
  5839. func (this *DialysisAPIController) GetRoleList() {
  5840. admin_user_id, _ := this.GetInt64("admin_user_id")
  5841. orgid := this.GetMobileAdminUserInfo().Org.Id
  5842. list, err := service.GetRoleList(orgid, admin_user_id)
  5843. fmt.Println(err)
  5844. this.ServeSuccessJSON(map[string]interface{}{
  5845. "list": list,
  5846. })
  5847. return
  5848. }
  5849. func ConsumablesDeliveryDeleteNew(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  5850. fmt.Println("退库222322232322332232332322332232332233wo", good_yc.GoodId)
  5851. // 先根据相关信息查询当天该耗材的出库信息
  5852. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  5853. if err != nil {
  5854. return err
  5855. }
  5856. var delete_count int64 = 0
  5857. delete_count = warehouseOutInfos.Count - count
  5858. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  5859. // 删除出库完成后,要增加对应批次的库存数量
  5860. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count, patient_id, record_time, good_yc.GoodId)
  5861. if errThree != nil {
  5862. return errThree
  5863. }
  5864. //增加退库数量
  5865. service.UpdateSumAddCancelCount(orgID, good_yc.GoodId, houseConfig.StorehouseOutInfo, delete_count)
  5866. //扣减出库数量
  5867. service.ModifyAddGoodSumCount(houseConfig.StorehouseOutInfo, delete_count, orgID, good_yc.GoodId)
  5868. //查询剩余库存
  5869. goodList, _ := service.GetAllGoodSumCount(good_yc.GoodId, orgID)
  5870. var sum_count int64
  5871. for _, item := range goodList {
  5872. sum_count += item.StockCount
  5873. }
  5874. // 在出库记录表里记录退库详情
  5875. warehouseOutInfo := &models.WarehouseOutInfo{
  5876. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5877. WarehouseOutId: warehouseOut.ID,
  5878. Status: 1,
  5879. Ctime: time.Now().Unix(),
  5880. OrgId: orgID,
  5881. Type: 1,
  5882. IsSys: 1,
  5883. SysRecordTime: record_time,
  5884. GoodTypeId: good_yc.GoodTypeId,
  5885. GoodId: good_yc.GoodId,
  5886. PatientId: good_yc.PatientId,
  5887. ConsumableType: 2,
  5888. StorehouseId: houseConfig.StorehouseOutInfo,
  5889. IsCheck: 1,
  5890. OverCount: sum_count,
  5891. }
  5892. warehouseOutInfo.Count = count
  5893. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  5894. warehouseOutInfo.Price = stockInInfo.Price
  5895. warehouseOutInfo.Dealer = stockInInfo.Dealer
  5896. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  5897. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  5898. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  5899. warehouseOutInfo.Number = warehouseOutInfos.Number
  5900. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  5901. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  5902. //查找当天是否存在出库记录
  5903. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5904. if errcod == gorm.ErrRecordNotFound {
  5905. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  5906. //插入详情明细表
  5907. if errOne != nil {
  5908. return errOne
  5909. }
  5910. //插入详情明细表
  5911. stockFlow := models.VmStockFlow{
  5912. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  5913. WarehouseOutId: warehouseOut.ID,
  5914. GoodId: good_yc.GoodId,
  5915. Number: warehouseOutInfos.Number,
  5916. ProductDate: stockInInfo.ProductDate,
  5917. ExpireDate: stockInInfo.ExpiryDate,
  5918. Count: count,
  5919. Price: stockInInfo.Price,
  5920. Status: 1,
  5921. Ctime: time.Now().Unix(),
  5922. UserOrgId: good_yc.OrgId,
  5923. Manufacturer: stockInInfo.Manufacturer,
  5924. Dealer: stockInInfo.Dealer,
  5925. LicenseNumber: stockInInfo.LicenseNumber,
  5926. IsEdit: 2,
  5927. Creator: creater,
  5928. SystemTime: record_time,
  5929. ConsumableType: 3,
  5930. WarehousingDetailId: 0,
  5931. IsSys: 1,
  5932. UpdateCreator: creater,
  5933. PatientId: patient_id,
  5934. StorehouseId: houseConfig.StorehouseOutInfo,
  5935. OverCount: sum_count,
  5936. ProjectId: good_yc.ProjectId,
  5937. }
  5938. err := service.CreateStockFlowOne(stockFlow)
  5939. fmt.Println("err", err)
  5940. } else if errcod == nil {
  5941. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time, good_yc.ProjectId)
  5942. }
  5943. //创建退库单
  5944. operation_time := time.Now().Unix()
  5945. //创建退库单
  5946. timeStr := time.Now().Format("2006-01-02")
  5947. timeArr := strings.Split(timeStr, "-")
  5948. total, _ := service.FindAllCancelStockTotal(orgID)
  5949. total = total + 1
  5950. orderNumber := "CKTKD" + strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000" + strconv.FormatInt(total, 10)
  5951. cancelStock := models.CancelStock{
  5952. OrderNumber: orderNumber,
  5953. OperaTime: operation_time,
  5954. OrgId: orgID,
  5955. Creater: warehouseOut.Creater,
  5956. Ctime: time.Now().Unix(),
  5957. Status: 1,
  5958. ReturnTime: record_time,
  5959. Type: 1,
  5960. StorehouseId: stockInInfo.StorehouseId,
  5961. IsCheck: 1,
  5962. }
  5963. _, msgerrkonde := service.GetCancelStockDetailByOrderNumberOne(record_time, orgID)
  5964. if msgerrkonde == gorm.ErrRecordNotFound {
  5965. service.AddSigleCancelStock(&cancelStock)
  5966. }
  5967. cancel, _ := service.GetLastCancelStockById(orgID)
  5968. manufacturer, _ := service.GetManufactureById(stockInInfo.Manufacturer)
  5969. deaerler, _ := service.GetDealerById(stockInInfo.Dealer)
  5970. cancelStockInfo := models.CancelStockInfo{
  5971. GoodId: stockInInfo.GoodId,
  5972. CancelStockId: cancel.ID,
  5973. GoodTypeId: stockInInfo.GoodTypeId,
  5974. Count: delete_count,
  5975. Price: stockInInfo.PackingPrice,
  5976. Total: 0,
  5977. ProductDate: stockInInfo.ProductDate,
  5978. ExpiryDate: stockInInfo.ExpiryDate,
  5979. Ctime: time.Now().Unix(),
  5980. Status: 1,
  5981. OrgId: orgID,
  5982. OrderNumber: cancel.OrderNumber,
  5983. Type: 0,
  5984. Dealer: deaerler.DealerName,
  5985. Manufacturer: manufacturer.ManufacturerName,
  5986. Number: stockInInfo.Number,
  5987. RegisterAccount: "",
  5988. Remark: "",
  5989. WarehouseInfoId: stockInInfo.ID,
  5990. PatientId: patient_id,
  5991. RecordDate: record_time,
  5992. StorehouseId: stockInInfo.StorehouseId,
  5993. IsCheck: 1,
  5994. }
  5995. service.CreateCancelStockInfoOne(&cancelStockInfo)
  5996. cancelInfo, _ := service.GetLastCancelStockInfoByGoodId(stockInInfo.GoodId)
  5997. flow := models.VmStockFlow{
  5998. WarehousingId: warehouseOutInfo.WarehouseInfotId,
  5999. GoodId: good_yc.GoodId,
  6000. Number: warehouseOutInfos.Number,
  6001. LicenseNumber: stockInInfo.LicenseNumber,
  6002. Count: delete_count,
  6003. UserOrgId: orgID,
  6004. PatientId: patient_id,
  6005. SystemTime: record_time,
  6006. ConsumableType: 7,
  6007. IsSys: 0,
  6008. WarehousingOrder: "",
  6009. WarehouseOutId: warehouseOutInfos.WarehouseOutId,
  6010. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  6011. IsEdit: 0,
  6012. CancelStockId: cancel.ID,
  6013. CancelOrderNumber: cancel.OrderNumber,
  6014. Manufacturer: manufacturer.ID,
  6015. Dealer: 0,
  6016. Creator: warehouseOut.Creater,
  6017. UpdateCreator: 0,
  6018. Status: 1,
  6019. Ctime: time.Now().Unix(),
  6020. Mtime: 0,
  6021. Price: stockInInfo.Price,
  6022. WarehousingDetailId: stockInInfo.ID,
  6023. WarehouseOutDetailId: warehouseOutInfos.ID,
  6024. CancelOutDetailId: cancelInfo.ID,
  6025. ProductDate: stockInInfo.ProductDate,
  6026. ExpireDate: stockInInfo.ExpiryDate,
  6027. StorehouseId: houseConfig.StorehouseOutInfo,
  6028. OverCount: sum_count,
  6029. }
  6030. service.CreateStockFlowOne(flow)
  6031. //更改自动出库的表格
  6032. details := models.BloodAutomaticReduceDetail{
  6033. WarehouseOutId: warehouseOutInfo.ID,
  6034. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  6035. PatientId: patient_id,
  6036. Ctime: time.Now().Unix(),
  6037. Mtime: time.Now().Unix(),
  6038. Status: 1,
  6039. RecordTime: record_time,
  6040. OrgId: orgID,
  6041. GoodId: good_yc.GoodId,
  6042. GoodTypeId: good_yc.GoodTypeId,
  6043. Count: count,
  6044. StorehouseId: houseConfig.StorehouseOutInfo,
  6045. }
  6046. //查询当天耗材是否已经存在数据
  6047. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  6048. if errcode == gorm.ErrRecordNotFound {
  6049. errTwo := service.CreateAutoReduceRecord(&details)
  6050. if errTwo != nil {
  6051. return errTwo
  6052. }
  6053. } else if errcode == nil {
  6054. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  6055. service.CreateAutoReduceRecord(&details)
  6056. }
  6057. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  6058. //增加出库库存数量
  6059. //service.ModifyReduceGoodSumCount(houseConfig.StorehouseOutInfo,delete_count,good_yc.OrgId,good_yc.GoodId)
  6060. if good_yc.Count == 0 {
  6061. return nil
  6062. } else {
  6063. return errors.New("退库和出库数据不匹配")
  6064. }
  6065. }
  6066. func (this *DialysisAPIController) SavePatientSign() {
  6067. adminUserInfo := this.GetMobileAdminUserInfo()
  6068. patient_id, _ := this.GetInt64("patient_id")
  6069. dialysis_date, _ := this.GetInt64("dialysis_date")
  6070. orgid := adminUserInfo.Org.Id
  6071. var esdata models.DialysisOrder
  6072. var err error
  6073. if err = json.Unmarshal(this.Ctx.Input.RequestBody, &esdata); err != nil {
  6074. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6075. return
  6076. }
  6077. esdata.Hash = esdata.Hash
  6078. esdata.Url = beego.AppConfig.String("qiniu_domain") + esdata.Hash
  6079. order := models.DialysisOrder{
  6080. Hash: esdata.Hash,
  6081. Url: esdata.Url,
  6082. }
  6083. err = service.UpdatePatientSign(patient_id, dialysis_date, order, orgid)
  6084. redis := service.RedisClient()
  6085. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_order"
  6086. redis.Set(key, "", time.Second)
  6087. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_orders_list_all"
  6088. //清空key 值
  6089. redis.Set(keyOne, "", time.Second)
  6090. //scheduleDateStartOne := startDate.Format("2006-01-02")
  6091. //keyTwo := "scheduals_" + scheduleDateStartOne + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  6092. //redis.Set(keyTwo, "", time.Second)
  6093. keyThree := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":doctor_advices"
  6094. redis.Set(keyThree, "", time.Second)
  6095. keyFour := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":monitor_records"
  6096. redis.Set(keyFour, "", time.Second)
  6097. keyFive := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  6098. redis.Set(keyFive, "", time.Second)
  6099. keySix := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":his_doctor_advice"
  6100. redis.Set(keySix, "", time.Second)
  6101. keySeven := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":device_list_all"
  6102. redis.Set(keySeven, "", time.Second)
  6103. if err != nil {
  6104. fmt.Println(err)
  6105. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  6106. return
  6107. }
  6108. this.ServeSuccessJSON(map[string]interface{}{
  6109. "electronic_signature": esdata,
  6110. })
  6111. }
  6112. func (this *DialysisAPIController) GetPatientSign() {
  6113. patient_id, _ := this.GetInt64("patient_id")
  6114. dialysis_date, _ := this.GetInt64("dialysis_date")
  6115. adminUserInfo := this.GetMobileAdminUserInfo()
  6116. orgId := adminUserInfo.Org.Id
  6117. dialysisOrder, err := service.GetPatientSign(patient_id, dialysis_date, orgId)
  6118. if err != nil {
  6119. fmt.Println(err)
  6120. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  6121. return
  6122. }
  6123. this.ServeSuccessJSON(map[string]interface{}{
  6124. "dialysisOrder": dialysisOrder,
  6125. })
  6126. }
  6127. func (this *DialysisAPIController) GetScheduleByPatient() {
  6128. patient_id, _ := this.GetInt64("patient_id")
  6129. schedule_date, _ := this.GetInt64("schedule_date")
  6130. orgid := this.GetMobileAdminUserInfo().Org.Id
  6131. schedule, _ := service.GetScheduleByPatient(patient_id, schedule_date, orgid)
  6132. this.ServeSuccessJSON(map[string]interface{}{
  6133. "schedule": schedule,
  6134. })
  6135. }
  6136. func (this *DialysisAPIController) GetDialysisRecordOrder() {
  6137. org_id := this.GetMobileAdminUserInfo().Org.Id
  6138. patient_id, _ := this.GetInt64("patient_id")
  6139. schedule_date, _ := this.GetInt64("schedule_date")
  6140. order, _ := service.GetDialysisRecordOrder(org_id, patient_id, schedule_date)
  6141. this.ServeSuccessJSON(map[string]interface{}{
  6142. "order": order,
  6143. })
  6144. }
  6145. func (this *DialysisAPIController) GetScheduleTypeByIdList() {
  6146. org_id := this.GetMobileAdminUserInfo().Org.Id
  6147. schedule_date := this.GetString("schedule_date")
  6148. schedule_type, _ := this.GetInt64("schedule_type")
  6149. timeLayout := "2006-01-02"
  6150. loc, _ := time.LoadLocation("Local")
  6151. var startdateunix int64
  6152. if len(schedule_date) > 0 {
  6153. theTime, err := time.ParseInLocation(timeLayout+"15:04:05", schedule_date+"00:00:00", loc)
  6154. if err != nil {
  6155. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6156. return
  6157. }
  6158. startdateunix = theTime.Unix()
  6159. }
  6160. list, _ := service.GetScheduleTypeById(org_id, startdateunix, schedule_type)
  6161. scheduals, _ := service.MobileGetDialysisScheduals(org_id, startdateunix, schedule_type)
  6162. devices, _ := service.GetAllDevicetByListSix(org_id)
  6163. for key, item := range scheduals {
  6164. // 床位信息
  6165. for _, device := range devices {
  6166. if item.BedId == device.ID {
  6167. scheduals[key].DeviceNumber = device
  6168. break
  6169. }
  6170. }
  6171. }
  6172. this.ServeSuccessJSON(map[string]interface{}{
  6173. "list": list,
  6174. "scheduals": scheduals,
  6175. })
  6176. }
  6177. func (this *DialysisAPIController) SavePatientPicture() {
  6178. patient_id, _ := this.GetInt64("patient_id")
  6179. dialysis_date, _ := this.GetInt64("schedule_date")
  6180. avatar := this.GetString("avatar")
  6181. fmt.Println("patient_id", patient_id)
  6182. orgId := this.GetMobileAdminUserInfo().Org.Id
  6183. order := models.DialysisOrder{
  6184. Url: avatar,
  6185. }
  6186. err := service.UpdatePatientSign(patient_id, dialysis_date, order, orgId)
  6187. redis := service.RedisClient()
  6188. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_order"
  6189. redis.Set(key, "", time.Second)
  6190. keyOne := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":dialysis_orders_list_all"
  6191. //清空key 值
  6192. redis.Set(keyOne, "", time.Second)
  6193. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":doctor_advices"
  6194. redis.Set(keyThree, "", time.Second)
  6195. keyFour := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":monitor_records"
  6196. redis.Set(keyFour, "", time.Second)
  6197. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":patient_info"
  6198. redis.Set(keyFive, "", time.Second)
  6199. keySix := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dialysis_date, 10) + ":his_doctor_advice"
  6200. redis.Set(keySix, "", time.Second)
  6201. keySeven := strconv.FormatInt(orgId, 10) + ":" + ":device_list_all"
  6202. redis.Set(keySeven, "", time.Second)
  6203. if err != nil {
  6204. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDBUpdate)
  6205. return
  6206. }
  6207. this.ServeSuccessJSON(map[string]interface{}{
  6208. "order": order,
  6209. })
  6210. }
  6211. func (this *DialysisAPIController) ExectionMobileAdvice() {
  6212. ids := this.GetString("ids")
  6213. idSplit := strings.Split(ids, ",")
  6214. orgId := this.GetMobileAdminUserInfo().Org.Id
  6215. config, _ := service.FindXTHisRecordByOrgIdSix(orgId)
  6216. execution_time := this.GetString("exce_time")
  6217. timeLayout2 := "2006-01-02 15:04:05"
  6218. loc, _ := time.LoadLocation("Local")
  6219. theTime, errs := time.ParseInLocation(timeLayout2, execution_time, loc)
  6220. if errs != nil {
  6221. utils.ErrorLog(errs.Error())
  6222. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6223. return
  6224. }
  6225. //his客户
  6226. if config.IsOpen == 1 {
  6227. list, _ := service.GetHisMobileAdviceGroupList(orgId, idSplit)
  6228. adviceList, _ := service.GetHisMobileAdviceList(orgId, idSplit)
  6229. for _, item := range list {
  6230. for _, it := range adviceList {
  6231. if item.DrugId == it.DrugId {
  6232. item.ChildDoctorAdvice = append(item.ChildDoctorAdvice, it)
  6233. }
  6234. }
  6235. }
  6236. for _, item := range list {
  6237. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6238. var sum_out_count int64
  6239. for _, itemThree := range item.ChildDoctorAdvice {
  6240. var prescribing_number int64
  6241. stringPrescribingNumber := strconv.FormatFloat(itemThree.PrescribingNumber, 'f', -1, 64)
  6242. parseIntPrescribingNumber, _ := strconv.ParseInt(stringPrescribingNumber, 10, 64)
  6243. if itemThree.PrescribingNumberUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
  6244. prescribing_number = parseIntPrescribingNumber * medical.MinNumber
  6245. }
  6246. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit != medical.MinUnit {
  6247. prescribing_number = parseIntPrescribingNumber
  6248. }
  6249. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit == medical.MinUnit {
  6250. prescribing_number = parseIntPrescribingNumber
  6251. }
  6252. sum_out_count += prescribing_number
  6253. }
  6254. drugStockOut, _ := service.GetDrugSumOutCountByDrugId(item.DrugId, orgId)
  6255. //库存不足
  6256. if sum_out_count > drugStockOut.FlushCount {
  6257. this.ServeSuccessJSON(map[string]interface{}{
  6258. "msg": "2",
  6259. "drug": medical,
  6260. "ids": ids,
  6261. })
  6262. return
  6263. }
  6264. }
  6265. creater := this.GetMobileAdminUserInfo().AdminUser.Id
  6266. //执行医嘱
  6267. errs := service.ExectionMobileAdvice(orgId, idSplit, theTime.Unix(), creater)
  6268. advices, _ := service.FindHisDoctorAdviceByIds(orgId, idSplit)
  6269. for _, item := range advices {
  6270. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6271. redis := service.RedisClient()
  6272. //清空key 值
  6273. redis.Set(key, "", time.Second)
  6274. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6275. redis.Set(keyTwo, "", time.Second)
  6276. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6277. redis.Set(keyThree, "", time.Second)
  6278. recordDate := theTime.Format("2006-01-02")
  6279. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6280. redis.Set(keyFour, "", time.Second)
  6281. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6282. redis.Set(keyFive, "", time.Second)
  6283. defer redis.Close()
  6284. }
  6285. if errs == nil {
  6286. //药品管理信息
  6287. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(orgId)
  6288. storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
  6289. if drugStockConfig.IsOpen == 1 {
  6290. for _, item := range advices {
  6291. advice, _ := service.FindHisDoctorAdviceById(orgId, item.ID)
  6292. config, _ := service.GetDrugOpenConfigOne(orgId)
  6293. if config.IsOpen != 1 {
  6294. //查询该药品是否有库存
  6295. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6296. pharmacyConfig, _ := service.FindPharmacyConfig(advice.UserOrgId)
  6297. if medical.IsUse == 2 {
  6298. if config.IsOpen != 1 {
  6299. if pharmacyConfig.IsOpen == 1 && medical.IsPharmacy == 0 {
  6300. service.HisDrugsDelivery(orgId, creater, &advice)
  6301. }
  6302. if pharmacyConfig.IsOpen != 1 {
  6303. service.HisDrugsDelivery(orgId, creater, &advice)
  6304. }
  6305. //更新字典里面的库存
  6306. stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
  6307. var sum_count int64
  6308. for _, its := range stockInfo {
  6309. if its.MaxUnit == medical.MaxUnit {
  6310. its.StockMaxNumber = its.StockMaxNumber * medical.MinNumber
  6311. }
  6312. sum_count += its.StockMaxNumber + its.StockMinNumber
  6313. }
  6314. service.UpdateBaseDrugSumTwo(item.DrugId, sum_count, item.UserOrgId)
  6315. //剩余库存
  6316. service.UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  6317. }
  6318. }
  6319. }
  6320. }
  6321. }
  6322. this.ServeSuccessJSON(map[string]interface{}{
  6323. "msg": "1",
  6324. "ids": ids,
  6325. })
  6326. return
  6327. } else {
  6328. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  6329. }
  6330. }
  6331. fmt.Println("config233322333223", config.IsOpen)
  6332. //血透客户
  6333. if config.IsOpen == 2 || config.IsOpen == 0 {
  6334. //药品管理信息
  6335. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(orgId)
  6336. if drugStockConfig.IsOpen == 1 {
  6337. list, _ := service.GetBloodMobileAdviceGroupList(orgId, idSplit)
  6338. adviceList, _ := service.GetBloodMobileAdviceList(orgId, idSplit)
  6339. for _, item := range list {
  6340. for _, it := range adviceList {
  6341. if item.DrugId == it.DrugId {
  6342. item.ChildDoctorAdvice = append(item.ChildDoctorAdvice, it)
  6343. }
  6344. }
  6345. }
  6346. for _, item := range list {
  6347. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6348. var sum_out_count int64
  6349. for _, itemThree := range item.ChildDoctorAdvice {
  6350. var prescribing_number int64
  6351. stringPrescribingNumber := strconv.FormatFloat(itemThree.PrescribingNumber, 'f', -1, 64)
  6352. parseIntPrescribingNumber, _ := strconv.ParseInt(stringPrescribingNumber, 10, 64)
  6353. if itemThree.PrescribingNumberUnit == medical.MaxUnit && medical.MaxUnit != medical.MinUnit {
  6354. prescribing_number = parseIntPrescribingNumber * medical.MinNumber
  6355. }
  6356. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit != medical.MinUnit {
  6357. prescribing_number = parseIntPrescribingNumber
  6358. }
  6359. if itemThree.PrescribingNumberUnit == medical.MinUnit && medical.MaxUnit == medical.MinUnit {
  6360. prescribing_number = parseIntPrescribingNumber
  6361. }
  6362. sum_out_count += prescribing_number
  6363. }
  6364. drugStockOut, _ := service.GetDrugSumOutCountByDrugId(item.DrugId, orgId)
  6365. //库存不足
  6366. if sum_out_count > drugStockOut.FlushCount {
  6367. this.ServeSuccessJSON(map[string]interface{}{
  6368. "msg": "2",
  6369. "drug": medical,
  6370. "ids": ids,
  6371. })
  6372. return
  6373. }
  6374. }
  6375. creater := this.GetMobileAdminUserInfo().AdminUser.Id
  6376. fmt.Println("creater2332243244224242424", creater)
  6377. //执行医嘱
  6378. errs := service.ExectionBloodMobileAdvice(orgId, idSplit, theTime.Unix(), creater)
  6379. advices, _ := service.FindAllDoctorAdviceByIds(orgId, idSplit)
  6380. for _, item := range advices {
  6381. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6382. redis := service.RedisClient()
  6383. //清空key 值
  6384. redis.Set(key, "", time.Second)
  6385. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6386. redis.Set(keyTwo, "", time.Second)
  6387. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6388. redis.Set(keyThree, "", time.Second)
  6389. recordDate := theTime.Format("2006-01-02")
  6390. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6391. redis.Set(keyFour, "", time.Second)
  6392. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6393. redis.Set(keyFive, "", time.Second)
  6394. defer redis.Close()
  6395. }
  6396. if errs == nil {
  6397. for _, item := range advices {
  6398. storeHouseConfig, _ := service.GetAllStoreHouseConfig(orgId)
  6399. medical, _ := service.GetBaseDrugMedical(item.DrugId)
  6400. //查询是否出库按钮开启
  6401. adviceSetting, _ := service.FindAdviceSettingById(item.UserOrgId)
  6402. if adviceSetting.IsAdviceOpen == 1 {
  6403. //查询是否出库按钮开启
  6404. prescriptionConfig, _ := service.FindPrescriptionConfigById(item.UserOrgId)
  6405. pharmacyConfig, _ := service.FindPharmacyConfig(item.UserOrgId)
  6406. if prescriptionConfig.IsOpen == 1 {
  6407. if medical.IsUse == 2 {
  6408. if pharmacyConfig.IsOpen == 1 && medical.IsPharmacy == 0 {
  6409. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6410. }
  6411. if pharmacyConfig.IsOpen != 1 {
  6412. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6413. }
  6414. //更新字典里面的库存
  6415. stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
  6416. var sum_count int64
  6417. for _, its := range stockInfo {
  6418. if its.MaxUnit == medical.MaxUnit {
  6419. its.StockMaxNumber = its.StockMaxNumber * medical.MinNumber
  6420. }
  6421. sum_count += its.StockMaxNumber + its.StockMinNumber
  6422. }
  6423. service.UpdateBaseDrugSumTwo(item.DrugId, sum_count, item.UserOrgId)
  6424. //剩余库存
  6425. service.UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  6426. }
  6427. }
  6428. } else {
  6429. pharmacyConfig, _ := service.FindPharmacyConfig(item.UserOrgId)
  6430. if medical.IsUse == 2 {
  6431. if pharmacyConfig.IsOpen == 1 && medical.IsPharmacy == 0 {
  6432. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6433. }
  6434. if pharmacyConfig.IsOpen != 1 {
  6435. service.DrugsDelivery(item.UserOrgId, item.ExecutionStaff, &item)
  6436. }
  6437. stockInfo, _ := service.GetDrugAllStockInfo(storeHouseConfig.DrugStorehouseOut, item.UserOrgId, item.DrugId)
  6438. var sum_count int64
  6439. for _, its := range stockInfo {
  6440. if its.MaxUnit == medical.MaxUnit {
  6441. its.StockMaxNumber = its.StockMaxNumber * medical.MinNumber
  6442. }
  6443. sum_count += its.StockMaxNumber + its.StockMinNumber
  6444. }
  6445. service.UpdateBaseDrugSumTwo(item.DrugId, sum_count, item.UserOrgId)
  6446. //剩余库存
  6447. service.UpdateDrugStockCount(item.DrugId, item.UserOrgId, storeHouseConfig.DrugStorehouseOut, sum_count)
  6448. }
  6449. }
  6450. }
  6451. }
  6452. this.ServeSuccessJSON(map[string]interface{}{
  6453. "msg": "1",
  6454. "ids": ids,
  6455. })
  6456. return
  6457. } else {
  6458. creater := this.GetMobileAdminUserInfo().AdminUser.Id
  6459. //执行医嘱
  6460. service.ExectionBloodMobileAdvice(orgId, idSplit, theTime.Unix(), creater)
  6461. advices, _ := service.FindAllDoctorAdviceByIds(orgId, idSplit)
  6462. for _, item := range advices {
  6463. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6464. redis := service.RedisClient()
  6465. //清空key 值
  6466. redis.Set(key, "", time.Second)
  6467. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6468. redis.Set(keyTwo, "", time.Second)
  6469. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6470. redis.Set(keyThree, "", time.Second)
  6471. recordDate := theTime.Format("2006-01-02")
  6472. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6473. redis.Set(keyFour, "", time.Second)
  6474. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6475. redis.Set(keyFive, "", time.Second)
  6476. defer redis.Close()
  6477. }
  6478. this.ServeSuccessJSON(map[string]interface{}{
  6479. "msg": "1",
  6480. "ids": ids,
  6481. })
  6482. return
  6483. }
  6484. }
  6485. }
  6486. func (this *DialysisAPIController) GetSettleMobileAdvice() {
  6487. ids := this.GetString("ids")
  6488. idSplit := strings.Split(ids, ",")
  6489. orgId := this.GetMobileAdminUserInfo().Org.Id
  6490. config, _ := service.FindXTHisRecordByOrgIdSix(orgId)
  6491. if config.IsOpen == 1 {
  6492. service.UpdateSettleMobileHisAdvice(orgId, idSplit)
  6493. this.ServeSuccessJSON(map[string]interface{}{
  6494. "msg": "1",
  6495. "ids": ids,
  6496. })
  6497. return
  6498. }
  6499. if config.IsOpen == 0 || config.IsOpen == 2 {
  6500. service.UpdateSettleMobileBloodAdvice(orgId, idSplit)
  6501. this.ServeSuccessJSON(map[string]interface{}{
  6502. "msg": "1",
  6503. "ids": ids,
  6504. })
  6505. return
  6506. }
  6507. }
  6508. func (this *DialysisAPIController) GetCheckMobileAdvice() {
  6509. ids := this.GetString("ids")
  6510. idSplit := strings.Split(ids, ",")
  6511. orgId := this.GetMobileAdminUserInfo().Org.Id
  6512. config, _ := service.FindXTHisRecordByOrgIdSix(orgId)
  6513. //his
  6514. if config.IsOpen == 1 {
  6515. checker := this.GetMobileAdminUserInfo().AdminUser.Id
  6516. theTime := time.Now()
  6517. advices := models.HisDoctorAdviceThirty{
  6518. CheckTime: theTime.Unix(),
  6519. Checker: checker,
  6520. UpdatedTime: time.Now().Unix(),
  6521. }
  6522. service.CheckHisMobileDoctorAdvice(orgId, idSplit, advices)
  6523. list, _ := service.FindDoctorAdviceByIds(orgId, idSplit)
  6524. for _, item := range list {
  6525. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6526. redis := service.RedisClient()
  6527. //清空key 值
  6528. redis.Set(key, "", time.Second)
  6529. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6530. redis.Set(keyTwo, "", time.Second)
  6531. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6532. redis.Set(keyThree, "", time.Second)
  6533. recordDate := theTime.Format("2006-01-02")
  6534. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6535. redis.Set(keyFour, "", time.Second)
  6536. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6537. redis.Set(keyFive, "", time.Second)
  6538. defer redis.Close()
  6539. }
  6540. this.ServeSuccessJSON(map[string]interface{}{
  6541. "msg": "1",
  6542. "ids": ids,
  6543. })
  6544. return
  6545. }
  6546. //血透
  6547. if config.IsOpen == 0 || config.IsOpen == 2 {
  6548. checker := this.GetMobileAdminUserInfo().AdminUser.Id
  6549. theTime := time.Now()
  6550. advices := models.DoctorAdvice{
  6551. CheckTime: theTime.Unix(),
  6552. Checker: checker,
  6553. UpdatedTime: time.Now().Unix(),
  6554. }
  6555. service.CheckBloodDoctorAdvice(orgId, idSplit, advices)
  6556. list, _ := service.FindDoctorAdviceByIds(orgId, idSplit)
  6557. for _, item := range list {
  6558. key := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":doctor_advices"
  6559. redis := service.RedisClient()
  6560. //清空key 值
  6561. redis.Set(key, "", time.Second)
  6562. keyTwo := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":advice_list_all"
  6563. redis.Set(keyTwo, "", time.Second)
  6564. keyThree := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.PatientId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_doctor_advice"
  6565. redis.Set(keyThree, "", time.Second)
  6566. recordDate := theTime.Format("2006-01-02")
  6567. keyFour := "scheduals_" + recordDate + "_" + strconv.FormatInt(orgId, 10)
  6568. redis.Set(keyFour, "", time.Second)
  6569. keyFive := strconv.FormatInt(orgId, 10) + ":" + strconv.FormatInt(item.AdviceDate, 10) + ":his_advices_list_all"
  6570. redis.Set(keyFive, "", time.Second)
  6571. defer redis.Close()
  6572. }
  6573. this.ServeSuccessJSON(map[string]interface{}{
  6574. "msg": "1",
  6575. "ids": ids,
  6576. })
  6577. return
  6578. }
  6579. }
  6580. func (this *DialysisAPIController) CheckSchedule() {
  6581. patientID, _ := this.GetInt64("patient_id")
  6582. recordDateStr := this.GetString("record_date")
  6583. nurseID, _ := this.GetInt64("nurse")
  6584. schedual_type, _ := this.GetInt64("schedual_type")
  6585. bedID, _ := this.GetInt64("bed")
  6586. start_time := this.GetString("start_time")
  6587. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  6588. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6589. return
  6590. }
  6591. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  6592. if parseStartDateErr != nil {
  6593. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  6594. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6595. return
  6596. }
  6597. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  6598. if parseErr != nil {
  6599. this.ErrorLog("时间解析失败:%v", parseErr)
  6600. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6601. return
  6602. }
  6603. adminUserInfo := this.GetMobileAdminUserInfo()
  6604. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  6605. if getPatientErr != nil {
  6606. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  6607. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6608. return
  6609. } else if patient == nil {
  6610. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  6611. return
  6612. }
  6613. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  6614. if getNurseErr != nil {
  6615. this.ErrorLog("获取护士失败:%v", getNurseErr)
  6616. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6617. return
  6618. } else if nurse == nil {
  6619. this.ErrorLog("护士不存在")
  6620. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6621. return
  6622. }
  6623. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  6624. if getDeviceNumberErr != nil {
  6625. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  6626. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6627. return
  6628. } else if deviceNumber == nil {
  6629. this.ErrorLog("床位号不存在")
  6630. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  6631. return
  6632. }
  6633. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  6634. if getRecordErr != nil {
  6635. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  6636. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  6637. return
  6638. } else if dialysisRecord != nil {
  6639. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  6640. return
  6641. }
  6642. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  6643. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  6644. timeLayout := "2006-01-02 15:04:05"
  6645. loc, _ := time.LoadLocation("Local")
  6646. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  6647. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  6648. schedulestartTime := theStartTime.Unix()
  6649. scheduleendTime := theEndTime.Unix()
  6650. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  6651. //sch, _ := service.GetSourceSch(adminUserInfo.Org.Id, patientID, scheduleendTime)
  6652. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  6653. //查询该床位是否有人用了
  6654. order, _ := service.GetDialysisOrderByBedIdTwo(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  6655. if err == nil {
  6656. if schedule.ID == 0 {
  6657. this.ServeSuccessJSON(map[string]interface{}{
  6658. "status": 0,
  6659. })
  6660. } else {
  6661. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  6662. if order.ID > 0 { //该机位被其他人占用了
  6663. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  6664. return
  6665. } else { //2022-11-04 更变需求,如果改床位有排班,但是没上机,则进行互换床位操作,如果改床位是本人的话,不做处理
  6666. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  6667. if daySchedule.ID > 0 && schedule.PatientId != daySchedule.PatientId {
  6668. this.ServeSuccessJSON(map[string]interface{}{
  6669. "status": 1,
  6670. "msg": "该机位已有排班,继续操作将会与原来的排班信息进行互调,请问是否继续?",
  6671. })
  6672. return
  6673. } else {
  6674. this.ServeSuccessJSON(map[string]interface{}{
  6675. "status": 0,
  6676. })
  6677. }
  6678. }
  6679. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 {
  6680. this.ServeSuccessJSON(map[string]interface{}{
  6681. "status": 2,
  6682. "msg": "当前机位已有患者在使用,请重新选择!",
  6683. })
  6684. }
  6685. }
  6686. } else {
  6687. this.ServeSuccessJSON(map[string]interface{}{
  6688. "status": 0,
  6689. })
  6690. }
  6691. }