dialysis_api_controller.go 210KB

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