dialysis_api_controller.go 204KB

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