dialysis_api_controller.go 182KB

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