dialysis_api_controller.go 204KB

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