dialysis_api_controller.go 205KB

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