dialysis_api_controller.go 212KB

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