dialysis_api_controller.go 177KB

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