dialysis_api_controller.go 180KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978
  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. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  978. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  979. //
  980. //if template.TemplateId == 2 || template.TemplateId == 6 {
  981. // if appRole.UserType == 3 {
  982. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  983. // if getPermissionErr != nil {
  984. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  985. // return
  986. // } else if headNursePermission == nil {
  987. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  988. // return
  989. // }
  990. // }
  991. //}
  992. //TODO 需要根据角色去判断
  993. prescription := models.DialysisPrescription{
  994. UserOrgId: adminUserInfo.Org.Id,
  995. PatientId: id,
  996. RecordDate: recordDate.Unix(),
  997. ModeId: mode_id,
  998. DialysisDuration: dialysis_duration,
  999. Dialyzer: dialyzer,
  1000. PerfusionApparatus: perfusion_apparatus,
  1001. BloodFlowVolume: blood_flow_volume,
  1002. DewaterAmount: dewater_amount,
  1003. DisplaceLiqui: displace_liqui,
  1004. ReplacementWay: replacement_way,
  1005. Anticoagulant: anticoagulant,
  1006. AnticoagulantShouji: anticoagulant_shouji,
  1007. AnticoagulantWeichi: anticoagulant_weichi,
  1008. AnticoagulantZongliang: anticoagulant_zongliang,
  1009. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1010. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1011. Kalium: kalium,
  1012. Sodium: sodium,
  1013. Calcium: calcium,
  1014. Bicarbonate: bicarbonate,
  1015. Glucose: glucose,
  1016. // DryWeight: dry_weight,
  1017. DialysateFlow: dialysate_flow,
  1018. DialysateTemperature: dialysate_temperature,
  1019. // PrescriptionDoctor: prescription_doctor,
  1020. ReplacementTotal: replacement_total,
  1021. Conductivity: conductivity,
  1022. Remark: remark,
  1023. Status: 1,
  1024. CreatedTime: time.Now().Unix(),
  1025. UpdatedTime: time.Now().Unix(),
  1026. DialysisDurationMinute: dialysisDurationMinute,
  1027. DialysisDurationHour: dialysisDurationHour,
  1028. TargetUltrafiltration: targetUltrafiltration,
  1029. DialysateFormulation: dialysateFormulation,
  1030. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1031. BodyFluid: body_fluid,
  1032. SpecialMedicine: special_medicine,
  1033. SpecialMedicineOther: special_medicine_other,
  1034. DisplaceLiquiPart: displace_liqui_part,
  1035. DisplaceLiquiValue: displace_liqui_value,
  1036. BloodAccess: blood_access,
  1037. Ultrafiltration: ultrafiltration,
  1038. BodyFluidOther: body_fluid_other,
  1039. Niprocart: niprocart,
  1040. Jms: jms,
  1041. FistulaNeedleSet: fistula_needle_set,
  1042. FistulaNeedleSet16: fistula_needle_set_16,
  1043. Hemoperfusion: hemoperfusion,
  1044. DialyserSterilised: dialyser_sterilised,
  1045. Filtryzer: filtryzer,
  1046. Dialyzers: dialyzers,
  1047. Injector: injector,
  1048. Bloodlines: bloodlines,
  1049. TubingHemodialysis: tubing_hemodialysis,
  1050. Package: safe_package,
  1051. ALiquid: a_liquid,
  1052. TargetKtv: target_ktv,
  1053. PreImpulse: pre_impulse,
  1054. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1055. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1056. Blood: blood,
  1057. DialysisDialyszers: dialysis_dialyszers,
  1058. DialysisIrrigation: dialysis_irrigation,
  1059. AntioxidantCommodityName: antioxidant_commodity_name,
  1060. DisplaceSpeed: displace_speed,
  1061. Illness: illness,
  1062. Amylaceum: amylaceum,
  1063. SingleTime: single_time,
  1064. SingleWater: single_water,
  1065. ReplacementFlow: replacement_flow,
  1066. PlasmaSeparator: plasma_separator,
  1067. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  1068. OxygenUptake: oxygen_uptake,
  1069. OxygenFlow: oxygen_flow,
  1070. OxygenTime: oxygen_time,
  1071. HemodialysisPipelines: hemodialysis_pipelines,
  1072. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  1073. PunctureNeedle: puncture_needle,
  1074. PunctureNeedleCount: puncture_needle_count,
  1075. Epo: epo,
  1076. EpoCount: epo_count,
  1077. }
  1078. //查询最近透析准备表里是否存在 透析器 灌流器
  1079. //
  1080. //splitStr := strings.Split(dialysis_dialyszers, ",")
  1081. //
  1082. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  1083. //
  1084. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  1085. //if len(mation)>0{
  1086. // for _, item := range splitStr {
  1087. // for _,it := range mation{
  1088. // if(item == it.SpecificationName){
  1089. //
  1090. // //查询最近一次的透析器
  1091. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1092. //
  1093. // if errcode == gorm.ErrRecordNotFound{
  1094. // //插入数据
  1095. // prepare := models.DialysisBeforePrepare{
  1096. // UserOrgId: adminUserInfo.Org.Id,
  1097. // PatientId: id,
  1098. // RecordDate: recordDate.Unix(),
  1099. // GoodTypeId: it.GoodTypeId,
  1100. // GoodId: it.ID,
  1101. // Count: 1,
  1102. // Ctime: time.Now().Unix(),
  1103. // Creater: adminUserInfo.AdminUser.Id,
  1104. // Status:1,
  1105. //
  1106. // }
  1107. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1108. // fmt.Println("",errcode)
  1109. // }
  1110. // }
  1111. // }
  1112. //
  1113. // }
  1114. //
  1115. // for _, item := range splitIrrigation {
  1116. // for _,it := range mation{
  1117. // if(item == it.SpecificationName){
  1118. // //查询最近一次的透析器
  1119. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  1120. // if errcode == gorm.ErrRecordNotFound{
  1121. // //插入数据
  1122. // prepare := models.DialysisBeforePrepare{
  1123. // UserOrgId: adminUserInfo.Org.Id,
  1124. // PatientId: id,
  1125. // RecordDate: recordDate.Unix(),
  1126. // GoodTypeId: it.GoodTypeId,
  1127. // GoodId: it.ID,
  1128. // Count: 1,
  1129. // Ctime: time.Now().Unix(),
  1130. // Creater: adminUserInfo.AdminUser.Id,
  1131. // Status:1,
  1132. //
  1133. // }
  1134. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  1135. // fmt.Println(errcode)
  1136. // }
  1137. // }
  1138. // }
  1139. // }
  1140. //}
  1141. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1142. if dialysisPrescription.ID == 0 { //新增
  1143. //if mode_id > 0 {
  1144. // //service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1145. //}
  1146. if appRole.UserType == 2 || appRole.UserType == 1 {
  1147. prescription.PrescriptionDoctor = adminUserInfo.AdminUser.Id
  1148. }
  1149. prescription.Creater = adminUserInfo.AdminUser.Id
  1150. err := service.AddSigleRecord(&prescription)
  1151. if err == nil {
  1152. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1153. if updateErr != nil {
  1154. utils.ErrorLog("%v", updateErr)
  1155. }
  1156. c.ServeSuccessJSON(map[string]interface{}{
  1157. "prescription": prescription,
  1158. })
  1159. }
  1160. } else { //修改
  1161. //if mode_id > 0 {
  1162. // service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1163. //}
  1164. //if template.TemplateId == 1 {
  1165. // if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater != 0 {
  1166. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1167. // if getPermissionErr != nil {
  1168. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1169. // return
  1170. // } else if headNursePermission == nil {
  1171. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1172. // return
  1173. // }
  1174. // }
  1175. //}
  1176. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1177. prescription.Modifier = adminUserInfo.AdminUser.Id
  1178. if appRole.UserType == 2 || appRole.UserType == 1 {
  1179. prescription_doctor := adminUserInfo.AdminUser.Id
  1180. prescription.PrescriptionDoctor = prescription_doctor
  1181. } else {
  1182. prescription.PrescriptionDoctor = dialysisPrescription.PrescriptionDoctor
  1183. }
  1184. if dialysisPrescription.Creater == 0 { //体重称
  1185. prescription.Creater = adminUserInfo.AdminUser.Id
  1186. } else {
  1187. prescription.Creater = dialysisPrescription.Creater
  1188. }
  1189. prescription.ID = dialysisPrescription.ID
  1190. err := service.UpDateDialysisPrescription(&prescription)
  1191. if err == nil {
  1192. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1193. if updateErr != nil {
  1194. utils.ErrorLog("%v", updateErr)
  1195. }
  1196. c.ServeSuccessJSON(map[string]interface{}{
  1197. "prescription": prescription,
  1198. })
  1199. }
  1200. }
  1201. }
  1202. func (c *DialysisAPIController) Finish() {
  1203. id, _ := c.GetInt64("patient", 0)
  1204. recordDateStr := c.GetString("record_date")
  1205. nurseID, _ := c.GetInt64("nurse")
  1206. end_time := c.GetString("end_time")
  1207. if id <= 0 || nurseID <= 0 {
  1208. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1209. return
  1210. }
  1211. adminUserInfo := c.GetMobileAdminUserInfo()
  1212. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1213. if patient.ID == 0 {
  1214. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1215. return
  1216. }
  1217. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1218. if getNurseErr != nil {
  1219. c.ErrorLog("获取护士失败:%v", getNurseErr)
  1220. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1221. return
  1222. } else if nurse == nil {
  1223. c.ErrorLog("护士不存在")
  1224. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1225. return
  1226. }
  1227. if len(recordDateStr) == 0 {
  1228. recordDateStr = time.Now().Format("2006-01-02")
  1229. }
  1230. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1231. if parseDateErr != nil {
  1232. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1233. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1234. return
  1235. }
  1236. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  1237. if parseEndDateErr != nil {
  1238. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  1239. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1240. return
  1241. }
  1242. //now := time.Now()
  1243. //year, month, day := now.Date()
  1244. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  1245. //todayTimeStamp := today_time.Unix()
  1246. // 获取当天的第一条透析纪录
  1247. fmonitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecordFirst(adminUserInfo.Org.Id, id, recordDate.Unix())
  1248. if getMonitorRecordsErr != nil {
  1249. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1250. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1251. return
  1252. }
  1253. // 获取当前的最后一条透析纪录
  1254. endmonitorRecords, getMonitorRecordsErr := service.MobileGetLastMonitorRecord(adminUserInfo.Org.Id, id, recordDate.Unix())
  1255. if getMonitorRecordsErr != nil {
  1256. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1257. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1258. return
  1259. }
  1260. fmt.Println(endmonitorRecords.UltrafiltrationVolume)
  1261. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1262. if getAADErr != nil {
  1263. c.ErrorLog("获取透后评估失败:%v", getAADErr)
  1264. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1265. return
  1266. }
  1267. lastAssessmentAfterDislysis, _ := service.MobileGetLastTimeAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1268. _, dialysisOrder := service.FindDialysisRecordById(adminUserInfo.Org.Id, id, recordDate.Unix())
  1269. var tempassessmentAfterDislysis models.AssessmentAfterDislysis
  1270. if assessmentAfterDislysis != nil {
  1271. tempassessmentAfterDislysis = *assessmentAfterDislysis
  1272. tempassessmentAfterDislysis.UpdatedTime = time.Now().Unix()
  1273. } else {
  1274. tempassessmentAfterDislysis.CreatedTime = time.Now().Unix()
  1275. tempassessmentAfterDislysis.AssessmentDate = recordDate.Unix()
  1276. tempassessmentAfterDislysis.Status = 1
  1277. tempassessmentAfterDislysis.PatientId = id
  1278. tempassessmentAfterDislysis.UserOrgId = adminUserInfo.Org.Id
  1279. }
  1280. if dialysisOrder.Stage == 1 {
  1281. temp_time := (float64(endDate.Unix()) - float64(dialysisOrder.StartTime)) / 3600
  1282. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  1283. fmt.Println(value)
  1284. a, b := math.Modf(value)
  1285. c, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  1286. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  1287. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", c*60), 10, 64)
  1288. fmt.Println(hour)
  1289. fmt.Println(minute)
  1290. tempassessmentAfterDislysis.ActualTreatmentHour = hour
  1291. tempassessmentAfterDislysis.ActualTreatmentMinute = minute
  1292. }
  1293. if fmonitorRecords.ID > 0 && endmonitorRecords.ID > 0 {
  1294. //var num1 int64
  1295. //num1 = endmonitorRecords.OperateTime - fmonitorRecords.OperateTime
  1296. //fmt.Println(num1)
  1297. //sub := float64(num1 / 3600)
  1298. //fmt.Println(sub)
  1299. //tempassessmentAfterDislysis.ActualTreatmentHour = int64(math.Floor(sub))
  1300. //sub2 := float64(((endmonitorRecords.OperateTime - fmonitorRecords.OperateTime) % 3600) / 60)
  1301. //tempassessmentAfterDislysis.ActualTreatmentMinute = int64(math.Floor(sub2))
  1302. tempassessmentAfterDislysis.Temperature = endmonitorRecords.Temperature
  1303. tempassessmentAfterDislysis.PulseFrequency = endmonitorRecords.PulseFrequency
  1304. tempassessmentAfterDislysis.BreathingRate = endmonitorRecords.BreathingRate
  1305. tempassessmentAfterDislysis.SystolicBloodPressure = endmonitorRecords.SystolicBloodPressure
  1306. tempassessmentAfterDislysis.DiastolicBloodPressure = endmonitorRecords.DiastolicBloodPressure
  1307. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1308. tempassessmentAfterDislysis.ActualDisplacement = endmonitorRecords.DisplacementQuantity
  1309. }
  1310. if adminUserInfo.Org.Id == 10101 || adminUserInfo.Org.Id == 9671 || adminUserInfo.Org.Id == 3877 {
  1311. fmt.Println("进来了麻豆腐阿方阿道夫阿道夫阿方阿道夫阿方阿凡达阿方阿凡达阿方阿的萨凡阿方阿斯顿发阿的萨凡阿的萨凡阿凡达")
  1312. evaluation, _ := service.MobileGetPredialysisEvaluation(adminUserInfo.Org.Id, id, recordDate.Unix())
  1313. if evaluation.SystolicBloodPressure == 0 {
  1314. evaluation.SystolicBloodPressure = fmonitorRecords.SystolicBloodPressure
  1315. pre := models.PredialysisEvaluation{
  1316. SystolicBloodPressure: evaluation.SystolicBloodPressure,
  1317. }
  1318. fmt.Println("prewe232323232322323232323", pre)
  1319. getNurseErr := service.UpdatePredialysisEvaluation(&pre, evaluation.ID)
  1320. fmt.Println(getNurseErr)
  1321. }
  1322. if evaluation.DiastolicBloodPressure == 0 {
  1323. evaluation.DiastolicBloodPressure = fmonitorRecords.DiastolicBloodPressure
  1324. pres := models.PredialysisEvaluation{
  1325. DiastolicBloodPressure: evaluation.DiastolicBloodPressure,
  1326. }
  1327. getNurseErr := service.UpdatePredialysisEvaluationTwo(&pres, evaluation.ID)
  1328. fmt.Println(getNurseErr)
  1329. }
  1330. if evaluation.PulseFrequency == 0 {
  1331. evaluation.PulseFrequency = fmonitorRecords.PulseFrequency
  1332. press := models.PredialysisEvaluation{
  1333. PulseFrequency: evaluation.PulseFrequency,
  1334. }
  1335. getNurseErr := service.UpdatePredialysisEvaluationThree(&press, evaluation.ID)
  1336. fmt.Println(getNurseErr)
  1337. }
  1338. }
  1339. if adminUserInfo.Org.Id == 9583 {
  1340. //获取透析处方的最后一条数据
  1341. diaPrescription, diaerr := service.GetLastDialysisPrescriptionByPatientId(adminUserInfo.Org.Id, id, recordDate.Unix())
  1342. if diaerr != nil {
  1343. c.ErrorLog("获取透析处方失败:%v", diaerr)
  1344. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1345. return
  1346. }
  1347. if diaPrescription.ID > 0 && adminUserInfo.Org.Id == 9583 {
  1348. tempassessmentAfterDislysis.ActualUltrafiltration = diaPrescription.TargetUltrafiltration
  1349. }
  1350. }
  1351. if endmonitorRecords.ID > 0 && adminUserInfo.Org.Id == 10060 {
  1352. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1353. }
  1354. if lastAssessmentAfterDislysis != nil {
  1355. tempassessmentAfterDislysis.BloodPressureType = lastAssessmentAfterDislysis.BloodPressureType
  1356. tempassessmentAfterDislysis.WeighingWay = lastAssessmentAfterDislysis.WeighingWay
  1357. tempassessmentAfterDislysis.Cruor = lastAssessmentAfterDislysis.Cruor
  1358. tempassessmentAfterDislysis.SymptomAfterDialysis = lastAssessmentAfterDislysis.SymptomAfterDialysis
  1359. tempassessmentAfterDislysis.InternalFistula = lastAssessmentAfterDislysis.InternalFistula
  1360. tempassessmentAfterDislysis.Catheter = lastAssessmentAfterDislysis.Catheter
  1361. tempassessmentAfterDislysis.Complication = lastAssessmentAfterDislysis.Complication
  1362. tempassessmentAfterDislysis.DialysisIntakes = lastAssessmentAfterDislysis.DialysisIntakes
  1363. tempassessmentAfterDislysis.DialysisIntakesFeed = lastAssessmentAfterDislysis.DialysisIntakesFeed
  1364. tempassessmentAfterDislysis.DialysisIntakesTransfusion = lastAssessmentAfterDislysis.DialysisIntakesTransfusion
  1365. tempassessmentAfterDislysis.DialysisIntakesBloodTransfusion = lastAssessmentAfterDislysis.DialysisIntakesBloodTransfusion
  1366. tempassessmentAfterDislysis.DialysisIntakesWashpipe = lastAssessmentAfterDislysis.DialysisIntakesWashpipe
  1367. tempassessmentAfterDislysis.BloodAccessPartId = lastAssessmentAfterDislysis.BloodAccessPartId
  1368. tempassessmentAfterDislysis.BloodAccessPartOperaId = lastAssessmentAfterDislysis.BloodAccessPartOperaId
  1369. tempassessmentAfterDislysis.PuncturePointOozingBlood = lastAssessmentAfterDislysis.PuncturePointOozingBlood
  1370. tempassessmentAfterDislysis.PuncturePointHaematoma = lastAssessmentAfterDislysis.PuncturePointHaematoma
  1371. tempassessmentAfterDislysis.InternalFistulaTremorAc = lastAssessmentAfterDislysis.InternalFistulaTremorAc
  1372. tempassessmentAfterDislysis.PatientGose = lastAssessmentAfterDislysis.PatientGose
  1373. tempassessmentAfterDislysis.InpatientDepartment = lastAssessmentAfterDislysis.InpatientDepartment
  1374. tempassessmentAfterDislysis.ObservationContent = lastAssessmentAfterDislysis.ObservationContent
  1375. tempassessmentAfterDislysis.ObservationContentOther = lastAssessmentAfterDislysis.ObservationContentOther
  1376. tempassessmentAfterDislysis.DryWeight = lastAssessmentAfterDislysis.DryWeight
  1377. tempassessmentAfterDislysis.DialysisProcess = lastAssessmentAfterDislysis.DialysisProcess
  1378. tempassessmentAfterDislysis.InAdvanceMinute = lastAssessmentAfterDislysis.InAdvanceMinute
  1379. tempassessmentAfterDislysis.InAdvanceReason = lastAssessmentAfterDislysis.InAdvanceReason
  1380. tempassessmentAfterDislysis.HemostasisMinute = lastAssessmentAfterDislysis.HemostasisMinute
  1381. tempassessmentAfterDislysis.HemostasisOpera = lastAssessmentAfterDislysis.HemostasisOpera
  1382. tempassessmentAfterDislysis.TremorNoise = lastAssessmentAfterDislysis.TremorNoise
  1383. tempassessmentAfterDislysis.DisequilibriumSyndrome = lastAssessmentAfterDislysis.DisequilibriumSyndrome
  1384. tempassessmentAfterDislysis.DisequilibriumSyndromeOption = lastAssessmentAfterDislysis.DisequilibriumSyndromeOption
  1385. tempassessmentAfterDislysis.ArterialTube = lastAssessmentAfterDislysis.ArterialTube
  1386. tempassessmentAfterDislysis.IntravenousTube = lastAssessmentAfterDislysis.IntravenousTube
  1387. tempassessmentAfterDislysis.Dialyzer = lastAssessmentAfterDislysis.Dialyzer
  1388. tempassessmentAfterDislysis.InAdvanceReasonOther = lastAssessmentAfterDislysis.InAdvanceReasonOther
  1389. tempassessmentAfterDislysis.IsEat = lastAssessmentAfterDislysis.IsEat
  1390. tempassessmentAfterDislysis.DialysisIntakesUnit = lastAssessmentAfterDislysis.DialysisIntakesUnit
  1391. tempassessmentAfterDislysis.CvcA = lastAssessmentAfterDislysis.CvcA
  1392. tempassessmentAfterDislysis.CvcV = lastAssessmentAfterDislysis.CvcV
  1393. tempassessmentAfterDislysis.Channel = lastAssessmentAfterDislysis.Channel
  1394. tempassessmentAfterDislysis.ReturnBlood = lastAssessmentAfterDislysis.ReturnBlood
  1395. tempassessmentAfterDislysis.RehydrationVolume = lastAssessmentAfterDislysis.RehydrationVolume
  1396. tempassessmentAfterDislysis.DialysisDuring = lastAssessmentAfterDislysis.DialysisDuring
  1397. tempassessmentAfterDislysis.StrokeVolume = lastAssessmentAfterDislysis.StrokeVolume
  1398. tempassessmentAfterDislysis.BloodFlow = lastAssessmentAfterDislysis.BloodFlow
  1399. tempassessmentAfterDislysis.SealingFluidDispose = lastAssessmentAfterDislysis.SealingFluidDispose
  1400. tempassessmentAfterDislysis.SealingFluidSpecial = lastAssessmentAfterDislysis.SealingFluidSpecial
  1401. }
  1402. err := service.UpdateAssessmentAfterDislysisRecord(&tempassessmentAfterDislysis)
  1403. if err != nil {
  1404. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1405. return
  1406. }
  1407. if dialysisOrder == nil {
  1408. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoStart)
  1409. return
  1410. }
  1411. if dialysisOrder.Stage == 2 {
  1412. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoEND)
  1413. return
  1414. }
  1415. if dialysisOrder.Stage == 1 {
  1416. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id)
  1417. //结束时候透析次数加1
  1418. service.UpdateSolutionByPatientId(id)
  1419. dialysisOrder.Stage = 2
  1420. dialysisOrder.FinishNurse = nurseID
  1421. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1422. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1423. dialysisOrder.EndTime = endDate.Unix()
  1424. go func() {
  1425. ssoDomain := beego.AppConfig.String("call_domain")
  1426. api := ssoDomain + "/index/downpatient"
  1427. values := make(url.Values)
  1428. values.Set("org_id", strconv.FormatInt(adminUserInfo.AdminUser.Id, 10))
  1429. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1430. values.Set("patient_id", strconv.FormatInt(id, 10))
  1431. http.PostForm(api, values)
  1432. }()
  1433. if err == nil {
  1434. c.ServeSuccessJSON(map[string]interface{}{
  1435. "dialysisOrder": dialysisOrder,
  1436. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1437. })
  1438. } else {
  1439. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1440. }
  1441. }
  1442. }
  1443. func (c *DialysisAPIController) GetAllZone() {
  1444. adminUserInfo := c.GetMobileAdminUserInfo()
  1445. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1446. if err == nil {
  1447. c.ServeSuccessJSON(map[string]interface{}{
  1448. "zone": zone,
  1449. })
  1450. }
  1451. }
  1452. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1453. adminUserInfo := c.GetMobileAdminUserInfo()
  1454. page, _ := c.GetInt64("page", 1)
  1455. limit, _ := c.GetInt64("limit", 10)
  1456. schedulType, _ := c.GetInt64("schedul_type", 0)
  1457. startTime, _ := c.GetInt64("schedul_time", 0)
  1458. partitionType, _ := c.GetInt64("partition_type", 0)
  1459. keywords := c.GetString("keywords")
  1460. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1461. if err == nil {
  1462. c.ServeSuccessJSON(map[string]interface{}{
  1463. "schedule": dialysisSchedule,
  1464. })
  1465. }
  1466. return
  1467. }
  1468. // /m/api/dialysis/start [post]
  1469. // @param patient_id:int
  1470. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1471. // @param nurse:int 上机护士
  1472. // @param bed:int 床位号
  1473. func (this *DialysisAPIController) StartDialysis() {
  1474. patientID, _ := this.GetInt64("patient_id")
  1475. recordDateStr := this.GetString("record_date")
  1476. nurseID, _ := this.GetInt64("nurse")
  1477. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1478. blood_drawing, _ := this.GetInt64("blood_drawing")
  1479. schedual_type, _ := this.GetInt64("schedual_type")
  1480. bedID, _ := this.GetInt64("bed")
  1481. start_time := this.GetString("start_time")
  1482. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1483. change_nurse, _ := this.GetInt64("change_nurse")
  1484. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  1485. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  1486. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1487. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1488. return
  1489. }
  1490. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1491. if parseStartDateErr != nil {
  1492. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1493. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1494. return
  1495. }
  1496. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1497. if parseErr != nil {
  1498. this.ErrorLog("时间解析失败:%v", parseErr)
  1499. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1500. return
  1501. }
  1502. adminUserInfo := this.GetMobileAdminUserInfo()
  1503. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1504. if getPatientErr != nil {
  1505. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1506. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1507. return
  1508. } else if patient == nil {
  1509. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1510. return
  1511. }
  1512. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1513. if getNurseErr != nil {
  1514. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1515. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1516. return
  1517. } else if nurse == nil {
  1518. this.ErrorLog("护士不存在")
  1519. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1520. return
  1521. }
  1522. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1523. //if getNurseErr != nil {
  1524. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  1525. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1526. // return
  1527. //} else if nurse == nil {
  1528. // this.ErrorLog("护士不存在")
  1529. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1530. // return
  1531. //}
  1532. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1533. if getDeviceNumberErr != nil {
  1534. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1535. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1536. return
  1537. } else if deviceNumber == nil {
  1538. this.ErrorLog("床位号不存在")
  1539. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1540. return
  1541. }
  1542. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1543. if getRecordErr != nil {
  1544. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1545. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1546. return
  1547. } else if dialysisRecord != nil {
  1548. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1549. return
  1550. }
  1551. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1552. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1553. timeLayout := "2006-01-02 15:04:05"
  1554. loc, _ := time.LoadLocation("Local")
  1555. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1556. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1557. schedulestartTime := theStartTime.Unix()
  1558. scheduleendTime := theEndTime.Unix()
  1559. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1560. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1561. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1562. //查询该床位是否有人用了
  1563. order, order_err := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1564. if err == gorm.ErrRecordNotFound { //空床位
  1565. // 修改了床位逻辑
  1566. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1567. if daySchedule.ID > 0 {
  1568. daySchedule.PartitionId = deviceNumber.ZoneID
  1569. daySchedule.BedId = bedID
  1570. daySchedule.ScheduleType = schedual_type
  1571. daySchedule.UpdatedTime = time.Now().Unix()
  1572. err := service.UpdateSchedule(&daySchedule)
  1573. if err != nil {
  1574. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1575. return
  1576. }
  1577. }
  1578. } else if err == nil {
  1579. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1580. if order_err == nil {
  1581. if order.ID > 0 { //该机位被其他人占用了
  1582. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1583. return
  1584. } else {
  1585. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1586. if daySchedule.ID > 0 {
  1587. daySchedule.PartitionId = deviceNumber.ZoneID
  1588. daySchedule.BedId = bedID
  1589. daySchedule.ScheduleType = schedual_type
  1590. daySchedule.UpdatedTime = time.Now().Unix()
  1591. err := service.UpdateSchedule(&daySchedule)
  1592. if err != nil {
  1593. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1594. return
  1595. }
  1596. }
  1597. }
  1598. } else if order_err == gorm.ErrRecordNotFound { //该床位没被占用
  1599. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1600. if daySchedule.ID > 0 {
  1601. daySchedule.PartitionId = deviceNumber.ZoneID
  1602. daySchedule.BedId = bedID
  1603. daySchedule.ScheduleType = schedual_type
  1604. daySchedule.UpdatedTime = time.Now().Unix()
  1605. err := service.UpdateSchedule(&daySchedule)
  1606. if err != nil {
  1607. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1608. return
  1609. }
  1610. }
  1611. }
  1612. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1613. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1614. return
  1615. }
  1616. } else if err != nil {
  1617. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1618. return
  1619. }
  1620. dialysisRecord = &models.DialysisOrder{
  1621. DialysisDate: recordDate.Unix(),
  1622. UserOrgId: adminUserInfo.Org.Id,
  1623. PatientId: patientID,
  1624. Stage: 1,
  1625. BedID: bedID,
  1626. StartNurse: nurseID,
  1627. Status: 1,
  1628. StartTime: startDate.Unix(),
  1629. CreatedTime: time.Now().Unix(),
  1630. UpdatedTime: time.Now().Unix(),
  1631. PunctureNurse: puncture_nurse,
  1632. Creator: adminUserInfo.AdminUser.Id,
  1633. Modifier: adminUserInfo.AdminUser.Id,
  1634. SchedualType: schedual_type,
  1635. WashpipeNurse: washpipe_nurse,
  1636. ChangeNurse: change_nurse,
  1637. DifficultPunctureNurse: difficult_puncture_nurse,
  1638. NewFistulaNurse: new_fistula_nurse,
  1639. }
  1640. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  1641. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1642. var tempdispose string
  1643. // 只针对中能建
  1644. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  1645. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  1646. }
  1647. var ultrafiltration_rate float64
  1648. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1649. //后期预增脱水量
  1650. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1651. fmt.Println(evaluation)
  1652. if prescription.ID > 0 {
  1653. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1654. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1655. if (template.TemplateId == 6 || template.TemplateId == 32) && adminUserInfo.Org.Id != 9671 { //adminUserInfo.Org.Id == 9538
  1656. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1657. }
  1658. //针对医师汇
  1659. if template.TemplateId == 6 && adminUserInfo.Org.Id == 9671 {
  1660. dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  1661. ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  1662. }
  1663. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  1664. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1665. }
  1666. // 只针对方济医院
  1667. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  1668. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1669. ultrafiltration_rate = value
  1670. }
  1671. }
  1672. }
  1673. record := models.MonitoringRecord{
  1674. UserOrgId: adminUserInfo.Org.Id,
  1675. PatientId: patientID,
  1676. DialysisOrderId: dialysisRecord.ID,
  1677. MonitoringDate: schedulestartTime,
  1678. OperateTime: startDate.Unix(),
  1679. // MonitoringTime: recordTime,
  1680. MonitoringNurse: nurseID,
  1681. Dispose: tempdispose,
  1682. UltrafiltrationRate: ultrafiltration_rate,
  1683. UltrafiltrationVolume: 0,
  1684. Status: 1,
  1685. CreatedTime: time.Now().Unix(),
  1686. UpdatedTime: time.Now().Unix(),
  1687. }
  1688. //只针对广慈医院
  1689. if template.TemplateId == 26 || template.TemplateId == 25 || template.TemplateId == 28 || adminUserInfo.Org.Id == 9987 || adminUserInfo.Org.Id == 9526 || template.TemplateId == 32 {
  1690. // 查询病人是否有透前评估数据
  1691. befor, errcode := service.GetAssessmentBefor(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1692. //如果有数据就插入
  1693. if errcode == nil {
  1694. record.SystolicBloodPressure = befor.SystolicBloodPressure
  1695. record.DiastolicBloodPressure = befor.DiastolicBloodPressure
  1696. record.BreathingRate = befor.BreathingRate
  1697. record.PulseFrequency = befor.PulseFrequency
  1698. record.Temperature = befor.Temperature
  1699. }
  1700. }
  1701. // 如果当天有插入数据,则不再往透析纪录里插入数据
  1702. if newdialysisRecord.ID > 0 {
  1703. err := service.CreateMonitor(&record)
  1704. if err != nil {
  1705. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  1706. return
  1707. }
  1708. }
  1709. go func() {
  1710. ssoDomain := beego.AppConfig.String("call_domain")
  1711. api := ssoDomain + "/index/uppatient"
  1712. values := make(url.Values)
  1713. values.Set("org_id", strconv.FormatInt(adminUserInfo.Org.Id, 10))
  1714. values.Set("admin_user_id", strconv.FormatInt(nurseID, 10))
  1715. values.Set("patient_id", strconv.FormatInt(patientID, 10))
  1716. values.Set("up_time", strconv.FormatInt(startDate.Unix(), 10))
  1717. http.PostForm(api, values)
  1718. }()
  1719. if createErr != nil {
  1720. this.ErrorLog("上机失败:%v", createErr)
  1721. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1722. return
  1723. }
  1724. this.ServeSuccessJSON(map[string]interface{}{
  1725. "dialysis_order": newdialysisRecord,
  1726. "monitor": record,
  1727. })
  1728. }
  1729. func (c *DialysisAPIController) PostSolution() {
  1730. id, _ := c.GetInt64("patient", 0)
  1731. recordDateStr := c.GetString("record_date")
  1732. if id <= 0 {
  1733. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1734. return
  1735. }
  1736. adminUserInfo := c.GetMobileAdminUserInfo()
  1737. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1738. if patient.ID == 0 {
  1739. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1740. return
  1741. }
  1742. if len(recordDateStr) == 0 {
  1743. recordDateStr = time.Now().Format("2006-01-02")
  1744. }
  1745. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1746. if parseDateErr != nil {
  1747. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1748. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1749. return
  1750. }
  1751. mode_id, _ := c.GetInt64("mode_id", 0)
  1752. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1753. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1754. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1755. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1756. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1757. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1758. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1759. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1760. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1761. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1762. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1763. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1764. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1765. kalium, _ := c.GetFloat("kalium", 0)
  1766. sodium, _ := c.GetFloat("sodium", 0)
  1767. calcium, _ := c.GetFloat("calcium", 0)
  1768. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1769. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1770. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1771. glucose, _ := c.GetFloat("glucose", 0)
  1772. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1773. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1774. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1775. conductivity, _ := c.GetFloat("conductivity", 0)
  1776. remark := c.GetString("remark")
  1777. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1778. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1779. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1780. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1781. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1782. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1783. special_medicine_other := c.GetString("special_medicine_other")
  1784. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1785. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1786. blood_access, _ := c.GetInt64("blood_access", 0)
  1787. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1788. body_fluid_other := c.GetString("body_fluid_other")
  1789. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1790. niprocart, _ := c.GetInt64("niprocart", 0)
  1791. jms, _ := c.GetInt64("jms", 0)
  1792. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1793. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1794. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1795. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1796. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1797. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1798. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1799. injector, _ := c.GetInt64("injector", 0)
  1800. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1801. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1802. safe_package, _ := c.GetInt64("package", 0)
  1803. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1804. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1805. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1806. blood := c.GetString("blood")
  1807. dialysis_dialyszers := c.GetString("dialysis_dialyszers")
  1808. dialysis_irrigation := c.GetString("dialysis_irrigation")
  1809. antioxidant_commodity_name := c.GetString("antioxidant_commodity_name")
  1810. displace_speed := c.GetString("displace_speed")
  1811. illness, _ := c.GetInt64("illness")
  1812. amylaceum := c.GetString("amylaceum")
  1813. single_time := c.GetString("single_time")
  1814. single_water := c.GetString("single_water")
  1815. replacement_flow := c.GetString("replacement_flow")
  1816. plasma_separator := c.GetString("plasma_separator")
  1817. bilirubin_adsorption_column := c.GetString("bilirubin_adsorption_column")
  1818. oxygen_uptake, _ := c.GetInt64("oxygen_uptake")
  1819. oxygen_flow := c.GetString("oxygen_flow")
  1820. oxygen_time := c.GetString("oxygen_time")
  1821. hemodialysis_pipelines := c.GetString("hemodialysis_pipelines")
  1822. hemodialysis_pipelines_count, _ := c.GetFloat("hemodialysis_pipelines_count", 0)
  1823. puncture_needle := c.GetString("puncture_needle")
  1824. puncture_needle_count, _ := c.GetFloat("puncture_needle_count", 0)
  1825. epo := c.GetString("epo")
  1826. epo_count, _ := c.GetFloat("epo_count", 0)
  1827. if mode_id > 0 {
  1828. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1829. }
  1830. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1831. //
  1832. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1833. // if appRole.UserType == 3 {
  1834. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1835. // if getPermissionErr != nil {
  1836. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1837. // return
  1838. // } else if headNursePermission == nil {
  1839. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1840. // return
  1841. // }
  1842. // }
  1843. //}
  1844. prescription := models.DialysisPrescription{
  1845. UserOrgId: adminUserInfo.Org.Id,
  1846. PatientId: id,
  1847. RecordDate: recordDate.Unix(),
  1848. ModeId: mode_id,
  1849. DialysisDuration: dialysis_duration,
  1850. Dialyzer: dialyzer,
  1851. PerfusionApparatus: perfusion_apparatus,
  1852. BloodFlowVolume: blood_flow_volume,
  1853. DewaterAmount: dewater_amount,
  1854. DisplaceLiqui: displace_liqui,
  1855. ReplacementWay: replacement_way,
  1856. Anticoagulant: anticoagulant,
  1857. AnticoagulantShouji: anticoagulant_shouji,
  1858. AnticoagulantWeichi: anticoagulant_weichi,
  1859. AnticoagulantZongliang: anticoagulant_zongliang,
  1860. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1861. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1862. Kalium: kalium,
  1863. Sodium: sodium,
  1864. Calcium: calcium,
  1865. Bicarbonate: bicarbonate,
  1866. Glucose: glucose,
  1867. // DryWeight: dry_weight,
  1868. DialysateFlow: dialysate_flow,
  1869. DialysateTemperature: dialysate_temperature,
  1870. Conductivity: conductivity,
  1871. Remark: remark,
  1872. Status: 1,
  1873. CreatedTime: time.Now().Unix(),
  1874. UpdatedTime: time.Now().Unix(),
  1875. DialysisDurationMinute: dialysisDurationMinute,
  1876. DialysisDurationHour: dialysisDurationHour,
  1877. TargetUltrafiltration: targetUltrafiltration,
  1878. DialysateFormulation: dialysateFormulation,
  1879. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1880. BodyFluid: body_fluid,
  1881. SpecialMedicine: special_medicine,
  1882. SpecialMedicineOther: special_medicine_other,
  1883. DisplaceLiquiPart: displace_liqui_part,
  1884. DisplaceLiquiValue: displace_liqui_value,
  1885. BloodAccess: blood_access,
  1886. Ultrafiltration: ultrafiltration,
  1887. BodyFluidOther: body_fluid_other,
  1888. ReplacementTotal: replacement_total,
  1889. Niprocart: niprocart,
  1890. Jms: jms,
  1891. FistulaNeedleSet: fistula_needle_set,
  1892. FistulaNeedleSet16: fistula_needle_set_16,
  1893. Hemoperfusion: hemoperfusion,
  1894. DialyserSterilised: dialyser_sterilised,
  1895. Filtryzer: filtryzer,
  1896. TargetKtv: target_ktv,
  1897. Dialyzers: dialyzers,
  1898. Injector: injector,
  1899. Bloodlines: bloodlines,
  1900. TubingHemodialysis: tubing_hemodialysis,
  1901. Package: safe_package,
  1902. ALiquid: a_liquid,
  1903. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1904. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1905. Blood: blood,
  1906. DialysisDialyszers: dialysis_dialyszers,
  1907. DialysisIrrigation: dialysis_irrigation,
  1908. AntioxidantCommodityName: antioxidant_commodity_name,
  1909. DisplaceSpeed: displace_speed,
  1910. Illness: illness,
  1911. Amylaceum: amylaceum,
  1912. SingleWater: single_water,
  1913. SingleTime: single_time,
  1914. ReplacementFlow: replacement_flow,
  1915. PlasmaSeparator: plasma_separator,
  1916. BilirubinAdsorptionColumn: bilirubin_adsorption_column,
  1917. OxygenUptake: oxygen_uptake,
  1918. OxygenTime: oxygen_time,
  1919. OxygenFlow: oxygen_flow,
  1920. HemodialysisPipelines: hemodialysis_pipelines,
  1921. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  1922. PunctureNeedle: puncture_needle,
  1923. PunctureNeedleCount: puncture_needle_count,
  1924. Epo: epo,
  1925. EpoCount: epo_count,
  1926. }
  1927. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1928. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1929. //
  1930. if appRole.UserType == 2 || appRole.UserType == 1 {
  1931. prescription_doctor = adminUserInfo.AdminUser.Id
  1932. prescription.PrescriptionDoctor = prescription_doctor
  1933. }
  1934. if dialysisPrescription.ID == 0 { //新增
  1935. prescription.Creater = adminUserInfo.AdminUser.Id
  1936. } else { //修改
  1937. if dialysisPrescription.Creater == 0 {
  1938. prescription.Creater = adminUserInfo.AdminUser.Id
  1939. } else {
  1940. prescription.Creater = dialysisPrescription.Creater
  1941. }
  1942. //if/**/
  1943. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1944. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  1945. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1946. // if getPermissionErr != nil {
  1947. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1948. // return
  1949. // } else if headNursePermission == nil {
  1950. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1951. // return
  1952. // }
  1953. //}
  1954. //prescription.Creater = dialysisPrescription.Creater
  1955. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1956. prescription.Modifier = adminUserInfo.AdminUser.Id
  1957. prescription.ID = dialysisPrescription.ID
  1958. }
  1959. solution := models.DialysisSolution{
  1960. RegistrarsId: adminUserInfo.AdminUser.Id,
  1961. UserOrgId: adminUserInfo.Org.Id,
  1962. Doctor: prescription_doctor,
  1963. PatientId: id,
  1964. ModeId: mode_id,
  1965. DialysisDuration: dialysis_duration,
  1966. PerfusionApparatus: perfusion_apparatus,
  1967. BloodFlowVolume: blood_flow_volume,
  1968. Dewater: dewater_amount,
  1969. DisplaceLiqui: displace_liqui,
  1970. ReplacementWay: replacement_way,
  1971. Anticoagulant: anticoagulant,
  1972. AnticoagulantShouji: anticoagulant_shouji,
  1973. AnticoagulantWeichi: anticoagulant_weichi,
  1974. AnticoagulantZongliang: anticoagulant_zongliang,
  1975. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1976. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1977. Kalium: kalium,
  1978. Sodium: sodium,
  1979. Calcium: calcium,
  1980. Bicarbonate: bicarbonate,
  1981. Glucose: glucose,
  1982. // DryWeight: dry_weight,
  1983. DialysateFlow: dialysate_flow,
  1984. DialysateTemperature: dialysate_temperature,
  1985. Conductivity: conductivity,
  1986. Remark: remark,
  1987. Status: 1,
  1988. CreatedTime: time.Now().Unix(),
  1989. UpdatedTime: time.Now().Unix(),
  1990. DialysisDurationMinute: dialysisDurationMinute,
  1991. DialysisDurationHour: dialysisDurationHour,
  1992. TargetUltrafiltration: targetUltrafiltration,
  1993. DialysateFormulation: dialysateFormulation,
  1994. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1995. BodyFluid: body_fluid,
  1996. SpecialMedicine: special_medicine,
  1997. SpecialMedicineOther: special_medicine_other,
  1998. DisplaceLiquiPart: displace_liqui_part,
  1999. DisplaceLiquiValue: displace_liqui_value,
  2000. BloodAccess: blood_access,
  2001. Ultrafiltration: ultrafiltration,
  2002. BodyFluidOther: body_fluid_other,
  2003. ReplacementTotal: replacement_total,
  2004. TargetKtv: target_ktv,
  2005. DialysisDialyszers: dialysis_dialyszers,
  2006. DialysisIrrigation: dialysis_irrigation,
  2007. HemodialysisPipelines: hemodialysis_pipelines,
  2008. HemodialysisPipelinesCount: hemodialysis_pipelines_count,
  2009. PunctureNeedle: puncture_needle,
  2010. PunctureNeedleCount: puncture_needle_count,
  2011. Epo: epo,
  2012. EpoCount: epo_count,
  2013. }
  2014. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  2015. //查询最近透析准备表里是否存在 透析器 灌流器
  2016. //splitStr := strings.Split(dialysis_dialyszers, ",")
  2017. //
  2018. //splitIrrigation := strings.Split(dialysis_irrigation, ",")
  2019. //
  2020. //mation, _ := service.GetGoodInfoMation(adminUserInfo.Org.Id)
  2021. //if len(mation)>0{
  2022. // for _, item := range splitStr {
  2023. // for _,it := range mation{
  2024. // if(item == it.SpecificationName){
  2025. //
  2026. // //查询最近一次的透析器
  2027. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2028. //
  2029. // if errcode == gorm.ErrRecordNotFound{
  2030. // //插入数据
  2031. // prepare := models.DialysisBeforePrepare{
  2032. // UserOrgId: adminUserInfo.Org.Id,
  2033. // PatientId: id,
  2034. // RecordDate: recordDate.Unix(),
  2035. // GoodTypeId: it.GoodTypeId,
  2036. // GoodId: it.ID,
  2037. // Count: 1,
  2038. // Ctime: time.Now().Unix(),
  2039. // Creater: adminUserInfo.AdminUser.Id,
  2040. // Status:1,
  2041. //
  2042. // }
  2043. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2044. // fmt.Println("",errcode)
  2045. // }
  2046. // }
  2047. // }
  2048. //
  2049. // }
  2050. //
  2051. // for _, item := range splitIrrigation {
  2052. // for _,it := range mation{
  2053. // if(item == it.SpecificationName){
  2054. // //查询最近一次的透析器
  2055. // _, errcode := service.GetDialysisBeforePrepare(it.GoodTypeId, it.ID, adminUserInfo.Org.Id,id)
  2056. // if errcode == gorm.ErrRecordNotFound{
  2057. // //插入数据
  2058. // prepare := models.DialysisBeforePrepare{
  2059. // UserOrgId: adminUserInfo.Org.Id,
  2060. // PatientId: id,
  2061. // RecordDate: recordDate.Unix(),
  2062. // GoodTypeId: it.GoodTypeId,
  2063. // GoodId: it.ID,
  2064. // Count: 1,
  2065. // Ctime: time.Now().Unix(),
  2066. // Creater: adminUserInfo.AdminUser.Id,
  2067. // Status:1,
  2068. //
  2069. // }
  2070. // errcode := service.CreateDialysisBeforePrepareOne(&prepare)
  2071. // fmt.Println(errcode)
  2072. // }
  2073. // }
  2074. // }
  2075. // }
  2076. //}
  2077. c.ServeSuccessJSON(map[string]interface{}{
  2078. "solution": &solution,
  2079. "prescription": &prescription,
  2080. })
  2081. }
  2082. func (c *DialysisAPIController) GetAcceptsAssessment() {
  2083. patient, _ := c.GetInt64("patient", 0)
  2084. adminUserInfo := c.GetMobileAdminUserInfo()
  2085. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  2086. c.ServeSuccessJSON(map[string]interface{}{
  2087. "receiveTreatmentAsses": receiveTreatmentAsses,
  2088. })
  2089. }
  2090. func (this *DialysisAPIController) PostSignInfo() {
  2091. patientID, _ := this.GetInt64("patient_id")
  2092. recordDateStr := this.GetString("date")
  2093. if patientID <= 0 {
  2094. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2095. return
  2096. }
  2097. if len(recordDateStr) == 0 {
  2098. recordDateStr = time.Now().Format("2006-01-02")
  2099. }
  2100. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  2101. if parseDateErr != nil {
  2102. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  2103. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2104. return
  2105. }
  2106. adminInfo := this.GetMobileAdminUserInfo()
  2107. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  2108. if err != nil {
  2109. this.ErrorLog("签名失败:%v", err)
  2110. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2111. return
  2112. }
  2113. this.ServeSuccessJSON(map[string]interface{}{
  2114. "doctor_id": adminInfo.AdminUser.Id,
  2115. })
  2116. }
  2117. func (this *DialysisAPIController) GetLastMonitorRecord() {
  2118. patientID, _ := this.GetInt64("patient_id")
  2119. adminInfo := this.GetMobileAdminUserInfo()
  2120. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  2121. this.ServeSuccessJSON(map[string]interface{}{
  2122. "monitor": record,
  2123. })
  2124. }
  2125. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  2126. thisTime := time.Now()
  2127. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  2128. timeLayout := "2006-01-02 15:04:05"
  2129. loc, _ := time.LoadLocation("Local")
  2130. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2131. theAssessmentDateTime := theStartTime.Unix()
  2132. patientID, _ := this.GetInt64("patient_id")
  2133. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  2134. adminInfo := this.GetMobileAdminUserInfo()
  2135. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2136. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  2137. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  2138. var ultrafiltration_rate float64
  2139. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2140. _, evaluation := service.FindPredialysisEvaluationByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  2141. fmt.Println(evaluation)
  2142. if prescription.ID > 0 {
  2143. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  2144. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  2145. if template.TemplateId == 6 && adminInfo.Org.Id != 9538 {
  2146. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  2147. record.UltrafiltrationRate = ultrafiltration_rate
  2148. }
  2149. //if template.TemplateId == 6 && adminInfo.Org.Id ==9671{
  2150. // dehydration, _ := strconv.ParseFloat(evaluation.Dehydration, 64)
  2151. // ultrafiltration_rate = math.Floor((prescription.TargetUltrafiltration + dehydration) / float64(totalMin) * 60 * 1000)
  2152. // record.UltrafiltrationRate = ultrafiltration_rate
  2153. //}
  2154. if template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 {
  2155. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1)
  2156. record.UltrafiltrationRate = ultrafiltration_rate
  2157. }
  2158. if template.TemplateId == 20 || template.TemplateId == 22 {
  2159. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  2160. record.UltrafiltrationRate = ultrafiltration_rate
  2161. }
  2162. // 只针对方济医院
  2163. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  2164. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  2165. ultrafiltration_rate = value
  2166. record.UltrafiltrationRate = ultrafiltration_rate
  2167. }
  2168. if adminInfo.Org.Id == 10101 {
  2169. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration*1000/float64(totalMin)*60), 6)
  2170. ultrafiltration_rate = value
  2171. record.UltrafiltrationRate = ultrafiltration_rate
  2172. }
  2173. }
  2174. }
  2175. // record.UltrafiltrationRate = ultrafiltration_rate
  2176. record.UltrafiltrationVolume = 0
  2177. 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
  2178. if ultrafiltration_rate > 0 {
  2179. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  2180. record.UltrafiltrationVolume = value
  2181. }
  2182. }
  2183. if template.TemplateId == 6 || template.TemplateId == 20 || template.TemplateId == 22 || template.TemplateId == 32 || template.TemplateId == 34 || template.TemplateId == 36 { //adminInfo.Org.Id == 9538
  2184. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  2185. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  2186. record.UltrafiltrationVolume = ultrafiltration_volume
  2187. }
  2188. }
  2189. this.ServeSuccessJSON(map[string]interface{}{
  2190. "monitor": record,
  2191. })
  2192. }
  2193. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  2194. record_id, _ := this.GetInt64("id")
  2195. nurseID, _ := this.GetInt64("nurse")
  2196. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  2197. bedID, _ := this.GetInt64("bed")
  2198. start_time := this.GetString("start_time")
  2199. schedual_type, _ := this.GetInt64("schedual_type")
  2200. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  2201. change_nurse, _ := this.GetInt64("change_nurse")
  2202. difficult_puncture_nurse, _ := this.GetInt64("difficult_puncture_nurse")
  2203. new_fistula_nurse, _ := this.GetInt64("new_fistula_nurse")
  2204. if record_id == 0 {
  2205. this.ErrorLog("id:%v", record_id)
  2206. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2207. return
  2208. }
  2209. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  2210. if parseStartDateErr != nil {
  2211. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  2212. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2213. return
  2214. }
  2215. adminUserInfo := this.GetMobileAdminUserInfo()
  2216. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2217. if getNurseErr != nil {
  2218. this.ErrorLog("获取护士失败:%v", getNurseErr)
  2219. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2220. return
  2221. } else if nurse == nil {
  2222. this.ErrorLog("护士不存在")
  2223. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2224. return
  2225. }
  2226. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  2227. //if getNurseErr != nil {
  2228. // this.ErrorLog("获取护士失败:%v", getNurseErr)
  2229. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2230. // return
  2231. //} else if nurse == nil {
  2232. // this.ErrorLog("护士不存在")
  2233. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2234. // return
  2235. //}
  2236. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  2237. if getDeviceNumberErr != nil {
  2238. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  2239. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2240. return
  2241. } else if deviceNumber == nil {
  2242. this.ErrorLog("床位号不存在")
  2243. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2244. return
  2245. }
  2246. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  2247. //
  2248. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  2249. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2250. // if getPermissionErr != nil {
  2251. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2252. // return
  2253. // } else if headNursePermission == nil {
  2254. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2255. // return
  2256. // }
  2257. //}
  2258. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  2259. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  2260. timeLayout := "2006-01-02 15:04:05"
  2261. loc, _ := time.LoadLocation("Local")
  2262. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  2263. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  2264. schedulestartTime := theStartTime.Unix()
  2265. scheduleendTime := theEndTime.Unix()
  2266. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  2267. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  2268. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2269. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  2270. if err == gorm.ErrRecordNotFound { //空床位
  2271. // 修改了床位逻辑
  2272. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  2273. if daySchedule.ID > 0 {
  2274. daySchedule.BedId = bedID
  2275. daySchedule.PartitionId = deviceNumber.ZoneID
  2276. daySchedule.ScheduleType = schedual_type
  2277. daySchedule.UpdatedTime = time.Now().Unix()
  2278. err := service.UpdateSchedule(&daySchedule)
  2279. if err != nil {
  2280. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2281. return
  2282. }
  2283. }
  2284. } else if err == nil {
  2285. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  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 schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  2299. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  2300. return
  2301. }
  2302. } else if err != nil {
  2303. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2304. return
  2305. }
  2306. }
  2307. dialysisRecord := &models.DialysisOrder{
  2308. ID: record_id,
  2309. UserOrgId: adminUserInfo.Org.Id,
  2310. BedID: bedID,
  2311. StartNurse: nurseID,
  2312. StartTime: startDate.Unix(),
  2313. PunctureNurse: puncture_nurse,
  2314. Creator: adminUserInfo.AdminUser.Id,
  2315. Modifier: adminUserInfo.AdminUser.Id,
  2316. WashpipeNurse: washpipe_nurse,
  2317. SchedualType: schedual_type,
  2318. ChangeNurse: change_nurse,
  2319. DifficultPunctureNurse: difficult_puncture_nurse,
  2320. NewFistulaNurse: new_fistula_nurse,
  2321. }
  2322. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  2323. if updateErr != nil {
  2324. this.ErrorLog("修改上机失败:%v", updateErr)
  2325. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2326. return
  2327. }
  2328. if updateErr == nil {
  2329. if tempDialysisRecord.Stage == 2 {
  2330. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  2331. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2332. fmt.Println(value)
  2333. a, b := math.Modf(value)
  2334. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2335. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2336. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2337. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  2338. if updateAssessmentErr != nil {
  2339. utils.ErrorLog("%v", updateAssessmentErr)
  2340. }
  2341. }
  2342. }
  2343. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2344. this.ServeSuccessJSON(map[string]interface{}{
  2345. "dialysis_order": dialysisRecords,
  2346. })
  2347. }
  2348. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  2349. record_id, _ := c.GetInt64("id")
  2350. nurseID, _ := c.GetInt64("nurse")
  2351. end_time := c.GetString("end_time")
  2352. if record_id <= 0 || nurseID <= 0 {
  2353. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2354. return
  2355. }
  2356. adminUserInfo := c.GetMobileAdminUserInfo()
  2357. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  2358. if getNurseErr != nil {
  2359. c.ErrorLog("获取护士失败:%v", getNurseErr)
  2360. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2361. return
  2362. } else if nurse == nil {
  2363. c.ErrorLog("护士不存在")
  2364. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2365. return
  2366. }
  2367. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  2368. if parseEndDateErr != nil {
  2369. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  2370. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2371. return
  2372. }
  2373. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2374. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2375. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2376. // if getPermissionErr != nil {
  2377. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2378. // return
  2379. // } else if headNursePermission == nil {
  2380. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2381. // return
  2382. // }
  2383. //}
  2384. dialysisRecord := &models.DialysisOrder{
  2385. ID: record_id,
  2386. UserOrgId: adminUserInfo.Org.Id,
  2387. EndTime: endDate.Unix(),
  2388. FinishNurse: nurseID,
  2389. FinishModifier: adminUserInfo.AdminUser.Id,
  2390. }
  2391. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  2392. if updateErr != nil {
  2393. c.ErrorLog("修改下机失败:%v", updateErr)
  2394. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2395. return
  2396. }
  2397. if updateErr == nil {
  2398. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  2399. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2400. a, b := math.Modf(value)
  2401. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2402. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2403. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2404. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  2405. if updateAssessmentErr != nil {
  2406. utils.ErrorLog("%v", updateAssessmentErr)
  2407. }
  2408. }
  2409. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2410. c.ServeSuccessJSON(map[string]interface{}{
  2411. "dialysis_order": dialysisRecords,
  2412. })
  2413. }
  2414. func (c *DialysisAPIController) GetLongAdvice() {
  2415. patient_id, _ := c.GetInt64("id")
  2416. adminUserInfo := c.GetMobileAdminUserInfo()
  2417. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  2418. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  2419. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  2420. c.ServeSuccessJSON(map[string]interface{}{
  2421. "status": "1",
  2422. })
  2423. return
  2424. } else { //开启推送提醒
  2425. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  2426. var advice_three []*models.DoctorAdvice
  2427. //groupNo := service.GetMaxLongAdviceGroupID(adminUserInfo.Org.Id, patient_id)
  2428. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id)
  2429. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id)
  2430. for _, advice := range advices {
  2431. if advice.FrequencyType == 3 {
  2432. t := time.Now()
  2433. week := int(t.Weekday())
  2434. fmt.Println(t.Weekday())
  2435. fmt.Println(week)
  2436. switch week {
  2437. case 1:
  2438. if strings.Index(advice.WeekDay, "周一") == -1 {
  2439. advice_three = append(advice_three, advice)
  2440. }
  2441. break
  2442. case 2:
  2443. if strings.Index(advice.WeekDay, "周二") == -1 {
  2444. advice_three = append(advice_three, advice)
  2445. }
  2446. break
  2447. case 3:
  2448. if strings.Index(advice.WeekDay, "周三") == -1 {
  2449. advice_three = append(advice_three, advice)
  2450. }
  2451. break
  2452. case 4:
  2453. if strings.Index(advice.WeekDay, "周四") == -1 {
  2454. advice_three = append(advice_three, advice)
  2455. }
  2456. break
  2457. case 5:
  2458. if strings.Index(advice.WeekDay, "周五") == -1 {
  2459. advice_three = append(advice_three, advice)
  2460. }
  2461. break
  2462. case 6:
  2463. if strings.Index(advice.WeekDay, "周六") == -1 {
  2464. advice_three = append(advice_three, advice)
  2465. }
  2466. break
  2467. case 0:
  2468. if strings.Index(advice.WeekDay, "周日") == -1 {
  2469. advice_three = append(advice_three, advice)
  2470. }
  2471. break
  2472. }
  2473. }
  2474. }
  2475. for _, advice := range advices_two {
  2476. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2477. now := p.Unix()
  2478. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2479. dayStr2 := "-" + dayStr
  2480. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2481. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2482. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2483. for _, ad := range advices {
  2484. advice_three = append(advice_three, ad)
  2485. }
  2486. }
  2487. if err == nil {
  2488. c.ServeSuccessJSON(map[string]interface{}{
  2489. "status": "2",
  2490. "advices": advices,
  2491. "advices_two": RemoveRepeatedElement(advice_three),
  2492. "is_open_remind": config.IsOpenRemind,
  2493. })
  2494. }
  2495. }
  2496. }
  2497. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  2498. newArr = make([]*models.DoctorAdvice, 0)
  2499. for i := 0; i < len(arr); i++ {
  2500. repeat := false
  2501. for j := i + 1; j < len(arr); j++ {
  2502. if arr[i].ID == arr[j].ID {
  2503. repeat = true
  2504. break
  2505. }
  2506. }
  2507. if !repeat {
  2508. newArr = append(newArr, arr[i])
  2509. }
  2510. }
  2511. return
  2512. }
  2513. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  2514. patient, _ := c.GetInt64("id", 0)
  2515. groupNo, _ := c.GetInt64("groupno", 0)
  2516. if patient <= 0 {
  2517. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2518. return
  2519. }
  2520. adminUserInfo := c.GetMobileAdminUserInfo()
  2521. dataBody := make(map[string]interface{}, 0)
  2522. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2523. if err != nil {
  2524. utils.ErrorLog(err.Error())
  2525. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2526. return
  2527. }
  2528. utils.ErrorLog("%v", dataBody)
  2529. timeLayout := "2006-01-02 15:04"
  2530. loc, _ := time.LoadLocation("Local")
  2531. timeLayout2 := "2006-01-02"
  2532. loc2, _ := time.LoadLocation("Local")
  2533. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  2534. utils.ErrorLog("advice_type")
  2535. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2536. return
  2537. }
  2538. adviceType := int64(2)
  2539. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  2540. utils.ErrorLog("advice_date")
  2541. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2542. return
  2543. }
  2544. adviceDate, _ := dataBody["advice_date"].(string)
  2545. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  2546. AdviceDate := theTime.Unix()
  2547. RecordDate := theTime.Unix()
  2548. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  2549. utils.ErrorLog("start_time")
  2550. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2551. return
  2552. }
  2553. startTime, _ := dataBody["start_time"].(string)
  2554. if len(startTime) == 0 {
  2555. utils.ErrorLog("len(start_time) == 0")
  2556. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2557. return
  2558. }
  2559. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  2560. if err != nil {
  2561. utils.ErrorLog(err.Error())
  2562. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2563. return
  2564. }
  2565. StartTime := theTime.Unix()
  2566. Remark := ""
  2567. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  2568. remark, _ := dataBody["remark"].(string)
  2569. Remark = remark
  2570. }
  2571. var advices []*models.GroupAdvice
  2572. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  2573. utils.ErrorLog("advices")
  2574. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2575. return
  2576. }
  2577. adviceNames := dataBody["advices"].([]interface{})
  2578. for _, adviceNameMap := range adviceNames {
  2579. adviceNameM := adviceNameMap.(map[string]interface{})
  2580. var advice models.GroupAdvice
  2581. advice.Remark = Remark
  2582. advice.AdviceType = adviceType
  2583. advice.StartTime = StartTime
  2584. advice.AdviceDate = AdviceDate
  2585. advice.RecordDate = RecordDate
  2586. advice.Status = 1
  2587. advice.CreatedTime = time.Now().Unix()
  2588. advice.UpdatedTime = time.Now().Unix()
  2589. advice.StopState = 2
  2590. advice.ExecutionState = 2
  2591. advice.UserOrgId = adminUserInfo.Org.Id
  2592. advice.PatientId = patient
  2593. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  2594. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  2595. utils.ErrorLog("advice_name")
  2596. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2597. return
  2598. }
  2599. adviceName, _ := adviceNameM["advice_name"].(string)
  2600. if len(adviceName) == 0 {
  2601. utils.ErrorLog("len(advice_name) == 0")
  2602. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2603. return
  2604. }
  2605. advice.AdviceName = adviceName
  2606. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  2607. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  2608. advice.DrugSpec = drugSpec
  2609. }
  2610. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  2611. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  2612. advice.AdviceDesc = adviceDesc
  2613. }
  2614. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  2615. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  2616. advice.DrugSpecUnit = drugSpecUnit
  2617. }
  2618. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  2619. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  2620. // advice.SingleDose = singleDose
  2621. //}
  2622. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  2623. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2624. advice.SingleDose = adviceNameM["single_dose"].(float64)
  2625. }
  2626. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  2627. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  2628. advice.SingleDoseUnit = singleDoseUnit
  2629. }
  2630. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  2631. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  2632. // advice.PrescribingNumber = prescribingNumber
  2633. //}
  2634. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  2635. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2636. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  2637. }
  2638. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  2639. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  2640. advice.PrescribingNumberUnit = prescribingNumberUnit
  2641. }
  2642. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  2643. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  2644. advice.DeliveryWay = deliveryWay
  2645. }
  2646. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  2647. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2648. advice.ExecutionFrequency = executionFrequency
  2649. }
  2650. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  2651. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  2652. advice.FrequencyType = frequency_type
  2653. }
  2654. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  2655. day_count := int64(adviceNameM["day_count"].(float64))
  2656. advice.DayCount = day_count
  2657. }
  2658. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  2659. week_day, _ := adviceNameM["week_day"].(string)
  2660. advice.WeekDay = week_day
  2661. }
  2662. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  2663. way := int64(adviceNameM["way"].(float64))
  2664. advice.Way = way
  2665. }
  2666. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  2667. drug_id := int64(adviceNameM["drug_id"].(float64))
  2668. advice.DrugId = drug_id
  2669. }
  2670. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  2671. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  2672. advice.DrugNameId = drug_name_id
  2673. }
  2674. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  2675. template_id, _ := adviceNameM["template_id"].(string)
  2676. advice.TemplateId = template_id
  2677. }
  2678. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  2679. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2680. advice.ExecutionFrequency = executionFrequency
  2681. }
  2682. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  2683. children := adviceNameM["child"].([]interface{})
  2684. if len(children) > 0 {
  2685. for _, childrenMap := range children {
  2686. childMap := childrenMap.(map[string]interface{})
  2687. var child models.GroupAdvice
  2688. child.Remark = Remark
  2689. child.AdviceType = adviceType
  2690. child.StartTime = StartTime
  2691. child.AdviceDate = AdviceDate
  2692. child.RecordDate = RecordDate
  2693. child.Status = 1
  2694. child.CreatedTime = time.Now().Unix()
  2695. child.UpdatedTime = time.Now().Unix()
  2696. child.StopState = 2
  2697. child.ExecutionState = 2
  2698. child.UserOrgId = adminUserInfo.Org.Id
  2699. child.PatientId = patient
  2700. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  2701. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  2702. utils.ErrorLog("child advice_name")
  2703. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2704. return
  2705. }
  2706. childAdviceName, _ := childMap["advice_name"].(string)
  2707. if len(childAdviceName) == 0 {
  2708. utils.ErrorLog("len(child advice_name) == 0")
  2709. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2710. return
  2711. }
  2712. child.AdviceName = childAdviceName
  2713. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  2714. childAdviceDesc, _ := childMap["advice_desc"].(string)
  2715. child.AdviceDesc = childAdviceDesc
  2716. }
  2717. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  2718. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  2719. child.DrugSpec = childDrugSpec
  2720. }
  2721. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  2722. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  2723. child.DrugSpecUnit = childDrugSpecUnit
  2724. }
  2725. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  2726. child.SingleDose = childMap["single_dose"].(float64)
  2727. }
  2728. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  2729. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  2730. child.SingleDoseUnit = childSingleDoseUnit
  2731. }
  2732. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  2733. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  2734. }
  2735. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  2736. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  2737. child.PrescribingNumberUnit = childPrescribingNumberUnit
  2738. }
  2739. child.DeliveryWay = advice.DeliveryWay
  2740. child.ExecutionFrequency = advice.ExecutionFrequency
  2741. advice.Children = append(advice.Children, &child)
  2742. }
  2743. }
  2744. }
  2745. temp_advice, _ := service.FindRemindAdvice(advice.UserOrgId, advice.AdviceName, advice.AdviceDesc, advice.TemplateId, advice.FrequencyType, patient, advice.RecordDate)
  2746. if temp_advice.ID == 0 {
  2747. advices = append(advices, &advice)
  2748. }
  2749. }
  2750. if len(advices) > 0 {
  2751. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  2752. if err != nil {
  2753. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  2754. return
  2755. }
  2756. c.ServeSuccessJSON(map[string]interface{}{
  2757. "msg": "ok",
  2758. "advices": list,
  2759. })
  2760. } else {
  2761. c.ServeSuccessJSON(map[string]interface{}{
  2762. "msg": "ok",
  2763. })
  2764. }
  2765. return
  2766. }
  2767. func (c *DialysisAPIController) UploadDryWeight() {
  2768. patient_id, _ := c.GetInt64("id")
  2769. dry_weight, _ := c.GetFloat("dry_weight")
  2770. doctor_id, _ := c.GetInt64("doctor_id")
  2771. remark := c.GetString("remark")
  2772. adminUserInfo := c.GetMobileAdminUserInfo()
  2773. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  2774. if err == gorm.ErrRecordNotFound {
  2775. dryWeight := &models.SgjPatientDryweight{
  2776. PatientId: patient_id,
  2777. DryWeight: dry_weight,
  2778. Remakes: remark,
  2779. Ctime: time.Now().Unix(),
  2780. Mtime: time.Now().Unix(),
  2781. Creator: doctor_id,
  2782. Status: 1,
  2783. UserOrgId: adminUserInfo.Org.Id,
  2784. AdjustedValue: "/",
  2785. UserId: adminUserInfo.AdminUser.Id,
  2786. }
  2787. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2788. if createErr == nil {
  2789. c.ServeSuccessJSON(map[string]interface{}{
  2790. "msg": "提交成功",
  2791. "weight": dryWeight,
  2792. })
  2793. }
  2794. } else {
  2795. dryWeight := &models.SgjPatientDryweight{
  2796. PatientId: patient_id,
  2797. DryWeight: dry_weight,
  2798. Remakes: remark,
  2799. Ctime: time.Now().Unix(),
  2800. Mtime: time.Now().Unix(),
  2801. Creator: doctor_id,
  2802. Status: 1,
  2803. UserOrgId: adminUserInfo.Org.Id,
  2804. AdjustedValue: "/",
  2805. UserId: adminUserInfo.AdminUser.Id,
  2806. }
  2807. var value float64
  2808. value = dry_weight - weightAdjust.DryWeight
  2809. if value < 0 {
  2810. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  2811. } else if value == 0 {
  2812. dryWeight.AdjustedValue = "/"
  2813. } else if value > 0 {
  2814. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  2815. }
  2816. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2817. if createErr == nil {
  2818. c.ServeSuccessJSON(map[string]interface{}{
  2819. "msg": "提交成功",
  2820. "weight": dryWeight,
  2821. })
  2822. }
  2823. }
  2824. }
  2825. func (c *DialysisAPIController) GetSolution() {
  2826. patient_id, _ := c.GetInt64("patient_id")
  2827. mode_id, _ := c.GetInt64("mode_id")
  2828. adminUserInfo := c.GetMobileAdminUserInfo()
  2829. solution, err := service.MobileGetDialysisSolutionByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2830. prescription, err := service.MobileGetLastDialysisPrescribeByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2831. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeId(adminUserInfo.Org.Id, mode_id)
  2832. if err != nil {
  2833. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2834. return
  2835. }
  2836. c.ServeSuccessJSON(map[string]interface{}{
  2837. "solution": solution,
  2838. "prescription": prescription,
  2839. "system_prescription": system_prescription,
  2840. })
  2841. }
  2842. func (c *DialysisAPIController) GetSchedule() {
  2843. schedual_type, _ := c.GetInt64("schedual_type")
  2844. adminUserInfo := c.GetMobileAdminUserInfo()
  2845. //timeLayout := "2006-01-02 15:04:05"
  2846. //
  2847. //date := time.Now().Format("2006-01-02") + " 00:00:00"
  2848. //loc, _ := time.LoadLocation("Local")
  2849. //theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  2850. //scheduleTime := theStartTime.Unix()
  2851. scheduleTime, _ := c.GetInt64("record_date")
  2852. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  2853. c.ServeSuccessJSON(map[string]interface{}{
  2854. "number": deviceNumber,
  2855. })
  2856. }
  2857. func (c *DialysisAPIController) GetPatientId() {
  2858. id, _ := c.GetInt64("id")
  2859. patientId, _ := service.GetPatientId(id)
  2860. //获取该患者的所有传染病
  2861. list, _ := service.GetPatientInfectious(id)
  2862. c.ServeSuccessJSON(map[string]interface{}{
  2863. "patient": patientId,
  2864. "infectioulist": list,
  2865. })
  2866. }
  2867. func (this *DialysisAPIController) GetDialysisSchedule() {
  2868. schedualDate := this.GetString("date")
  2869. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  2870. if parseDateErr != nil {
  2871. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2872. return
  2873. }
  2874. adminInfo := this.GetMobileAdminUserInfo()
  2875. orgID := adminInfo.Org.Id
  2876. redis := service.RedisClient()
  2877. defer redis.Close()
  2878. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  2879. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  2880. if len(scheduals) > 0 {
  2881. //缓存数据
  2882. scheduals_json, err := json.Marshal(scheduals)
  2883. if err == nil {
  2884. redis.Set(key, scheduals_json, time.Second*30)
  2885. }
  2886. }
  2887. this.ServeSuccessJSON(map[string]interface{}{
  2888. "scheduals": scheduals,
  2889. })
  2890. }
  2891. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  2892. change_type, _ := this.GetInt64("type", 0)
  2893. record_date := this.GetString("record_time")
  2894. patient_id, _ := this.GetInt64("patient_id", 0)
  2895. timeLayout := "2006-01-02"
  2896. loc, _ := time.LoadLocation("Local")
  2897. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2898. record_time := theAdviceRecordTime.Unix()
  2899. adminUserInfo := this.GetMobileAdminUserInfo()
  2900. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  2901. if err == nil {
  2902. if len(advices) == 0 {
  2903. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  2904. return
  2905. } else {
  2906. this.ServeSuccessJSON(map[string]interface{}{
  2907. "advices": advices,
  2908. "schedule": sch,
  2909. })
  2910. return
  2911. }
  2912. } else {
  2913. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2914. return
  2915. }
  2916. }
  2917. func (c *DialysisAPIController) CreateConsumables() {
  2918. record_date := c.GetString("record_time")
  2919. patient_id, _ := c.GetInt64("patient_id", 0)
  2920. active, _ := c.GetInt64("active")
  2921. adminUser := c.GetMobileAdminUserInfo()
  2922. timeLayout := "2006-01-02"
  2923. loc, _ := time.LoadLocation("Local")
  2924. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2925. record_time := theRecordTime.Unix()
  2926. dataBody := make(map[string]interface{}, 0)
  2927. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2928. if err != nil {
  2929. utils.ErrorLog(err.Error())
  2930. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2931. return
  2932. }
  2933. var beforePrepares []*models.DialysisBeforePrepareGoods
  2934. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  2935. var dialysisBefor []*models.DialysisBeforePrepare
  2936. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2937. goods, _ := dataBody["goods"].([]interface{})
  2938. if len(goods) > 0 {
  2939. for _, item := range goods {
  2940. items := item.(map[string]interface{})
  2941. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2942. utils.ErrorLog("good_id")
  2943. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2944. return
  2945. }
  2946. good_id := int64(items["good_id"].(float64))
  2947. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2948. utils.ErrorLog("good_type_id")
  2949. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2950. return
  2951. }
  2952. good_type_id := int64(items["good_type_id"].(float64))
  2953. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2954. utils.ErrorLog("count")
  2955. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2956. return
  2957. }
  2958. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2959. commdity_code := items["commdity_code"].(string)
  2960. fmt.Println("commdity", commdity_code)
  2961. prepareGoods := &models.DialysisBeforePrepareGoods{
  2962. GoodTypeId: good_type_id,
  2963. GoodId: good_id,
  2964. Count: count,
  2965. }
  2966. beforePrepares = append(beforePrepares, prepareGoods)
  2967. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  2968. GoodTypeId: good_type_id,
  2969. GoodId: good_id,
  2970. Count: count,
  2971. }
  2972. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  2973. prepare := &models.DialysisBeforePrepare{
  2974. GoodTypeId: good_type_id,
  2975. GoodId: good_id,
  2976. Count: count,
  2977. PatientId: patient_id,
  2978. RecordDate: record_time,
  2979. UserOrgId: adminUser.Org.Id,
  2980. Status: 1,
  2981. Ctime: time.Now().Unix(),
  2982. Creater: adminUser.AdminUser.Id,
  2983. CommdityCode: commdity_code,
  2984. }
  2985. dialysisBefor = append(dialysisBefor, prepare)
  2986. }
  2987. }
  2988. //查询是否有库存
  2989. for _, item := range dialysisBefor {
  2990. warehouse, err := service.FindFirstWarehousingInfoByStock(item.GoodId, item.GoodTypeId)
  2991. fmt.Println("库存数量00000000000000000000", warehouse.StockCount, err)
  2992. if err == gorm.ErrRecordNotFound {
  2993. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  2994. c.ServeSuccessJSON(map[string]interface{}{
  2995. "message": "1",
  2996. "good_name": goodObj.GoodName,
  2997. "specification_name": goodObj.SpecificationName,
  2998. })
  2999. return
  3000. }
  3001. if err != nil {
  3002. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3003. c.ServeSuccessJSON(map[string]interface{}{
  3004. "message": "1",
  3005. "good_name": goodObj.GoodName,
  3006. "specification_name": goodObj.SpecificationName,
  3007. })
  3008. return
  3009. }
  3010. }
  3011. fmt.Println("dialysisBefor9999999999999999999", dialysisBefor, active)
  3012. //新增
  3013. if active == 1 && len(goods) > 0 {
  3014. for _, item := range dialysisBefor {
  3015. dialyPrepareOne := models.DialysisBeforePrepare{
  3016. GoodTypeId: item.GoodTypeId,
  3017. GoodId: item.GoodId,
  3018. PatientId: item.PatientId,
  3019. RecordDate: item.RecordDate,
  3020. UserOrgId: item.UserOrgId,
  3021. Count: item.Count,
  3022. Ctime: time.Now().Unix(),
  3023. Creater: item.Creater,
  3024. CommdityCode: item.CommdityCode,
  3025. Status: 1,
  3026. }
  3027. //先清除再插入
  3028. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3029. err = service.CreateDialysisBeforePrepareOne(&dialyPrepareOne)
  3030. }
  3031. if err == nil {
  3032. c.ServeSuccessJSON(map[string]interface{}{
  3033. "msg": "保存成功",
  3034. "message": "2",
  3035. })
  3036. return
  3037. } else {
  3038. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3039. return
  3040. }
  3041. }
  3042. if len(beforePrepares) > 0 && active == 2 {
  3043. for _, item := range beforePrepares {
  3044. //1.查看该患者该耗材型号最后一次出库数量
  3045. goodInfo, _ := service.GetLastGoodListByPatientId(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3046. //判断当前出库数量和最后一次出库数量的大小
  3047. //如果当前出库数量小于或等于最后一次出库数量 正常出库后 需要退库操作
  3048. if item.Count <= goodInfo.Count {
  3049. //出库
  3050. err = ConsumablesDeliveryTotalSeven(adminUser.Org.Id, patient_id, record_time, beforePrepares, adminUser.AdminUser.Id, item.Count)
  3051. //查询今日出库数据
  3052. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3053. for _, it := range list {
  3054. prepare := models.DialysisBeforePrepare{
  3055. UserOrgId: it.OrgId,
  3056. PatientId: patient_id,
  3057. RecordDate: it.RecordTime,
  3058. GoodId: it.GoodId,
  3059. GoodTypeId: it.GoodTypeId,
  3060. Count: it.Count,
  3061. Ctime: time.Now().Unix(),
  3062. Creater: adminUser.AdminUser.Id,
  3063. Status: 1,
  3064. }
  3065. //删除准备表数据
  3066. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3067. service.CreateDialysisBeforePrepareOne(&prepare)
  3068. }
  3069. }
  3070. var last_total int64
  3071. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3072. if item.Count >= goodInfo.Count {
  3073. //查询当前批次当前耗材最后一条出库数据
  3074. lastOutInfo, _ := service.GetLastWarehouOutInfoByPatientId(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3075. //计算当前出库和最后一次出库数据相差数据
  3076. last_total = item.Count - lastOutInfo.Count
  3077. //查询该批次剩余库存
  3078. lastInfo, _ := service.GetLastStockOut(lastOutInfo.WarehouseInfotId)
  3079. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3080. if lastInfo.StockCount >= last_total {
  3081. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3082. //service.ConsumablesDeliveryTotalEight(adminInfo.Org.Id, patient_id, record_time, beforePrepares,adminInfo.AdminUser.Id,item.Count)
  3083. //查询今日出库数据
  3084. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3085. for _, it := range list {
  3086. prepare := models.DialysisBeforePrepare{
  3087. UserOrgId: it.OrgId,
  3088. PatientId: patient_id,
  3089. RecordDate: it.RecordTime,
  3090. GoodId: it.GoodId,
  3091. GoodTypeId: it.GoodTypeId,
  3092. Count: it.Count,
  3093. Ctime: time.Now().Unix(),
  3094. Creater: adminUser.AdminUser.Id,
  3095. Status: 1,
  3096. }
  3097. //删除准备表数据
  3098. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3099. service.CreateDialysisBeforePrepareOne(&prepare)
  3100. }
  3101. }
  3102. //如果库存不够,则出库到下一个批次
  3103. if lastInfo.StockCount < last_total {
  3104. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3105. //查询今日出库数据
  3106. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3107. for _, it := range list {
  3108. prepare := models.DialysisBeforePrepare{
  3109. UserOrgId: it.OrgId,
  3110. PatientId: patient_id,
  3111. RecordDate: it.RecordTime,
  3112. GoodId: it.GoodId,
  3113. GoodTypeId: it.GoodTypeId,
  3114. Count: it.Count,
  3115. Ctime: time.Now().Unix(),
  3116. Creater: adminUser.AdminUser.Id,
  3117. Status: 1,
  3118. }
  3119. //删除准备表数据
  3120. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3121. service.CreateDialysisBeforePrepareOne(&prepare)
  3122. }
  3123. if err != nil {
  3124. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3125. c.ServeSuccessJSON(map[string]interface{}{
  3126. "message": "1",
  3127. "good_name": goodObj.GoodName,
  3128. "specification_name": goodObj.SpecificationName,
  3129. })
  3130. return
  3131. }
  3132. }
  3133. }
  3134. if err != nil {
  3135. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3136. c.ServeSuccessJSON(map[string]interface{}{
  3137. "message": "1",
  3138. "good_name": goodObj.GoodName,
  3139. "specification_name": goodObj.SpecificationName,
  3140. })
  3141. return
  3142. }
  3143. }
  3144. //出库
  3145. //err = service.ConsumablesDeliveryTotal(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3146. //fmt.Println("err", err)
  3147. ////查询今日出库数据
  3148. //list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3149. //
  3150. //if len(list) == 0 {
  3151. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3152. // return
  3153. //}
  3154. //
  3155. //for _, item := range list {
  3156. // prepare := models.DialysisBeforePrepare{
  3157. // UserOrgId: item.OrgId,
  3158. // PatientId: patient_id,
  3159. // RecordDate: item.RecordTime,
  3160. // GoodId: item.GoodId,
  3161. // GoodTypeId: item.GoodTypeId,
  3162. // Count: item.Count,
  3163. // Ctime: time.Now().Unix(),
  3164. // Creater: adminUser.AdminUser.Id,
  3165. // Status: 1,
  3166. // }
  3167. // //删除准备表数据
  3168. // service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3169. // service.CreateDialysisBeforePrepareOne(&prepare)
  3170. //}
  3171. }
  3172. }
  3173. var errs error
  3174. if errs == nil {
  3175. c.ServeSuccessJSON(map[string]interface{}{
  3176. "msg": "提交成功",
  3177. "message": "2",
  3178. "good_name": "",
  3179. "specification_name": "",
  3180. })
  3181. return
  3182. } else {
  3183. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3184. return
  3185. }
  3186. }
  3187. func (c *DialysisAPIController) CreateStockOutInfo() {
  3188. patient_id, _ := c.GetInt64("patient_id", 0)
  3189. record_date := c.GetString("record_time")
  3190. if patient_id <= 0 {
  3191. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3192. return
  3193. }
  3194. adminInfo := c.GetMobileAdminUserInfo()
  3195. timeLayout := "2006-01-02"
  3196. loc, _ := time.LoadLocation("Local")
  3197. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3198. record_time := theRecordTime.Unix()
  3199. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3200. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3201. consumables = RemoveRepeatedGood(consumables)
  3202. if record.IsOpen == 1 {
  3203. //查询是否有库存
  3204. for _, item := range consumables {
  3205. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId)
  3206. if item.Count > warehouse.Count {
  3207. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3208. c.ServeSuccessJSON(map[string]interface{}{
  3209. "message": "1",
  3210. "good_name": goodObj.GoodName,
  3211. "specification_name": goodObj.SpecificationName,
  3212. })
  3213. return
  3214. }
  3215. }
  3216. //查询是否有出库单
  3217. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3218. if err == gorm.ErrRecordNotFound {
  3219. //没有记录,则创建出库单
  3220. timeStr := time.Now().Format("2006-01-02")
  3221. timeArr := strings.Split(timeStr, "-")
  3222. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3223. total = total + 1
  3224. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3225. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3226. number = number + total
  3227. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3228. creater := adminInfo.AdminUser.Id
  3229. warehouseOut := models.WarehouseOut{
  3230. WarehouseOutOrderNumber: warehousing_out_order,
  3231. OperationTime: time.Now().Unix(),
  3232. OrgId: adminInfo.Org.Id,
  3233. Creater: creater,
  3234. Ctime: time.Now().Unix(),
  3235. Status: 1,
  3236. WarehouseOutTime: record_time,
  3237. Dealer: 0,
  3238. Manufacturer: 0,
  3239. Type: 1,
  3240. IsSys: 1,
  3241. }
  3242. err := service.AddSigleWarehouseOut(&warehouseOut)
  3243. if err != nil {
  3244. utils.TraceLog("创建出库单失败 err = %v", err)
  3245. } else {
  3246. for _, item := range consumables {
  3247. //出库
  3248. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, item.Count)
  3249. }
  3250. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3251. if len(list) == 0 {
  3252. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3253. return
  3254. }
  3255. for _, item := range list {
  3256. prepare := models.DialysisBeforePrepare{
  3257. UserOrgId: adminInfo.Org.Id,
  3258. PatientId: patient_id,
  3259. RecordDate: record_time,
  3260. GoodId: item.GoodId,
  3261. GoodTypeId: item.GoodTypeId,
  3262. Count: item.Count,
  3263. Creater: adminInfo.AdminUser.Id,
  3264. Status: 1,
  3265. Ctime: time.Now().Unix(),
  3266. }
  3267. //清空准备表数据
  3268. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3269. service.CreateDialysisBeforePrepareOne(&prepare)
  3270. }
  3271. }
  3272. //
  3273. } else if err == nil {
  3274. for _, item := range consumables {
  3275. //出库
  3276. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &out, item.Count)
  3277. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3278. if len(list) == 0 {
  3279. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3280. return
  3281. }
  3282. for _, item := range list {
  3283. prepare := models.DialysisBeforePrepare{
  3284. UserOrgId: adminInfo.Org.Id,
  3285. PatientId: patient_id,
  3286. RecordDate: record_time,
  3287. GoodId: item.GoodId,
  3288. GoodTypeId: item.GoodTypeId,
  3289. Count: item.Count,
  3290. Creater: adminInfo.AdminUser.Id,
  3291. Status: 1,
  3292. Ctime: time.Now().Unix(),
  3293. }
  3294. //清空准备表数据
  3295. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3296. service.CreateDialysisBeforePrepareOne(&prepare)
  3297. }
  3298. }
  3299. }
  3300. c.ServeSuccessJSON(map[string]interface{}{
  3301. "msg": "提交成功",
  3302. "message": "2",
  3303. "good_name": "",
  3304. "specification_name": "",
  3305. })
  3306. return
  3307. } else {
  3308. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  3309. return
  3310. }
  3311. }
  3312. func (c *DialysisAPIController) EditConsumables() {
  3313. patient_id, _ := c.GetInt64("patient_id", 0)
  3314. record_date := c.GetString("record_time")
  3315. if patient_id <= 0 {
  3316. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3317. return
  3318. }
  3319. adminInfo := c.GetMobileAdminUserInfo()
  3320. timeLayout := "2006-01-02"
  3321. loc, _ := time.LoadLocation("Local")
  3322. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3323. record_time := theRecordTime.Unix()
  3324. dataBody := make(map[string]interface{}, 0)
  3325. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3326. if err != nil {
  3327. utils.ErrorLog(err.Error())
  3328. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3329. return
  3330. }
  3331. var beforePrepares []*models.DialysisBeforePrepareGoods
  3332. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3333. //判断是否开启自动出库
  3334. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3335. if record.IsOpen == 1 {
  3336. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3337. goods, _ := dataBody["goods"].([]interface{})
  3338. if len(goods) > 0 {
  3339. for _, item := range goods {
  3340. items := item.(map[string]interface{})
  3341. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3342. utils.ErrorLog("good_id")
  3343. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3344. return
  3345. }
  3346. good_id := int64(items["good_id"].(float64))
  3347. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3348. utils.ErrorLog("good_type_id")
  3349. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3350. return
  3351. }
  3352. good_type_id := int64(items["good_type_id"].(float64))
  3353. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3354. utils.ErrorLog("count")
  3355. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3356. return
  3357. }
  3358. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3359. commdity_code := items["commdity_code"].(string)
  3360. fmt.Println(commdity_code)
  3361. prepareGoods := &models.DialysisBeforePrepareGoods{
  3362. GoodTypeId: good_type_id,
  3363. GoodId: good_id,
  3364. Count: count,
  3365. }
  3366. beforePrepares = append(beforePrepares, prepareGoods)
  3367. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3368. GoodTypeId: good_type_id,
  3369. GoodId: good_id,
  3370. Count: count,
  3371. }
  3372. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3373. }
  3374. for _, item := range beforePrepares {
  3375. fmt.Println("23232323232323为什么99999999999999999999999999999999", item.GoodId)
  3376. //1.查看该患者该耗材型号最后一次出库数量
  3377. goodInfo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3378. //判断当前出库数量和最后一次出库数量的大小
  3379. //如果当前出库数量小于最后一次出库数量 正常出库后 需要退库操作
  3380. fmt.Println("当前出库数量", item.Count)
  3381. fmt.Println("最后一次出库数量", goodInfo.Count)
  3382. if item.Count < goodInfo.Count {
  3383. //出库
  3384. err = ConsumablesDeliveryTotalSeven(adminInfo.Org.Id, patient_id, record_time, beforePrepares, adminInfo.AdminUser.Id, item.Count)
  3385. break
  3386. }
  3387. var last_total int64
  3388. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3389. if item.Count > goodInfo.Count {
  3390. //计算当前出库和最后一次出库数据相差数据
  3391. last_total = item.Count - goodInfo.Count
  3392. //查询该批次剩余库存
  3393. lastInfo, _ := service.GetLastStockOut(goodInfo.WarehouseInfotId)
  3394. if lastInfo.StockCount == 0 {
  3395. //查询该耗材的总库存
  3396. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  3397. if wareinfo.StockCount == 0 {
  3398. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3399. c.ServeSuccessJSON(map[string]interface{}{
  3400. "message": "1",
  3401. "good_name": goodObj.GoodName,
  3402. "specification_name": goodObj.SpecificationName,
  3403. })
  3404. return
  3405. }
  3406. }
  3407. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3408. fmt.Println("剩余库存", lastInfo.StockCount)
  3409. fmt.Println("差", last_total)
  3410. if lastInfo.StockCount >= last_total {
  3411. err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3412. break
  3413. }
  3414. //如果库存不够,则出库到下一个批次
  3415. if lastInfo.StockCount < last_total {
  3416. err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3417. break
  3418. }
  3419. }
  3420. }
  3421. //查询今日出库数据
  3422. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3423. for _, it := range list {
  3424. prepare := models.DialysisBeforePrepare{
  3425. UserOrgId: it.OrgId,
  3426. PatientId: patient_id,
  3427. RecordDate: it.RecordTime,
  3428. GoodId: it.GoodId,
  3429. GoodTypeId: it.GoodTypeId,
  3430. Count: it.Count,
  3431. Ctime: time.Now().Unix(),
  3432. Creater: adminInfo.AdminUser.Id,
  3433. Status: 1,
  3434. }
  3435. //删除准备表数据
  3436. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, it.GoodId, it.GoodTypeId)
  3437. service.CreateDialysisBeforePrepareOne(&prepare)
  3438. if err != nil {
  3439. goodObj, _ := service.GetGoodInformationByGoodId(it.GoodId)
  3440. c.ServeSuccessJSON(map[string]interface{}{
  3441. "message": "2",
  3442. "good_name": goodObj.GoodName,
  3443. "specification_name": goodObj.SpecificationName,
  3444. })
  3445. return
  3446. }
  3447. }
  3448. }
  3449. }
  3450. //更新自动出库的地方
  3451. var errs error
  3452. if errs == nil {
  3453. c.ServeSuccessJSON(map[string]interface{}{
  3454. "msg": "修改成功",
  3455. "message": "2",
  3456. "good_name": "",
  3457. "specification_name": "",
  3458. })
  3459. return
  3460. } else {
  3461. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3462. return
  3463. }
  3464. }
  3465. }
  3466. func (c *DialysisAPIController) GetDialysisGoods() {
  3467. schedualDate := c.GetString("schedule_date")
  3468. schedule_type, _ := c.GetInt64("schedule_type")
  3469. partition_id, _ := c.GetInt64("partition_id")
  3470. page, _ := c.GetInt("page")
  3471. patient_id, _ := c.GetInt64("patient_id")
  3472. schedualEndDate := int64(0)
  3473. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3474. if parseDateErr != nil && len(schedualDate) != 0 {
  3475. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3476. return
  3477. }
  3478. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  3479. if parseDateErr != nil && len(schedualDate) != 0 {
  3480. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3481. return
  3482. }
  3483. schedualEndDate = endDate.Unix()
  3484. adminUser := c.GetMobileAdminUserInfo()
  3485. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  3486. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  3487. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  3488. //获取当天该病人的透析处方
  3489. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  3490. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3491. if err == gorm.ErrRecordNotFound {
  3492. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3493. if patient_id != 0 {
  3494. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3495. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3496. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3497. item.LastAutomaticReduceDetail = goodUser
  3498. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3499. item.Project = project
  3500. }
  3501. }
  3502. c.ServeSuccessJSON(map[string]interface{}{
  3503. "dialysis_goods": dialysisGoods,
  3504. "good_type": goodTypes,
  3505. "total": total,
  3506. "prescribe": prescribe,
  3507. "good_info": good_info,
  3508. })
  3509. return
  3510. } else if err == nil {
  3511. //获取当天排班的每个患者的库存使用情况
  3512. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3513. if patient_id != 0 {
  3514. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3515. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3516. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3517. item.Project = project
  3518. fmt.Println(goodUser)
  3519. fmt.Println(lastGoodUserDetial)
  3520. item.LastAutomaticReduceDetail = goodUser
  3521. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3522. }
  3523. }
  3524. if err == nil {
  3525. c.ServeSuccessJSON(map[string]interface{}{
  3526. "dialysis_goods": dialysisGoods,
  3527. "good_type": goodTypes,
  3528. "total": total,
  3529. "prescribe": prescribe,
  3530. "good_info": good_info,
  3531. "project": project,
  3532. })
  3533. return
  3534. } else {
  3535. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3536. return
  3537. }
  3538. } else if err != nil {
  3539. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3540. return
  3541. }
  3542. }
  3543. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  3544. start_time := c.GetString("start_time")
  3545. end_time := c.GetString("end_time")
  3546. timeLayout := "2006-01-02"
  3547. loc, _ := time.LoadLocation("Local")
  3548. var theStartTime int64
  3549. if len(start_time) > 0 {
  3550. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3551. if err != nil {
  3552. utils.ErrorLog(err.Error())
  3553. }
  3554. theStartTime = theTime.Unix()
  3555. }
  3556. var theEndtTime int64
  3557. if len(end_time) > 0 {
  3558. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3559. if err != nil {
  3560. utils.ErrorLog(err.Error())
  3561. }
  3562. theEndtTime = theTime.Unix()
  3563. }
  3564. adminUser := c.GetMobileAdminUserInfo()
  3565. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  3566. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  3567. if err == nil {
  3568. c.ServeSuccessJSON(map[string]interface{}{
  3569. "stock_out": outInfo,
  3570. "stockCount": stockCount,
  3571. })
  3572. return
  3573. } else {
  3574. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3575. return
  3576. }
  3577. }
  3578. func (c *DialysisAPIController) GetStockInGoodInfo() {
  3579. patient_id, _ := c.GetInt64("patient_id", 0)
  3580. record_time := c.GetString("record_time")
  3581. adminUser := c.GetMobileAdminUserInfo()
  3582. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  3583. if parseDateErr != nil && len(record_time) != 0 {
  3584. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3585. return
  3586. }
  3587. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  3588. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3589. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  3590. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  3591. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  3592. //获取今日患者的透析处方参数
  3593. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  3594. c.ServeSuccessJSON(map[string]interface{}{
  3595. "good_type": goodTypes,
  3596. "good_user": goodUser,
  3597. "good_info": good_info,
  3598. "last_good_user": lastGoodUserDetial,
  3599. "project": project,
  3600. "prescription": prescribe,
  3601. })
  3602. return
  3603. }
  3604. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  3605. patient_id, _ := c.GetInt64("patient_id", 0)
  3606. record_date := c.GetString("record_time")
  3607. timeLayout := "2006-01-02"
  3608. loc, _ := time.LoadLocation("Local")
  3609. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3610. record_time := theRecordTime.Unix()
  3611. adminInfo := c.GetMobileAdminUserInfo()
  3612. dataBody := make(map[string]interface{}, 0)
  3613. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3614. if err != nil {
  3615. utils.ErrorLog(err.Error())
  3616. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3617. return
  3618. }
  3619. var beforePrepares []*models.DialysisBeforePrepareGoods
  3620. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3621. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3622. goods, _ := dataBody["goods"].([]interface{})
  3623. if len(goods) > 0 {
  3624. for _, item := range goods {
  3625. items := item.(map[string]interface{})
  3626. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3627. utils.ErrorLog("good_id")
  3628. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3629. return
  3630. }
  3631. good_id := int64(items["good_id"].(float64))
  3632. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3633. utils.ErrorLog("good_type_id")
  3634. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3635. return
  3636. }
  3637. good_type_id := int64(items["good_type_id"].(float64))
  3638. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3639. utils.ErrorLog("count")
  3640. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3641. return
  3642. }
  3643. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3644. prepare := &models.DialysisBeforePrepareGoods{
  3645. GoodId: good_id,
  3646. GoodTypeId: good_type_id,
  3647. Count: count,
  3648. }
  3649. beforePrepares = append(beforePrepares, prepare)
  3650. newPrepare := &models.NewDialysisBeforePrepareGoods{
  3651. GoodId: good_id,
  3652. GoodTypeId: good_type_id,
  3653. Count: count,
  3654. }
  3655. newBeforePrepares = append(newBeforePrepares, newPrepare)
  3656. }
  3657. }
  3658. }
  3659. fmt.Println("前端数据9999999999999", beforePrepares)
  3660. //查询是否有库存
  3661. for _, item := range beforePrepares {
  3662. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId)
  3663. if item.Count > warehouse.Count {
  3664. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3665. c.ServeSuccessJSON(map[string]interface{}{
  3666. "message": "1",
  3667. "good_name": goodObj.GoodName,
  3668. "specification_name": goodObj.SpecificationName,
  3669. })
  3670. return
  3671. }
  3672. }
  3673. //出库逻辑
  3674. err = service.ConsumablesDeliveryTotal(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  3675. if err != nil {
  3676. utils.ErrorLog(err.Error())
  3677. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3678. return
  3679. }
  3680. //查询当天出库的数据
  3681. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3682. for _, item := range list {
  3683. prepare := models.DialysisBeforePrepare{
  3684. UserOrgId: item.OrgId,
  3685. PatientId: item.PatientId,
  3686. RecordDate: item.RecordTime,
  3687. GoodId: item.GoodId,
  3688. GoodTypeId: item.GoodTypeId,
  3689. Count: item.Count,
  3690. Creater: adminInfo.AdminUser.Id,
  3691. Status: 1,
  3692. Ctime: time.Now().Unix(),
  3693. }
  3694. //清空准备表的数据
  3695. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3696. //插入准备表数据
  3697. service.CreateDialysisBeforePrepareOne(&prepare)
  3698. }
  3699. //更新自动出库的地方
  3700. var errs error
  3701. if errs == nil {
  3702. c.ServeSuccessJSON(map[string]interface{}{
  3703. "msg": "修改成功",
  3704. "message": "2",
  3705. "good_name": "",
  3706. "specification_name": "",
  3707. })
  3708. return
  3709. } else {
  3710. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3711. return
  3712. }
  3713. }
  3714. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3715. newArr = make([]*models.DialysisBeforePrepare, 0)
  3716. for i := 0; i < len(arr); i++ {
  3717. repeat := false
  3718. for j := i + 1; j < len(arr); j++ {
  3719. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  3720. repeat = true
  3721. break
  3722. }
  3723. }
  3724. if !repeat {
  3725. newArr = append(newArr, arr[i])
  3726. }
  3727. }
  3728. return
  3729. }
  3730. func (c *DialysisAPIController) GetAllDrug() {
  3731. patient_id, _ := c.GetInt64("patient_id", 0)
  3732. adminInfo := c.GetMobileAdminUserInfo()
  3733. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3734. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  3735. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  3736. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  3737. c.ServeSuccessJSON(map[string]interface{}{
  3738. "base_drug_config": drugStockConfig,
  3739. "private_drug_config": privateDrugConfig,
  3740. "base_drug_list": drugList,
  3741. "private_drug_list": privateDrugList,
  3742. })
  3743. }
  3744. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3745. newArr = make([]*models.DialysisBeforePrepare, 0)
  3746. for i := 0; i < len(arr); i++ {
  3747. repeat := false
  3748. for j := i + 1; j < len(arr); j++ {
  3749. if arr[i].GoodId == arr[j].GoodId {
  3750. repeat = true
  3751. break
  3752. }
  3753. }
  3754. if !repeat {
  3755. newArr = append(newArr, arr[i])
  3756. }
  3757. }
  3758. return
  3759. }
  3760. func (c *DialysisAPIController) GetDepartment() {
  3761. adminInfo := c.GetMobileAdminUserInfo()
  3762. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  3763. if err == nil {
  3764. c.ServeSuccessJSON(map[string]interface{}{
  3765. "departments": departments,
  3766. })
  3767. } else {
  3768. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3769. return
  3770. }
  3771. }
  3772. func (c *DialysisAPIController) GetMobilePrintStockGood() {
  3773. types, _ := c.GetInt("type", 0)
  3774. start_time := c.GetString("start_time")
  3775. end_time := c.GetString("end_time")
  3776. orgId := c.GetMobileAdminUserInfo().Org.Id
  3777. timeLayout := "2006-01-02"
  3778. loc, _ := time.LoadLocation("Local")
  3779. var startTime int64
  3780. if len(start_time) > 0 {
  3781. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3782. if err != nil {
  3783. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3784. return
  3785. }
  3786. startTime = theTime.Unix()
  3787. }
  3788. var endTime int64
  3789. if len(end_time) > 0 {
  3790. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3791. if err != nil {
  3792. utils.ErrorLog(err.Error())
  3793. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3794. return
  3795. }
  3796. endTime = theTime.Unix()
  3797. }
  3798. list, err := service.FindPrintStockGoodInfoByType(types, startTime, endTime, orgId)
  3799. stockTotal, err := service.GetOutStockTotalCountTwo(startTime, endTime, orgId)
  3800. if err != nil {
  3801. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  3802. } else {
  3803. c.ServeSuccessJSON(map[string]interface{}{
  3804. "list": list,
  3805. "type": types,
  3806. "stockTotal": stockTotal,
  3807. })
  3808. }
  3809. }
  3810. func (c *DialysisAPIController) BatchDeleteMonitor() {
  3811. fmt.Println("jin2222245555555555")
  3812. ids := c.GetString("ids")
  3813. fmt.Println("dis22222222", ids)
  3814. idArray := strings.Split(ids, ",")
  3815. err := service.BatchDeleteMonitor(idArray)
  3816. fmt.Print("err", err)
  3817. c.ServeSuccessJSON(map[string]interface{}{
  3818. "msg": "批量删除成功",
  3819. })
  3820. return
  3821. }
  3822. func (c *DialysisAPIController) GetPatientDialysisRecordList() {
  3823. id, _ := c.GetInt64("id")
  3824. fmt.Println(id)
  3825. timeLayout := "2006-01-02"
  3826. loc, _ := time.LoadLocation("Local")
  3827. start_time := time.Now().Format("2006-01-02")
  3828. startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3829. fmt.Println("start_timestart_time", start_time)
  3830. nowTime := time.Now()
  3831. endTime := nowTime.AddDate(-1, 0, 0)
  3832. endTimes := endTime.Format("2006-01-02")
  3833. endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", endTimes+" 00:00:00", loc)
  3834. list, _ := service.GetPatientDialysisRecordList(id, endtime.Unix(), startime.Unix())
  3835. c.ServeSuccessJSON(map[string]interface{}{
  3836. "list": list,
  3837. })
  3838. return
  3839. }
  3840. func (c *DialysisAPIController) BathDeleteAdviceList() {
  3841. dataBody := make(map[string]interface{}, 0)
  3842. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3843. ids := c.GetString("ids")
  3844. fmt.Println("dis22222222", ids)
  3845. idArray := strings.Split(ids, ",")
  3846. origin, _ := c.GetInt64("origin")
  3847. if origin == 1 {
  3848. err = service.BatchDeleteAdvice(idArray)
  3849. fmt.Print("err", err)
  3850. c.ServeSuccessJSON(map[string]interface{}{
  3851. "msg": "批量删除成功",
  3852. })
  3853. return
  3854. }
  3855. if origin == 2 {
  3856. service.BatchDeleteHisAdvice(idArray)
  3857. }
  3858. }
  3859. func (c *DialysisAPIController) UpdateAutoReduceDetail() {
  3860. good_id, _ := c.GetInt64("good_id")
  3861. count, _ := c.GetInt64("count")
  3862. record_time, _ := c.GetInt64("record_time")
  3863. patient_id, _ := c.GetInt64("patient_id")
  3864. detail, _ := service.UpdateAutoReduceDetail(good_id, count, record_time, patient_id)
  3865. c.ServeSuccessJSON(map[string]interface{}{
  3866. "detail": detail,
  3867. })
  3868. return
  3869. }
  3870. func (c *DialysisAPIController) DeleteAutoReduceDetail() {
  3871. good_id, _ := c.GetInt64("good_id")
  3872. record_time, _ := c.GetInt64("record_time")
  3873. patient_id, _ := c.GetInt64("patient_id")
  3874. fmt.Println("0000000000000000", patient_id)
  3875. service.DeleteDialysisBeforOne(good_id, record_time, patient_id)
  3876. fmt.Println()
  3877. err := service.DeleteAutoReduceDetail(good_id, record_time, patient_id)
  3878. fmt.Print("err", err)
  3879. c.ServeSuccessJSON(map[string]interface{}{
  3880. "msg": "批量删除成功",
  3881. })
  3882. return
  3883. }
  3884. func (c *DialysisAPIController) BatchAdviceCheck() {
  3885. ids := c.GetString("ids")
  3886. idArray := strings.Split(ids, ",")
  3887. creator, _ := c.GetInt64("creator")
  3888. origin, _ := c.GetInt64("origin")
  3889. if origin == 1 {
  3890. err := service.BatchAdviceCheck(idArray, creator)
  3891. fmt.Println(err)
  3892. list, _ := service.GetAdviceExecutionById(idArray)
  3893. c.ServeSuccessJSON(map[string]interface{}{
  3894. "list": list,
  3895. })
  3896. return
  3897. }
  3898. if origin == 2 {
  3899. service.BatchHisAdviceCheck(idArray, creator)
  3900. list, _ := service.GetHisAdviceExecutionById(idArray)
  3901. c.ServeSuccessJSON(map[string]interface{}{
  3902. "list": list,
  3903. })
  3904. return
  3905. }
  3906. }
  3907. func (c *DialysisAPIController) BatchAdviceExecution() {
  3908. ids := c.GetString("ids")
  3909. idArray := strings.Split(ids, ",")
  3910. executionTime := c.GetString("execution_time")
  3911. creator, _ := c.GetInt64("creator")
  3912. timeLayout := "2006-01-02 15:04:05"
  3913. loc, _ := time.LoadLocation("Local")
  3914. theTime, _ := time.ParseInLocation(timeLayout, executionTime, loc)
  3915. orgin, _ := c.GetInt64("origin")
  3916. if orgin == 1 {
  3917. err := service.BatchAdviceExecution(idArray, creator, theTime.Unix())
  3918. list, _ := service.GetAdviceExecutionById(idArray)
  3919. fmt.Println(err)
  3920. c.ServeSuccessJSON(map[string]interface{}{
  3921. "list": list,
  3922. })
  3923. return
  3924. }
  3925. if orgin == 2 {
  3926. err := service.BatchHisAdviceExecution(idArray, creator, theTime.Unix())
  3927. list, _ := service.GetHisAdviceExecutionById(idArray)
  3928. fmt.Println(err)
  3929. c.ServeSuccessJSON(map[string]interface{}{
  3930. "list": list,
  3931. })
  3932. return
  3933. }
  3934. }
  3935. func (c *DialysisAPIController) UpdateStockGoods() {
  3936. good_id, _ := c.GetInt64("good_id")
  3937. record_time, _ := c.GetInt64("record_time")
  3938. patient_id, _ := c.GetInt64("patient_id")
  3939. count, _ := c.GetInt64("count")
  3940. err := service.UpdateStockGoods(good_id, record_time, patient_id, count)
  3941. fmt.Print("err", err)
  3942. c.ServeSuccessJSON(map[string]interface{}{
  3943. "msg": "更新成功",
  3944. })
  3945. return
  3946. }
  3947. //当前数据比上一次出库数据少
  3948. func ConsumablesDeliveryTotalSeven(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, creater int64, count int64) (err error) {
  3949. fmt.Println("w我的中国馆公共区发电房阿道夫安抚安抚安抚安抚安抚安抚阿道夫阿道夫阿凡达阿道夫a", count)
  3950. //查询该患者当天已经出库的耗材信息
  3951. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  3952. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  3953. for i := len(goods_yc) - 1; i >= 0; i-- {
  3954. goods_yc_temp := goods_yc[i]
  3955. for j := len(goods) - 1; j >= 0; j-- {
  3956. goods_temp := goods[j]
  3957. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  3958. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  3959. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  3960. if goods_yc_temp.Count == goods_temp.Count {
  3961. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  3962. goods = append(goods[:j], goods[j+1:]...)
  3963. break
  3964. }
  3965. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  3966. if goods_yc_temp.Count > goods_temp.Count {
  3967. temp_count := goods_yc_temp.Count - goods_temp.Count
  3968. goods_yc[i].Count = temp_count
  3969. goods = append(goods[:j], goods[j+1:]...)
  3970. break
  3971. }
  3972. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  3973. if goods_yc_temp.Count < goods_temp.Count {
  3974. temp_count := goods_temp.Count - goods_yc_temp.Count
  3975. //fmt.Println("988888888888888", temp_count)
  3976. goods[j].Count = temp_count
  3977. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  3978. //fmt.Println("888888888", goods_yc)
  3979. break
  3980. }
  3981. }
  3982. }
  3983. }
  3984. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  3985. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  3986. fmt.Println("goodsy999999999999", goods_yc)
  3987. //退库
  3988. if len(goods_yc) > 0 {
  3989. for _, good_yc := range goods_yc {
  3990. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  3991. ConsumablesDeliveryDeleteFour(orgID, record_time, good_yc, &out, patient_id, creater, count)
  3992. }
  3993. }
  3994. return nil
  3995. }
  3996. //耗材出库删除
  3997. func ConsumablesDeliveryDeleteFour(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  3998. fmt.Println("count2323223884584854854854u5454785487547845785478758487545475475487,count", count)
  3999. // 先根据相关信息查询当天该耗材的出库信息
  4000. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  4001. fmt.Println("errr232323232323232323232323232", err)
  4002. if err != nil {
  4003. return err
  4004. }
  4005. var delete_count int64 = 0
  4006. delete_count = warehouseOutInfos.Count - count
  4007. fmt.Println("delete_count2323232", delete_count)
  4008. // 在出库记录表里记录退库详情
  4009. warehouseOutInfo := &models.WarehouseOutInfo{
  4010. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4011. WarehouseOutId: warehouseOut.ID,
  4012. Status: 1,
  4013. Ctime: time.Now().Unix(),
  4014. OrgId: orgID,
  4015. Type: 1,
  4016. IsSys: 1,
  4017. SysRecordTime: record_time,
  4018. GoodTypeId: good_yc.GoodTypeId,
  4019. GoodId: good_yc.GoodId,
  4020. PatientId: good_yc.PatientId,
  4021. ConsumableType: 2,
  4022. }
  4023. warehouseOutInfo.Count = count
  4024. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4025. warehouseOutInfo.Price = stockInInfo.Price
  4026. warehouseOutInfo.Dealer = stockInInfo.Dealer
  4027. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  4028. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  4029. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  4030. warehouseOutInfo.Number = warehouseOutInfos.Number
  4031. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  4032. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  4033. //查找当天是否存在出库记录
  4034. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time)
  4035. fmt.Println("errcode2323223255556652324242424242424242424242424242242", errcod)
  4036. if errcod == gorm.ErrRecordNotFound {
  4037. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4038. //插入详情明细表
  4039. stockFlow := models.VmStockFlow{
  4040. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4041. WarehouseOutId: warehouseOut.ID,
  4042. GoodId: good_yc.GoodId,
  4043. Number: warehouseOutInfos.Number,
  4044. ProductDate: stockInInfo.ProductDate,
  4045. ExpireDate: stockInInfo.ExpiryDate,
  4046. Count: count,
  4047. Price: stockInInfo.Price,
  4048. Status: 1,
  4049. Ctime: time.Now().Unix(),
  4050. UserOrgId: good_yc.OrgId,
  4051. Manufacturer: stockInInfo.Manufacturer,
  4052. Dealer: stockInInfo.Dealer,
  4053. LicenseNumber: stockInInfo.LicenseNumber,
  4054. IsEdit: 2,
  4055. Creator: creater,
  4056. SystemTime: record_time,
  4057. ConsumableType: 3,
  4058. WarehousingDetailId: 0,
  4059. IsSys: 1,
  4060. UpdateCreator: creater,
  4061. PatientId: patient_id,
  4062. }
  4063. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4064. if errflow == gorm.ErrRecordNotFound {
  4065. //创建流水表
  4066. err := service.CreateStockFlowOne(stockFlow)
  4067. fmt.Println("h2h3h2323342i24i242i4u2i4242u42424", err)
  4068. } else if errflow == nil {
  4069. //插入详情明细表
  4070. stockFlow := models.VmStockFlow{
  4071. ID: exsit.ID,
  4072. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4073. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4074. WarehouseOutId: warehouseOut.ID,
  4075. GoodId: good_yc.GoodId,
  4076. Number: warehouseOutInfos.Number,
  4077. ProductDate: stockInInfo.ProductDate,
  4078. ExpireDate: stockInInfo.ExpiryDate,
  4079. Count: exsit.Count - delete_count,
  4080. Price: stockInInfo.Price,
  4081. Status: 1,
  4082. Ctime: time.Now().Unix(),
  4083. UserOrgId: good_yc.OrgId,
  4084. Manufacturer: stockInInfo.Manufacturer,
  4085. Dealer: stockInInfo.Dealer,
  4086. LicenseNumber: stockInInfo.LicenseNumber,
  4087. IsEdit: 2,
  4088. Creator: creater,
  4089. SystemTime: record_time,
  4090. ConsumableType: 3,
  4091. WarehousingDetailId: 0,
  4092. IsSys: 1,
  4093. UpdateCreator: creater,
  4094. PatientId: patient_id,
  4095. }
  4096. service.UpdatedStockFlow(stockFlow)
  4097. }
  4098. if errOne != nil {
  4099. return errOne
  4100. }
  4101. } else if errcod == nil {
  4102. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time)
  4103. //插入详情明细表
  4104. stockFlow := models.VmStockFlow{
  4105. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4106. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4107. WarehouseOutId: warehouseOut.ID,
  4108. GoodId: good_yc.GoodId,
  4109. Number: warehouseOutInfos.Number,
  4110. ProductDate: stockInInfo.ProductDate,
  4111. ExpireDate: stockInInfo.ExpiryDate,
  4112. Count: count,
  4113. Price: stockInInfo.Price,
  4114. Status: 1,
  4115. Ctime: time.Now().Unix(),
  4116. UserOrgId: good_yc.OrgId,
  4117. Manufacturer: stockInInfo.Manufacturer,
  4118. Dealer: stockInInfo.Dealer,
  4119. LicenseNumber: stockInInfo.LicenseNumber,
  4120. IsEdit: 2,
  4121. Creator: creater,
  4122. SystemTime: record_time,
  4123. ConsumableType: 3,
  4124. WarehousingDetailId: 0,
  4125. IsSys: 1,
  4126. UpdateCreator: creater,
  4127. PatientId: patient_id,
  4128. ReturnCount: delete_count,
  4129. }
  4130. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4131. if errflows == gorm.ErrRecordNotFound {
  4132. //创建流水表
  4133. service.CreateStockFlowOne(stockFlow)
  4134. } else if errflows == nil {
  4135. stockFlow := models.VmStockFlow{
  4136. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4137. ID: exsit.ID,
  4138. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4139. WarehouseOutId: warehouseOut.ID,
  4140. GoodId: good_yc.GoodId,
  4141. Number: warehouseOutInfos.Number,
  4142. ProductDate: stockInInfo.ProductDate,
  4143. ExpireDate: stockInInfo.ExpiryDate,
  4144. Count: exsit.Count - delete_count,
  4145. Price: stockInInfo.Price,
  4146. Status: 1,
  4147. Ctime: time.Now().Unix(),
  4148. UserOrgId: good_yc.OrgId,
  4149. Manufacturer: stockInInfo.Manufacturer,
  4150. Dealer: stockInInfo.Dealer,
  4151. LicenseNumber: stockInInfo.LicenseNumber,
  4152. IsEdit: 2,
  4153. Creator: creater,
  4154. SystemTime: record_time,
  4155. ConsumableType: 3,
  4156. WarehousingDetailId: 0,
  4157. IsSys: 1,
  4158. UpdateCreator: creater,
  4159. PatientId: patient_id,
  4160. ReturnCount: delete_count,
  4161. }
  4162. service.UpdatedStockFlow(stockFlow)
  4163. }
  4164. }
  4165. //更改自动出库的表格
  4166. details := models.BloodAutomaticReduceDetail{
  4167. WarehouseOutId: warehouseOutInfo.ID,
  4168. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  4169. PatientId: patient_id,
  4170. Ctime: time.Now().Unix(),
  4171. Mtime: time.Now().Unix(),
  4172. Status: 1,
  4173. RecordTime: record_time,
  4174. OrgId: orgID,
  4175. GoodId: good_yc.GoodId,
  4176. GoodTypeId: good_yc.GoodTypeId,
  4177. Count: count,
  4178. }
  4179. //查询当天耗材是否已经存在数据
  4180. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4181. if errcode == gorm.ErrRecordNotFound {
  4182. errTwo := service.CreateAutoReduceRecord(&details)
  4183. if errTwo != nil {
  4184. return errTwo
  4185. }
  4186. } else if errcode == nil {
  4187. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4188. service.CreateAutoReduceRecord(&details)
  4189. }
  4190. // 删除出库完成后,要增加对应批次的库存数量
  4191. fmt.Println("deletecount2323232323232323232323232323", delete_count)
  4192. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count)
  4193. if errThree != nil {
  4194. return errThree
  4195. }
  4196. if good_yc.Count == 0 {
  4197. return nil
  4198. } else {
  4199. return errors.New("退库和出库数据不匹配")
  4200. }
  4201. }
  4202. func ConsumablesDeliveryTotalSix(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, goodOne []*models.NewDialysisBeforePrepareGoods, creater int64) (err error) {
  4203. //查询该患者当天已经出库的耗材信息
  4204. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  4205. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  4206. for i := len(goods_yc) - 1; i >= 0; i-- {
  4207. goods_yc_temp := goods_yc[i]
  4208. for j := len(goods) - 1; j >= 0; j-- {
  4209. goods_temp := goods[j]
  4210. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  4211. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  4212. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  4213. if goods_yc_temp.Count == goods_temp.Count {
  4214. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4215. goods = append(goods[:j], goods[j+1:]...)
  4216. break
  4217. }
  4218. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  4219. if goods_yc_temp.Count > goods_temp.Count {
  4220. temp_count := goods_yc_temp.Count - goods_temp.Count
  4221. goods_yc[i].Count = temp_count
  4222. goods = append(goods[:j], goods[j+1:]...)
  4223. break
  4224. }
  4225. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  4226. if goods_yc_temp.Count < goods_temp.Count {
  4227. temp_count := goods_temp.Count - goods_yc_temp.Count
  4228. goods[j].Count = temp_count
  4229. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4230. break
  4231. }
  4232. }
  4233. }
  4234. }
  4235. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  4236. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  4237. fmt.Println("goods222222222222", goods)
  4238. fmt.Println("goodsy999999999999", goods_yc)
  4239. if len(goods) > 0 {
  4240. out, err := service.FindStockOutByIsSys(orgID, 1, record_time)
  4241. if err == gorm.ErrRecordNotFound {
  4242. //没有记录,则创建出库单
  4243. timeStr := time.Now().Format("2006-01-02")
  4244. timeArr := strings.Split(timeStr, "-")
  4245. total, _ := service.FindAllWarehouseOut(orgID)
  4246. total = total + 1
  4247. warehousing_out_order := strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4248. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4249. number = number + total
  4250. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4251. warehouseOut := models.WarehouseOut{
  4252. WarehouseOutOrderNumber: warehousing_out_order,
  4253. OperationTime: time.Now().Unix(),
  4254. OrgId: orgID,
  4255. Creater: creater,
  4256. Ctime: time.Now().Unix(),
  4257. Status: 1,
  4258. WarehouseOutTime: record_time,
  4259. Dealer: 0,
  4260. Manufacturer: 0,
  4261. Type: 1,
  4262. IsSys: 1,
  4263. }
  4264. err := service.AddSigleWarehouseOut(&warehouseOut)
  4265. if err != nil {
  4266. utils.TraceLog("创建出库单失败 err = %v", err)
  4267. return err
  4268. } else {
  4269. out = warehouseOut
  4270. }
  4271. }
  4272. for _, item := range goods {
  4273. var newCount int64 = 0
  4274. for _, it := range goodOne {
  4275. if item.GoodTypeId == it.GoodTypeId && item.GoodId == it.GoodId {
  4276. newCount = it.Count
  4277. }
  4278. }
  4279. prepare := models.DialysisBeforePrepare{
  4280. GoodTypeId: item.GoodTypeId,
  4281. GoodId: item.GoodId,
  4282. Count: item.Count,
  4283. }
  4284. fmt.Println("到这里了吗34344343434334343434", newCount)
  4285. service.ConsumablesDelivery(orgID, patient_id, record_time, &prepare, &out, newCount)
  4286. }
  4287. }
  4288. if len(goods_yc) > 0 {
  4289. for _, good_yc := range goods_yc {
  4290. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  4291. ConsumablesDeliveryDeleteThree(orgID, record_time, good_yc, &out)
  4292. }
  4293. }
  4294. return nil
  4295. }
  4296. //耗材出库删除
  4297. func ConsumablesDeliveryDeleteThree(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut) (err error) {
  4298. // 先根据相关信息查询当天该耗材的出库信息
  4299. warehouseOutInfos, err := service.FindStockOutInfoByStockOne(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time)
  4300. if err != nil {
  4301. return err
  4302. }
  4303. var delete_count int64 = 0
  4304. for _, ware := range warehouseOutInfos {
  4305. // 判断当前出库的数据和删除出库数量
  4306. if good_yc.Count <= ware.Count {
  4307. delete_count = good_yc.Count
  4308. } else {
  4309. delete_count = ware.Count
  4310. }
  4311. // 在出库记录表里记录退库详情
  4312. warehouseOutInfo := &models.WarehouseOutInfo{
  4313. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4314. WarehouseOutId: warehouseOut.ID,
  4315. Status: 1,
  4316. Ctime: time.Now().Unix(),
  4317. Remark: "",
  4318. OrgId: orgID,
  4319. Type: 1,
  4320. Manufacturer: 0,
  4321. Dealer: 0,
  4322. IsSys: 0,
  4323. SysRecordTime: record_time,
  4324. GoodTypeId: good_yc.GoodTypeId,
  4325. GoodId: good_yc.GoodId,
  4326. }
  4327. warehouseOutInfo.Count = delete_count
  4328. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4329. warehouseOutInfo.Price = stockInInfo.Price
  4330. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4331. if errOne != nil {
  4332. return errOne
  4333. }
  4334. //更改自动出库的表格
  4335. // 删除出库完成后,要增加对应批次的库存数量
  4336. fmt.Println("deletecount2323232323232323232323232323", delete_count)
  4337. errThree := service.UpDateWarehouseInfoByStockDelete(ware.WarehouseInfotId, delete_count)
  4338. if errThree != nil {
  4339. return errThree
  4340. }
  4341. }
  4342. if good_yc.Count == 0 {
  4343. return nil
  4344. } else {
  4345. return errors.New("退库和出库数据不匹配")
  4346. }
  4347. }