dialysis_api_controller.go 259KB

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