dialysis_api_controller.go 189KB

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