dialysis_api_controller.go 200KB

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