dialysis_api_controller.go 216KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797
  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. advices, err := service.GetLastLongAdviceByGroupNoOne(adminUserInfo.Org.Id, patient_id)
  2898. advices_two, err := service.GetLastLongAdviceByGroupNoFour(adminUserInfo.Org.Id, patient_id)
  2899. for _, advice := range advices {
  2900. if advice.FrequencyType == 3 {
  2901. t := time.Now()
  2902. week := int(t.Weekday())
  2903. fmt.Println(t.Weekday())
  2904. fmt.Println(week)
  2905. switch week {
  2906. case 1:
  2907. if strings.Index(advice.WeekDay, "周一") == -1 {
  2908. advice_three = append(advice_three, advice)
  2909. }
  2910. break
  2911. case 2:
  2912. if strings.Index(advice.WeekDay, "周二") == -1 {
  2913. advice_three = append(advice_three, advice)
  2914. }
  2915. break
  2916. case 3:
  2917. if strings.Index(advice.WeekDay, "周三") == -1 {
  2918. advice_three = append(advice_three, advice)
  2919. }
  2920. break
  2921. case 4:
  2922. if strings.Index(advice.WeekDay, "周四") == -1 {
  2923. advice_three = append(advice_three, advice)
  2924. }
  2925. break
  2926. case 5:
  2927. if strings.Index(advice.WeekDay, "周五") == -1 {
  2928. advice_three = append(advice_three, advice)
  2929. }
  2930. break
  2931. case 6:
  2932. if strings.Index(advice.WeekDay, "周六") == -1 {
  2933. advice_three = append(advice_three, advice)
  2934. }
  2935. break
  2936. case 0:
  2937. if strings.Index(advice.WeekDay, "周日") == -1 {
  2938. advice_three = append(advice_three, advice)
  2939. }
  2940. break
  2941. }
  2942. }
  2943. }
  2944. for _, advice := range advices_two {
  2945. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2946. now := p.Unix()
  2947. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2948. dayStr2 := "-" + dayStr
  2949. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2950. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2951. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2952. for _, ad := range advices {
  2953. advice_three = append(advice_three, ad)
  2954. }
  2955. }
  2956. if err == nil {
  2957. c.ServeSuccessJSON(map[string]interface{}{
  2958. "status": "2",
  2959. "advices": advices,
  2960. "advices_two": RemoveRepeatedElement(advice_three),
  2961. "is_open_remind": config.IsOpenRemind,
  2962. "his_config_open": hisConfig.IsOpen,
  2963. "is_advice_open": is_advice_open.IsAdviceOpen,
  2964. "prescription_open": prescription_open.IsOpen,
  2965. })
  2966. }
  2967. }
  2968. }
  2969. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  2970. newArr = make([]*models.DoctorAdvice, 0)
  2971. for i := 0; i < len(arr); i++ {
  2972. repeat := false
  2973. for j := i + 1; j < len(arr); j++ {
  2974. if arr[i].ID == arr[j].ID {
  2975. repeat = true
  2976. break
  2977. }
  2978. }
  2979. if !repeat {
  2980. newArr = append(newArr, arr[i])
  2981. }
  2982. }
  2983. return
  2984. }
  2985. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  2986. patient, _ := c.GetInt64("id", 0)
  2987. groupNo, _ := c.GetInt64("groupno", 0)
  2988. if patient <= 0 {
  2989. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2990. return
  2991. }
  2992. adminUserInfo := c.GetMobileAdminUserInfo()
  2993. dataBody := make(map[string]interface{}, 0)
  2994. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2995. if err != nil {
  2996. utils.ErrorLog(err.Error())
  2997. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2998. return
  2999. }
  3000. utils.ErrorLog("%v", dataBody)
  3001. timeLayout := "2006-01-02 15:04"
  3002. loc, _ := time.LoadLocation("Local")
  3003. timeLayout2 := "2006-01-02"
  3004. loc2, _ := time.LoadLocation("Local")
  3005. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  3006. utils.ErrorLog("advice_type")
  3007. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3008. return
  3009. }
  3010. adviceType := int64(2)
  3011. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  3012. utils.ErrorLog("advice_date")
  3013. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3014. return
  3015. }
  3016. adviceDate, _ := dataBody["advice_date"].(string)
  3017. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  3018. AdviceDate := theTime.Unix()
  3019. RecordDate := theTime.Unix()
  3020. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  3021. utils.ErrorLog("start_time")
  3022. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3023. return
  3024. }
  3025. startTime, _ := dataBody["start_time"].(string)
  3026. if len(startTime) == 0 {
  3027. utils.ErrorLog("len(start_time) == 0")
  3028. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3029. return
  3030. }
  3031. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  3032. if err != nil {
  3033. utils.ErrorLog(err.Error())
  3034. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3035. return
  3036. }
  3037. StartTime := theTime.Unix()
  3038. Remark := ""
  3039. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  3040. remark, _ := dataBody["remark"].(string)
  3041. Remark = remark
  3042. }
  3043. var advices []*models.GroupAdvice
  3044. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  3045. utils.ErrorLog("advices")
  3046. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3047. return
  3048. }
  3049. adviceNames := dataBody["advices"].([]interface{})
  3050. for _, adviceNameMap := range adviceNames {
  3051. adviceNameM := adviceNameMap.(map[string]interface{})
  3052. var advice models.GroupAdvice
  3053. advice.Remark = Remark
  3054. advice.AdviceType = adviceType
  3055. advice.StartTime = StartTime
  3056. advice.AdviceDate = AdviceDate
  3057. advice.RecordDate = RecordDate
  3058. advice.Status = 1
  3059. advice.CreatedTime = time.Now().Unix()
  3060. advice.UpdatedTime = time.Now().Unix()
  3061. advice.StopState = 2
  3062. advice.ExecutionState = 2
  3063. advice.UserOrgId = adminUserInfo.Org.Id
  3064. advice.PatientId = patient
  3065. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  3066. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  3067. utils.ErrorLog("advice_name")
  3068. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3069. return
  3070. }
  3071. adviceName, _ := adviceNameM["advice_name"].(string)
  3072. if len(adviceName) == 0 {
  3073. utils.ErrorLog("len(advice_name) == 0")
  3074. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3075. return
  3076. }
  3077. advice.AdviceName = adviceName
  3078. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  3079. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  3080. advice.DrugSpec = drugSpec
  3081. }
  3082. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  3083. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  3084. advice.AdviceDesc = adviceDesc
  3085. }
  3086. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  3087. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  3088. advice.DrugSpecUnit = drugSpecUnit
  3089. }
  3090. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  3091. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  3092. // advice.SingleDose = singleDose
  3093. //}
  3094. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  3095. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3096. advice.SingleDose = adviceNameM["single_dose"].(float64)
  3097. }
  3098. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  3099. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  3100. advice.SingleDoseUnit = singleDoseUnit
  3101. }
  3102. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  3103. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  3104. // advice.PrescribingNumber = prescribingNumber
  3105. //}
  3106. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  3107. //single_dose := int64(adviceNameM["single_dose"].(float64))
  3108. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  3109. }
  3110. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  3111. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  3112. advice.PrescribingNumberUnit = prescribingNumberUnit
  3113. }
  3114. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  3115. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  3116. advice.DeliveryWay = deliveryWay
  3117. }
  3118. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  3119. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3120. advice.ExecutionFrequency = executionFrequency
  3121. }
  3122. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  3123. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  3124. advice.FrequencyType = frequency_type
  3125. }
  3126. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  3127. day_count := int64(adviceNameM["day_count"].(float64))
  3128. advice.DayCount = day_count
  3129. }
  3130. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  3131. week_day, _ := adviceNameM["week_day"].(string)
  3132. advice.WeekDay = week_day
  3133. }
  3134. if adviceNameM["way"] != nil || reflect.TypeOf(adviceNameM["way"]).String() == "float64" {
  3135. way := int64(adviceNameM["way"].(float64))
  3136. advice.Way = way
  3137. }
  3138. if adviceNameM["drug_id"] != nil || reflect.TypeOf(adviceNameM["drug_id"]).String() == "float64" {
  3139. drug_id := int64(adviceNameM["drug_id"].(float64))
  3140. advice.DrugId = drug_id
  3141. }
  3142. if adviceNameM["drug_name_id"] != nil || reflect.TypeOf(adviceNameM["drug_name_id"]).String() == "float64" {
  3143. drug_name_id := int64(adviceNameM["drug_name_id"].(float64))
  3144. advice.DrugNameId = drug_name_id
  3145. }
  3146. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  3147. template_id, _ := adviceNameM["template_id"].(string)
  3148. advice.TemplateId = template_id
  3149. }
  3150. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  3151. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  3152. advice.ExecutionFrequency = executionFrequency
  3153. }
  3154. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  3155. children := adviceNameM["child"].([]interface{})
  3156. if len(children) > 0 {
  3157. for _, childrenMap := range children {
  3158. childMap := childrenMap.(map[string]interface{})
  3159. var child models.GroupAdvice
  3160. child.Remark = Remark
  3161. child.AdviceType = adviceType
  3162. child.StartTime = StartTime
  3163. child.AdviceDate = AdviceDate
  3164. child.RecordDate = RecordDate
  3165. child.Status = 1
  3166. child.CreatedTime = time.Now().Unix()
  3167. child.UpdatedTime = time.Now().Unix()
  3168. child.StopState = 2
  3169. child.ExecutionState = 2
  3170. child.UserOrgId = adminUserInfo.Org.Id
  3171. child.PatientId = patient
  3172. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  3173. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  3174. utils.ErrorLog("child advice_name")
  3175. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3176. return
  3177. }
  3178. childAdviceName, _ := childMap["advice_name"].(string)
  3179. if len(childAdviceName) == 0 {
  3180. utils.ErrorLog("len(child advice_name) == 0")
  3181. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3182. return
  3183. }
  3184. child.AdviceName = childAdviceName
  3185. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  3186. childAdviceDesc, _ := childMap["advice_desc"].(string)
  3187. child.AdviceDesc = childAdviceDesc
  3188. }
  3189. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  3190. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  3191. child.DrugSpec = childDrugSpec
  3192. }
  3193. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  3194. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  3195. child.DrugSpecUnit = childDrugSpecUnit
  3196. }
  3197. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  3198. child.SingleDose = childMap["single_dose"].(float64)
  3199. }
  3200. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  3201. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  3202. child.SingleDoseUnit = childSingleDoseUnit
  3203. }
  3204. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  3205. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  3206. }
  3207. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  3208. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  3209. child.PrescribingNumberUnit = childPrescribingNumberUnit
  3210. }
  3211. child.DeliveryWay = advice.DeliveryWay
  3212. child.ExecutionFrequency = advice.ExecutionFrequency
  3213. advice.Children = append(advice.Children, &child)
  3214. }
  3215. }
  3216. }
  3217. temp_advice, _ := service.FindRemindAdvice(advice.UserOrgId, advice.AdviceName, advice.AdviceDesc, advice.TemplateId, advice.FrequencyType, patient, advice.RecordDate)
  3218. if temp_advice.ID == 0 {
  3219. advices = append(advices, &advice)
  3220. }
  3221. }
  3222. if len(advices) > 0 {
  3223. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  3224. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient, 10) + ":" + strconv.FormatInt(RecordDate, 10) + ":doctor_advices"
  3225. redis := service.RedisClient()
  3226. //清空key 值
  3227. redis.Set(key, "", time.Second)
  3228. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(AdviceDate, 10) + ":advice_list_all"
  3229. redis.Set(keyOne, "", time.Second)
  3230. keyThree := "scheduals_" + adviceDate + "_" + strconv.FormatInt(adminUserInfo.Org.Id, 10)
  3231. defer redis.Close()
  3232. redis.Set(keyThree, "", time.Second)
  3233. if err != nil {
  3234. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  3235. return
  3236. }
  3237. c.ServeSuccessJSON(map[string]interface{}{
  3238. "msg": "ok",
  3239. "advices": list,
  3240. })
  3241. } else {
  3242. c.ServeSuccessJSON(map[string]interface{}{
  3243. "msg": "ok",
  3244. })
  3245. }
  3246. return
  3247. }
  3248. func (c *DialysisAPIController) UploadDryWeight() {
  3249. patient_id, _ := c.GetInt64("id")
  3250. dry_weight, _ := c.GetFloat("dry_weight")
  3251. doctor_id, _ := c.GetInt64("doctor_id")
  3252. remark := c.GetString("remark")
  3253. adminUserInfo := c.GetMobileAdminUserInfo()
  3254. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  3255. if err == gorm.ErrRecordNotFound {
  3256. dryWeight := &models.SgjPatientDryweight{
  3257. PatientId: patient_id,
  3258. DryWeight: dry_weight,
  3259. Remakes: remark,
  3260. Ctime: time.Now().Unix(),
  3261. Mtime: time.Now().Unix(),
  3262. Creator: doctor_id,
  3263. Status: 1,
  3264. UserOrgId: adminUserInfo.Org.Id,
  3265. AdjustedValue: "/",
  3266. UserId: adminUserInfo.AdminUser.Id,
  3267. }
  3268. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3269. redis := service.RedisClient()
  3270. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + ":assessment_befores_list_all"
  3271. redis.Set(keyOne, "", time.Second)
  3272. loc, _ := time.LoadLocation("Local")
  3273. nowTime := time.Now()
  3274. nowDay := nowTime.Format("2006-01-02")
  3275. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3276. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3277. redis.Set(key, "", time.Second)
  3278. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3279. redis.Set(keyTwo, "", time.Second)
  3280. redis.Close()
  3281. if createErr == nil {
  3282. c.ServeSuccessJSON(map[string]interface{}{
  3283. "msg": "提交成功",
  3284. "weight": dryWeight,
  3285. })
  3286. }
  3287. } else {
  3288. dryWeight := &models.SgjPatientDryweight{
  3289. PatientId: patient_id,
  3290. DryWeight: dry_weight,
  3291. Remakes: remark,
  3292. Ctime: time.Now().Unix(),
  3293. Mtime: time.Now().Unix(),
  3294. Creator: doctor_id,
  3295. Status: 1,
  3296. UserOrgId: adminUserInfo.Org.Id,
  3297. AdjustedValue: "/",
  3298. UserId: adminUserInfo.AdminUser.Id,
  3299. }
  3300. var value float64
  3301. value = dry_weight - weightAdjust.DryWeight
  3302. if value < 0 {
  3303. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  3304. } else if value == 0 {
  3305. dryWeight.AdjustedValue = "/"
  3306. } else if value > 0 {
  3307. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  3308. }
  3309. createErr := service.CreatePatientWeightAdjust(dryWeight)
  3310. redis := service.RedisClient()
  3311. loc, _ := time.LoadLocation("Local")
  3312. nowTime := time.Now()
  3313. nowDay := nowTime.Format("2006-01-02")
  3314. dayTime, _ := time.ParseInLocation("2006-01-02 15:04:05", nowDay+" 00:00:00", loc)
  3315. keyOne := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_befores_list_all"
  3316. redis.Set(keyOne, "", time.Second)
  3317. key := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(dayTime.Unix(), 10) + ":assessment_before_dislysis"
  3318. redis.Set(key, "", time.Second)
  3319. keyTwo := strconv.FormatInt(adminUserInfo.Org.Id, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":last_dry_weight"
  3320. redis.Set(keyTwo, "", time.Second)
  3321. redis.Close()
  3322. if createErr == nil {
  3323. c.ServeSuccessJSON(map[string]interface{}{
  3324. "msg": "提交成功",
  3325. "weight": dryWeight,
  3326. })
  3327. }
  3328. }
  3329. }
  3330. func (c *DialysisAPIController) GetSolution() {
  3331. patient_id, _ := c.GetInt64("patient_id")
  3332. mode_id, _ := c.GetInt64("mode_id")
  3333. adminUserInfo := c.GetMobileAdminUserInfo()
  3334. solution, err := service.MobileGetDialysisSolutionByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3335. prescription, err := service.MobileGetLastDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, patient_id, mode_id)
  3336. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeIdSeven(adminUserInfo.Org.Id, mode_id)
  3337. if err != nil {
  3338. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3339. return
  3340. }
  3341. c.ServeSuccessJSON(map[string]interface{}{
  3342. "solution": solution,
  3343. "prescription": prescription,
  3344. "system_prescription": system_prescription,
  3345. })
  3346. }
  3347. func (c *DialysisAPIController) GetSchedule() {
  3348. schedual_type, _ := c.GetInt64("schedual_type")
  3349. adminUserInfo := c.GetMobileAdminUserInfo()
  3350. //timeLayout := "2006-01-02 15:04:05"
  3351. //
  3352. //date := time.Now().Format("2006-01-02") + " 00:00:00"
  3353. //loc, _ := time.LoadLocation("Local")
  3354. //theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  3355. //scheduleTime := theStartTime.Unix()
  3356. scheduleTime, _ := c.GetInt64("record_date")
  3357. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  3358. list, _ := service.GetAllBedNumberSeven(adminUserInfo.Org.Id)
  3359. c.ServeSuccessJSON(map[string]interface{}{
  3360. "number": deviceNumber,
  3361. "list": list,
  3362. })
  3363. }
  3364. func (c *DialysisAPIController) GetPatientId() {
  3365. id, _ := c.GetInt64("id")
  3366. //orgid := c.GetMobileAdminUserInfo().Org.Id
  3367. patientId, _ := service.GetPatientId(id)
  3368. //获取该患者的所有传染病
  3369. list, _ := service.GetPatientInfectious(id)
  3370. c.ServeSuccessJSON(map[string]interface{}{
  3371. "patient": patientId,
  3372. "infectioulist": list,
  3373. })
  3374. }
  3375. func (this *DialysisAPIController) GetDialysisSchedule() {
  3376. schedualDate := this.GetString("date")
  3377. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3378. if parseDateErr != nil {
  3379. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3380. return
  3381. }
  3382. adminInfo := this.GetMobileAdminUserInfo()
  3383. orgID := adminInfo.Org.Id
  3384. redis := service.RedisClient()
  3385. defer redis.Close()
  3386. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  3387. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  3388. if len(scheduals) > 0 {
  3389. //缓存数据
  3390. scheduals_json, err := json.Marshal(scheduals)
  3391. if err == nil {
  3392. redis.Set(key, scheduals_json, time.Second*30)
  3393. }
  3394. }
  3395. this.ServeSuccessJSON(map[string]interface{}{
  3396. "scheduals": scheduals,
  3397. })
  3398. }
  3399. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  3400. change_type, _ := this.GetInt64("type", 0)
  3401. record_date := this.GetString("record_time")
  3402. patient_id, _ := this.GetInt64("patient_id", 0)
  3403. timeLayout := "2006-01-02"
  3404. loc, _ := time.LoadLocation("Local")
  3405. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3406. record_time := theAdviceRecordTime.Unix()
  3407. adminUserInfo := this.GetMobileAdminUserInfo()
  3408. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  3409. if err == nil {
  3410. if len(advices) == 0 {
  3411. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  3412. return
  3413. } else {
  3414. this.ServeSuccessJSON(map[string]interface{}{
  3415. "advices": advices,
  3416. "schedule": sch,
  3417. })
  3418. return
  3419. }
  3420. } else {
  3421. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3422. return
  3423. }
  3424. }
  3425. func (c *DialysisAPIController) CreateConsumables() {
  3426. record_date := c.GetString("record_time")
  3427. patient_id, _ := c.GetInt64("patient_id", 0)
  3428. active, _ := c.GetInt64("active")
  3429. adminUser := c.GetMobileAdminUserInfo()
  3430. timeLayout := "2006-01-02"
  3431. loc, _ := time.LoadLocation("Local")
  3432. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3433. record_time := theRecordTime.Unix()
  3434. dataBody := make(map[string]interface{}, 0)
  3435. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3436. if err != nil {
  3437. utils.ErrorLog(err.Error())
  3438. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3439. return
  3440. }
  3441. houseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3442. var beforePrepares []*models.DialysisBeforePrepareGoods
  3443. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3444. var dialysisBefor []*models.DialysisBeforePrepare
  3445. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3446. goods, _ := dataBody["goods"].([]interface{})
  3447. if len(goods) > 0 {
  3448. for _, item := range goods {
  3449. items := item.(map[string]interface{})
  3450. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3451. utils.ErrorLog("good_id")
  3452. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3453. return
  3454. }
  3455. good_id := int64(items["good_id"].(float64))
  3456. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3457. utils.ErrorLog("good_type_id")
  3458. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3459. return
  3460. }
  3461. good_type_id := int64(items["good_type_id"].(float64))
  3462. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3463. utils.ErrorLog("count")
  3464. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3465. return
  3466. }
  3467. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3468. commdity_code := items["commdity_code"].(string)
  3469. fmt.Println("commdity", commdity_code)
  3470. prepareGoods := &models.DialysisBeforePrepareGoods{
  3471. GoodTypeId: good_type_id,
  3472. GoodId: good_id,
  3473. Count: count,
  3474. StorehouseId: houseConfig.StorehouseOutInfo,
  3475. }
  3476. beforePrepares = append(beforePrepares, prepareGoods)
  3477. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3478. GoodTypeId: good_type_id,
  3479. GoodId: good_id,
  3480. Count: count,
  3481. StorehouseId: houseConfig.StorehouseOutInfo,
  3482. }
  3483. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3484. prepare := &models.DialysisBeforePrepare{
  3485. GoodTypeId: good_type_id,
  3486. GoodId: good_id,
  3487. Count: count,
  3488. PatientId: patient_id,
  3489. RecordDate: record_time,
  3490. UserOrgId: adminUser.Org.Id,
  3491. Status: 1,
  3492. Ctime: time.Now().Unix(),
  3493. Creater: adminUser.AdminUser.Id,
  3494. CommdityCode: commdity_code,
  3495. StorehouseId: houseConfig.StorehouseOutInfo,
  3496. }
  3497. dialysisBefor = append(dialysisBefor, prepare)
  3498. }
  3499. }
  3500. //查询是否有库存
  3501. for _, item := range dialysisBefor {
  3502. _, err := service.FindFirstWarehousingInfoByStock(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  3503. if err == gorm.ErrRecordNotFound {
  3504. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3505. c.ServeSuccessJSON(map[string]interface{}{
  3506. "message": "1",
  3507. "good_name": goodObj.GoodName,
  3508. "specification_name": goodObj.SpecificationName,
  3509. })
  3510. return
  3511. }
  3512. if err != nil {
  3513. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3514. c.ServeSuccessJSON(map[string]interface{}{
  3515. "message": "1",
  3516. "good_name": goodObj.GoodName,
  3517. "specification_name": goodObj.SpecificationName,
  3518. })
  3519. return
  3520. }
  3521. }
  3522. //新增
  3523. if active == 1 && len(goods) > 0 {
  3524. for _, item := range dialysisBefor {
  3525. dialyPrepareOne := models.DialysisBeforePrepare{
  3526. GoodTypeId: item.GoodTypeId,
  3527. GoodId: item.GoodId,
  3528. PatientId: item.PatientId,
  3529. RecordDate: item.RecordDate,
  3530. UserOrgId: item.UserOrgId,
  3531. Count: item.Count,
  3532. Ctime: time.Now().Unix(),
  3533. Creater: item.Creater,
  3534. CommdityCode: item.CommdityCode,
  3535. Status: 1,
  3536. StorehouseId: houseConfig.StorehouseOutInfo,
  3537. }
  3538. //先清除再插入
  3539. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3540. err = service.CreateDialysisBeforePrepareOne(&dialyPrepareOne)
  3541. //查询默认仓库
  3542. //houseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3543. //goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.GoodId, adminUser.Org.Id)
  3544. //var sum_count int64
  3545. //var sum_in_count int64
  3546. //for _, it := range goodList {
  3547. // sum_count += it.StockCount
  3548. // sum_in_count += it.WarehousingCount
  3549. //}
  3550. //service.UpdateGoodByGoodId(item.GoodId, sum_count, sum_in_count, adminUser.Org.Id)
  3551. //查询默认仓库
  3552. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3553. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3554. var total_count int64
  3555. for _, it := range stockList {
  3556. total_count += it.StockCount
  3557. }
  3558. //基础库插入数据
  3559. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3560. }
  3561. if err == nil {
  3562. c.ServeSuccessJSON(map[string]interface{}{
  3563. "msg": "保存成功",
  3564. "message": "2",
  3565. })
  3566. return
  3567. } else {
  3568. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3569. return
  3570. }
  3571. }
  3572. if len(beforePrepares) > 0 && active == 2 {
  3573. for _, item := range beforePrepares {
  3574. //1.查看该患者该耗材型号最后一次出库数量
  3575. goodInfo, _ := service.GetLastGoodListByPatientId(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3576. //判断当前出库数量和最后一次出库数量的大小
  3577. //如果当前出库数量小于或等于最后一次出库数量 正常出库后 需要退库操作
  3578. if item.Count <= goodInfo.Count {
  3579. //出库
  3580. err = ConsumablesDeliveryTotalSeven(adminUser.Org.Id, patient_id, record_time, beforePrepares, adminUser.AdminUser.Id, item.Count)
  3581. //查询今日出库数据
  3582. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3583. for _, it := range list {
  3584. prepare := models.DialysisBeforePrepare{
  3585. UserOrgId: it.OrgId,
  3586. PatientId: patient_id,
  3587. RecordDate: it.RecordTime,
  3588. GoodId: it.GoodId,
  3589. GoodTypeId: it.GoodTypeId,
  3590. Count: it.Count,
  3591. Ctime: time.Now().Unix(),
  3592. Creater: adminUser.AdminUser.Id,
  3593. Status: 1,
  3594. StorehouseId: houseConfig.StorehouseOutInfo,
  3595. }
  3596. //删除准备表数据
  3597. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3598. service.CreateDialysisBeforePrepareOne(&prepare)
  3599. }
  3600. }
  3601. var last_total int64
  3602. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3603. if item.Count >= goodInfo.Count {
  3604. //查询当前批次当前耗材最后一条出库数据
  3605. lastOutInfo, _ := service.GetLastWarehouOutInfoByPatientId(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3606. //计算当前出库和最后一次出库数据相差数据
  3607. last_total = item.Count - lastOutInfo.Count
  3608. //查询该批次剩余库存
  3609. lastInfo, _ := service.GetLastStockOut(lastOutInfo.WarehouseInfotId)
  3610. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3611. if lastInfo.StockCount >= last_total {
  3612. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3613. //service.ConsumablesDeliveryTotalEight(adminInfo.Org.Id, patient_id, record_time, beforePrepares,adminInfo.AdminUser.Id,item.Count)
  3614. //查询今日出库数据
  3615. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3616. for _, it := range list {
  3617. prepare := models.DialysisBeforePrepare{
  3618. UserOrgId: it.OrgId,
  3619. PatientId: patient_id,
  3620. RecordDate: it.RecordTime,
  3621. GoodId: it.GoodId,
  3622. GoodTypeId: it.GoodTypeId,
  3623. Count: it.Count,
  3624. Ctime: time.Now().Unix(),
  3625. Creater: adminUser.AdminUser.Id,
  3626. Status: 1,
  3627. StorehouseId: houseConfig.StorehouseOutInfo,
  3628. }
  3629. //删除准备表数据
  3630. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3631. service.CreateDialysisBeforePrepareOne(&prepare)
  3632. //查询默认仓库
  3633. //houseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3634. //goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.GoodId, adminUser.Org.Id)
  3635. //var sum_count int64
  3636. //var sum_in_count int64
  3637. //for _, it := range goodList {
  3638. // sum_count += it.StockCount
  3639. // sum_in_count += it.WarehousingCount
  3640. //}
  3641. //service.UpdateGoodByGoodId(item.GoodId, sum_count, sum_in_count, adminUser.Org.Id)
  3642. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3643. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3644. var total_count int64
  3645. for _, it := range stockList {
  3646. total_count += it.StockCount
  3647. }
  3648. //基础库插入数据
  3649. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3650. }
  3651. }
  3652. //如果库存不够,则出库到下一个批次
  3653. if lastInfo.StockCount < last_total {
  3654. err = ConsumablesDeliveryTotalSix(adminUser.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminUser.AdminUser.Id)
  3655. //查询今日出库数据
  3656. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminUser.Org.Id, patient_id, record_time)
  3657. for _, it := range list {
  3658. prepare := models.DialysisBeforePrepare{
  3659. UserOrgId: it.OrgId,
  3660. PatientId: patient_id,
  3661. RecordDate: it.RecordTime,
  3662. GoodId: it.GoodId,
  3663. GoodTypeId: it.GoodTypeId,
  3664. Count: it.Count,
  3665. Ctime: time.Now().Unix(),
  3666. Creater: adminUser.AdminUser.Id,
  3667. Status: 1,
  3668. StorehouseId: houseConfig.StorehouseOutInfo,
  3669. }
  3670. //删除准备表数据
  3671. service.DeleteDialysisBefor(adminUser.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3672. service.CreateDialysisBeforePrepareOne(&prepare)
  3673. //查询默认仓库
  3674. //houseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3675. //goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.GoodId, adminUser.Org.Id)
  3676. //var sum_count int64
  3677. //var sum_in_count int64
  3678. //for _, it := range goodList {
  3679. // sum_count += it.StockCount
  3680. // sum_in_count += it.WarehousingCount
  3681. //}
  3682. //service.UpdateGoodByGoodId(item.GoodId, sum_count, sum_in_count, adminUser.Org.Id)
  3683. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminUser.Org.Id)
  3684. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminUser.Org.Id)
  3685. var total_count int64
  3686. for _, it := range stockList {
  3687. total_count += it.StockCount
  3688. }
  3689. //基础库插入数据
  3690. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminUser.Org.Id)
  3691. }
  3692. if err != nil {
  3693. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3694. c.ServeSuccessJSON(map[string]interface{}{
  3695. "message": "1",
  3696. "good_name": goodObj.GoodName,
  3697. "specification_name": goodObj.SpecificationName,
  3698. })
  3699. return
  3700. }
  3701. }
  3702. }
  3703. if err != nil {
  3704. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3705. c.ServeSuccessJSON(map[string]interface{}{
  3706. "message": "1",
  3707. "good_name": goodObj.GoodName,
  3708. "specification_name": goodObj.SpecificationName,
  3709. })
  3710. return
  3711. }
  3712. }
  3713. }
  3714. }
  3715. var errs error
  3716. if errs == nil {
  3717. c.ServeSuccessJSON(map[string]interface{}{
  3718. "msg": "提交成功",
  3719. "message": "2",
  3720. "good_name": "",
  3721. "specification_name": "",
  3722. })
  3723. return
  3724. } else {
  3725. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3726. return
  3727. }
  3728. }
  3729. func (c *DialysisAPIController) CreateStockOutInfo() {
  3730. patient_id, _ := c.GetInt64("patient_id", 0)
  3731. record_date := c.GetString("record_time")
  3732. if patient_id <= 0 {
  3733. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3734. return
  3735. }
  3736. adminInfo := c.GetMobileAdminUserInfo()
  3737. timeLayout := "2006-01-02"
  3738. loc, _ := time.LoadLocation("Local")
  3739. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3740. record_time := theRecordTime.Unix()
  3741. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3742. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3743. consumables = RemoveRepeatedGood(consumables)
  3744. if record.IsOpen == 1 {
  3745. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  3746. //查询是否有库存
  3747. for _, item := range consumables {
  3748. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, houseConfig.StorehouseOutInfo)
  3749. if item.Count > warehouse.Count {
  3750. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3751. c.ServeSuccessJSON(map[string]interface{}{
  3752. "message": "1",
  3753. "good_name": goodObj.GoodName,
  3754. "specification_name": goodObj.SpecificationName,
  3755. })
  3756. return
  3757. }
  3758. }
  3759. //查询是否有出库单
  3760. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3761. if err == gorm.ErrRecordNotFound {
  3762. //没有记录,则创建出库单
  3763. timeStr := time.Now().Format("2006-01-02")
  3764. timeArr := strings.Split(timeStr, "-")
  3765. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3766. total = total + 1
  3767. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3768. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3769. number = number + total
  3770. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3771. creater := adminInfo.AdminUser.Id
  3772. warehouseOut := models.WarehouseOut{
  3773. WarehouseOutOrderNumber: warehousing_out_order,
  3774. OperationTime: time.Now().Unix(),
  3775. OrgId: adminInfo.Org.Id,
  3776. Creater: creater,
  3777. Ctime: time.Now().Unix(),
  3778. Status: 1,
  3779. WarehouseOutTime: record_time,
  3780. Dealer: 0,
  3781. Manufacturer: 0,
  3782. Type: 1,
  3783. IsSys: 1,
  3784. StorehouseId: houseConfig.StorehouseOutInfo,
  3785. IsCheck: 1,
  3786. }
  3787. err := service.AddSigleWarehouseOut(&warehouseOut)
  3788. if err != nil {
  3789. utils.TraceLog("创建出库单失败 err = %v", err)
  3790. } else {
  3791. for _, item := range consumables {
  3792. //出库
  3793. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &warehouseOut, item.Count)
  3794. }
  3795. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3796. if len(list) == 0 {
  3797. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3798. return
  3799. }
  3800. for _, item := range list {
  3801. prepare := models.DialysisBeforePrepare{
  3802. UserOrgId: adminInfo.Org.Id,
  3803. PatientId: patient_id,
  3804. RecordDate: record_time,
  3805. GoodId: item.GoodId,
  3806. GoodTypeId: item.GoodTypeId,
  3807. Count: item.Count,
  3808. Creater: adminInfo.AdminUser.Id,
  3809. Status: 1,
  3810. Ctime: time.Now().Unix(),
  3811. StorehouseId: houseConfig.StorehouseOutInfo,
  3812. }
  3813. //清空准备表数据
  3814. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3815. service.CreateDialysisBeforePrepareOne(&prepare)
  3816. //查询默认仓库
  3817. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  3818. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  3819. var total_count int64
  3820. for _, it := range stockList {
  3821. total_count += it.StockCount
  3822. }
  3823. //基础库插入数据
  3824. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  3825. }
  3826. }
  3827. //
  3828. } else if err == nil {
  3829. for _, item := range consumables {
  3830. //出库
  3831. service.ConsumablesDelivery(item.UserOrgId, patient_id, record_time, item, &out, item.Count)
  3832. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  3833. if len(list) == 0 {
  3834. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3835. return
  3836. }
  3837. for _, item := range list {
  3838. prepare := models.DialysisBeforePrepare{
  3839. UserOrgId: adminInfo.Org.Id,
  3840. PatientId: patient_id,
  3841. RecordDate: record_time,
  3842. GoodId: item.GoodId,
  3843. GoodTypeId: item.GoodTypeId,
  3844. Count: item.Count,
  3845. Creater: adminInfo.AdminUser.Id,
  3846. Status: 1,
  3847. Ctime: time.Now().Unix(),
  3848. StorehouseId: houseConfig.StorehouseOutInfo,
  3849. }
  3850. //清空准备表数据
  3851. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  3852. service.CreateDialysisBeforePrepareOne(&prepare)
  3853. //查询默认仓库
  3854. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  3855. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  3856. var total_count int64
  3857. for _, it := range stockList {
  3858. total_count += it.StockCount
  3859. }
  3860. //基础库插入数据
  3861. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  3862. }
  3863. }
  3864. }
  3865. c.ServeSuccessJSON(map[string]interface{}{
  3866. "msg": "提交成功",
  3867. "message": "2",
  3868. "good_name": "",
  3869. "specification_name": "",
  3870. })
  3871. return
  3872. } else {
  3873. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  3874. return
  3875. }
  3876. }
  3877. func (c *DialysisAPIController) EditConsumables() {
  3878. patient_id, _ := c.GetInt64("patient_id", 0)
  3879. record_date := c.GetString("record_time")
  3880. if patient_id <= 0 {
  3881. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3882. return
  3883. }
  3884. adminInfo := c.GetMobileAdminUserInfo()
  3885. timeLayout := "2006-01-02"
  3886. loc, _ := time.LoadLocation("Local")
  3887. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3888. record_time := theRecordTime.Unix()
  3889. dataBody := make(map[string]interface{}, 0)
  3890. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3891. if err != nil {
  3892. utils.ErrorLog(err.Error())
  3893. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3894. return
  3895. }
  3896. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  3897. var beforePrepares []*models.DialysisBeforePrepareGoods
  3898. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  3899. //判断是否开启自动出库
  3900. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3901. if record.IsOpen == 1 {
  3902. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3903. goods, _ := dataBody["goods"].([]interface{})
  3904. if len(goods) > 0 {
  3905. for _, item := range goods {
  3906. items := item.(map[string]interface{})
  3907. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3908. utils.ErrorLog("good_id")
  3909. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3910. return
  3911. }
  3912. good_id := int64(items["good_id"].(float64))
  3913. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3914. utils.ErrorLog("good_type_id")
  3915. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3916. return
  3917. }
  3918. good_type_id := int64(items["good_type_id"].(float64))
  3919. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3920. utils.ErrorLog("count")
  3921. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3922. return
  3923. }
  3924. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3925. commdity_code := items["commdity_code"].(string)
  3926. fmt.Println(commdity_code)
  3927. prepareGoods := &models.DialysisBeforePrepareGoods{
  3928. GoodTypeId: good_type_id,
  3929. GoodId: good_id,
  3930. Count: count,
  3931. StorehouseId: houseConfig.StorehouseOutInfo,
  3932. }
  3933. beforePrepares = append(beforePrepares, prepareGoods)
  3934. newPrepareGoods := &models.NewDialysisBeforePrepareGoods{
  3935. GoodTypeId: good_type_id,
  3936. GoodId: good_id,
  3937. Count: count,
  3938. StorehouseId: houseConfig.StorehouseOutInfo,
  3939. }
  3940. newBeforePrepares = append(newBeforePrepares, newPrepareGoods)
  3941. }
  3942. for _, item := range beforePrepares {
  3943. //1.查看该患者该耗材型号最后一次出库数量
  3944. goodInfo, _ := service.GetLastGoodListByPatientIdOne(record_time, patient_id, item.GoodId, item.GoodTypeId)
  3945. //判断当前出库数量和最后一次出库数量的大小
  3946. //如果当前出库数量小于最后一次出库数量 正常出库后 需要退库操作
  3947. if item.Count < goodInfo.Count {
  3948. //出库
  3949. err = ConsumablesDeliveryTotalSeven(adminInfo.Org.Id, patient_id, record_time, beforePrepares, adminInfo.AdminUser.Id, item.Count)
  3950. //houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  3951. //goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.GoodId, adminInfo.Org.Id)
  3952. //var sum_count int64
  3953. //var sum_in_count int64
  3954. //for _, it := range goodList {
  3955. // sum_count += it.StockCount
  3956. // sum_in_count += it.WarehousingCount
  3957. //}
  3958. //service.UpdateGoodByGoodId(item.GoodId, sum_count, sum_in_count, adminInfo.Org.Id)
  3959. //查询默认仓库
  3960. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  3961. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  3962. var total_count int64
  3963. for _, it := range stockList {
  3964. total_count += it.StockCount
  3965. }
  3966. //基础库插入数据
  3967. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  3968. break
  3969. }
  3970. var last_total int64
  3971. //如果当前出库数量大于 最后一次出库数量,那么则需要去查询当前批次耗材的库存是否足够
  3972. if item.Count > goodInfo.Count {
  3973. //计算当前出库和最后一次出库数据相差数据
  3974. last_total = item.Count - goodInfo.Count
  3975. //查询该批次剩余库存
  3976. lastInfo, _ := service.GetLastStockOut(goodInfo.WarehouseInfotId)
  3977. if lastInfo.StockCount == 0 {
  3978. //查询该耗材的总库存
  3979. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  3980. if wareinfo.StockCount == 0 {
  3981. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3982. c.ServeSuccessJSON(map[string]interface{}{
  3983. "message": "1",
  3984. "good_name": goodObj.GoodName,
  3985. "specification_name": goodObj.SpecificationName,
  3986. })
  3987. return
  3988. }
  3989. }
  3990. //比较剩余库存 和 当前相差的数量,库存剩余量大于则正常出库
  3991. //查询该耗材的总库存
  3992. wareinfo, _ := service.GetStockGoodCount(item.GoodId)
  3993. // 如果库存差大于剩余库存则提示库存不足
  3994. if last_total > wareinfo.StockCount {
  3995. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  3996. c.ServeSuccessJSON(map[string]interface{}{
  3997. "message": "1",
  3998. "good_name": goodObj.GoodName,
  3999. "specification_name": goodObj.SpecificationName,
  4000. })
  4001. return
  4002. } else {
  4003. err = ConsumablesDeliveryTotalSix(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  4004. //houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4005. //goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.GoodId, adminInfo.Org.Id)
  4006. //var sum_count int64
  4007. //var sum_in_count int64
  4008. //for _, it := range goodList {
  4009. // sum_count += it.StockCount
  4010. // sum_in_count += it.WarehousingCount
  4011. //}
  4012. //service.UpdateGoodByGoodId(item.GoodId, sum_count, sum_in_count, adminInfo.Org.Id)
  4013. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4014. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4015. var total_count int64
  4016. for _, it := range stockList {
  4017. total_count += it.StockCount
  4018. }
  4019. //基础库插入数据
  4020. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4021. break
  4022. }
  4023. }
  4024. }
  4025. //查询今日出库数据
  4026. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4027. for _, it := range list {
  4028. prepare := models.DialysisBeforePrepare{
  4029. UserOrgId: it.OrgId,
  4030. PatientId: patient_id,
  4031. RecordDate: it.RecordTime,
  4032. GoodId: it.GoodId,
  4033. GoodTypeId: it.GoodTypeId,
  4034. Count: it.Count,
  4035. Ctime: time.Now().Unix(),
  4036. Creater: adminInfo.AdminUser.Id,
  4037. Status: 1,
  4038. StorehouseId: houseConfig.StorehouseOutInfo,
  4039. }
  4040. //删除准备表数据
  4041. service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, it.GoodId, it.GoodTypeId)
  4042. service.CreateDialysisBeforePrepareOne(&prepare)
  4043. //查询默认仓库
  4044. //houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4045. //goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, it.GoodId, adminInfo.Org.Id)
  4046. //var sum_count int64
  4047. //var sum_in_count int64
  4048. //for _, it := range goodList {
  4049. // sum_count += it.StockCount
  4050. // sum_in_count += it.WarehousingCount
  4051. //}
  4052. //service.UpdateGoodByGoodId(it.GoodId, sum_count, sum_in_count, adminInfo.Org.Id)
  4053. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4054. stockList, _ := service.GetStockCountByGoodId(it.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4055. var total_count int64
  4056. for _, it := range stockList {
  4057. total_count += it.StockCount
  4058. }
  4059. //基础库插入数据
  4060. service.UpdateGoodInfoReduceSumCount(it.GoodId, total_count, adminInfo.Org.Id)
  4061. if err != nil {
  4062. goodObj, _ := service.GetGoodInformationByGoodId(it.GoodId)
  4063. c.ServeSuccessJSON(map[string]interface{}{
  4064. "message": "2",
  4065. "good_name": goodObj.GoodName,
  4066. "specification_name": goodObj.SpecificationName,
  4067. })
  4068. return
  4069. }
  4070. }
  4071. }
  4072. }
  4073. //更新自动出库的地方
  4074. var errs error
  4075. if errs == nil {
  4076. c.ServeSuccessJSON(map[string]interface{}{
  4077. "msg": "修改成功",
  4078. "message": "2",
  4079. "good_name": "",
  4080. "specification_name": "",
  4081. })
  4082. return
  4083. } else {
  4084. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4085. return
  4086. }
  4087. }
  4088. }
  4089. func (c *DialysisAPIController) GetDialysisGoods() {
  4090. schedualDate := c.GetString("schedule_date")
  4091. schedule_type, _ := c.GetInt64("schedule_type")
  4092. partition_id, _ := c.GetInt64("partition_id")
  4093. page, _ := c.GetInt("page")
  4094. patient_id, _ := c.GetInt64("patient_id")
  4095. schedualEndDate := int64(0)
  4096. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  4097. if parseDateErr != nil && len(schedualDate) != 0 {
  4098. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4099. return
  4100. }
  4101. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  4102. if parseDateErr != nil && len(schedualDate) != 0 {
  4103. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4104. return
  4105. }
  4106. schedualEndDate = endDate.Unix()
  4107. adminUser := c.GetMobileAdminUserInfo()
  4108. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  4109. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  4110. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  4111. //获取当天该病人的透析处方
  4112. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  4113. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  4114. if err == gorm.ErrRecordNotFound {
  4115. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  4116. if patient_id != 0 {
  4117. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  4118. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  4119. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  4120. item.LastAutomaticReduceDetail = goodUser
  4121. item.LastDialysisBeforePrepare = lastGoodUserDetial
  4122. item.Project = project
  4123. }
  4124. }
  4125. c.ServeSuccessJSON(map[string]interface{}{
  4126. "dialysis_goods": dialysisGoods,
  4127. "good_type": goodTypes,
  4128. "total": total,
  4129. "prescribe": prescribe,
  4130. "good_info": good_info,
  4131. })
  4132. return
  4133. } else if err == nil {
  4134. //获取当天排班的每个患者的库存使用情况
  4135. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  4136. if patient_id != 0 {
  4137. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  4138. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  4139. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  4140. item.Project = project
  4141. item.LastAutomaticReduceDetail = goodUser
  4142. item.LastDialysisBeforePrepare = lastGoodUserDetial
  4143. }
  4144. }
  4145. if err == nil {
  4146. c.ServeSuccessJSON(map[string]interface{}{
  4147. "dialysis_goods": dialysisGoods,
  4148. "good_type": goodTypes,
  4149. "total": total,
  4150. "prescribe": prescribe,
  4151. "good_info": good_info,
  4152. "project": project,
  4153. })
  4154. return
  4155. } else {
  4156. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4157. return
  4158. }
  4159. } else if err != nil {
  4160. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4161. return
  4162. }
  4163. }
  4164. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  4165. start_time := c.GetString("start_time")
  4166. end_time := c.GetString("end_time")
  4167. timeLayout := "2006-01-02"
  4168. loc, _ := time.LoadLocation("Local")
  4169. var theStartTime int64
  4170. if len(start_time) > 0 {
  4171. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  4172. if err != nil {
  4173. utils.ErrorLog(err.Error())
  4174. }
  4175. theStartTime = theTime.Unix()
  4176. }
  4177. var theEndtTime int64
  4178. if len(end_time) > 0 {
  4179. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  4180. if err != nil {
  4181. utils.ErrorLog(err.Error())
  4182. }
  4183. theEndtTime = theTime.Unix()
  4184. }
  4185. adminUser := c.GetMobileAdminUserInfo()
  4186. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  4187. stockCount, err := service.GetOutStockTotalCountOne(theStartTime, theEndtTime, adminUser.Org.Id)
  4188. if err == nil {
  4189. c.ServeSuccessJSON(map[string]interface{}{
  4190. "stock_out": outInfo,
  4191. "stockCount": stockCount,
  4192. })
  4193. return
  4194. } else {
  4195. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4196. return
  4197. }
  4198. }
  4199. func (c *DialysisAPIController) GetStockInGoodInfo() {
  4200. patient_id, _ := c.GetInt64("patient_id", 0)
  4201. record_time := c.GetString("record_time")
  4202. adminUser := c.GetMobileAdminUserInfo()
  4203. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  4204. if parseDateErr != nil && len(record_time) != 0 {
  4205. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4206. return
  4207. }
  4208. goodTypes, _ := service.FindAllGoodTypeOne(adminUser.Org.Id)
  4209. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  4210. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  4211. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  4212. project, _ := service.GetHisPrescriptionProject(adminUser.Org.Id, patient_id, date.Unix())
  4213. //获取今日患者的透析处方参数
  4214. prescribe, parseDateErr := service.GetDialysisPrescribe(adminUser.Org.Id, patient_id, date.Unix())
  4215. c.ServeSuccessJSON(map[string]interface{}{
  4216. "good_type": goodTypes,
  4217. "good_user": goodUser,
  4218. "good_info": good_info,
  4219. "last_good_user": lastGoodUserDetial,
  4220. "project": project,
  4221. "prescription": prescribe,
  4222. })
  4223. return
  4224. }
  4225. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  4226. patient_id, _ := c.GetInt64("patient_id", 0)
  4227. record_date := c.GetString("record_time")
  4228. timeLayout := "2006-01-02"
  4229. loc, _ := time.LoadLocation("Local")
  4230. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  4231. record_time := theRecordTime.Unix()
  4232. adminInfo := c.GetMobileAdminUserInfo()
  4233. dataBody := make(map[string]interface{}, 0)
  4234. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  4235. if err != nil {
  4236. utils.ErrorLog(err.Error())
  4237. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4238. return
  4239. }
  4240. houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4241. var beforePrepares []*models.DialysisBeforePrepareGoods
  4242. var newBeforePrepares []*models.NewDialysisBeforePrepareGoods
  4243. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  4244. goods, _ := dataBody["goods"].([]interface{})
  4245. if len(goods) > 0 {
  4246. for _, item := range goods {
  4247. items := item.(map[string]interface{})
  4248. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  4249. utils.ErrorLog("good_id")
  4250. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4251. return
  4252. }
  4253. good_id := int64(items["good_id"].(float64))
  4254. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  4255. utils.ErrorLog("good_type_id")
  4256. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4257. return
  4258. }
  4259. good_type_id := int64(items["good_type_id"].(float64))
  4260. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  4261. utils.ErrorLog("count")
  4262. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4263. return
  4264. }
  4265. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  4266. if items["project_id"] == nil || reflect.TypeOf(items["project_id"]).String() != "float64" {
  4267. utils.ErrorLog("project_id")
  4268. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4269. return
  4270. }
  4271. project_id := int64(items["project_id"].(float64))
  4272. prepare := &models.DialysisBeforePrepareGoods{
  4273. GoodId: good_id,
  4274. GoodTypeId: good_type_id,
  4275. Count: count,
  4276. ProjectId: project_id,
  4277. StorehouseId: houseConfig.StorehouseOutInfo,
  4278. }
  4279. beforePrepares = append(beforePrepares, prepare)
  4280. newPrepare := &models.NewDialysisBeforePrepareGoods{
  4281. GoodId: good_id,
  4282. GoodTypeId: good_type_id,
  4283. Count: count,
  4284. ProjectId: project_id,
  4285. StorehouseId: houseConfig.StorehouseOutInfo,
  4286. }
  4287. newBeforePrepares = append(newBeforePrepares, newPrepare)
  4288. }
  4289. }
  4290. }
  4291. //查询是否有库存
  4292. for _, item := range beforePrepares {
  4293. storeConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4294. warehouse, _ := service.FindFirstWarehousingInfoByStockTwo(item.GoodId, item.GoodTypeId, storeConfig.StorehouseOutInfo)
  4295. if item.Count > warehouse.Count {
  4296. goodObj, _ := service.GetGoodInformationByGoodId(item.GoodId)
  4297. c.ServeSuccessJSON(map[string]interface{}{
  4298. "message": "1",
  4299. "good_name": goodObj.GoodName,
  4300. "specification_name": goodObj.SpecificationName,
  4301. })
  4302. return
  4303. }
  4304. }
  4305. //出库逻辑
  4306. err = service.ConsumablesDeliveryTotal(adminInfo.Org.Id, patient_id, record_time, beforePrepares, newBeforePrepares, adminInfo.AdminUser.Id)
  4307. if err != nil {
  4308. utils.ErrorLog(err.Error())
  4309. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4310. return
  4311. }
  4312. //查询当天出库的数据
  4313. list, _ := service.GetAutoReduceRecordInfoByPatientId(adminInfo.Org.Id, patient_id, record_time)
  4314. for _, item := range list {
  4315. prepare := models.DialysisBeforePrepare{
  4316. UserOrgId: item.OrgId,
  4317. PatientId: item.PatientId,
  4318. RecordDate: item.RecordTime,
  4319. GoodId: item.GoodId,
  4320. GoodTypeId: item.GoodTypeId,
  4321. Count: item.Count,
  4322. Creater: adminInfo.AdminUser.Id,
  4323. Status: 1,
  4324. Ctime: time.Now().Unix(),
  4325. ProjectId: item.ProjectId,
  4326. StorehouseId: houseConfig.StorehouseOutInfo,
  4327. }
  4328. //清空准备表的数据
  4329. err = service.DeleteDialysisBefor(adminInfo.Org.Id, patient_id, record_time, item.GoodId, item.GoodTypeId)
  4330. //插入准备表数据
  4331. service.CreateDialysisBeforePrepareOne(&prepare)
  4332. //查询默认仓库
  4333. //houseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4334. //goodList, _ := service.GetGoodSumCountByStoreId(houseConfig.StorehouseOutInfo, item.GoodId, adminInfo.Org.Id)
  4335. //var sum_count int64
  4336. //var sum_in_count int64
  4337. //for _, it := range goodList {
  4338. // sum_count += it.StockCount
  4339. // sum_in_count += it.WarehousingCount
  4340. //}
  4341. //service.UpdateGoodByGoodId(item.GoodId, sum_count, sum_in_count, adminInfo.Org.Id)
  4342. //查询默认仓库
  4343. storeHouseConfig, _ := service.GetAllStoreHouseConfig(adminInfo.Org.Id)
  4344. stockList, _ := service.GetStockCountByGoodId(item.GoodId, storeHouseConfig.StorehouseOutInfo, adminInfo.Org.Id)
  4345. var total_count int64
  4346. for _, it := range stockList {
  4347. total_count += it.StockCount
  4348. }
  4349. //基础库插入数据
  4350. service.UpdateGoodInfoReduceSumCount(item.GoodId, total_count, adminInfo.Org.Id)
  4351. }
  4352. //更新自动出库的地方
  4353. var errs error
  4354. if errs == nil {
  4355. c.ServeSuccessJSON(map[string]interface{}{
  4356. "msg": "修改成功",
  4357. "message": "2",
  4358. "good_name": "",
  4359. "specification_name": "",
  4360. })
  4361. return
  4362. } else {
  4363. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4364. return
  4365. }
  4366. }
  4367. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  4368. newArr = make([]*models.DialysisBeforePrepare, 0)
  4369. for i := 0; i < len(arr); i++ {
  4370. repeat := false
  4371. for j := i + 1; j < len(arr); j++ {
  4372. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  4373. repeat = true
  4374. break
  4375. }
  4376. }
  4377. if !repeat {
  4378. newArr = append(newArr, arr[i])
  4379. }
  4380. }
  4381. return
  4382. }
  4383. func (c *DialysisAPIController) GetAllDrug() {
  4384. patient_id, _ := c.GetInt64("patient_id", 0)
  4385. adminInfo := c.GetMobileAdminUserInfo()
  4386. _, drugStockConfig := service.FindDrugStockAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  4387. privateDrugConfig, _ := service.GetDrugSetByUserOrgId(adminInfo.Org.Id)
  4388. drugList, _ := service.GetAllBaseDrugLibList(adminInfo.Org.Id)
  4389. privateDrugList, _ := service.GetPrivateDrugList(patient_id, adminInfo.Org.Id)
  4390. c.ServeSuccessJSON(map[string]interface{}{
  4391. "base_drug_config": drugStockConfig,
  4392. "private_drug_config": privateDrugConfig,
  4393. "base_drug_list": drugList,
  4394. "private_drug_list": privateDrugList,
  4395. })
  4396. }
  4397. func RemoveRepeatedGoodTwo(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  4398. newArr = make([]*models.DialysisBeforePrepare, 0)
  4399. for i := 0; i < len(arr); i++ {
  4400. repeat := false
  4401. for j := i + 1; j < len(arr); j++ {
  4402. if arr[i].GoodId == arr[j].GoodId {
  4403. repeat = true
  4404. break
  4405. }
  4406. }
  4407. if !repeat {
  4408. newArr = append(newArr, arr[i])
  4409. }
  4410. }
  4411. return
  4412. }
  4413. func (c *DialysisAPIController) GetDepartment() {
  4414. adminInfo := c.GetMobileAdminUserInfo()
  4415. departments, err := service.GetAllDepartMent(adminInfo.Org.Id)
  4416. if err == nil {
  4417. c.ServeSuccessJSON(map[string]interface{}{
  4418. "departments": departments,
  4419. })
  4420. } else {
  4421. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  4422. return
  4423. }
  4424. }
  4425. func (c *DialysisAPIController) GetMobilePrintStockGood() {
  4426. types, _ := c.GetInt("type", 0)
  4427. start_time := c.GetString("start_time")
  4428. end_time := c.GetString("end_time")
  4429. orgId := c.GetMobileAdminUserInfo().Org.Id
  4430. timeLayout := "2006-01-02"
  4431. loc, _ := time.LoadLocation("Local")
  4432. var startTime int64
  4433. if len(start_time) > 0 {
  4434. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  4435. if err != nil {
  4436. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4437. return
  4438. }
  4439. startTime = theTime.Unix()
  4440. }
  4441. var endTime int64
  4442. if len(end_time) > 0 {
  4443. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  4444. if err != nil {
  4445. utils.ErrorLog(err.Error())
  4446. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  4447. return
  4448. }
  4449. endTime = theTime.Unix()
  4450. }
  4451. list, err := service.FindPrintStockGoodInfoByType(types, startTime, endTime, orgId)
  4452. stockTotal, err := service.GetOutStockTotalCountTwo(startTime, endTime, orgId)
  4453. if err != nil {
  4454. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  4455. } else {
  4456. c.ServeSuccessJSON(map[string]interface{}{
  4457. "list": list,
  4458. "type": types,
  4459. "stockTotal": stockTotal,
  4460. })
  4461. }
  4462. }
  4463. func (c *DialysisAPIController) BatchDeleteMonitor() {
  4464. ids := c.GetString("ids")
  4465. //patient_id, _ := c.GetInt64("patient_id")
  4466. //monitoring_date, _ := c.GetInt64("monitoring_date")
  4467. idArray := strings.Split(ids, ",")
  4468. err := service.BatchDeleteMonitor(idArray)
  4469. fmt.Print("err", err)
  4470. //orgid := c.GetMobileAdminUserInfo().Org.Id
  4471. //redis := service.RedisClient()
  4472. //key := strconv.FormatInt(orgid, 10) + ":" + ":monitor_record_list_all"
  4473. //redis.Set(key, "", time.Second)
  4474. //keyOne := strconv.FormatInt(orgid, 10) + ":" + strconv.FormatInt(patient_id, 10) + ":" + strconv.FormatInt(monitoring_date, 10) + ":monitor_records"
  4475. //redis.Set(keyOne, "", time.Second)
  4476. //fmt.Println("keyo呢32332322332332232332",keyOne)
  4477. //redis.Close()
  4478. c.ServeSuccessJSON(map[string]interface{}{
  4479. "msg": "批量删除成功",
  4480. })
  4481. return
  4482. }
  4483. func (c *DialysisAPIController) GetPatientDialysisRecordList() {
  4484. id, _ := c.GetInt64("id")
  4485. timeLayout := "2006-01-02"
  4486. loc, _ := time.LoadLocation("Local")
  4487. start_time := time.Now().Format("2006-01-02")
  4488. startime, _ := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  4489. nowTime := time.Now()
  4490. endTime := nowTime.AddDate(-1, 0, 0)
  4491. endTimes := endTime.Format("2006-01-02")
  4492. endtime, _ := time.ParseInLocation(timeLayout+" 15:04:05", endTimes+" 00:00:00", loc)
  4493. list, _ := service.GetPatientDialysisRecordList(id, endtime.Unix(), startime.Unix())
  4494. c.ServeSuccessJSON(map[string]interface{}{
  4495. "list": list,
  4496. })
  4497. return
  4498. }
  4499. func (c *DialysisAPIController) BathDeleteAdviceList() {
  4500. dataBody := make(map[string]interface{}, 0)
  4501. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  4502. ids := c.GetString("ids")
  4503. idArray := strings.Split(ids, ",")
  4504. origin, _ := c.GetInt64("origin")
  4505. if origin == 1 {
  4506. err = service.BatchDeleteAdvice(idArray)
  4507. fmt.Print("err", err)
  4508. c.ServeSuccessJSON(map[string]interface{}{
  4509. "msg": "批量删除成功",
  4510. })
  4511. return
  4512. }
  4513. if origin == 2 {
  4514. service.BatchDeleteHisAdvice(idArray)
  4515. }
  4516. }
  4517. func (c *DialysisAPIController) UpdateAutoReduceDetail() {
  4518. good_id, _ := c.GetInt64("good_id")
  4519. count, _ := c.GetInt64("count")
  4520. record_time, _ := c.GetInt64("record_time")
  4521. patient_id, _ := c.GetInt64("patient_id")
  4522. detail, _ := service.UpdateAutoReduceDetail(good_id, count, record_time, patient_id)
  4523. c.ServeSuccessJSON(map[string]interface{}{
  4524. "detail": detail,
  4525. })
  4526. return
  4527. }
  4528. func (c *DialysisAPIController) DeleteAutoReduceDetail() {
  4529. good_id, _ := c.GetInt64("good_id")
  4530. record_time, _ := c.GetInt64("record_time")
  4531. patient_id, _ := c.GetInt64("patient_id")
  4532. service.DeleteDialysisBeforOne(good_id, record_time, patient_id)
  4533. err := service.DeleteAutoReduceDetail(good_id, record_time, patient_id)
  4534. fmt.Print("err", err)
  4535. c.ServeSuccessJSON(map[string]interface{}{
  4536. "msg": "批量删除成功",
  4537. })
  4538. return
  4539. }
  4540. func (c *DialysisAPIController) BatchAdviceCheck() {
  4541. ids := c.GetString("ids")
  4542. idArray := strings.Split(ids, ",")
  4543. creator, _ := c.GetInt64("creator")
  4544. origin, _ := c.GetInt64("origin")
  4545. if origin == 1 {
  4546. err := service.BatchAdviceCheck(idArray, creator)
  4547. fmt.Println(err)
  4548. list, _ := service.GetAdviceExecutionById(idArray)
  4549. c.ServeSuccessJSON(map[string]interface{}{
  4550. "list": list,
  4551. })
  4552. return
  4553. }
  4554. if origin == 2 {
  4555. service.BatchHisAdviceCheck(idArray, creator)
  4556. list, _ := service.GetHisAdviceExecutionById(idArray)
  4557. c.ServeSuccessJSON(map[string]interface{}{
  4558. "list": list,
  4559. })
  4560. return
  4561. }
  4562. }
  4563. func (c *DialysisAPIController) BatchAdviceExecution() {
  4564. ids := c.GetString("ids")
  4565. idArray := strings.Split(ids, ",")
  4566. executionTime := c.GetString("execution_time")
  4567. creator, _ := c.GetInt64("creator")
  4568. timeLayout := "2006-01-02 15:04:05"
  4569. loc, _ := time.LoadLocation("Local")
  4570. theTime, _ := time.ParseInLocation(timeLayout, executionTime, loc)
  4571. orgin, _ := c.GetInt64("origin")
  4572. if orgin == 1 {
  4573. err := service.BatchAdviceExecution(idArray, creator, theTime.Unix())
  4574. list, _ := service.GetAdviceExecutionById(idArray)
  4575. fmt.Println(err)
  4576. c.ServeSuccessJSON(map[string]interface{}{
  4577. "list": list,
  4578. })
  4579. return
  4580. }
  4581. if orgin == 2 {
  4582. err := service.BatchHisAdviceExecution(idArray, creator, theTime.Unix())
  4583. list, _ := service.GetHisAdviceExecutionById(idArray)
  4584. fmt.Println(err)
  4585. c.ServeSuccessJSON(map[string]interface{}{
  4586. "list": list,
  4587. })
  4588. return
  4589. }
  4590. }
  4591. func (c *DialysisAPIController) UpdateStockGoods() {
  4592. good_id, _ := c.GetInt64("good_id")
  4593. record_time, _ := c.GetInt64("record_time")
  4594. patient_id, _ := c.GetInt64("patient_id")
  4595. count, _ := c.GetInt64("count")
  4596. err := service.UpdateStockGoods(good_id, record_time, patient_id, count)
  4597. fmt.Print("err", err)
  4598. c.ServeSuccessJSON(map[string]interface{}{
  4599. "msg": "更新成功",
  4600. })
  4601. return
  4602. }
  4603. //当前数据比上一次出库数据少
  4604. func ConsumablesDeliveryTotalSeven(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, creater int64, count int64) (err error) {
  4605. //查询该患者当天已经出库的耗材信息
  4606. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  4607. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  4608. for i := len(goods_yc) - 1; i >= 0; i-- {
  4609. goods_yc_temp := goods_yc[i]
  4610. for j := len(goods) - 1; j >= 0; j-- {
  4611. goods_temp := goods[j]
  4612. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  4613. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  4614. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  4615. if goods_yc_temp.Count == goods_temp.Count {
  4616. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4617. goods = append(goods[:j], goods[j+1:]...)
  4618. break
  4619. }
  4620. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  4621. if goods_yc_temp.Count > goods_temp.Count {
  4622. temp_count := goods_yc_temp.Count - goods_temp.Count
  4623. goods_yc[i].Count = temp_count
  4624. goods = append(goods[:j], goods[j+1:]...)
  4625. break
  4626. }
  4627. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  4628. if goods_yc_temp.Count < goods_temp.Count {
  4629. temp_count := goods_temp.Count - goods_yc_temp.Count
  4630. goods[j].Count = temp_count
  4631. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4632. break
  4633. }
  4634. }
  4635. }
  4636. }
  4637. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  4638. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  4639. //退库
  4640. if len(goods_yc) > 0 {
  4641. for _, good_yc := range goods_yc {
  4642. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  4643. ConsumablesDeliveryDeleteFour(orgID, record_time, good_yc, &out, patient_id, creater, count)
  4644. }
  4645. }
  4646. return nil
  4647. }
  4648. //耗材出库删除
  4649. func ConsumablesDeliveryDeleteFour(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut, patient_id int64, creater int64, count int64) (err error) {
  4650. // 先根据相关信息查询当天该耗材的出库信息
  4651. warehouseOutInfos, err := service.FindStockOutInfoByStockTwo(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time, good_yc.PatientId)
  4652. if err != nil {
  4653. return err
  4654. }
  4655. var delete_count int64 = 0
  4656. delete_count = warehouseOutInfos.Count - count
  4657. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  4658. // 在出库记录表里记录退库详情
  4659. warehouseOutInfo := &models.WarehouseOutInfo{
  4660. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4661. WarehouseOutId: warehouseOut.ID,
  4662. Status: 1,
  4663. Ctime: time.Now().Unix(),
  4664. OrgId: orgID,
  4665. Type: 1,
  4666. IsSys: 1,
  4667. SysRecordTime: record_time,
  4668. GoodTypeId: good_yc.GoodTypeId,
  4669. GoodId: good_yc.GoodId,
  4670. PatientId: good_yc.PatientId,
  4671. ConsumableType: 2,
  4672. StorehouseId: houseConfig.StorehouseOutInfo,
  4673. IsCheck: 1,
  4674. }
  4675. warehouseOutInfo.Count = count
  4676. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4677. warehouseOutInfo.Price = stockInInfo.Price
  4678. warehouseOutInfo.Dealer = stockInInfo.Dealer
  4679. warehouseOutInfo.Manufacturer = stockInInfo.Manufacturer
  4680. warehouseOutInfo.ExpiryDate = stockInInfo.ExpiryDate
  4681. warehouseOutInfo.ProductDate = stockInInfo.ProductDate
  4682. warehouseOutInfo.Number = warehouseOutInfos.Number
  4683. warehouseOutInfo.LicenseNumber = stockInInfo.LicenseNumber
  4684. warehouseOutInfo.WarehouseInfotId = stockInInfo.ID
  4685. //查找当天是否存在出库记录
  4686. _, errcod := service.GetWarehouseOutInfoIsExistOne(good_yc.GoodId, good_yc.PatientId, record_time)
  4687. if errcod == gorm.ErrRecordNotFound {
  4688. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4689. //插入详情明细表
  4690. stockFlow := models.VmStockFlow{
  4691. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4692. WarehouseOutId: warehouseOut.ID,
  4693. GoodId: good_yc.GoodId,
  4694. Number: warehouseOutInfos.Number,
  4695. ProductDate: stockInInfo.ProductDate,
  4696. ExpireDate: stockInInfo.ExpiryDate,
  4697. Count: count,
  4698. Price: stockInInfo.Price,
  4699. Status: 1,
  4700. Ctime: time.Now().Unix(),
  4701. UserOrgId: good_yc.OrgId,
  4702. Manufacturer: stockInInfo.Manufacturer,
  4703. Dealer: stockInInfo.Dealer,
  4704. LicenseNumber: stockInInfo.LicenseNumber,
  4705. IsEdit: 2,
  4706. Creator: creater,
  4707. SystemTime: record_time,
  4708. ConsumableType: 3,
  4709. WarehousingDetailId: 0,
  4710. IsSys: 1,
  4711. UpdateCreator: creater,
  4712. PatientId: patient_id,
  4713. StorehouseId: houseConfig.StorehouseOutInfo,
  4714. }
  4715. exsit, errflow := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4716. if errflow == gorm.ErrRecordNotFound {
  4717. //创建流水表
  4718. err := service.CreateStockFlowOne(stockFlow)
  4719. fmt.Println("err", err)
  4720. } else if errflow == nil {
  4721. //插入详情明细表
  4722. stockFlow := models.VmStockFlow{
  4723. ID: exsit.ID,
  4724. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4725. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4726. WarehouseOutId: warehouseOut.ID,
  4727. GoodId: good_yc.GoodId,
  4728. Number: warehouseOutInfos.Number,
  4729. ProductDate: stockInInfo.ProductDate,
  4730. ExpireDate: stockInInfo.ExpiryDate,
  4731. Count: exsit.Count - delete_count,
  4732. Price: stockInInfo.Price,
  4733. Status: 1,
  4734. Ctime: time.Now().Unix(),
  4735. UserOrgId: good_yc.OrgId,
  4736. Manufacturer: stockInInfo.Manufacturer,
  4737. Dealer: stockInInfo.Dealer,
  4738. LicenseNumber: stockInInfo.LicenseNumber,
  4739. IsEdit: 2,
  4740. Creator: creater,
  4741. SystemTime: record_time,
  4742. ConsumableType: 3,
  4743. WarehousingDetailId: 0,
  4744. IsSys: 1,
  4745. UpdateCreator: creater,
  4746. PatientId: patient_id,
  4747. StorehouseId: houseConfig.StorehouseOutInfo,
  4748. }
  4749. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  4750. }
  4751. if errOne != nil {
  4752. return errOne
  4753. }
  4754. } else if errcod == nil {
  4755. service.UpdatedWarehouseOutInfo(warehouseOutInfo, good_yc.GoodId, good_yc.PatientId, record_time)
  4756. //插入详情明细表
  4757. stockFlow := models.VmStockFlow{
  4758. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4759. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4760. WarehouseOutId: warehouseOut.ID,
  4761. GoodId: good_yc.GoodId,
  4762. Number: warehouseOutInfos.Number,
  4763. ProductDate: stockInInfo.ProductDate,
  4764. ExpireDate: stockInInfo.ExpiryDate,
  4765. Count: count,
  4766. Price: stockInInfo.Price,
  4767. Status: 1,
  4768. Ctime: time.Now().Unix(),
  4769. UserOrgId: good_yc.OrgId,
  4770. Manufacturer: stockInInfo.Manufacturer,
  4771. Dealer: stockInInfo.Dealer,
  4772. LicenseNumber: stockInInfo.LicenseNumber,
  4773. IsEdit: 2,
  4774. Creator: creater,
  4775. SystemTime: record_time,
  4776. ConsumableType: 3,
  4777. WarehousingDetailId: 0,
  4778. IsSys: 1,
  4779. UpdateCreator: creater,
  4780. PatientId: patient_id,
  4781. ReturnCount: delete_count,
  4782. StorehouseId: houseConfig.StorehouseOutInfo,
  4783. }
  4784. exsit, errflows := service.GetStockFlowIsExsit(warehouseOutInfos.WarehouseInfotId, patient_id, record_time, good_yc.GoodId)
  4785. if errflows == gorm.ErrRecordNotFound {
  4786. //创建流水表
  4787. service.CreateStockFlowOne(stockFlow)
  4788. } else if errflows == nil {
  4789. stockFlow := models.VmStockFlow{
  4790. WarehousingId: warehouseOutInfos.WarehouseInfotId,
  4791. ID: exsit.ID,
  4792. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4793. WarehouseOutId: warehouseOut.ID,
  4794. GoodId: good_yc.GoodId,
  4795. Number: warehouseOutInfos.Number,
  4796. ProductDate: stockInInfo.ProductDate,
  4797. ExpireDate: stockInInfo.ExpiryDate,
  4798. Count: exsit.Count - delete_count,
  4799. Price: stockInInfo.Price,
  4800. Status: 1,
  4801. Ctime: time.Now().Unix(),
  4802. UserOrgId: good_yc.OrgId,
  4803. Manufacturer: stockInInfo.Manufacturer,
  4804. Dealer: stockInInfo.Dealer,
  4805. LicenseNumber: stockInInfo.LicenseNumber,
  4806. IsEdit: 2,
  4807. Creator: creater,
  4808. SystemTime: record_time,
  4809. ConsumableType: 3,
  4810. WarehousingDetailId: 0,
  4811. IsSys: 1,
  4812. UpdateCreator: creater,
  4813. PatientId: patient_id,
  4814. ReturnCount: delete_count,
  4815. StorehouseId: houseConfig.StorehouseOutInfo,
  4816. }
  4817. //service.UpdatedStockFlow(stockFlow)
  4818. service.UpdatedStockFlowOne(stockFlow, warehouseOut.ID, patient_id, record_time, good_yc.GoodId)
  4819. }
  4820. }
  4821. //更改自动出库的表格
  4822. details := models.BloodAutomaticReduceDetail{
  4823. WarehouseOutId: warehouseOutInfo.ID,
  4824. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  4825. PatientId: patient_id,
  4826. Ctime: time.Now().Unix(),
  4827. Mtime: time.Now().Unix(),
  4828. Status: 1,
  4829. RecordTime: record_time,
  4830. OrgId: orgID,
  4831. GoodId: good_yc.GoodId,
  4832. GoodTypeId: good_yc.GoodTypeId,
  4833. Count: count,
  4834. StorehouseId: houseConfig.StorehouseOutInfo,
  4835. }
  4836. //查询当天耗材是否已经存在数据
  4837. _, errcode := service.GetAutoMaticReduceDetail(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4838. if errcode == gorm.ErrRecordNotFound {
  4839. errTwo := service.CreateAutoReduceRecord(&details)
  4840. if errTwo != nil {
  4841. return errTwo
  4842. }
  4843. } else if errcode == nil {
  4844. service.DeleteAutoRedeceDetailTwo(orgID, patient_id, record_time, good_yc.GoodId, good_yc.GoodTypeId)
  4845. service.CreateAutoReduceRecord(&details)
  4846. }
  4847. // 删除出库完成后,要增加对应批次的库存数量
  4848. errThree := service.UpDateWarehouseInfoByStockDelete(warehouseOutInfos.WarehouseInfotId, delete_count)
  4849. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  4850. errOne := service.UpDateWarehouStockFlowByStockDelete(warehouseOutInfos.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  4851. fmt.Println("errOne", errOne)
  4852. if errThree != nil {
  4853. return errThree
  4854. }
  4855. if good_yc.Count == 0 {
  4856. return nil
  4857. } else {
  4858. return errors.New("退库和出库数据不匹配")
  4859. }
  4860. }
  4861. func ConsumablesDeliveryTotalSix(orgID int64, patient_id int64, record_time int64, goods []*models.DialysisBeforePrepareGoods, goodOne []*models.NewDialysisBeforePrepareGoods, creater int64) (err error) {
  4862. //查询该患者当天已经出库的耗材信息
  4863. goods_yc, _ := service.FindConsumablesByDateThree(orgID, patient_id, record_time)
  4864. // 和新请求的出库数据进行对比,分出那些是继续出库的,那些是需要删除出库的
  4865. for i := len(goods_yc) - 1; i >= 0; i-- {
  4866. goods_yc_temp := goods_yc[i]
  4867. for j := len(goods) - 1; j >= 0; j-- {
  4868. goods_temp := goods[j]
  4869. // 已经出库和新请求出库都存在该耗材,则判断出库数量,分成是继续出库,还是删除出库
  4870. if goods_yc_temp.GoodTypeId == goods_temp.GoodTypeId && goods_yc_temp.GoodId == goods_temp.GoodId {
  4871. // 已经出库和新请求出库的出库数量一致,则清除两个结构体里的数据(既不出库,也不删除出库)
  4872. if goods_yc_temp.Count == goods_temp.Count {
  4873. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4874. goods = append(goods[:j], goods[j+1:]...)
  4875. break
  4876. }
  4877. // 如果已经出库的数量 大于 新请求出库的数量,则代表需要删除出库
  4878. if goods_yc_temp.Count > goods_temp.Count {
  4879. temp_count := goods_yc_temp.Count - goods_temp.Count
  4880. goods_yc[i].Count = temp_count
  4881. goods = append(goods[:j], goods[j+1:]...)
  4882. break
  4883. }
  4884. // 如果已经出库的数量 小于 新请求出库的梳理,则代表需要增加出库
  4885. if goods_yc_temp.Count < goods_temp.Count {
  4886. temp_count := goods_temp.Count - goods_yc_temp.Count
  4887. goods[j].Count = temp_count
  4888. goods_yc = append(goods_yc[:i], goods_yc[i+1:]...)
  4889. break
  4890. }
  4891. }
  4892. }
  4893. }
  4894. // goods_yc 这个数据就是需要已经出库了,但是现在需要删除出库的耗材数据
  4895. // goods 这个数据就是需要出库的耗材的数据(新增的数据)
  4896. if len(goods) > 0 {
  4897. out, err := service.FindStockOutByIsSys(orgID, 1, record_time)
  4898. houseConfig, _ := service.GetAllStoreHouseConfig(orgID)
  4899. if err == gorm.ErrRecordNotFound {
  4900. //没有记录,则创建出库单
  4901. timeStr := time.Now().Format("2006-01-02")
  4902. timeArr := strings.Split(timeStr, "-")
  4903. total, _ := service.FindAllWarehouseOut(orgID)
  4904. total = total + 1
  4905. warehousing_out_order := strconv.FormatInt(orgID, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  4906. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  4907. number = number + total
  4908. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  4909. warehouseOut := models.WarehouseOut{
  4910. WarehouseOutOrderNumber: warehousing_out_order,
  4911. OperationTime: time.Now().Unix(),
  4912. OrgId: orgID,
  4913. Creater: creater,
  4914. Ctime: time.Now().Unix(),
  4915. Status: 1,
  4916. WarehouseOutTime: record_time,
  4917. Dealer: 0,
  4918. Manufacturer: 0,
  4919. Type: 1,
  4920. IsSys: 1,
  4921. StorehouseId: houseConfig.StorehouseOutInfo,
  4922. IsCheck: 1,
  4923. }
  4924. err := service.AddSigleWarehouseOut(&warehouseOut)
  4925. if err != nil {
  4926. utils.TraceLog("创建出库单失败 err = %v", err)
  4927. return err
  4928. } else {
  4929. out = warehouseOut
  4930. }
  4931. }
  4932. for _, item := range goods {
  4933. var newCount int64 = 0
  4934. for _, it := range goodOne {
  4935. if item.GoodTypeId == it.GoodTypeId && item.GoodId == it.GoodId {
  4936. newCount = it.Count
  4937. }
  4938. }
  4939. prepare := models.DialysisBeforePrepare{
  4940. GoodTypeId: item.GoodTypeId,
  4941. GoodId: item.GoodId,
  4942. Count: item.Count,
  4943. StorehouseId: houseConfig.StorehouseOutInfo,
  4944. }
  4945. service.ConsumablesDelivery(orgID, patient_id, record_time, &prepare, &out, newCount)
  4946. }
  4947. }
  4948. if len(goods_yc) > 0 {
  4949. for _, good_yc := range goods_yc {
  4950. out, _ := service.FindStockOutByIsSys(orgID, 1, record_time)
  4951. ConsumablesDeliveryDeleteThree(orgID, record_time, good_yc, &out)
  4952. }
  4953. }
  4954. return nil
  4955. }
  4956. //耗材出库删除
  4957. func ConsumablesDeliveryDeleteThree(orgID int64, record_time int64, good_yc *models.BloodAutomaticReduceDetail, warehouseOut *models.WarehouseOut) (err error) {
  4958. // 先根据相关信息查询当天该耗材的出库信息
  4959. warehouseOutInfos, err := service.FindStockOutInfoByStockOne(orgID, good_yc.GoodTypeId, good_yc.GoodId, record_time)
  4960. if err != nil {
  4961. return err
  4962. }
  4963. var delete_count int64 = 0
  4964. for _, ware := range warehouseOutInfos {
  4965. // 判断当前出库的数据和删除出库数量
  4966. if good_yc.Count <= ware.Count {
  4967. delete_count = good_yc.Count
  4968. } else {
  4969. delete_count = ware.Count
  4970. }
  4971. // 在出库记录表里记录退库详情
  4972. warehouseOutInfo := &models.WarehouseOutInfo{
  4973. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  4974. WarehouseOutId: warehouseOut.ID,
  4975. Status: 1,
  4976. Ctime: time.Now().Unix(),
  4977. Remark: "",
  4978. OrgId: orgID,
  4979. Type: 1,
  4980. Manufacturer: 0,
  4981. Dealer: 0,
  4982. IsSys: 0,
  4983. SysRecordTime: record_time,
  4984. GoodTypeId: good_yc.GoodTypeId,
  4985. GoodId: good_yc.GoodId,
  4986. StorehouseId: warehouseOut.StorehouseId,
  4987. IsCheck: 1,
  4988. }
  4989. warehouseOutInfo.Count = delete_count
  4990. stockInInfo, _ := service.FindLastStockInInfoRecord(good_yc.GoodId, orgID)
  4991. warehouseOutInfo.Price = stockInInfo.Price
  4992. errOne := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  4993. if errOne != nil {
  4994. return errOne
  4995. }
  4996. // 删除出库完成后,要增加对应批次的库存数量
  4997. // 删除出库完成后,要改变流水库存
  4998. errOne = service.UpDateWarehouStockFlowByStockDelete(ware.WarehouseInfotId, record_time, good_yc.GoodId, delete_count, good_yc.PatientId)
  4999. fmt.Println("errOne", errOne)
  5000. errThree := service.UpDateWarehouseInfoByStockDelete(ware.WarehouseInfotId, delete_count)
  5001. service.ModifyGoodAddInformation(good_yc.GoodId, delete_count, good_yc.OrgId)
  5002. if errThree != nil {
  5003. return errThree
  5004. }
  5005. }
  5006. if good_yc.Count == 0 {
  5007. return nil
  5008. } else {
  5009. return errors.New("退库和出库数据不匹配")
  5010. }
  5011. }
  5012. func (this *DialysisAPIController) GetMobileScheduleList() {
  5013. limit, _ := this.GetInt64("limit")
  5014. page, _ := this.GetInt64("page")
  5015. type_options_visible, _ := this.GetInt64("type_options_visible")
  5016. sch_type_options_visible, _ := this.GetInt64("sch_type_options_visible")
  5017. zone_options_visible, _ := this.GetInt64("zone_options_visible")
  5018. fmt.Println(limit, page, type_options_visible, sch_type_options_visible, zone_options_visible)
  5019. }
  5020. func RemoveRepeatedCheckRecod(arr []*models.HisPrescriptionProject) (newArr []*models.HisPrescriptionProject) {
  5021. newArr = make([]*models.HisPrescriptionProject, 0)
  5022. for i := 0; i < len(arr); i++ {
  5023. repeat := false
  5024. for j := i + 1; j < len(arr); j++ {
  5025. if arr[i].TeamId == arr[j].TeamId {
  5026. repeat = true
  5027. break
  5028. }
  5029. }
  5030. if !repeat {
  5031. newArr = append(newArr, arr[i])
  5032. }
  5033. }
  5034. return
  5035. }
  5036. func (this *DialysisAPIController) GetRoleList() {
  5037. admin_user_id, _ := this.GetInt64("admin_user_id")
  5038. orgid := this.GetMobileAdminUserInfo().Org.Id
  5039. list, err := service.GetRoleList(orgid, admin_user_id)
  5040. fmt.Println(err)
  5041. this.ServeSuccessJSON(map[string]interface{}{
  5042. "list": list,
  5043. })
  5044. return
  5045. }