dialysis_api_controller.go 182KB

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