dialysis_api_controller.go 212KB

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