dialysis_api_controller.go 181KB

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