dialysis_api_controller.go 212KB

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