dialysis_api_controller.go 188KB

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