dialysis_api_controller.go 203KB

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