dialysis_api_controller.go 202KB

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