dialysis_api_controller.go 211KB

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