dialysis_api_controller.go 264KB

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