dialysis_api_controller.go 216KB

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