dialysis_api_controller.go 211KB

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