dialysis_api_controller.go 215KB

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