dialysis_api_controller.go 178KB

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