dialysis_api_controller.go 220KB

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