dialysis_api_controller.go 216KB

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