dialysis_api_controller.go 204KB

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