dialysis_api_controller.go 204KB

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