dialysis_api_controller.go 221KB

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