dialysis_api_controller.go 181KB

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