dialysis_api_controller.go 211KB

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