dialysis_api_controller.go 201KB

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