dialysis_api_controller.go 186KB

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