dialysis_api_controller.go 203KB

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