dialysis_api_controller.go 182KB

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