dialysis_api_controller.go 220KB

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