dialysis_api_controller.go 156KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238
  1. package mobile_api_controllers
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/jinzhu/gorm"
  6. "reflect"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "XT_New/enums"
  11. "XT_New/models"
  12. "XT_New/service"
  13. "XT_New/utils"
  14. "math"
  15. )
  16. // type DialysisTestAPIController struct {
  17. // MobileBaseAPIController
  18. // }
  19. // [get]/m/api/test
  20. // func (this *DialysisTestAPIController) Test() {
  21. // orgID := int64(3907)
  22. // now := time.Now()
  23. // nextWeek := now.AddDate(0, 0, 7)
  24. // nextWeekMon, nextWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextWeek)
  25. // nextTwoWeek := now.AddDate(0, 0, 14)
  26. // nextTwoWeekMon, nextTwoWeekSun := utils.GetMondayAndSundayOfWeekDate(&nextTwoWeek)
  27. // nextWeekSchs, getNextWeekSchErr := service.GetWeekSchedule(orgID, nextWeekMon.Unix(), nextWeekSun.Unix())
  28. // nextTwoWeekSchs, getNextTwoWeekSchErr := service.GetWeekSchedule(orgID, nextTwoWeekMon.Unix(), nextTwoWeekSun.Unix())
  29. // if getNextWeekSchErr != nil || getNextTwoWeekSchErr != nil {
  30. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  31. // return
  32. // }
  33. // exchangeErr := service.ExchangeScheduleTimeWithWeekSchedules(orgID, nextWeekSchs, nextTwoWeekSchs)
  34. // if exchangeErr != nil {
  35. // this.ErrorLog("%v", exchangeErr)
  36. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  37. // return
  38. // }
  39. // this.ServeSuccessJSON(map[string]interface{}{
  40. // // "now": now,
  41. // // "next_week": nextWeek,f
  42. // // "next_week_mon": nextWeekMon,
  43. // // "next_week_sun": nextWeekSun,
  44. // // "next_two_week_mon": nextTwoWeekMon,
  45. // // "next_two_week_sun": nextTwoWeekSun,
  46. // "next_week_schs": nextWeekSchs,
  47. // "next_two_week_schs": nextTwoWeekSchs,
  48. // })
  49. // }
  50. type DialysisAPIController struct {
  51. MobileBaseAPIAuthController
  52. }
  53. // /m/api/scheduals [get]
  54. // @param type:int
  55. // @param date:string
  56. func (this *DialysisAPIController) Scheduals() {
  57. schedualType, _ := this.GetInt64("type")
  58. schedualDate := this.GetString("date")
  59. if schedualType != 0 && schedualType != 1 && schedualType != 2 && schedualType != 3 {
  60. schedualType = 0
  61. }
  62. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  63. if parseDateErr != nil {
  64. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  65. return
  66. }
  67. adminInfo := this.GetMobileAdminUserInfo()
  68. orgID := adminInfo.Org.Id
  69. redis := service.RedisClient()
  70. defer redis.Close()
  71. // cur_date := time.Now().Format("2006-01-02")
  72. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  73. scheduals_json_str, _ := redis.Get(key).Result()
  74. if len(scheduals_json_str) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  75. scheduals, err := service.MobileGetDialysisScheduals(orgID, date.Unix(), schedualType)
  76. if err != nil {
  77. this.ErrorLog("获取排班信息失败:%v", err)
  78. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  79. } else {
  80. if len(scheduals) > 0 {
  81. //缓存数据
  82. scheduals_json, err := json.Marshal(scheduals)
  83. if err == nil {
  84. redis.Set(key, scheduals_json, time.Second*30)
  85. }
  86. }
  87. this.ServeSuccessJSON(map[string]interface{}{
  88. "scheduals": scheduals,
  89. })
  90. }
  91. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  92. var dat []map[string]interface{}
  93. if err := json.Unmarshal([]byte(scheduals_json_str), &dat); err == nil {
  94. } else {
  95. }
  96. this.ServeSuccessJSON(map[string]interface{}{
  97. "scheduals": dat,
  98. "redis": "true",
  99. "date": schedualDate,
  100. })
  101. }
  102. }
  103. // /m/api/waiting_scheduals [get]
  104. // @param date:string
  105. func (this *DialysisAPIController) WaitingScheduals() {
  106. schedualDate := this.GetString("date")
  107. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  108. if parseDateErr != nil && len(schedualDate) != 0 {
  109. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  110. return
  111. }
  112. adminInfo := this.GetMobileAdminUserInfo()
  113. orgID := adminInfo.Org.Id
  114. redis := service.RedisClient()
  115. defer redis.Close()
  116. // cur_date := time.Now().Format("2006-01-02")
  117. key := "wait_scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  118. wait_scheduals, _ := redis.Get(key).Result()
  119. if len(wait_scheduals) == 0 { //没有到缓存数据,从数据库中获取数据,进行缓存到redis
  120. scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  121. if err != nil {
  122. this.ErrorLog("获取排班信息失败:%v", err)
  123. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  124. } else {
  125. returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  126. for _, s := range scheduals {
  127. returnScheduals = append(returnScheduals, s)
  128. }
  129. if len(returnScheduals) > 0 {
  130. //缓存数据
  131. wait_scheduals_json, err := json.Marshal(scheduals)
  132. if err == nil {
  133. redis.Set(key, wait_scheduals_json, time.Second*30)
  134. }
  135. }
  136. this.ServeSuccessJSON(map[string]interface{}{
  137. "scheduals": scheduals,
  138. })
  139. }
  140. } else { //缓存数据了数据,将redis缓存的json字符串转为map
  141. var dat []map[string]interface{}
  142. if err := json.Unmarshal([]byte(wait_scheduals), &dat); err == nil {
  143. } else {
  144. }
  145. this.ServeSuccessJSON(map[string]interface{}{
  146. "scheduals": dat,
  147. "redis": "true",
  148. "date": schedualDate,
  149. })
  150. }
  151. }
  152. //else{
  153. // fmt.Println("33333333")
  154. //
  155. // scheduals, err := service.MobileGetWaitingScheduals(orgID, date.Unix())
  156. // if err != nil {
  157. // this.ErrorLog("获取排班信息失败:%v", err)
  158. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  159. // } else {
  160. // returnScheduals := make([]*service.MDialysisScheduleVM, 0, len(scheduals))
  161. // for _, s := range scheduals {
  162. //
  163. // returnScheduals = append(returnScheduals, s)
  164. // }
  165. //
  166. // this.ServeSuccessJSON(map[string]interface{}{
  167. // "scheduals": returnScheduals,
  168. // })
  169. // }
  170. //
  171. // }
  172. //if err == nil{
  173. //
  174. //
  175. //
  176. //
  177. //
  178. //}else{
  179. //}
  180. // /m/api/dialysis/record [get]
  181. // @param patient_id:int
  182. // @param date:string (yyyy-MM-dd)
  183. func (this *DialysisAPIController) DialysisRecord() {
  184. patientID, _ := this.GetInt64("patient_id")
  185. recordDateStr := this.GetString("date")
  186. if patientID <= 0 {
  187. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  188. return
  189. }
  190. if len(recordDateStr) == 0 {
  191. recordDateStr = time.Now().Format("2006-01-02")
  192. }
  193. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  194. if parseDateErr != nil {
  195. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  196. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  197. return
  198. }
  199. adminInfo := this.GetMobileAdminUserInfo()
  200. patient, getPatientErr := service.MobileGetPatientDetail(adminInfo.Org.Id, patientID)
  201. if getPatientErr != nil {
  202. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  203. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  204. return
  205. } else if patient == nil {
  206. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  207. return
  208. }
  209. schedual, getSchedualErr := service.MobileGetSchedualDetail(adminInfo.Org.Id, patientID, date.Unix())
  210. // this.TraceLog("==================================%+v", schedual)
  211. if getSchedualErr != nil {
  212. this.ErrorLog("获取患者排班信息失败:%v", getSchedualErr)
  213. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  214. return
  215. }
  216. receiverTreatmentAccess, getRTARErr := service.MobileGetReceiverTreatmentAccessRecord(adminInfo.Org.Id, patientID, date.Unix())
  217. if getRTARErr != nil {
  218. this.ErrorLog("获取接诊评估失败:%v", getRTARErr)
  219. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  220. return
  221. }
  222. predialysisEvaluation, getPEErr := service.MobileGetPredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  223. if getPEErr != nil {
  224. this.ErrorLog("获取透前评估失败:%v", getPEErr)
  225. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  226. return
  227. }
  228. lastPredialysisEvaluation, getLPEErr := service.MobileGetLastTimePredialysisEvaluation(adminInfo.Org.Id, patientID, date.Unix())
  229. if getLPEErr != nil {
  230. this.ErrorLog("获取上一次透前评估失败:%v", getLPEErr)
  231. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  232. return
  233. }
  234. doctorAdvices, getDoctorAdvicesErr := service.MobileGetDoctorAdvicesByGroups(adminInfo.Org.Id, patientID, date.Unix())
  235. if getDoctorAdvicesErr != nil {
  236. this.ErrorLog("获取临时医嘱失败:%v", getDoctorAdvicesErr)
  237. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  238. return
  239. }
  240. dialysisOrder, getDialysisOrderErr := service.MobileGetSchedualDialysisRecord(adminInfo.Org.Id, patientID, date.Unix())
  241. if getDialysisOrderErr != nil {
  242. this.ErrorLog("获取透析记录失败:%v", getDialysisOrderErr)
  243. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  244. return
  245. }
  246. doubleCheck, getDoubleCheckErr := service.MobileGetDoubleCheck(adminInfo.Org.Id, patientID, date.Unix())
  247. if getDoubleCheckErr != nil {
  248. this.ErrorLog("获取双人核对记录失败:%v", getDoubleCheckErr)
  249. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  250. return
  251. }
  252. monitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecords(adminInfo.Org.Id, patientID, date.Unix())
  253. if getMonitorRecordsErr != nil {
  254. this.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  255. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  256. return
  257. }
  258. var lastMonitorRecord *models.MonitoringRecord
  259. lastMonitorRecord, getLastErr := service.MobileGetLastMonitorRecord(adminInfo.Org.Id, patientID, date.Unix())
  260. if getLastErr != nil {
  261. this.ErrorLog("获取上一次透析的监测记录失败:%v", getLastErr)
  262. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  263. return
  264. }
  265. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  266. if getAADErr != nil {
  267. this.ErrorLog("获取透后评估失败:%v", getAADErr)
  268. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  269. return
  270. }
  271. lastAssessmentAfterDislysis, getLAADErr := service.MobileGetLastTimeAssessmentAfterDislysis(adminInfo.Org.Id, patientID, date.Unix())
  272. if getLAADErr != nil {
  273. this.ErrorLog("获取上一次透后评估失败:%v", getLAADErr)
  274. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  275. return
  276. }
  277. treatmentSummary, getTreatmentSummaryErr := service.MobileGetTreatmentSummary(adminInfo.Org.Id, patientID, date.Unix())
  278. if getTreatmentSummaryErr != nil {
  279. this.ErrorLog("获取治疗小结失败:%v", getTreatmentSummaryErr)
  280. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  281. return
  282. }
  283. dialysisPrescribe, _ := service.MobileGetDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, date.Unix(), schedual.ModeId)
  284. //if getDialysisPrescribeErr != nil {
  285. // this.ErrorLog("获取透析处方失败:%v", getDialysisPrescribeErr)
  286. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  287. // return
  288. //}
  289. dialysisSolution, _ := service.MobileGetDialysisSolutionByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  290. //if getDialysisSolutionErr != nil {
  291. // this.ErrorLog("获取透析方案失败:%v", getDialysisSolutionErr)
  292. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  293. // return
  294. //}
  295. lastDialysisPrescribe, _ := service.MobileGetLastDialysisPrescribeByModeId(adminInfo.Org.Id, patientID, schedual.ModeId)
  296. //fmt.Println("上次透析处方",lastDialysisPrescribe.DialyzerPerfusionApparatus)
  297. //if getDialysisPrescribeErr != nil {
  298. // this.ErrorLog("获取透析处方失败:%v", getDialysisPrescribeErr)
  299. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  300. // return
  301. //}
  302. //获取系统透析处方模版
  303. systemDialysisPrescribe, _ := service.MobileGetSystemDialysisPrescribeByModeId(adminInfo.Org.Id, schedual.ModeId)
  304. //if getSystemDialysisPrescribeErr != nil {
  305. // this.ErrorLog("获取系统透析处方失败:%v", getSystemDialysisPrescribeErr)
  306. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  307. // return
  308. //}
  309. //dialysisSolution, getDialysisSolutionErr := service.MobileGetDialysisSolution(adminInfo.Org.Id, patientID)
  310. //operators, _ := service.GetAllAdminUserES(adminInfo.Org.Id, adminInfo.App.Id)
  311. if getLPEErr != nil {
  312. this.ErrorLog("获取上一次透前评估失败:%v", getLPEErr)
  313. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  314. return
  315. }
  316. lastDryWeightDislysis, getDryErr := service.MobileGetLastDryWeight(adminInfo.Org.Id, patientID)
  317. if getDryErr != nil {
  318. this.ErrorLog("获取最后一条干体重失败:%v", getDryErr)
  319. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  320. return
  321. }
  322. //headNurses, _ := service.GetAllSpecialPermissionAdminUsersWithoutStatus(adminInfo.Org.Id, adminInfo.App.Id, models.SpecialPermissionTypeHeadNurse)
  323. _, gobalConfig := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  324. //goodTypes, _ := service.FindAllGoodTypeByType(1) //查出所有库存配置的系统类型
  325. //goodInfos, _ := service.FindAllGoodInfo(adminInfo.Org.Id) //查出所有库存配置的系统类型
  326. operators, _ := service.GetAllStarfEs(adminInfo.Org.Id)
  327. //consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patientID, date.Unix())
  328. //lastConsumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patientID, date.Unix())
  329. returnData := map[string]interface{}{
  330. "patient": patient,
  331. "schedual": schedual,
  332. "prescription": dialysisPrescribe,
  333. "solution": dialysisSolution,
  334. "last_prescription": lastDialysisPrescribe,
  335. "receiver_treatment_access": receiverTreatmentAccess,
  336. "predialysis_evaluation": predialysisEvaluation,
  337. "doctor_advices": doctorAdvices,
  338. "double_check": doubleCheck,
  339. "assessment_after_dislysis": assessmentAfterDislysis,
  340. "treatment_summary": treatmentSummary,
  341. "monitor_records": monitorRecords,
  342. "dialysis_order": dialysisOrder,
  343. "operators": operators,
  344. "last_predialysis_evaluation": lastPredialysisEvaluation,
  345. "last_assessment_after_dislysis": lastAssessmentAfterDislysis,
  346. "last_monitor_record": lastMonitorRecord,
  347. "config": gobalConfig,
  348. "dry_weight": lastDryWeightDislysis,
  349. "system_prescription": systemDialysisPrescribe,
  350. }
  351. this.ServeSuccessJSON(returnData)
  352. }
  353. func (c *DialysisAPIController) GetDialysisGlobalConfig() {
  354. adminInfo := c.GetMobileAdminUserInfo()
  355. adminUsers, _ := service.GetAllAdminUsers(adminInfo.Org.Id, adminInfo.App.Id)
  356. devices, _ := service.GetValidDevicesBy(adminInfo.Org.Id, 0, 0)
  357. device_numbers, _ := service.GetAllValidDeviceNumbers(adminInfo.Org.Id)
  358. returnData := map[string]interface{}{
  359. "admin_users": adminUsers,
  360. "devices": devices,
  361. "device_numbers": device_numbers,
  362. }
  363. c.ServeSuccessJSON(returnData)
  364. }
  365. func (c *DialysisAPIController) PostAtreatmentInfo() {
  366. id, _ := c.GetInt64("patient", 0)
  367. recordDateStr := c.GetString("record_date")
  368. propagandaAndEducationContent := c.GetString("propagandaAndEducationContent")
  369. summaryContent := c.GetString("summaryContent")
  370. changeMedicalNurseId, _ := c.GetInt64("changeMedicalNurse", 0)
  371. treatNurseId, _ := c.GetInt64("treatNurse", 0)
  372. checkStaffId, _ := c.GetInt64("checkStaff", 0)
  373. deboardNurseId, _ := c.GetInt64("deboardNurse", 0)
  374. treatDoctor, _ := c.GetInt64("treatDoctor", 0)
  375. nursingRecord := c.GetString("nursing_record")
  376. fmt.Println("护理记录", nursingRecord)
  377. specialRecord := c.GetString("special_record")
  378. fmt.Println("特殊记录", specialRecord)
  379. adminUserInfo := c.GetMobileAdminUserInfo()
  380. changeMedicalNurseId = adminUserInfo.AdminUser.Id
  381. checkStaffId = adminUserInfo.AdminUser.Id
  382. deboardNurseId = adminUserInfo.AdminUser.Id
  383. treatDoctor = adminUserInfo.AdminUser.Id
  384. if id <= 0 {
  385. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  386. return
  387. }
  388. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  389. if patient.ID == 0 {
  390. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  391. return
  392. }
  393. if len(recordDateStr) == 0 {
  394. recordDateStr = time.Now().Format("2006-01-02")
  395. }
  396. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  397. if parseDateErr != nil {
  398. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  399. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  400. return
  401. }
  402. //now := time.Now()
  403. //year, month, day := now.Date()
  404. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  405. //todayTimeStamp := today_time.Unix()
  406. summary := models.TreatmentSummary{
  407. UserOrgId: adminUserInfo.Org.Id,
  408. PatientId: id,
  409. AssessmentDate: recordDate.Unix(),
  410. Mission: propagandaAndEducationContent,
  411. DialysisSummary: summaryContent,
  412. SjNurse: changeMedicalNurseId,
  413. ZlNurse: treatNurseId,
  414. HdNurse: checkStaffId,
  415. XjNurse: deboardNurseId,
  416. ZlDoctor: treatDoctor,
  417. CreatedTime: time.Now().Unix(),
  418. Status: 1,
  419. NursingRecord: nursingRecord,
  420. SpecialRecord: specialRecord,
  421. }
  422. _, treatmentSummary := service.FindTreatmentSummaryByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  423. if treatmentSummary.ID == 0 { //新增
  424. summary.Creater = adminUserInfo.AdminUser.Id
  425. service.AddSigleSummaryRecord(&summary)
  426. c.ServeSuccessJSON(map[string]interface{}{
  427. "summary": summary,
  428. })
  429. } else { //修改
  430. //if treatmentSummary.Creater != adminUserInfo.AdminUser.Id {
  431. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  432. // if getPermissionErr != nil {
  433. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  434. // return
  435. // } else if headNursePermission == nil {
  436. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  437. // return
  438. // }
  439. //}
  440. summary.Creater = treatmentSummary.Creater
  441. summary.CreatedTime = treatmentSummary.CreatedTime
  442. summary.Modifier = adminUserInfo.AdminUser.Id
  443. summary.ID = treatmentSummary.ID
  444. service.UpdateSummeRecord(&summary)
  445. c.ServeSuccessJSON(map[string]interface{}{
  446. "summary": summary,
  447. })
  448. }
  449. }
  450. func (c *DialysisAPIController) PostDoubleCheck() {
  451. id, _ := c.GetInt64("patient", 0)
  452. recordDateStr := c.GetString("record_date")
  453. checkTimeStr := c.GetString("check_time")
  454. firstCheckTimeStr := c.GetString("first_check_time")
  455. creater, _ := c.GetInt64("creater", 0)
  456. modifier, _ := c.GetInt64("modifier", 0)
  457. dialysis_item_check, _ := c.GetInt64("dialysis_item_check", 0)
  458. dialysis_parameter_check, _ := c.GetInt64("dialysis_parameter_check", 0)
  459. vascular_access_verification, _ := c.GetInt64("vascular_access_verification", 0)
  460. pipeline_connection_check, _ := c.GetInt64("pipeline_connection_check", 0)
  461. dialysis_item_desc := c.GetString("dialysis_item_desc")
  462. dialysis_parameter_desc := c.GetString("dialysis_parameter_desc")
  463. vascular_access_desc := c.GetString("vascular_access_desc")
  464. pipeline_connection_desc := c.GetString("pipeline_connection_desc")
  465. collator, _ := c.GetInt64("collator", 0)
  466. if id <= 0 {
  467. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  468. return
  469. }
  470. adminUserInfo := c.GetMobileAdminUserInfo()
  471. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  472. if patient.ID == 0 {
  473. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  474. return
  475. }
  476. if len(recordDateStr) == 0 {
  477. recordDateStr = time.Now().Format("2006-01-02")
  478. }
  479. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  480. if parseDateErr != nil {
  481. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  482. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  483. return
  484. }
  485. var checkDate int64
  486. if len(checkTimeStr) == 0 {
  487. checkDate = 0
  488. } else {
  489. checkDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", checkTimeStr)
  490. checkDate = checkDateUnix.Unix()
  491. }
  492. var firstCheckDate int64
  493. if len(firstCheckTimeStr) == 0 {
  494. firstCheckDate = 0
  495. } else {
  496. firstCheckDateUnix, _ := utils.ParseTimeStringToTime("2006-01-02 15:04:05", firstCheckTimeStr)
  497. firstCheckDate = firstCheckDateUnix.Unix()
  498. }
  499. //now := time.Now()
  500. //year, month, day := now.Date()
  501. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  502. //todayTimeStamp := today_time.Unix()
  503. doubleCheck := models.DoubleCheck{
  504. UserOrgId: adminUserInfo.Org.Id,
  505. PatientId: id,
  506. DialysisItemCheck: dialysis_item_check,
  507. DialysisParameterCheck: dialysis_parameter_check,
  508. VascularAccessVerification: vascular_access_verification,
  509. PipelineConnectionCheck: pipeline_connection_check,
  510. DialysisItemDesc: dialysis_item_desc,
  511. DialysisParameterDesc: dialysis_parameter_desc,
  512. VascularAccessDesc: vascular_access_desc,
  513. PipelineConnectionDesc: pipeline_connection_desc,
  514. Collator: collator,
  515. Status: 1,
  516. CreatedTime: time.Now().Unix(),
  517. CheckDate: recordDate.Unix(),
  518. UpdatedTime: time.Now().Unix(),
  519. }
  520. _, check := service.FindDoubleCheckByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  521. if check.ID == 0 { //新增
  522. doubleCheck.FirstCheckTime = firstCheckDate
  523. doubleCheck.CheckTime = checkDate
  524. doubleCheck.Creater = creater
  525. doubleCheck.Modifier = modifier
  526. err := service.AddSigleDoubleCheck(&doubleCheck)
  527. if err == nil {
  528. c.ServeSuccessJSON(map[string]interface{}{
  529. "doubleCheck": &doubleCheck,
  530. })
  531. }
  532. } else { //修改
  533. doubleCheck.FirstCheckTime = firstCheckDate
  534. doubleCheck.CheckTime = checkDate
  535. doubleCheck.Creater = creater
  536. doubleCheck.Modifier = modifier
  537. doubleCheck.CreatedTime = check.CreatedTime
  538. doubleCheck.ID = check.ID
  539. err := service.UpdateDoubleCheck(&doubleCheck)
  540. if err == nil {
  541. c.ServeSuccessJSON(map[string]interface{}{
  542. "doubleCheck": &doubleCheck,
  543. })
  544. }
  545. }
  546. }
  547. func (c *DialysisAPIController) PostAcceptsAssessment() {
  548. id, _ := c.GetInt64("patient", 0)
  549. recordDateStr := c.GetString("record_date")
  550. way, _ := c.GetInt64("way", 0)
  551. consciousness, _ := c.GetInt64("consciousness", 0)
  552. appetite, _ := c.GetInt64("appetite", 0)
  553. condition, _ := c.GetInt64("condition", 0)
  554. posture, _ := c.GetInt64("posture")
  555. sick_condition, _ := c.GetInt64("sick_condition", 0)
  556. danger_level, _ := c.GetInt64("danger_level", 0)
  557. intake, _ := c.GetInt64("intake", 0)
  558. nutrition, _ := c.GetInt64("nutrition", 0)
  559. psychological_assessment, _ := c.GetInt64("psychological_assessment", 0)
  560. psychological_assessment_other := c.GetString("psychological_assessment_other")
  561. score := c.GetString("score")
  562. sick_condition_other := c.GetString("sick_condition_other")
  563. //precaution, _ := c.GetInt64("precaution", 0)
  564. precaution := c.GetString("precaution")
  565. precaution_other := c.GetString("precaution_other")
  566. psychological_other := c.GetString("psychological_other")
  567. admission_number := c.GetString("admission_number")
  568. if id <= 0 {
  569. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  570. return
  571. }
  572. adminUserInfo := c.GetMobileAdminUserInfo()
  573. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  574. if patient.ID == 0 {
  575. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  576. return
  577. }
  578. //now := time.Now()
  579. //year, month, day := now.Date()
  580. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  581. //todayTimeStamp := today_time.Unix()
  582. if len(recordDateStr) == 0 {
  583. recordDateStr = time.Now().Format("2006-01-02")
  584. }
  585. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  586. if parseDateErr != nil {
  587. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  588. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  589. return
  590. }
  591. _, receiveTreatment := service.FindReceiveTreatmentAssesByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  592. receiveTreatmentAsses := models.ReceiveTreatmentAsses{
  593. UserOrgId: adminUserInfo.Org.Id,
  594. PatientId: id,
  595. RecordDate: recordDate.Unix(),
  596. Way: way,
  597. Consciousness: consciousness,
  598. Appetite: appetite,
  599. Condition: condition,
  600. SickCondition: sick_condition,
  601. DangerLevel: danger_level,
  602. Intake: intake,
  603. Nutrition: nutrition,
  604. PsychologicalAssessment: psychological_assessment,
  605. PsychologicalAssessmentOther: psychological_assessment_other,
  606. SickConditionOther: sick_condition_other,
  607. Posture: posture,
  608. CreatedTime: time.Now().Unix(),
  609. UpdateTime: time.Now().Unix(),
  610. Status: 1,
  611. Score: score,
  612. Precaution: precaution,
  613. PrecautionOther: precaution_other,
  614. PsychologicalOther: psychological_other,
  615. AdmissionNumber: admission_number,
  616. }
  617. if receiveTreatment.ID == 0 { //新增
  618. receiveTreatmentAsses.Creater = adminUserInfo.AdminUser.Id
  619. err := service.AddSigleReceiveTreatmentAssesRecord(&receiveTreatmentAsses)
  620. if err == nil {
  621. c.ServeSuccessJSON(map[string]interface{}{
  622. "receiveTreatmentAsses": receiveTreatmentAsses,
  623. })
  624. }
  625. } else { //修改
  626. //if receiveTreatment.Creater != adminUserInfo.AdminUser.Id {
  627. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  628. // if getPermissionErr != nil {
  629. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  630. // return
  631. // } else if headNursePermission == nil {
  632. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  633. // return
  634. // }
  635. //}
  636. receiveTreatmentAsses.Creater = receiveTreatment.Creater
  637. receiveTreatmentAsses.CreatedTime = receiveTreatment.CreatedTime
  638. receiveTreatmentAsses.Modifier = adminUserInfo.AdminUser.Id
  639. receiveTreatmentAsses.ID = receiveTreatment.ID
  640. err := service.UpadateReceiveTreatmentAsses(&receiveTreatmentAsses)
  641. if err == nil {
  642. c.ServeSuccessJSON(map[string]interface{}{
  643. "receiveTreatmentAsses": receiveTreatmentAsses,
  644. })
  645. }
  646. }
  647. }
  648. func (c *DialysisAPIController) PostAssessmentAfterDislysis() {
  649. id, _ := c.GetInt64("patient", 0)
  650. recordDateStr := c.GetString("record_date")
  651. weightAfter, _ := c.GetFloat("weight_after", 0)
  652. additionalWeight, _ := c.GetFloat("additional_weight", 0)
  653. weightReduce, _ := c.GetFloat("weight_loss", 0)
  654. temperature, _ := c.GetFloat("temperature", 0)
  655. pulse_frequency, _ := c.GetFloat("pulse_frequency", 0)
  656. breathing_rate, _ := c.GetFloat("breathing_rate", 0)
  657. systolic_blood_pressure, _ := c.GetFloat("systolic_blood_pressure", 0)
  658. diastolic_blood_pressure, _ := c.GetFloat("diastolic_blood_pressure", 0)
  659. actual_ultrafiltration, _ := c.GetFloat("actual_ultrafiltration", 0)
  660. actual_displacement, _ := c.GetFloat("actual_displacement", 0)
  661. actualtreatHour, _ := c.GetInt64("actual_treatment_hour", 0)
  662. actualtreatmin, _ := c.GetInt64("actual_treatment_minute", 0)
  663. cruor := c.GetString("cruor")
  664. symptomsAfterDialysi := c.GetString("symptom_after_dialysis")
  665. internalFistula := c.GetString("internal_fistula")
  666. catheter := c.GetString("catheter")
  667. complications := c.GetString("complication")
  668. remark := c.GetString("remark")
  669. dialysateVolume, _ := c.GetInt64("dialysis_intakes", 0)
  670. dialysis_intakes_unit, _ := c.GetInt64("dialysis_intakes_unit", 0)
  671. blood_access_part_id, _ := c.GetInt64("blood_access_part_id", 0)
  672. blood_access_part_opera_id, _ := c.GetInt64("blood_access_part_opera_id", 0)
  673. puncturePointOozingBlood, _ := c.GetInt64("puncture_point_oozing_blood", 0)
  674. puncturePointHaematoma, _ := c.GetInt64("puncture_point_haematoma", 0)
  675. internalFistulaTremorAc, _ := c.GetInt64("internal_fistula_tremor_ac", 0)
  676. patientGose, _ := c.GetInt64("patient_gose", 0)
  677. inpatientDepartment := c.GetString("inpatient_department")
  678. observationContent := c.GetString("observation_content")
  679. observationContentOther := c.GetString("observation_content_other")
  680. dialysis_process, _ := c.GetInt64("dialysis_process", 0)
  681. in_advance_minute, _ := c.GetFloat("in_advance_minute", 0)
  682. in_advance_reason := c.GetString("in_advance_reason")
  683. hemostasis_minute, _ := c.GetInt64("hemostasis_minute", 0)
  684. hemostasis_opera, _ := c.GetInt64("hemostasis_opera", 0)
  685. tremor_noise, _ := c.GetInt64("tremor_noise", 0)
  686. disequilibrium_syndrome, _ := c.GetInt64("disequilibrium_syndrome", 0)
  687. disequilibrium_syndrome_option := c.GetString("disequilibrium_syndrome_option")
  688. arterial_tube, _ := c.GetInt64("arterial_tube", 0)
  689. intravenous_tube, _ := c.GetInt64("intravenous_tube", 0)
  690. dialyzer, _ := c.GetInt64("dialyzer", 0)
  691. in_advance_reason_other := c.GetString("in_advance_reason_other")
  692. is_eat, _ := c.GetInt64("is_eat", 0)
  693. cvc_a, _ := c.GetFloat("cvc_a", 0)
  694. cvc_v, _ := c.GetFloat("cvc_v", 0)
  695. channels, _ := c.GetInt64("channel", 0)
  696. return_blood, _ := c.GetInt64("return_blood", 0)
  697. rehydration_volume, _ := c.GetInt64("rehydration_volume", 0)
  698. dialysis_during, _ := c.GetInt64("dialysis_during", 0)
  699. stroke_volume, _ := c.GetInt64("stroke_volume", 0)
  700. blood_flow, _ := c.GetInt64("blood_flow", 0)
  701. //sealing_fluid_dispose, _ := c.GetInt64("sealing_fluid_dispose", 0)
  702. sealing_fluid_dispose := c.GetString("sealing_fluid_dispose")
  703. sealing_fluid_special := c.GetString("sealing_fluid_special")
  704. dosage_of_anticoagulants, _ := c.GetFloat("dosage_of_anticoagulants")
  705. supine_systolic_blood_pressure := c.GetString("supine_systolic_blood_pressure")
  706. setting_pressure := c.GetString("setting_pressure")
  707. supine_diastolic_blood_pressure := c.GetString("supine_diastolic_blood_pressure")
  708. diastolic_pressure := c.GetString("diastolic_pressure")
  709. if id <= 0 {
  710. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  711. return
  712. }
  713. adminUserInfo := c.GetMobileAdminUserInfo()
  714. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  715. if patient.ID == 0 {
  716. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  717. return
  718. }
  719. if len(recordDateStr) == 0 {
  720. recordDateStr = time.Now().Format("2006-01-02")
  721. }
  722. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  723. if parseDateErr != nil {
  724. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  725. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  726. return
  727. }
  728. //now := time.Now()
  729. //year, month, day := now.Date()
  730. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  731. //todayTimeStamp := today_time.Unix()
  732. //_, evaluation := service.FindPredialysisEvaluationByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  733. assessmentAfterDislysis := models.AssessmentAfterDislysis{
  734. UserOrgId: adminUserInfo.Org.Id,
  735. PatientId: id,
  736. AssessmentDate: recordDate.Unix(),
  737. Temperature: temperature,
  738. PulseFrequency: pulse_frequency,
  739. BreathingRate: breathing_rate,
  740. SystolicBloodPressure: systolic_blood_pressure,
  741. DiastolicBloodPressure: diastolic_blood_pressure,
  742. ActualUltrafiltration: actual_ultrafiltration,
  743. ActualDisplacement: actual_displacement,
  744. ActualTreatmentHour: actualtreatHour,
  745. ActualTreatmentMinute: actualtreatmin,
  746. WeightAfter: weightAfter,
  747. AdditionalWeight: additionalWeight,
  748. WeightLoss: weightReduce,
  749. Cruor: cruor,
  750. SymptomAfterDialysis: symptomsAfterDialysi,
  751. InternalFistula: internalFistula,
  752. Catheter: catheter,
  753. Complication: complications,
  754. DialysisIntakes: dialysateVolume,
  755. CreatedTime: time.Now().Unix(),
  756. Status: 1,
  757. Remark: remark,
  758. BloodAccessPartId: blood_access_part_id,
  759. BloodAccessPartOperaId: blood_access_part_opera_id,
  760. DialysisIntakesUnit: dialysis_intakes_unit,
  761. PuncturePointOozingBlood: puncturePointOozingBlood,
  762. PuncturePointHaematoma: puncturePointHaematoma,
  763. InternalFistulaTremorAc: internalFistulaTremorAc,
  764. PatientGose: patientGose,
  765. InpatientDepartment: inpatientDepartment,
  766. ObservationContent: observationContent,
  767. ObservationContentOther: observationContentOther,
  768. DialysisProcess: dialysis_process,
  769. InAdvanceMinute: in_advance_minute,
  770. InAdvanceReason: in_advance_reason,
  771. HemostasisMinute: hemostasis_minute,
  772. HemostasisOpera: hemostasis_opera,
  773. TremorNoise: tremor_noise,
  774. DisequilibriumSyndrome: disequilibrium_syndrome,
  775. DisequilibriumSyndromeOption: disequilibrium_syndrome_option,
  776. ArterialTube: arterial_tube,
  777. IntravenousTube: intravenous_tube,
  778. Dialyzer: dialyzer,
  779. InAdvanceReasonOther: in_advance_reason_other,
  780. IsEat: is_eat,
  781. CvcA: cvc_a,
  782. CvcV: cvc_v,
  783. Channel: channels,
  784. ReturnBlood: return_blood,
  785. RehydrationVolume: rehydration_volume,
  786. DialysisDuring: dialysis_during,
  787. StrokeVolume: stroke_volume,
  788. BloodFlow: blood_flow,
  789. SealingFluidDispose: sealing_fluid_dispose,
  790. SealingFluidSpecial: sealing_fluid_special,
  791. DosageOfAnticoagulants: dosage_of_anticoagulants,
  792. SupineDiastolicBloodPressure: supine_diastolic_blood_pressure,
  793. SupineSystolicBloodPressure: supine_systolic_blood_pressure,
  794. SettingPressure: setting_pressure,
  795. DiastolicPressure: diastolic_pressure,
  796. }
  797. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  798. _, assessmentAfter := service.FindAssessmentAfterDislysisByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  799. if assessmentAfter.ID == 0 { //新增
  800. if appRole.UserType == 2 || appRole.UserType == 1 {
  801. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  802. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  803. } else {
  804. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  805. }
  806. err := service.AddSigleAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  807. if err == nil {
  808. c.ServeSuccessJSON(map[string]interface{}{
  809. "assessmentAfterDislysis": assessmentAfterDislysis,
  810. })
  811. }
  812. } else { //修改
  813. if appRole.UserType == 2 || appRole.UserType == 1 {
  814. assessmentAfterDislysis.AssessmentDoctor = adminUserInfo.AdminUser.Id
  815. assessmentAfterDislysis.AssessmentTime = time.Now().Unix()
  816. } else {
  817. assessmentAfterDislysis.Modifier = adminUserInfo.AdminUser.Id
  818. if assessmentAfterDislysis.Creater == 0 {
  819. assessmentAfterDislysis.Creater = adminUserInfo.AdminUser.Id
  820. }
  821. }
  822. assessmentAfterDislysis.CreatedTime = assessmentAfter.CreatedTime
  823. assessmentAfterDislysis.ID = assessmentAfter.ID
  824. err := service.UpdateAssessmentAfterDislysisRecord(&assessmentAfterDislysis)
  825. if err == nil {
  826. c.ServeSuccessJSON(map[string]interface{}{
  827. "assessmentAfterDislysis": assessmentAfterDislysis,
  828. })
  829. }
  830. }
  831. }
  832. func (c *DialysisAPIController) PostDialysisPrescription() {
  833. id, _ := c.GetInt64("patient", 0)
  834. recordDateStr := c.GetString("record_date")
  835. if id <= 0 {
  836. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  837. return
  838. }
  839. adminUserInfo := c.GetMobileAdminUserInfo()
  840. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  841. if patient.ID == 0 {
  842. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  843. return
  844. }
  845. if len(recordDateStr) == 0 {
  846. recordDateStr = time.Now().Format("2006-01-02")
  847. }
  848. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  849. if parseDateErr != nil {
  850. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  851. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  852. return
  853. }
  854. mode_id, _ := c.GetInt64("mode_id", 0)
  855. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  856. dialyzer, _ := c.GetInt64("dialyzer", 0)
  857. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  858. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  859. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  860. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  861. replacement_total, _ := c.GetFloat("replacement_total", 0)
  862. replacement_way, _ := c.GetInt64("replacement_way", 0)
  863. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  864. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  865. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  866. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  867. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  868. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  869. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  870. kalium, _ := c.GetFloat("kalium", 0)
  871. sodium, _ := c.GetFloat("sodium", 0)
  872. calcium, _ := c.GetFloat("calcium", 0)
  873. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  874. glucose, _ := c.GetFloat("glucose", 0)
  875. // prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  876. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  877. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  878. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  879. conductivity, _ := c.GetFloat("conductivity", 0)
  880. remark := c.GetString("remark")
  881. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  882. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  883. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  884. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  885. body_fluid, _ := c.GetInt64("body_fluid", 0)
  886. special_medicine, _ := c.GetInt64("special_medicine", 0)
  887. special_medicine_other := c.GetString("special_medicine_other")
  888. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  889. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  890. blood_access, _ := c.GetInt64("blood_access", 0)
  891. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  892. body_fluid_other := c.GetString("body_fluid_other")
  893. niprocart, _ := c.GetInt64("niprocart", 0)
  894. jms, _ := c.GetInt64("jms", 0)
  895. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  896. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  897. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  898. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  899. filtryzer, _ := c.GetInt64("filtryzer", 0)
  900. target_ktv, _ := c.GetFloat("target_ktv", 0)
  901. dialyzers, _ := c.GetInt64("dialyzers", 0)
  902. injector, _ := c.GetInt64("injector", 0)
  903. bloodlines, _ := c.GetInt64("bloodlines", 0)
  904. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  905. safe_package, _ := c.GetInt64("package", 0)
  906. a_liquid, _ := c.GetInt64("a_liquid", 0)
  907. pre_impulse, parseDateErr := c.GetFloat("pre_impulse", 0)
  908. fmt.Println("预冲量====", pre_impulse)
  909. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  910. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  911. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  912. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  913. //
  914. //if template.TemplateId == 2 || template.TemplateId == 6 {
  915. // if appRole.UserType == 3 {
  916. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  917. // if getPermissionErr != nil {
  918. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  919. // return
  920. // } else if headNursePermission == nil {
  921. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  922. // return
  923. // }
  924. // }
  925. //}
  926. //TODO 需要根据角色去判断
  927. prescription := models.DialysisPrescription{
  928. UserOrgId: adminUserInfo.Org.Id,
  929. PatientId: id,
  930. RecordDate: recordDate.Unix(),
  931. ModeId: mode_id,
  932. DialysisDuration: dialysis_duration,
  933. Dialyzer: dialyzer,
  934. PerfusionApparatus: perfusion_apparatus,
  935. BloodFlowVolume: blood_flow_volume,
  936. DewaterAmount: dewater_amount,
  937. DisplaceLiqui: displace_liqui,
  938. ReplacementWay: replacement_way,
  939. Anticoagulant: anticoagulant,
  940. AnticoagulantShouji: anticoagulant_shouji,
  941. AnticoagulantWeichi: anticoagulant_weichi,
  942. AnticoagulantZongliang: anticoagulant_zongliang,
  943. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  944. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  945. Kalium: kalium,
  946. Sodium: sodium,
  947. Calcium: calcium,
  948. Bicarbonate: bicarbonate,
  949. Glucose: glucose,
  950. // DryWeight: dry_weight,
  951. DialysateFlow: dialysate_flow,
  952. DialysateTemperature: dialysate_temperature,
  953. // PrescriptionDoctor: prescription_doctor,
  954. ReplacementTotal: replacement_total,
  955. Conductivity: conductivity,
  956. Remark: remark,
  957. Status: 1,
  958. CreatedTime: time.Now().Unix(),
  959. UpdatedTime: time.Now().Unix(),
  960. DialysisDurationMinute: dialysisDurationMinute,
  961. DialysisDurationHour: dialysisDurationHour,
  962. TargetUltrafiltration: targetUltrafiltration,
  963. DialysateFormulation: dialysateFormulation,
  964. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  965. BodyFluid: body_fluid,
  966. SpecialMedicine: special_medicine,
  967. SpecialMedicineOther: special_medicine_other,
  968. DisplaceLiquiPart: displace_liqui_part,
  969. DisplaceLiquiValue: displace_liqui_value,
  970. BloodAccess: blood_access,
  971. Ultrafiltration: ultrafiltration,
  972. BodyFluidOther: body_fluid_other,
  973. Niprocart: niprocart,
  974. Jms: jms,
  975. FistulaNeedleSet: fistula_needle_set,
  976. FistulaNeedleSet16: fistula_needle_set_16,
  977. Hemoperfusion: hemoperfusion,
  978. DialyserSterilised: dialyser_sterilised,
  979. Filtryzer: filtryzer,
  980. Dialyzers: dialyzers,
  981. Injector: injector,
  982. Bloodlines: bloodlines,
  983. TubingHemodialysis: tubing_hemodialysis,
  984. Package: safe_package,
  985. ALiquid: a_liquid,
  986. TargetKtv: target_ktv,
  987. PreImpulse: pre_impulse,
  988. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  989. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  990. }
  991. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  992. if dialysisPrescription.ID == 0 { //新增
  993. //if mode_id > 0 {
  994. // //service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  995. //}
  996. if appRole.UserType == 2 || appRole.UserType == 1 {
  997. prescription.PrescriptionDoctor = adminUserInfo.AdminUser.Id
  998. }
  999. prescription.Creater = adminUserInfo.AdminUser.Id
  1000. err := service.AddSigleRecord(&prescription)
  1001. if err == nil {
  1002. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1003. if updateErr != nil {
  1004. utils.ErrorLog("%v", updateErr)
  1005. }
  1006. c.ServeSuccessJSON(map[string]interface{}{
  1007. "prescription": prescription,
  1008. })
  1009. }
  1010. } else { //修改
  1011. //if mode_id > 0 {
  1012. // service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1013. //}
  1014. //if template.TemplateId == 1 {
  1015. // if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater != 0 {
  1016. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1017. // if getPermissionErr != nil {
  1018. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1019. // return
  1020. // } else if headNursePermission == nil {
  1021. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePrescriptionPermissionDeniedModify)
  1022. // return
  1023. // }
  1024. // }
  1025. //}
  1026. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1027. prescription.Modifier = adminUserInfo.AdminUser.Id
  1028. if appRole.UserType == 2 || appRole.UserType == 1 {
  1029. prescription_doctor := adminUserInfo.AdminUser.Id
  1030. prescription.PrescriptionDoctor = prescription_doctor
  1031. } else {
  1032. prescription.PrescriptionDoctor = dialysisPrescription.PrescriptionDoctor
  1033. }
  1034. if dialysisPrescription.Creater == 0 { //体重称
  1035. prescription.Creater = adminUserInfo.AdminUser.Id
  1036. } else {
  1037. prescription.Creater = dialysisPrescription.Creater
  1038. }
  1039. prescription.ID = dialysisPrescription.ID
  1040. err := service.UpDateDialysisPrescription(&prescription)
  1041. if err == nil {
  1042. updateErr := service.UpdateScheduleModeId(patient.ID, adminUserInfo.Org.Id, recordDate.Unix(), mode_id)
  1043. if updateErr != nil {
  1044. utils.ErrorLog("%v", updateErr)
  1045. }
  1046. c.ServeSuccessJSON(map[string]interface{}{
  1047. "prescription": prescription,
  1048. })
  1049. }
  1050. }
  1051. }
  1052. func (c *DialysisAPIController) Finish() {
  1053. id, _ := c.GetInt64("patient", 0)
  1054. recordDateStr := c.GetString("record_date")
  1055. nurseID, _ := c.GetInt64("nurse")
  1056. end_time := c.GetString("end_time")
  1057. if id <= 0 || nurseID <= 0 {
  1058. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1059. return
  1060. }
  1061. adminUserInfo := c.GetMobileAdminUserInfo()
  1062. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1063. if patient.ID == 0 {
  1064. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1065. return
  1066. }
  1067. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1068. if getNurseErr != nil {
  1069. c.ErrorLog("获取护士失败:%v", getNurseErr)
  1070. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1071. return
  1072. } else if nurse == nil {
  1073. c.ErrorLog("护士不存在")
  1074. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1075. return
  1076. }
  1077. if len(recordDateStr) == 0 {
  1078. recordDateStr = time.Now().Format("2006-01-02")
  1079. }
  1080. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1081. if parseDateErr != nil {
  1082. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1083. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1084. return
  1085. }
  1086. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  1087. if parseEndDateErr != nil {
  1088. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  1089. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1090. return
  1091. }
  1092. //now := time.Now()
  1093. //year, month, day := now.Date()
  1094. //today_time := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
  1095. //todayTimeStamp := today_time.Unix()
  1096. // 获取当天的第一条透析纪录
  1097. fmonitorRecords, getMonitorRecordsErr := service.MobileGetMonitorRecordFirst(adminUserInfo.Org.Id, id, recordDate.Unix())
  1098. if getMonitorRecordsErr != nil {
  1099. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1100. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1101. return
  1102. }
  1103. // 获取当前的最后一条透析纪录
  1104. endmonitorRecords, getMonitorRecordsErr := service.MobileGetLastMonitorRecord(adminUserInfo.Org.Id, id, recordDate.Unix())
  1105. if getMonitorRecordsErr != nil {
  1106. c.ErrorLog("获取透析监测记录失败:%v", getMonitorRecordsErr)
  1107. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1108. return
  1109. }
  1110. fmt.Println(endmonitorRecords.UltrafiltrationVolume)
  1111. assessmentAfterDislysis, getAADErr := service.MobileGetAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1112. if getAADErr != nil {
  1113. c.ErrorLog("获取透后评估失败:%v", getAADErr)
  1114. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1115. return
  1116. }
  1117. lastAssessmentAfterDislysis, _ := service.MobileGetLastTimeAssessmentAfterDislysis(adminUserInfo.Org.Id, id, recordDate.Unix())
  1118. _, dialysisOrder := service.FindDialysisRecordById(adminUserInfo.Org.Id, id, recordDate.Unix())
  1119. var tempassessmentAfterDislysis models.AssessmentAfterDislysis
  1120. if assessmentAfterDislysis != nil {
  1121. tempassessmentAfterDislysis = *assessmentAfterDislysis
  1122. tempassessmentAfterDislysis.UpdatedTime = time.Now().Unix()
  1123. } else {
  1124. tempassessmentAfterDislysis.CreatedTime = time.Now().Unix()
  1125. tempassessmentAfterDislysis.AssessmentDate = recordDate.Unix()
  1126. tempassessmentAfterDislysis.Status = 1
  1127. tempassessmentAfterDislysis.PatientId = id
  1128. tempassessmentAfterDislysis.UserOrgId = adminUserInfo.Org.Id
  1129. }
  1130. if dialysisOrder.Stage == 1 {
  1131. temp_time := (float64(endDate.Unix()) - float64(dialysisOrder.StartTime)) / 3600
  1132. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  1133. fmt.Println(value)
  1134. a, b := math.Modf(value)
  1135. c, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  1136. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  1137. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", c*60), 10, 64)
  1138. fmt.Println(hour)
  1139. fmt.Println(minute)
  1140. tempassessmentAfterDislysis.ActualTreatmentHour = hour
  1141. tempassessmentAfterDislysis.ActualTreatmentMinute = minute
  1142. }
  1143. if fmonitorRecords.ID > 0 && endmonitorRecords.ID > 0 {
  1144. //var num1 int64
  1145. //num1 = endmonitorRecords.OperateTime - fmonitorRecords.OperateTime
  1146. //fmt.Println(num1)
  1147. //sub := float64(num1 / 3600)
  1148. //fmt.Println(sub)
  1149. //tempassessmentAfterDislysis.ActualTreatmentHour = int64(math.Floor(sub))
  1150. //sub2 := float64(((endmonitorRecords.OperateTime - fmonitorRecords.OperateTime) % 3600) / 60)
  1151. //tempassessmentAfterDislysis.ActualTreatmentMinute = int64(math.Floor(sub2))
  1152. tempassessmentAfterDislysis.Temperature = endmonitorRecords.Temperature
  1153. tempassessmentAfterDislysis.PulseFrequency = endmonitorRecords.PulseFrequency
  1154. tempassessmentAfterDislysis.BreathingRate = endmonitorRecords.BreathingRate
  1155. tempassessmentAfterDislysis.SystolicBloodPressure = endmonitorRecords.SystolicBloodPressure
  1156. tempassessmentAfterDislysis.DiastolicBloodPressure = endmonitorRecords.DiastolicBloodPressure
  1157. tempassessmentAfterDislysis.ActualUltrafiltration = endmonitorRecords.UltrafiltrationVolume
  1158. tempassessmentAfterDislysis.ActualDisplacement = endmonitorRecords.DisplacementQuantity
  1159. }
  1160. if lastAssessmentAfterDislysis != nil {
  1161. tempassessmentAfterDislysis.BloodPressureType = lastAssessmentAfterDislysis.BloodPressureType
  1162. tempassessmentAfterDislysis.WeighingWay = lastAssessmentAfterDislysis.WeighingWay
  1163. tempassessmentAfterDislysis.Cruor = lastAssessmentAfterDislysis.Cruor
  1164. tempassessmentAfterDislysis.SymptomAfterDialysis = lastAssessmentAfterDislysis.SymptomAfterDialysis
  1165. tempassessmentAfterDislysis.InternalFistula = lastAssessmentAfterDislysis.InternalFistula
  1166. tempassessmentAfterDislysis.Catheter = lastAssessmentAfterDislysis.Catheter
  1167. tempassessmentAfterDislysis.Complication = lastAssessmentAfterDislysis.Complication
  1168. tempassessmentAfterDislysis.DialysisIntakes = lastAssessmentAfterDislysis.DialysisIntakes
  1169. tempassessmentAfterDislysis.DialysisIntakesFeed = lastAssessmentAfterDislysis.DialysisIntakesFeed
  1170. tempassessmentAfterDislysis.DialysisIntakesTransfusion = lastAssessmentAfterDislysis.DialysisIntakesTransfusion
  1171. tempassessmentAfterDislysis.DialysisIntakesBloodTransfusion = lastAssessmentAfterDislysis.DialysisIntakesBloodTransfusion
  1172. tempassessmentAfterDislysis.DialysisIntakesWashpipe = lastAssessmentAfterDislysis.DialysisIntakesWashpipe
  1173. tempassessmentAfterDislysis.BloodAccessPartId = lastAssessmentAfterDislysis.BloodAccessPartId
  1174. tempassessmentAfterDislysis.BloodAccessPartOperaId = lastAssessmentAfterDislysis.BloodAccessPartOperaId
  1175. tempassessmentAfterDislysis.PuncturePointOozingBlood = lastAssessmentAfterDislysis.PuncturePointOozingBlood
  1176. tempassessmentAfterDislysis.PuncturePointHaematoma = lastAssessmentAfterDislysis.PuncturePointHaematoma
  1177. tempassessmentAfterDislysis.InternalFistulaTremorAc = lastAssessmentAfterDislysis.InternalFistulaTremorAc
  1178. tempassessmentAfterDislysis.PatientGose = lastAssessmentAfterDislysis.PatientGose
  1179. tempassessmentAfterDislysis.InpatientDepartment = lastAssessmentAfterDislysis.InpatientDepartment
  1180. tempassessmentAfterDislysis.ObservationContent = lastAssessmentAfterDislysis.ObservationContent
  1181. tempassessmentAfterDislysis.ObservationContentOther = lastAssessmentAfterDislysis.ObservationContentOther
  1182. tempassessmentAfterDislysis.DryWeight = lastAssessmentAfterDislysis.DryWeight
  1183. tempassessmentAfterDislysis.DialysisProcess = lastAssessmentAfterDislysis.DialysisProcess
  1184. tempassessmentAfterDislysis.InAdvanceMinute = lastAssessmentAfterDislysis.InAdvanceMinute
  1185. tempassessmentAfterDislysis.InAdvanceReason = lastAssessmentAfterDislysis.InAdvanceReason
  1186. tempassessmentAfterDislysis.HemostasisMinute = lastAssessmentAfterDislysis.HemostasisMinute
  1187. tempassessmentAfterDislysis.HemostasisOpera = lastAssessmentAfterDislysis.HemostasisOpera
  1188. tempassessmentAfterDislysis.TremorNoise = lastAssessmentAfterDislysis.TremorNoise
  1189. tempassessmentAfterDislysis.DisequilibriumSyndrome = lastAssessmentAfterDislysis.DisequilibriumSyndrome
  1190. tempassessmentAfterDislysis.DisequilibriumSyndromeOption = lastAssessmentAfterDislysis.DisequilibriumSyndromeOption
  1191. tempassessmentAfterDislysis.ArterialTube = lastAssessmentAfterDislysis.ArterialTube
  1192. tempassessmentAfterDislysis.IntravenousTube = lastAssessmentAfterDislysis.IntravenousTube
  1193. tempassessmentAfterDislysis.Dialyzer = lastAssessmentAfterDislysis.Dialyzer
  1194. tempassessmentAfterDislysis.InAdvanceReasonOther = lastAssessmentAfterDislysis.InAdvanceReasonOther
  1195. tempassessmentAfterDislysis.IsEat = lastAssessmentAfterDislysis.IsEat
  1196. tempassessmentAfterDislysis.DialysisIntakesUnit = lastAssessmentAfterDislysis.DialysisIntakesUnit
  1197. tempassessmentAfterDislysis.CvcA = lastAssessmentAfterDislysis.CvcA
  1198. tempassessmentAfterDislysis.CvcV = lastAssessmentAfterDislysis.CvcV
  1199. tempassessmentAfterDislysis.Channel = lastAssessmentAfterDislysis.Channel
  1200. tempassessmentAfterDislysis.ReturnBlood = lastAssessmentAfterDislysis.ReturnBlood
  1201. tempassessmentAfterDislysis.RehydrationVolume = lastAssessmentAfterDislysis.RehydrationVolume
  1202. tempassessmentAfterDislysis.DialysisDuring = lastAssessmentAfterDislysis.DialysisDuring
  1203. tempassessmentAfterDislysis.StrokeVolume = lastAssessmentAfterDislysis.StrokeVolume
  1204. tempassessmentAfterDislysis.BloodFlow = lastAssessmentAfterDislysis.BloodFlow
  1205. tempassessmentAfterDislysis.SealingFluidDispose = lastAssessmentAfterDislysis.SealingFluidDispose
  1206. tempassessmentAfterDislysis.SealingFluidSpecial = lastAssessmentAfterDislysis.SealingFluidSpecial
  1207. }
  1208. err := service.UpdateAssessmentAfterDislysisRecord(&tempassessmentAfterDislysis)
  1209. if err != nil {
  1210. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1211. return
  1212. }
  1213. if dialysisOrder == nil {
  1214. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoStart)
  1215. return
  1216. }
  1217. if dialysisOrder.Stage == 2 {
  1218. c.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderNoEND)
  1219. return
  1220. }
  1221. if dialysisOrder.Stage == 1 {
  1222. err := service.ModifyDialysisRecord(dialysisOrder.ID, nurseID, endDate.Unix(), adminUserInfo.AdminUser.Id)
  1223. //结束时候透析次数加1
  1224. service.UpdateSolutionByPatientId(id)
  1225. dialysisOrder.Stage = 2
  1226. dialysisOrder.FinishNurse = nurseID
  1227. dialysisOrder.FinishCreator = adminUserInfo.AdminUser.Id
  1228. dialysisOrder.FinishModifier = adminUserInfo.AdminUser.Id
  1229. dialysisOrder.EndTime = endDate.Unix()
  1230. if err == nil {
  1231. c.ServeSuccessJSON(map[string]interface{}{
  1232. "dialysisOrder": dialysisOrder,
  1233. "assessmentAfterDislysis": tempassessmentAfterDislysis,
  1234. })
  1235. } else {
  1236. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  1237. }
  1238. }
  1239. }
  1240. func (c *DialysisAPIController) GetAllZone() {
  1241. adminUserInfo := c.GetMobileAdminUserInfo()
  1242. err, zone := service.GetAllDeviceZone(adminUserInfo.Org.Id)
  1243. if err == nil {
  1244. c.ServeSuccessJSON(map[string]interface{}{
  1245. "zone": zone,
  1246. })
  1247. }
  1248. }
  1249. func (c *DialysisAPIController) GetSchedualPatientsList() {
  1250. adminUserInfo := c.GetMobileAdminUserInfo()
  1251. page, _ := c.GetInt64("page", 1)
  1252. limit, _ := c.GetInt64("limit", 10)
  1253. schedulType, _ := c.GetInt64("schedul_type", 0)
  1254. startTime, _ := c.GetInt64("schedul_time", 0)
  1255. partitionType, _ := c.GetInt64("partition_type", 0)
  1256. keywords := c.GetString("keywords")
  1257. dialysisSchedule, err := service.GetSchedualPatientList(adminUserInfo.Org.Id, startTime/1000, schedulType, partitionType, keywords, page, limit)
  1258. if err == nil {
  1259. c.ServeSuccessJSON(map[string]interface{}{
  1260. "schedule": dialysisSchedule,
  1261. })
  1262. }
  1263. return
  1264. }
  1265. // /m/api/dialysis/start [post]
  1266. // @param patient_id:int
  1267. // @param record_date:string 排班时间 (yyyy-mm-dd)
  1268. // @param nurse:int 上机护士
  1269. // @param bed:int 床位号
  1270. func (this *DialysisAPIController) StartDialysis() {
  1271. patientID, _ := this.GetInt64("patient_id")
  1272. recordDateStr := this.GetString("record_date")
  1273. nurseID, _ := this.GetInt64("nurse")
  1274. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1275. blood_drawing, _ := this.GetInt64("blood_drawing")
  1276. schedual_type, _ := this.GetInt64("schedual_type")
  1277. bedID, _ := this.GetInt64("bed")
  1278. start_time := this.GetString("start_time")
  1279. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1280. if patientID <= 0 || len(recordDateStr) == 0 || nurseID <= 0 || bedID <= 0 {
  1281. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1282. return
  1283. }
  1284. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1285. if parseStartDateErr != nil {
  1286. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1287. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1288. return
  1289. }
  1290. recordDate, parseErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1291. if parseErr != nil {
  1292. this.ErrorLog("时间解析失败:%v", parseErr)
  1293. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1294. return
  1295. }
  1296. adminUserInfo := this.GetMobileAdminUserInfo()
  1297. patient, getPatientErr := service.MobileGetPatientById(adminUserInfo.Org.Id, patientID)
  1298. if getPatientErr != nil {
  1299. this.ErrorLog("获取患者信息失败:%v", getPatientErr)
  1300. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1301. return
  1302. } else if patient == nil {
  1303. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1304. return
  1305. }
  1306. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1307. if getNurseErr != nil {
  1308. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1309. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1310. return
  1311. } else if nurse == nil {
  1312. this.ErrorLog("护士不存在")
  1313. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1314. return
  1315. }
  1316. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1317. if getNurseErr != nil {
  1318. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1319. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1320. return
  1321. } else if nurse == nil {
  1322. this.ErrorLog("护士不存在")
  1323. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1324. return
  1325. }
  1326. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1327. if getDeviceNumberErr != nil {
  1328. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1329. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1330. return
  1331. } else if deviceNumber == nil {
  1332. this.ErrorLog("床位号不存在")
  1333. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1334. return
  1335. }
  1336. dialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1337. if getRecordErr != nil {
  1338. this.ErrorLog("获取透析记录失败:%v", getRecordErr)
  1339. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1340. return
  1341. } else if dialysisRecord != nil {
  1342. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatStart)
  1343. return
  1344. }
  1345. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1346. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1347. timeLayout := "2006-01-02 15:04:05"
  1348. loc, _ := time.LoadLocation("Local")
  1349. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1350. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1351. schedulestartTime := theStartTime.Unix()
  1352. scheduleendTime := theEndTime.Unix()
  1353. template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1354. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1355. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1356. //查询该床位是否有人用了
  1357. order, order_err := service.GetDialysisOrderByBedId(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1358. if err == gorm.ErrRecordNotFound { //空床位
  1359. // 修改了床位逻辑
  1360. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1361. if daySchedule.ID > 0 {
  1362. daySchedule.PartitionId = deviceNumber.ZoneID
  1363. daySchedule.BedId = bedID
  1364. daySchedule.ScheduleType = schedual_type
  1365. daySchedule.UpdatedTime = time.Now().Unix()
  1366. err := service.UpdateSchedule(&daySchedule)
  1367. if err != nil {
  1368. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1369. return
  1370. }
  1371. }
  1372. } else if err == nil {
  1373. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1374. if order_err == nil {
  1375. if order.ID > 0 { //该机位被其他人占用了
  1376. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1377. return
  1378. } else {
  1379. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1380. if daySchedule.ID > 0 {
  1381. daySchedule.PartitionId = deviceNumber.ZoneID
  1382. daySchedule.BedId = bedID
  1383. daySchedule.ScheduleType = schedual_type
  1384. daySchedule.UpdatedTime = time.Now().Unix()
  1385. err := service.UpdateSchedule(&daySchedule)
  1386. if err != nil {
  1387. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1388. return
  1389. }
  1390. }
  1391. }
  1392. } else if order_err == gorm.ErrRecordNotFound { //该床位没被占用
  1393. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, patientID)
  1394. if daySchedule.ID > 0 {
  1395. daySchedule.PartitionId = deviceNumber.ZoneID
  1396. daySchedule.BedId = bedID
  1397. daySchedule.ScheduleType = schedual_type
  1398. daySchedule.UpdatedTime = time.Now().Unix()
  1399. err := service.UpdateSchedule(&daySchedule)
  1400. if err != nil {
  1401. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1402. return
  1403. }
  1404. }
  1405. }
  1406. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1407. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1408. return
  1409. }
  1410. } else if err != nil {
  1411. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1412. return
  1413. }
  1414. dialysisRecord = &models.DialysisOrder{
  1415. DialysisDate: recordDate.Unix(),
  1416. UserOrgId: adminUserInfo.Org.Id,
  1417. PatientId: patientID,
  1418. Stage: 1,
  1419. BedID: bedID,
  1420. StartNurse: nurseID,
  1421. Status: 1,
  1422. StartTime: startDate.Unix(),
  1423. CreatedTime: time.Now().Unix(),
  1424. UpdatedTime: time.Now().Unix(),
  1425. PunctureNurse: puncture_nurse,
  1426. Creator: adminUserInfo.AdminUser.Id,
  1427. Modifier: adminUserInfo.AdminUser.Id,
  1428. SchedualType: schedual_type,
  1429. WashpipeNurse: washpipe_nurse,
  1430. }
  1431. createErr := service.MobileCreateDialysisOrder(adminUserInfo.Org.Id, patientID, dialysisRecord)
  1432. newdialysisRecord, getRecordErr := service.MobileGetDialysisRecord(adminUserInfo.Org.Id, patientID, recordDate.Unix())
  1433. var tempdispose string
  1434. // 只针对中能建
  1435. if blood_drawing > 0 && adminUserInfo.Org.Id == 9538 {
  1436. tempdispose = "引血" + strconv.FormatInt(blood_drawing, 10) + "ml/min"
  1437. }
  1438. var ultrafiltration_rate float64
  1439. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, schedulestartTime, adminUserInfo.Org.Id)
  1440. if prescription.ID > 0 {
  1441. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1442. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1443. if template.TemplateId == 6 { //adminUserInfo.Org.Id == 9538
  1444. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1445. }
  1446. if template.TemplateId == 20 || template.TemplateId == 22 { //adminUserInfo.Org.Id == 9538
  1447. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1448. }
  1449. // 只针对方济医院
  1450. if template.TemplateId == 1 && adminUserInfo.Org.Id != 9849 {
  1451. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1452. ultrafiltration_rate = value
  1453. }
  1454. }
  1455. }
  1456. record := models.MonitoringRecord{
  1457. UserOrgId: adminUserInfo.Org.Id,
  1458. PatientId: patientID,
  1459. DialysisOrderId: dialysisRecord.ID,
  1460. MonitoringDate: schedulestartTime,
  1461. OperateTime: startDate.Unix(),
  1462. // MonitoringTime: recordTime,
  1463. MonitoringNurse: nurseID,
  1464. Dispose: tempdispose,
  1465. UltrafiltrationRate: ultrafiltration_rate,
  1466. UltrafiltrationVolume: 0,
  1467. Status: 1,
  1468. CreatedTime: time.Now().Unix(),
  1469. UpdatedTime: time.Now().Unix(),
  1470. }
  1471. // 如果当天有插入数据,则不再往透析纪录里插入数据
  1472. if newdialysisRecord.ID > 0 {
  1473. err := service.CreateMonitor(&record)
  1474. if err != nil {
  1475. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeMonitorCreate)
  1476. return
  1477. }
  1478. }
  1479. if createErr != nil {
  1480. this.ErrorLog("上机失败:%v", createErr)
  1481. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1482. return
  1483. }
  1484. this.ServeSuccessJSON(map[string]interface{}{
  1485. "dialysis_order": newdialysisRecord,
  1486. "monitor": record,
  1487. })
  1488. }
  1489. func (c *DialysisAPIController) PostSolution() {
  1490. id, _ := c.GetInt64("patient", 0)
  1491. recordDateStr := c.GetString("record_date")
  1492. if id <= 0 {
  1493. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1494. return
  1495. }
  1496. adminUserInfo := c.GetMobileAdminUserInfo()
  1497. patient, _ := service.FindPatientById(adminUserInfo.Org.Id, id)
  1498. if patient.ID == 0 {
  1499. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodePatientNoExist)
  1500. return
  1501. }
  1502. if len(recordDateStr) == 0 {
  1503. recordDateStr = time.Now().Format("2006-01-02")
  1504. }
  1505. recordDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1506. if parseDateErr != nil {
  1507. c.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1508. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1509. return
  1510. }
  1511. mode_id, _ := c.GetInt64("mode_id", 0)
  1512. dialysis_duration, _ := c.GetFloat("dialysis_duration", 0)
  1513. dialyzer, _ := c.GetInt64("dialyzer", 0)
  1514. perfusion_apparatus, _ := c.GetInt64("perfusion_apparatus", 0)
  1515. blood_flow_volume, _ := c.GetFloat("blood_flow_volume", 0)
  1516. dewater_amount, _ := c.GetFloat("dewater_amount", 0)
  1517. displace_liqui, _ := c.GetFloat("displace_liqui", 0)
  1518. replacement_way, _ := c.GetInt64("replacement_way", 0)
  1519. anticoagulant, _ := c.GetInt64("anticoagulant", 0)
  1520. anticoagulant_shouji, _ := c.GetFloat("anticoagulant_shouji", 0)
  1521. anticoagulant_weichi, _ := c.GetFloat("anticoagulant_weichi", 0)
  1522. anticoagulant_zongliang, _ := c.GetFloat("anticoagulant_zongliang", 0)
  1523. anticoagulant_gaimingcheng := c.GetString("anticoagulant_gaimingcheng")
  1524. anticoagulant_gaijiliang := c.GetString("anticoagulant_gaijiliang")
  1525. kalium, _ := c.GetFloat("kalium", 0)
  1526. sodium, _ := c.GetFloat("sodium", 0)
  1527. calcium, _ := c.GetFloat("calcium", 0)
  1528. bicarbonate, _ := c.GetFloat("bicarbonate", 0)
  1529. prescription_doctor, _ := c.GetInt64("prescription_doctor", 0)
  1530. dialyzerPerfusionApparatus := c.GetString("dialyzer_perfusion_apparatus")
  1531. glucose, _ := c.GetFloat("glucose", 0)
  1532. // dry_weight, _ := c.GetFloat("dry_weight", 0)
  1533. dialysate_flow, _ := c.GetFloat("dialysate_flow", 0)
  1534. dialysate_temperature, _ := c.GetFloat("dialysate_temperature", 0)
  1535. conductivity, _ := c.GetFloat("conductivity", 0)
  1536. remark := c.GetString("remark")
  1537. dialysisDurationHour, _ := c.GetInt64("dialysis_duration_hour", 0)
  1538. dialysisDurationMinute, _ := c.GetInt64("dialysis_duration_minute", 0)
  1539. targetUltrafiltration, _ := c.GetFloat("target_ultrafiltration", 0)
  1540. dialysateFormulation, _ := c.GetInt64("dialysate_formulation", 0)
  1541. body_fluid, _ := c.GetInt64("body_fluid", 0)
  1542. special_medicine, _ := c.GetInt64("special_medicine", 0)
  1543. special_medicine_other := c.GetString("special_medicine_other")
  1544. displace_liqui_part, _ := c.GetInt64("displace_liqui_part", 0)
  1545. displace_liqui_value, _ := c.GetFloat("displace_liqui_value", 0)
  1546. blood_access, _ := c.GetInt64("blood_access", 0)
  1547. ultrafiltration, _ := c.GetFloat("ultrafiltration", 0)
  1548. body_fluid_other := c.GetString("body_fluid_other")
  1549. replacement_total, _ := c.GetFloat("replacement_total", 0)
  1550. niprocart, _ := c.GetInt64("niprocart", 0)
  1551. jms, _ := c.GetInt64("jms", 0)
  1552. fistula_needle_set, _ := c.GetInt64("fistula_needle_set", 0)
  1553. fistula_needle_set_16, _ := c.GetInt64("fistula_needle_set_16", 0)
  1554. hemoperfusion, _ := c.GetInt64("hemoperfusion", 0)
  1555. dialyser_sterilised, _ := c.GetInt64("dialyser_sterilised", 0)
  1556. filtryzer, _ := c.GetInt64("filtryzer", 0)
  1557. target_ktv, _ := c.GetFloat("target_ktv", 0)
  1558. dialyzers, _ := c.GetInt64("dialyzers", 0)
  1559. injector, _ := c.GetInt64("injector", 0)
  1560. bloodlines, _ := c.GetInt64("bloodlines", 0)
  1561. tubing_hemodialysis, _ := c.GetInt64("tubing_hemodialysis", 0)
  1562. safe_package, _ := c.GetInt64("package", 0)
  1563. a_liquid, _ := c.GetInt64("a_liquid", 0)
  1564. anticoagulant_stop_time_hour, _ := c.GetInt64("anticoagulant_stop_time_hour", 0)
  1565. anticoagulant_stop_time_min, _ := c.GetInt64("anticoagulant_stop_time_min", 0)
  1566. if mode_id > 0 {
  1567. service.ModifyScheduleMode(mode_id, patient.ID, recordDate.Unix(), adminUserInfo.Org.Id)
  1568. }
  1569. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1570. //
  1571. //if template.TemplateId == 2 || template.TemplateId == 6 {
  1572. // if appRole.UserType == 3 {
  1573. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1574. // if getPermissionErr != nil {
  1575. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1576. // return
  1577. // } else if headNursePermission == nil {
  1578. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1579. // return
  1580. // }
  1581. // }
  1582. //}
  1583. prescription := models.DialysisPrescription{
  1584. UserOrgId: adminUserInfo.Org.Id,
  1585. PatientId: id,
  1586. RecordDate: recordDate.Unix(),
  1587. ModeId: mode_id,
  1588. DialysisDuration: dialysis_duration,
  1589. Dialyzer: dialyzer,
  1590. PerfusionApparatus: perfusion_apparatus,
  1591. BloodFlowVolume: blood_flow_volume,
  1592. DewaterAmount: dewater_amount,
  1593. DisplaceLiqui: displace_liqui,
  1594. ReplacementWay: replacement_way,
  1595. Anticoagulant: anticoagulant,
  1596. AnticoagulantShouji: anticoagulant_shouji,
  1597. AnticoagulantWeichi: anticoagulant_weichi,
  1598. AnticoagulantZongliang: anticoagulant_zongliang,
  1599. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1600. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1601. Kalium: kalium,
  1602. Sodium: sodium,
  1603. Calcium: calcium,
  1604. Bicarbonate: bicarbonate,
  1605. Glucose: glucose,
  1606. // DryWeight: dry_weight,
  1607. DialysateFlow: dialysate_flow,
  1608. DialysateTemperature: dialysate_temperature,
  1609. Conductivity: conductivity,
  1610. Remark: remark,
  1611. Status: 1,
  1612. CreatedTime: time.Now().Unix(),
  1613. UpdatedTime: time.Now().Unix(),
  1614. DialysisDurationMinute: dialysisDurationMinute,
  1615. DialysisDurationHour: dialysisDurationHour,
  1616. TargetUltrafiltration: targetUltrafiltration,
  1617. DialysateFormulation: dialysateFormulation,
  1618. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1619. BodyFluid: body_fluid,
  1620. SpecialMedicine: special_medicine,
  1621. SpecialMedicineOther: special_medicine_other,
  1622. DisplaceLiquiPart: displace_liqui_part,
  1623. DisplaceLiquiValue: displace_liqui_value,
  1624. BloodAccess: blood_access,
  1625. Ultrafiltration: ultrafiltration,
  1626. BodyFluidOther: body_fluid_other,
  1627. ReplacementTotal: replacement_total,
  1628. Niprocart: niprocart,
  1629. Jms: jms,
  1630. FistulaNeedleSet: fistula_needle_set,
  1631. FistulaNeedleSet16: fistula_needle_set_16,
  1632. Hemoperfusion: hemoperfusion,
  1633. DialyserSterilised: dialyser_sterilised,
  1634. Filtryzer: filtryzer,
  1635. TargetKtv: target_ktv,
  1636. Dialyzers: dialyzers,
  1637. Injector: injector,
  1638. Bloodlines: bloodlines,
  1639. TubingHemodialysis: tubing_hemodialysis,
  1640. Package: safe_package,
  1641. ALiquid: a_liquid,
  1642. AnticoagulantStopTimeMin: anticoagulant_stop_time_min,
  1643. AnticoagulantStopTimeHour: anticoagulant_stop_time_hour,
  1644. }
  1645. _, dialysisPrescription := service.FindDialysisPrescriptionByReordDate(id, recordDate.Unix(), adminUserInfo.Org.Id)
  1646. appRole, _ := service.FindAdminRoleTypeById(adminUserInfo.Org.Id, adminUserInfo.AdminUser.Id, adminUserInfo.App.Id)
  1647. //
  1648. if appRole.UserType == 2 || appRole.UserType == 1 {
  1649. prescription_doctor = adminUserInfo.AdminUser.Id
  1650. prescription.PrescriptionDoctor = prescription_doctor
  1651. }
  1652. if dialysisPrescription.ID == 0 { //新增
  1653. prescription.Creater = adminUserInfo.AdminUser.Id
  1654. } else { //修改
  1655. if dialysisPrescription.Creater == 0 {
  1656. prescription.Creater = adminUserInfo.AdminUser.Id
  1657. } else {
  1658. prescription.Creater = dialysisPrescription.Creater
  1659. }
  1660. //if/**/
  1661. //template, _ := service.GetOrgInfoTemplate(adminUserInfo.Org.Id)
  1662. //if dialysisPrescription.Creater != adminUserInfo.AdminUser.Id && dialysisPrescription.Creater > 0 {
  1663. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1664. // if getPermissionErr != nil {
  1665. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1666. // return
  1667. // } else if headNursePermission == nil {
  1668. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1669. // return
  1670. // }
  1671. //}
  1672. //prescription.Creater = dialysisPrescription.Creater
  1673. prescription.CreatedTime = dialysisPrescription.CreatedTime
  1674. prescription.Modifier = adminUserInfo.AdminUser.Id
  1675. prescription.ID = dialysisPrescription.ID
  1676. }
  1677. solution := models.DialysisSolution{
  1678. RegistrarsId: adminUserInfo.AdminUser.Id,
  1679. UserOrgId: adminUserInfo.Org.Id,
  1680. Doctor: prescription_doctor,
  1681. PatientId: id,
  1682. ModeId: mode_id,
  1683. DialysisDuration: dialysis_duration,
  1684. PerfusionApparatus: perfusion_apparatus,
  1685. BloodFlowVolume: blood_flow_volume,
  1686. Dewater: dewater_amount,
  1687. DisplaceLiqui: displace_liqui,
  1688. ReplacementWay: replacement_way,
  1689. Anticoagulant: anticoagulant,
  1690. AnticoagulantShouji: anticoagulant_shouji,
  1691. AnticoagulantWeichi: anticoagulant_weichi,
  1692. AnticoagulantZongliang: anticoagulant_zongliang,
  1693. AnticoagulantGaimingcheng: anticoagulant_gaimingcheng,
  1694. AnticoagulantGaijiliang: anticoagulant_gaijiliang,
  1695. Kalium: kalium,
  1696. Sodium: sodium,
  1697. Calcium: calcium,
  1698. Bicarbonate: bicarbonate,
  1699. Glucose: glucose,
  1700. // DryWeight: dry_weight,
  1701. DialysateFlow: dialysate_flow,
  1702. DialysateTemperature: dialysate_temperature,
  1703. Conductivity: conductivity,
  1704. Remark: remark,
  1705. Status: 1,
  1706. CreatedTime: time.Now().Unix(),
  1707. UpdatedTime: time.Now().Unix(),
  1708. DialysisDurationMinute: dialysisDurationMinute,
  1709. DialysisDurationHour: dialysisDurationHour,
  1710. TargetUltrafiltration: targetUltrafiltration,
  1711. DialysateFormulation: dialysateFormulation,
  1712. DialyzerPerfusionApparatus: dialyzerPerfusionApparatus,
  1713. BodyFluid: body_fluid,
  1714. SpecialMedicine: special_medicine,
  1715. SpecialMedicineOther: special_medicine_other,
  1716. DisplaceLiquiPart: displace_liqui_part,
  1717. DisplaceLiquiValue: displace_liqui_value,
  1718. BloodAccess: blood_access,
  1719. Ultrafiltration: ultrafiltration,
  1720. BodyFluidOther: body_fluid_other,
  1721. ReplacementTotal: replacement_total,
  1722. TargetKtv: target_ktv,
  1723. }
  1724. service.SavePrescriptionAndCreateSolution(&solution, &prescription)
  1725. c.ServeSuccessJSON(map[string]interface{}{
  1726. "solution": &solution,
  1727. "prescription": &prescription,
  1728. })
  1729. }
  1730. func (c *DialysisAPIController) GetAcceptsAssessment() {
  1731. patient, _ := c.GetInt64("patient", 0)
  1732. adminUserInfo := c.GetMobileAdminUserInfo()
  1733. _, receiveTreatmentAsses := service.GetLastAcceptsAssessment(patient, adminUserInfo.Org.Id)
  1734. c.ServeSuccessJSON(map[string]interface{}{
  1735. "receiveTreatmentAsses": receiveTreatmentAsses,
  1736. })
  1737. }
  1738. func (this *DialysisAPIController) PostSignInfo() {
  1739. patientID, _ := this.GetInt64("patient_id")
  1740. recordDateStr := this.GetString("date")
  1741. if patientID <= 0 {
  1742. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1743. return
  1744. }
  1745. if len(recordDateStr) == 0 {
  1746. recordDateStr = time.Now().Format("2006-01-02")
  1747. }
  1748. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", recordDateStr)
  1749. if parseDateErr != nil {
  1750. this.ErrorLog("日期(%v)解析错误:%v", recordDateStr, parseDateErr)
  1751. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1752. return
  1753. }
  1754. adminInfo := this.GetMobileAdminUserInfo()
  1755. err := service.UpDateDialysisPrescriptionDoctorSign(patientID, date.Unix(), adminInfo.Org.Id, adminInfo.AdminUser.Id)
  1756. if err != nil {
  1757. this.ErrorLog("签名失败:%v", err)
  1758. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1759. return
  1760. }
  1761. this.ServeSuccessJSON(map[string]interface{}{
  1762. "doctor_id": adminInfo.AdminUser.Id,
  1763. })
  1764. }
  1765. func (this *DialysisAPIController) GetLastMonitorRecord() {
  1766. patientID, _ := this.GetInt64("patient_id")
  1767. adminInfo := this.GetMobileAdminUserInfo()
  1768. record, _ := service.FindLastMonitorRecord(patientID, adminInfo.Org.Id)
  1769. this.ServeSuccessJSON(map[string]interface{}{
  1770. "monitor": record,
  1771. })
  1772. }
  1773. func (this *DialysisAPIController) GetLastMonitorRecordTody() {
  1774. thisTime := time.Now()
  1775. scheduleDateStart := thisTime.Format("2006-01-02") + " 00:00:00"
  1776. timeLayout := "2006-01-02 15:04:05"
  1777. loc, _ := time.LoadLocation("Local")
  1778. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1779. theAssessmentDateTime := theStartTime.Unix()
  1780. patientID, _ := this.GetInt64("patient_id")
  1781. monitorDate, _ := this.GetInt64("monitoring_date", theAssessmentDateTime)
  1782. adminInfo := this.GetMobileAdminUserInfo()
  1783. record, _ := service.FindLastMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  1784. fristrecord, _ := service.FindFirstMonitorRecordToday(patientID, adminInfo.Org.Id, monitorDate)
  1785. template, _ := service.GetOrgInfoTemplate(adminInfo.Org.Id)
  1786. var ultrafiltration_rate float64
  1787. _, prescription := service.FindDialysisPrescriptionByReordDate(patientID, theAssessmentDateTime, adminInfo.Org.Id)
  1788. if prescription.ID > 0 {
  1789. fmt.Println("444444444")
  1790. if prescription.TargetUltrafiltration > 0 && prescription.DialysisDurationHour > 0 {
  1791. fmt.Println("4444444445555")
  1792. totalMin := prescription.DialysisDurationHour*60 + prescription.DialysisDurationMinute
  1793. if template.TemplateId == 6 {
  1794. fmt.Println("12222222")
  1795. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60 * 1000)
  1796. record.UltrafiltrationRate = ultrafiltration_rate
  1797. }
  1798. if template.TemplateId == 20 || template.TemplateId == 22 {
  1799. ultrafiltration_rate = math.Floor(prescription.TargetUltrafiltration / float64(totalMin) * 60)
  1800. record.UltrafiltrationRate = ultrafiltration_rate
  1801. }
  1802. // 只针对方济医院
  1803. if template.TemplateId == 1 && adminInfo.Org.Id != 9849 {
  1804. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", prescription.TargetUltrafiltration/float64(totalMin)*60), 6)
  1805. ultrafiltration_rate = value
  1806. record.UltrafiltrationRate = ultrafiltration_rate
  1807. }
  1808. }
  1809. }
  1810. // record.UltrafiltrationRate = ultrafiltration_rate
  1811. record.UltrafiltrationVolume = 0
  1812. 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
  1813. if ultrafiltration_rate > 0 {
  1814. value, _ := strconv.ParseFloat(fmt.Sprintf("%.3f", float64(record.OperateTime+3600-fristrecord.OperateTime)/3600*ultrafiltration_rate), 6)
  1815. record.UltrafiltrationVolume = value
  1816. }
  1817. }
  1818. if template.TemplateId == 6 || template.TemplateId == 20 || template.TemplateId == 22 { //adminInfo.Org.Id == 9538
  1819. if ultrafiltration_rate > 0 && adminInfo.Org.Id != 9538 {
  1820. ultrafiltration_volume := math.Floor(float64(record.OperateTime+3600-fristrecord.OperateTime) / 3600 * ultrafiltration_rate)
  1821. record.UltrafiltrationVolume = ultrafiltration_volume
  1822. }
  1823. }
  1824. this.ServeSuccessJSON(map[string]interface{}{
  1825. "monitor": record,
  1826. })
  1827. }
  1828. func (this *DialysisAPIController) ModifyStartDialysisOrder() {
  1829. record_id, _ := this.GetInt64("id")
  1830. nurseID, _ := this.GetInt64("nurse")
  1831. puncture_nurse, _ := this.GetInt64("puncture_nurse")
  1832. bedID, _ := this.GetInt64("bed")
  1833. start_time := this.GetString("start_time")
  1834. schedual_type, _ := this.GetInt64("schedual_type")
  1835. washpipe_nurse, _ := this.GetInt64("washpipe_nurse")
  1836. if record_id == 0 {
  1837. this.ErrorLog("id:%v", record_id)
  1838. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1839. return
  1840. }
  1841. startDate, parseStartDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", start_time)
  1842. if parseStartDateErr != nil {
  1843. this.ErrorLog("时间解析失败:%v", parseStartDateErr)
  1844. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1845. return
  1846. }
  1847. adminUserInfo := this.GetMobileAdminUserInfo()
  1848. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1849. if getNurseErr != nil {
  1850. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1851. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1852. return
  1853. } else if nurse == nil {
  1854. this.ErrorLog("护士不存在")
  1855. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1856. return
  1857. }
  1858. nurse, getNurseErr = service.GetAdminUserByUserID(puncture_nurse)
  1859. if getNurseErr != nil {
  1860. this.ErrorLog("获取护士失败:%v", getNurseErr)
  1861. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1862. return
  1863. } else if nurse == nil {
  1864. this.ErrorLog("护士不存在")
  1865. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1866. return
  1867. }
  1868. deviceNumber, getDeviceNumberErr := service.GetDeviceNumberByID(adminUserInfo.Org.Id, bedID)
  1869. if getDeviceNumberErr != nil {
  1870. this.ErrorLog("获取床位号失败:%v", getDeviceNumberErr)
  1871. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1872. return
  1873. } else if deviceNumber == nil {
  1874. this.ErrorLog("床位号不存在")
  1875. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1876. return
  1877. }
  1878. _, tempDialysisRecord := service.FindDialysisOrderById(record_id)
  1879. //
  1880. //if tempDialysisRecord.Creator != adminUserInfo.AdminUser.Id {
  1881. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  1882. // if getPermissionErr != nil {
  1883. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1884. // return
  1885. // } else if headNursePermission == nil {
  1886. // this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  1887. // return
  1888. // }
  1889. //}
  1890. scheduleDateStart := startDate.Format("2006-01-02") + " 00:00:00"
  1891. scheduleDateEnd := startDate.Format("2006-01-02") + " 23:59:59"
  1892. timeLayout := "2006-01-02 15:04:05"
  1893. loc, _ := time.LoadLocation("Local")
  1894. theStartTime, _ := time.ParseInLocation(timeLayout, scheduleDateStart, loc)
  1895. theEndTime, _ := time.ParseInLocation(timeLayout, scheduleDateEnd, loc)
  1896. schedulestartTime := theStartTime.Unix()
  1897. scheduleendTime := theEndTime.Unix()
  1898. //查询更改的机号,是否有人用了,如果只是排班了,但是没上机,直接替换,如果排班且上机了,就提示他无法上机
  1899. schedule, err := service.GetDayScheduleByBedid(adminUserInfo.Org.Id, schedulestartTime, bedID, schedual_type)
  1900. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1901. if daySchedule.BedId != bedID || daySchedule.ScheduleType != schedual_type {
  1902. if err == gorm.ErrRecordNotFound { //空床位
  1903. // 修改了床位逻辑
  1904. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1905. if daySchedule.ID > 0 {
  1906. daySchedule.BedId = bedID
  1907. daySchedule.PartitionId = deviceNumber.ZoneID
  1908. daySchedule.ScheduleType = schedual_type
  1909. daySchedule.UpdatedTime = time.Now().Unix()
  1910. err := service.UpdateSchedule(&daySchedule)
  1911. if err != nil {
  1912. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1913. return
  1914. }
  1915. }
  1916. } else if err == nil {
  1917. if schedule.ID > 0 && schedule.DialysisOrder.ID == 0 { //有排班没上机记录
  1918. daySchedule, _ := service.GetDaySchedule(adminUserInfo.Org.Id, schedulestartTime, scheduleendTime, tempDialysisRecord.PatientId)
  1919. if daySchedule.ID > 0 {
  1920. daySchedule.BedId = bedID
  1921. daySchedule.PartitionId = deviceNumber.ZoneID
  1922. daySchedule.ScheduleType = schedual_type
  1923. daySchedule.UpdatedTime = time.Now().Unix()
  1924. err := service.UpdateSchedule(&daySchedule)
  1925. if err != nil {
  1926. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1927. return
  1928. }
  1929. }
  1930. } else if schedule.ID > 0 && schedule.DialysisOrder.ID > 0 { //有排班且有上机记录
  1931. this.ServeFailJSONWithSGJErrorCode(enums.ErrorDialysisOrderRepeatBed)
  1932. return
  1933. }
  1934. } else if err != nil {
  1935. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1936. return
  1937. }
  1938. }
  1939. dialysisRecord := &models.DialysisOrder{
  1940. ID: record_id,
  1941. UserOrgId: adminUserInfo.Org.Id,
  1942. BedID: bedID,
  1943. StartNurse: nurseID,
  1944. StartTime: startDate.Unix(),
  1945. PunctureNurse: puncture_nurse,
  1946. Creator: adminUserInfo.AdminUser.Id,
  1947. Modifier: adminUserInfo.AdminUser.Id,
  1948. WashpipeNurse: washpipe_nurse,
  1949. SchedualType: schedual_type,
  1950. }
  1951. updateErr := service.ModifyStartDialysisOrder(dialysisRecord)
  1952. if updateErr != nil {
  1953. this.ErrorLog("修改上机失败:%v", updateErr)
  1954. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1955. return
  1956. }
  1957. if updateErr == nil {
  1958. if tempDialysisRecord.Stage == 2 {
  1959. temp_time := (float64(tempDialysisRecord.EndTime) - float64(startDate.Unix())) / 3600
  1960. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  1961. fmt.Println(value)
  1962. a, b := math.Modf(value)
  1963. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  1964. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  1965. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  1966. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecord.PatientId, tempDialysisRecord.UserOrgId, tempDialysisRecord.DialysisDate, hour, minute)
  1967. if updateAssessmentErr != nil {
  1968. utils.ErrorLog("%v", updateAssessmentErr)
  1969. }
  1970. }
  1971. }
  1972. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  1973. this.ServeSuccessJSON(map[string]interface{}{
  1974. "dialysis_order": dialysisRecords,
  1975. })
  1976. }
  1977. func (c *DialysisAPIController) ModifyFinishDialysisOrder() {
  1978. record_id, _ := c.GetInt64("id")
  1979. nurseID, _ := c.GetInt64("nurse")
  1980. end_time := c.GetString("end_time")
  1981. if record_id <= 0 || nurseID <= 0 {
  1982. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1983. return
  1984. }
  1985. adminUserInfo := c.GetMobileAdminUserInfo()
  1986. nurse, getNurseErr := service.GetAdminUserByUserID(nurseID)
  1987. if getNurseErr != nil {
  1988. c.ErrorLog("获取护士失败:%v", getNurseErr)
  1989. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  1990. return
  1991. } else if nurse == nil {
  1992. c.ErrorLog("护士不存在")
  1993. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  1994. return
  1995. }
  1996. endDate, parseEndDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", end_time)
  1997. if parseEndDateErr != nil {
  1998. c.ErrorLog("日期(%v)解析错误:%v", end_time, parseEndDateErr)
  1999. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2000. return
  2001. }
  2002. _, tempDialysisRecords := service.FindDialysisOrderById(record_id)
  2003. //if tempDialysisRecords.FinishCreator != adminUserInfo.AdminUser.Id {
  2004. // headNursePermission, getPermissionErr := service.GetAdminUserSpecialPermission(adminUserInfo.Org.Id, adminUserInfo.App.Id, adminUserInfo.AdminUser.Id, models.SpecialPermissionTypeHeadNurse)
  2005. // if getPermissionErr != nil {
  2006. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2007. // return
  2008. // } else if headNursePermission == nil {
  2009. // c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDialysisPermissionDeniedModify)
  2010. // return
  2011. // }
  2012. //}
  2013. dialysisRecord := &models.DialysisOrder{
  2014. ID: record_id,
  2015. UserOrgId: adminUserInfo.Org.Id,
  2016. EndTime: endDate.Unix(),
  2017. FinishNurse: nurseID,
  2018. FinishModifier: adminUserInfo.AdminUser.Id,
  2019. }
  2020. updateErr := service.ModifyFinishDialysisOrder(dialysisRecord)
  2021. if updateErr != nil {
  2022. c.ErrorLog("修改下机失败:%v", updateErr)
  2023. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDataException)
  2024. return
  2025. }
  2026. if updateErr == nil {
  2027. temp_time := (float64(endDate.Unix()) - float64(tempDialysisRecords.StartTime)) / 3600
  2028. value, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", temp_time), 64)
  2029. a, b := math.Modf(value)
  2030. tempMinute, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", b), 64)
  2031. hour, _ := strconv.ParseInt(fmt.Sprintf("%.0f", a), 10, 64)
  2032. minute, _ := strconv.ParseInt(fmt.Sprintf("%.0f", tempMinute*60), 10, 64)
  2033. updateAssessmentErr := service.UpdateAssessmentAfterDate(tempDialysisRecords.PatientId, tempDialysisRecords.UserOrgId, tempDialysisRecords.DialysisDate, hour, minute)
  2034. if updateAssessmentErr != nil {
  2035. utils.ErrorLog("%v", updateAssessmentErr)
  2036. }
  2037. }
  2038. _, dialysisRecords := service.FindDialysisOrderById(record_id)
  2039. c.ServeSuccessJSON(map[string]interface{}{
  2040. "dialysis_order": dialysisRecords,
  2041. })
  2042. }
  2043. func (c *DialysisAPIController) GetLongAdvice() {
  2044. patient_id, _ := c.GetInt64("id")
  2045. adminUserInfo := c.GetMobileAdminUserInfo()
  2046. _, config := service.FindDoctorAdviceRecordByOrgId(adminUserInfo.Org.Id)
  2047. //patient, _ := service.FindPatientIsOpenRemindById(patient_id, adminUserInfo.Org.Id)
  2048. if config.IsOpenRemind == 0 { //针对老用户,即没开启推送功能,也没有 不开启推送功能,不做任何处理
  2049. c.ServeSuccessJSON(map[string]interface{}{
  2050. "status": "1",
  2051. })
  2052. return
  2053. } else { //开启推送提醒
  2054. //开启推送提醒逻辑 提交长期处方的时候,弹起长期医嘱推送
  2055. var advice_three []*models.DoctorAdvice
  2056. //groupNo := service.GetMaxLongAdviceGroupID(adminUserInfo.Org.Id, patient_id)
  2057. advices, err := service.GetLastLongAdviceByGroupNo(adminUserInfo.Org.Id, patient_id)
  2058. advices_two, err := service.GetLastLongAdviceByGroupNoThree(adminUserInfo.Org.Id, patient_id)
  2059. for _, advice := range advices {
  2060. if advice.FrequencyType == 3 {
  2061. t := time.Now()
  2062. week := int(t.Weekday())
  2063. switch week {
  2064. case 1:
  2065. if strings.Index(advice.WeekDay, "周一") == -1 {
  2066. advice_three = append(advice_three, advice)
  2067. }
  2068. break
  2069. case 2:
  2070. if strings.Index(advice.WeekDay, "周二") == -1 {
  2071. advice_three = append(advice_three, advice)
  2072. }
  2073. break
  2074. case 3:
  2075. if strings.Index(advice.WeekDay, "周三") == -1 {
  2076. advice_three = append(advice_three, advice)
  2077. }
  2078. break
  2079. case 4:
  2080. if strings.Index(advice.WeekDay, "周四") == -1 {
  2081. advice_three = append(advice_three, advice)
  2082. }
  2083. break
  2084. case 5:
  2085. if strings.Index(advice.WeekDay, "周五") == -1 {
  2086. advice_three = append(advice_three, advice)
  2087. }
  2088. break
  2089. case 6:
  2090. if strings.Index(advice.WeekDay, "周六") == -1 {
  2091. advice_three = append(advice_three, advice)
  2092. }
  2093. break
  2094. case 0:
  2095. if strings.Index(advice.WeekDay, "周日") == -1 {
  2096. advice_three = append(advice_three, advice)
  2097. }
  2098. break
  2099. }
  2100. }
  2101. }
  2102. for _, advice := range advices_two {
  2103. p, _ := time.Parse("2006-01-02", time.Now().Format("2006-01-02"))
  2104. now := p.Unix()
  2105. dayStr := strconv.FormatInt(advice.DayCount, 10)
  2106. dayStr2 := "-" + dayStr
  2107. count, _ := strconv.ParseInt(dayStr2, 10, 64)
  2108. oldTime := time.Now().AddDate(0, 0, int(count)).Unix()
  2109. advices, _ := service.FindAllDoctorAdviceByTime(now, oldTime, patient_id, adminUserInfo.Org.Id, advice.TemplateId)
  2110. for _, ad := range advices {
  2111. advice_three = append(advice_three, ad)
  2112. }
  2113. }
  2114. if err == nil {
  2115. c.ServeSuccessJSON(map[string]interface{}{
  2116. "status": "2",
  2117. "advices": advices,
  2118. "advices_two": RemoveRepeatedElement(advice_three),
  2119. "is_open_remind": config.IsOpenRemind,
  2120. })
  2121. }
  2122. }
  2123. }
  2124. func RemoveRepeatedElement(arr []*models.DoctorAdvice) (newArr []*models.DoctorAdvice) {
  2125. newArr = make([]*models.DoctorAdvice, 0)
  2126. for i := 0; i < len(arr); i++ {
  2127. repeat := false
  2128. for j := i + 1; j < len(arr); j++ {
  2129. if arr[i].ID == arr[j].ID {
  2130. repeat = true
  2131. break
  2132. }
  2133. }
  2134. if !repeat {
  2135. newArr = append(newArr, arr[i])
  2136. }
  2137. }
  2138. return
  2139. }
  2140. func (c *DialysisAPIController) CreateRemindDoctorAdvice() {
  2141. patient, _ := c.GetInt64("id", 0)
  2142. groupNo, _ := c.GetInt64("groupno", 0)
  2143. if patient <= 0 {
  2144. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2145. return
  2146. }
  2147. adminUserInfo := c.GetMobileAdminUserInfo()
  2148. dataBody := make(map[string]interface{}, 0)
  2149. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2150. if err != nil {
  2151. utils.ErrorLog(err.Error())
  2152. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2153. return
  2154. }
  2155. utils.ErrorLog("%v", dataBody)
  2156. timeLayout := "2006-01-02 15:04"
  2157. loc, _ := time.LoadLocation("Local")
  2158. timeLayout2 := "2006-01-02"
  2159. loc2, _ := time.LoadLocation("Local")
  2160. if dataBody["advice_type"] == nil || reflect.TypeOf(dataBody["advice_type"]).String() != "float64" {
  2161. utils.ErrorLog("advice_type")
  2162. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2163. return
  2164. }
  2165. adviceType := int64(2)
  2166. if dataBody["advice_date"] == nil || reflect.TypeOf(dataBody["advice_date"]).String() != "string" {
  2167. utils.ErrorLog("advice_date")
  2168. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2169. return
  2170. }
  2171. adviceDate, _ := dataBody["advice_date"].(string)
  2172. theTime, err := time.ParseInLocation(timeLayout2, adviceDate, loc2)
  2173. AdviceDate := theTime.Unix()
  2174. RecordDate := theTime.Unix()
  2175. if dataBody["start_time"] == nil || reflect.TypeOf(dataBody["start_time"]).String() != "string" {
  2176. utils.ErrorLog("start_time")
  2177. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2178. return
  2179. }
  2180. startTime, _ := dataBody["start_time"].(string)
  2181. if len(startTime) == 0 {
  2182. utils.ErrorLog("len(start_time) == 0")
  2183. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2184. return
  2185. }
  2186. theTime, err = time.ParseInLocation(timeLayout, startTime, loc)
  2187. if err != nil {
  2188. utils.ErrorLog(err.Error())
  2189. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2190. return
  2191. }
  2192. StartTime := theTime.Unix()
  2193. Remark := ""
  2194. if dataBody["remark"] != nil && reflect.TypeOf(dataBody["remark"]).String() == "string" {
  2195. remark, _ := dataBody["remark"].(string)
  2196. Remark = remark
  2197. }
  2198. var advices []*models.GroupAdvice
  2199. if dataBody["advices"] == nil || reflect.TypeOf(dataBody["advices"]).String() != "[]interface {}" {
  2200. utils.ErrorLog("advices")
  2201. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2202. return
  2203. }
  2204. adviceNames := dataBody["advices"].([]interface{})
  2205. for _, adviceNameMap := range adviceNames {
  2206. adviceNameM := adviceNameMap.(map[string]interface{})
  2207. var advice models.GroupAdvice
  2208. advice.Remark = Remark
  2209. advice.AdviceType = adviceType
  2210. advice.StartTime = StartTime
  2211. advice.AdviceDate = AdviceDate
  2212. advice.RecordDate = RecordDate
  2213. advice.Status = 1
  2214. advice.CreatedTime = time.Now().Unix()
  2215. advice.UpdatedTime = time.Now().Unix()
  2216. advice.StopState = 2
  2217. advice.ExecutionState = 2
  2218. advice.UserOrgId = adminUserInfo.Org.Id
  2219. advice.PatientId = patient
  2220. advice.AdviceDoctor = adminUserInfo.AdminUser.Id
  2221. if adviceNameM["advice_name"] == nil || reflect.TypeOf(adviceNameM["advice_name"]).String() != "string" {
  2222. utils.ErrorLog("advice_name")
  2223. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2224. return
  2225. }
  2226. adviceName, _ := adviceNameM["advice_name"].(string)
  2227. if len(adviceName) == 0 {
  2228. utils.ErrorLog("len(advice_name) == 0")
  2229. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2230. return
  2231. }
  2232. advice.AdviceName = adviceName
  2233. if adviceNameM["drug_spec"] != nil && reflect.TypeOf(adviceNameM["drug_spec"]).String() == "string" {
  2234. drugSpec, _ := strconv.ParseFloat(adviceNameM["drug_spec"].(string), 64)
  2235. advice.DrugSpec = drugSpec
  2236. }
  2237. if adviceNameM["advice_desc"] != nil && reflect.TypeOf(adviceNameM["advice_desc"]).String() == "string" {
  2238. adviceDesc, _ := adviceNameM["advice_desc"].(string)
  2239. advice.AdviceDesc = adviceDesc
  2240. }
  2241. if adviceNameM["drug_spec_unit"] != nil && reflect.TypeOf(adviceNameM["drug_spec_unit"]).String() == "string" {
  2242. drugSpecUnit, _ := adviceNameM["drug_spec_unit"].(string)
  2243. advice.DrugSpecUnit = drugSpecUnit
  2244. }
  2245. //if adviceNameM["single_dose"] != nil && reflect.TypeOf(adviceNameM["single_dose"]).String() == "string" {
  2246. // singleDose, _ := strconv.ParseFloat(adviceNameM["single_dose"].(string), 64)
  2247. // advice.SingleDose = singleDose
  2248. //}
  2249. if adviceNameM["single_dose"] != nil || reflect.TypeOf(adviceNameM["single_dose"]).String() == "float64" {
  2250. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2251. advice.SingleDose = adviceNameM["single_dose"].(float64)
  2252. }
  2253. if adviceNameM["single_dose_unit"] != nil && reflect.TypeOf(adviceNameM["single_dose_unit"]).String() == "string" {
  2254. singleDoseUnit, _ := adviceNameM["single_dose_unit"].(string)
  2255. advice.SingleDoseUnit = singleDoseUnit
  2256. }
  2257. //if adviceNameM["prescribing_number"] != nil && reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "string" {
  2258. // prescribingNumber, _ := strconv.ParseFloat(adviceNameM["prescribing_number"].(string), 64)
  2259. // advice.PrescribingNumber = prescribingNumber
  2260. //}
  2261. if adviceNameM["prescribing_number"] != nil || reflect.TypeOf(adviceNameM["prescribing_number"]).String() == "float64" {
  2262. //single_dose := int64(adviceNameM["single_dose"].(float64))
  2263. advice.PrescribingNumber = adviceNameM["prescribing_number"].(float64)
  2264. }
  2265. if adviceNameM["prescribing_number_unit"] != nil && reflect.TypeOf(adviceNameM["prescribing_number_unit"]).String() == "string" {
  2266. prescribingNumberUnit, _ := adviceNameM["prescribing_number_unit"].(string)
  2267. advice.PrescribingNumberUnit = prescribingNumberUnit
  2268. }
  2269. if adviceNameM["delivery_way"] != nil && reflect.TypeOf(adviceNameM["delivery_way"]).String() == "string" {
  2270. deliveryWay, _ := adviceNameM["delivery_way"].(string)
  2271. advice.DeliveryWay = deliveryWay
  2272. }
  2273. if adviceNameM["execution_frequency"] != nil && reflect.TypeOf(adviceNameM["execution_frequency"]).String() == "string" {
  2274. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2275. advice.ExecutionFrequency = executionFrequency
  2276. }
  2277. if adviceNameM["frequency_type"] != nil || reflect.TypeOf(adviceNameM["frequency_type"]).String() == "float64" {
  2278. frequency_type := int64(adviceNameM["frequency_type"].(float64))
  2279. advice.FrequencyType = frequency_type
  2280. }
  2281. if adviceNameM["day_count"] != nil || reflect.TypeOf(adviceNameM["day_count"]).String() == "float64" {
  2282. day_count := int64(adviceNameM["day_count"].(float64))
  2283. advice.DayCount = day_count
  2284. }
  2285. if adviceNameM["week_day"] != nil && reflect.TypeOf(adviceNameM["week_day"]).String() == "string" {
  2286. week_day, _ := adviceNameM["week_day"].(string)
  2287. advice.WeekDay = week_day
  2288. }
  2289. if adviceNameM["template_id"] != nil && reflect.TypeOf(adviceNameM["template_id"]).String() == "string" {
  2290. template_id, _ := adviceNameM["template_id"].(string)
  2291. advice.TemplateId = template_id
  2292. }
  2293. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "string" {
  2294. executionFrequency, _ := adviceNameM["execution_frequency"].(string)
  2295. advice.ExecutionFrequency = executionFrequency
  2296. }
  2297. if adviceNameM["child"] != nil && reflect.TypeOf(adviceNameM["child"]).String() == "[]interface {}" {
  2298. children := adviceNameM["child"].([]interface{})
  2299. if len(children) > 0 {
  2300. for _, childrenMap := range children {
  2301. childMap := childrenMap.(map[string]interface{})
  2302. var child models.GroupAdvice
  2303. child.Remark = Remark
  2304. child.AdviceType = adviceType
  2305. child.StartTime = StartTime
  2306. child.AdviceDate = AdviceDate
  2307. child.RecordDate = RecordDate
  2308. child.Status = 1
  2309. child.CreatedTime = time.Now().Unix()
  2310. child.UpdatedTime = time.Now().Unix()
  2311. child.StopState = 2
  2312. child.ExecutionState = 2
  2313. child.UserOrgId = adminUserInfo.Org.Id
  2314. child.PatientId = patient
  2315. child.AdviceDoctor = adminUserInfo.AdminUser.Id
  2316. if childMap["advice_name"] == nil || reflect.TypeOf(childMap["advice_name"]).String() != "string" {
  2317. utils.ErrorLog("child advice_name")
  2318. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2319. return
  2320. }
  2321. childAdviceName, _ := childMap["advice_name"].(string)
  2322. if len(childAdviceName) == 0 {
  2323. utils.ErrorLog("len(child advice_name) == 0")
  2324. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2325. return
  2326. }
  2327. child.AdviceName = childAdviceName
  2328. if childMap["advice_desc"] != nil && reflect.TypeOf(childMap["advice_desc"]).String() == "string" {
  2329. childAdviceDesc, _ := childMap["advice_desc"].(string)
  2330. child.AdviceDesc = childAdviceDesc
  2331. }
  2332. if childMap["drug_spec"] != nil && reflect.TypeOf(childMap["drug_spec"]).String() == "string" {
  2333. childDrugSpec, _ := strconv.ParseFloat(childMap["drug_spec"].(string), 64)
  2334. child.DrugSpec = childDrugSpec
  2335. }
  2336. if childMap["drug_spec_unit"] != nil && reflect.TypeOf(childMap["drug_spec_unit"]).String() == "string" {
  2337. childDrugSpecUnit, _ := childMap["drug_spec_unit"].(string)
  2338. child.DrugSpecUnit = childDrugSpecUnit
  2339. }
  2340. if childMap["single_dose"] != nil && reflect.TypeOf(childMap["single_dose"]).String() == "float64" {
  2341. child.SingleDose = childMap["single_dose"].(float64)
  2342. }
  2343. if childMap["single_dose_unit"] != nil && reflect.TypeOf(childMap["single_dose_unit"]).String() == "string" {
  2344. childSingleDoseUnit, _ := childMap["single_dose_unit"].(string)
  2345. child.SingleDoseUnit = childSingleDoseUnit
  2346. }
  2347. if childMap["prescribing_number"] != nil && reflect.TypeOf(childMap["prescribing_number"]).String() == "float64" {
  2348. child.PrescribingNumber = childMap["prescribing_number"].(float64)
  2349. }
  2350. if childMap["prescribing_number_unit"] != nil && reflect.TypeOf(childMap["prescribing_number_unit"]).String() == "string" {
  2351. childPrescribingNumberUnit, _ := childMap["prescribing_number_unit"].(string)
  2352. child.PrescribingNumberUnit = childPrescribingNumberUnit
  2353. }
  2354. child.DeliveryWay = advice.DeliveryWay
  2355. child.ExecutionFrequency = advice.ExecutionFrequency
  2356. advice.Children = append(advice.Children, &child)
  2357. }
  2358. }
  2359. }
  2360. advices = append(advices, &advice)
  2361. }
  2362. list, err := service.CreateMGroupAdvice(adminUserInfo.Org.Id, advices, groupNo)
  2363. if err != nil {
  2364. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeCreateDoctorAdviceFail)
  2365. return
  2366. }
  2367. c.ServeSuccessJSON(map[string]interface{}{
  2368. "msg": "ok",
  2369. "advices": list,
  2370. })
  2371. return
  2372. }
  2373. func (c *DialysisAPIController) UploadDryWeight() {
  2374. patient_id, _ := c.GetInt64("id")
  2375. dry_weight, _ := c.GetFloat("dry_weight")
  2376. doctor_id, _ := c.GetInt64("doctor_id")
  2377. remark := c.GetString("remark")
  2378. adminUserInfo := c.GetMobileAdminUserInfo()
  2379. weightAdjust, err := service.FindLastDryWeightAdjust(adminUserInfo.Org.Id, patient_id)
  2380. if err == gorm.ErrRecordNotFound {
  2381. dryWeight := &models.SgjPatientDryweight{
  2382. PatientId: patient_id,
  2383. DryWeight: dry_weight,
  2384. Remakes: remark,
  2385. Ctime: time.Now().Unix(),
  2386. Mtime: time.Now().Unix(),
  2387. Creator: doctor_id,
  2388. Status: 1,
  2389. UserOrgId: adminUserInfo.Org.Id,
  2390. AdjustedValue: "/",
  2391. UserId: adminUserInfo.AdminUser.Id,
  2392. }
  2393. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2394. if createErr == nil {
  2395. c.ServeSuccessJSON(map[string]interface{}{
  2396. "msg": "提交成功",
  2397. "weight": dryWeight,
  2398. })
  2399. }
  2400. } else {
  2401. dryWeight := &models.SgjPatientDryweight{
  2402. PatientId: patient_id,
  2403. DryWeight: dry_weight,
  2404. Remakes: remark,
  2405. Ctime: time.Now().Unix(),
  2406. Mtime: time.Now().Unix(),
  2407. Creator: doctor_id,
  2408. Status: 1,
  2409. UserOrgId: adminUserInfo.Org.Id,
  2410. AdjustedValue: "/",
  2411. UserId: adminUserInfo.AdminUser.Id,
  2412. }
  2413. var value float64
  2414. value = dry_weight - weightAdjust.DryWeight
  2415. if value < 0 {
  2416. dryWeight.AdjustedValue = strconv.FormatFloat(math.Abs(value), 'f', 1, 64) + "(下调)"
  2417. } else if value == 0 {
  2418. dryWeight.AdjustedValue = "/"
  2419. } else if value > 0 {
  2420. dryWeight.AdjustedValue = strconv.FormatFloat(value, 'f', 1, 64) + "(上调)"
  2421. }
  2422. createErr := service.CreatePatientWeightAdjust(dryWeight)
  2423. if createErr == nil {
  2424. c.ServeSuccessJSON(map[string]interface{}{
  2425. "msg": "提交成功",
  2426. "weight": dryWeight,
  2427. })
  2428. }
  2429. }
  2430. }
  2431. func (c *DialysisAPIController) GetSolution() {
  2432. patient_id, _ := c.GetInt64("patient_id")
  2433. mode_id, _ := c.GetInt64("mode_id")
  2434. adminUserInfo := c.GetMobileAdminUserInfo()
  2435. solution, err := service.MobileGetDialysisSolutionByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2436. prescription, err := service.MobileGetLastDialysisPrescribeByModeId(adminUserInfo.Org.Id, patient_id, mode_id)
  2437. system_prescription, err := service.MobileGetSystemDialysisPrescribeByModeId(adminUserInfo.Org.Id, mode_id)
  2438. if err != nil {
  2439. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2440. return
  2441. }
  2442. c.ServeSuccessJSON(map[string]interface{}{
  2443. "solution": solution,
  2444. "prescription": prescription,
  2445. "system_prescription": system_prescription,
  2446. })
  2447. }
  2448. func (c *DialysisAPIController) GetSchedule() {
  2449. schedual_type, _ := c.GetInt64("schedual_type")
  2450. adminUserInfo := c.GetMobileAdminUserInfo()
  2451. timeLayout := "2006-01-02 15:04:05"
  2452. date := time.Now().Format("2006-01-02") + " 00:00:00"
  2453. loc, _ := time.LoadLocation("Local")
  2454. theStartTime, _ := time.ParseInLocation(timeLayout, date, loc)
  2455. scheduleTime := theStartTime.Unix()
  2456. deviceNumber, _ := service.GetAllDeviceNumbers(adminUserInfo.Org.Id, scheduleTime, schedual_type)
  2457. c.ServeSuccessJSON(map[string]interface{}{
  2458. "number": deviceNumber,
  2459. })
  2460. }
  2461. func (c *DialysisAPIController) GetPatientId() {
  2462. id, _ := c.GetInt64("id")
  2463. patientId, _ := service.GetPatientId(id)
  2464. c.ServeSuccessJSON(map[string]interface{}{
  2465. "patient": patientId,
  2466. })
  2467. }
  2468. func (this *DialysisAPIController) GetDialysisSchedule() {
  2469. schedualDate := this.GetString("date")
  2470. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  2471. if parseDateErr != nil {
  2472. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2473. return
  2474. }
  2475. adminInfo := this.GetMobileAdminUserInfo()
  2476. orgID := adminInfo.Org.Id
  2477. redis := service.RedisClient()
  2478. defer redis.Close()
  2479. key := "scheduals_" + schedualDate + "_" + strconv.FormatInt(orgID, 10)
  2480. scheduals, _ := service.MobileGetDialysisScheduals(orgID, date.Unix(), 0)
  2481. if len(scheduals) > 0 {
  2482. //缓存数据
  2483. scheduals_json, err := json.Marshal(scheduals)
  2484. if err == nil {
  2485. redis.Set(key, scheduals_json, time.Second*30)
  2486. }
  2487. }
  2488. this.ServeSuccessJSON(map[string]interface{}{
  2489. "scheduals": scheduals,
  2490. })
  2491. }
  2492. func (this *DialysisAPIController) GetLastOrNextDoctorAdvice() {
  2493. change_type, _ := this.GetInt64("type", 0)
  2494. record_date := this.GetString("record_time")
  2495. patient_id, _ := this.GetInt64("patient_id", 0)
  2496. timeLayout := "2006-01-02"
  2497. loc, _ := time.LoadLocation("Local")
  2498. theAdviceRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2499. record_time := theAdviceRecordTime.Unix()
  2500. adminUserInfo := this.GetMobileAdminUserInfo()
  2501. advices, sch, err := service.GetDoctorAdviceByType(change_type, record_time, adminUserInfo.Org.Id, patient_id)
  2502. if err == nil {
  2503. if len(advices) == 0 {
  2504. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeDoctorAdviceEmpty)
  2505. return
  2506. } else {
  2507. this.ServeSuccessJSON(map[string]interface{}{
  2508. "advices": advices,
  2509. "schedule": sch,
  2510. })
  2511. return
  2512. }
  2513. } else {
  2514. this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2515. return
  2516. }
  2517. }
  2518. func (c *DialysisAPIController) CreateConsumables() {
  2519. record_date := c.GetString("record_time")
  2520. patient_id, _ := c.GetInt64("patient_id", 0)
  2521. adminUser := c.GetMobileAdminUserInfo()
  2522. timeLayout := "2006-01-02"
  2523. loc, _ := time.LoadLocation("Local")
  2524. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2525. record_time := theRecordTime.Unix()
  2526. dataBody := make(map[string]interface{}, 0)
  2527. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2528. if err != nil {
  2529. utils.ErrorLog(err.Error())
  2530. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2531. return
  2532. }
  2533. var beforePrepares []*models.DialysisBeforePrepare
  2534. var updateBeforePrepares []*models.DialysisBeforePrepare
  2535. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2536. goods, _ := dataBody["goods"].([]interface{})
  2537. if len(goods) > 0 {
  2538. for _, item := range goods {
  2539. items := item.(map[string]interface{})
  2540. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2541. utils.ErrorLog("good_id")
  2542. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2543. return
  2544. }
  2545. good_id := int64(items["good_id"].(float64))
  2546. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2547. utils.ErrorLog("good_type_id")
  2548. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2549. return
  2550. }
  2551. good_type_id := int64(items["good_type_id"].(float64))
  2552. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2553. utils.ErrorLog("count")
  2554. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2555. return
  2556. }
  2557. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2558. adminUser := c.GetMobileAdminUserInfo()
  2559. prepare := &models.DialysisBeforePrepare{
  2560. UserOrgId: adminUser.Org.Id,
  2561. PatientId: patient_id,
  2562. RecordDate: record_time,
  2563. GoodId: good_id,
  2564. GoodTypeId: good_type_id,
  2565. Count: count,
  2566. Ctime: time.Now().Unix(),
  2567. Mtime: time.Now().Unix(),
  2568. Creater: adminUser.AdminUser.Id,
  2569. Modifier: 0,
  2570. }
  2571. record_count := service.FindDialysisBeforePrepare(prepare.PatientId, prepare.GoodId, prepare.GoodTypeId, adminUser.Org.Id, record_time)
  2572. if record_count == 0 {
  2573. beforePrepares = append(beforePrepares, prepare)
  2574. }
  2575. }
  2576. }
  2577. }
  2578. if len(beforePrepares) > 0 {
  2579. service.CreateDialysisBeforePrepare(beforePrepares)
  2580. }
  2581. var errs error
  2582. if dataBody["update_goods"] != nil && reflect.TypeOf(dataBody["update_goods"]).String() == "[]interface {}" {
  2583. goods, _ := dataBody["update_goods"].([]interface{})
  2584. if len(goods) > 0 {
  2585. for _, item := range goods {
  2586. items := item.(map[string]interface{})
  2587. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  2588. utils.ErrorLog("record_time")
  2589. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2590. return
  2591. }
  2592. record_time := int64(items["record_time"].(float64))
  2593. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  2594. utils.ErrorLog("id")
  2595. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2596. return
  2597. }
  2598. id := int64(items["id"].(float64))
  2599. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  2600. utils.ErrorLog("patient_id")
  2601. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2602. return
  2603. }
  2604. patient_id := int64(items["patient_id"].(float64))
  2605. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  2606. utils.ErrorLog("creater")
  2607. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2608. return
  2609. }
  2610. creater := int64(items["creater"].(float64))
  2611. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2612. utils.ErrorLog("good_id")
  2613. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2614. return
  2615. }
  2616. good_id := int64(items["good_id"].(float64))
  2617. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2618. utils.ErrorLog("good_type_id")
  2619. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2620. return
  2621. }
  2622. good_type_id := int64(items["good_type_id"].(float64))
  2623. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2624. utils.ErrorLog("count")
  2625. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2626. return
  2627. }
  2628. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2629. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  2630. utils.ErrorLog("ctime")
  2631. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2632. return
  2633. }
  2634. ctime := int64(items["ctime"].(float64))
  2635. prepare := &models.DialysisBeforePrepare{
  2636. ID: id,
  2637. UserOrgId: adminUser.Org.Id,
  2638. PatientId: patient_id,
  2639. RecordDate: record_time,
  2640. GoodId: good_id,
  2641. GoodTypeId: good_type_id,
  2642. Count: count,
  2643. Ctime: ctime,
  2644. Mtime: time.Now().Unix(),
  2645. Creater: creater,
  2646. Modifier: adminUser.AdminUser.Id,
  2647. Status: 1,
  2648. }
  2649. updateBeforePrepares = append(updateBeforePrepares, prepare)
  2650. }
  2651. }
  2652. updateBeforePrepares = RemoveRepeatedGood(updateBeforePrepares)
  2653. if len(updateBeforePrepares) > 0 {
  2654. for _, item := range updateBeforePrepares {
  2655. errs = service.UpdateDialysisBeforePrepareTwo(item)
  2656. }
  2657. }
  2658. }
  2659. if errs == nil {
  2660. c.ServeSuccessJSON(map[string]interface{}{
  2661. "msg": "提交成功",
  2662. })
  2663. return
  2664. } else {
  2665. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  2666. return
  2667. }
  2668. }
  2669. func (c *DialysisAPIController) CreateStockOutInfo() {
  2670. patient_id, _ := c.GetInt64("patient_id", 0)
  2671. record_date := c.GetString("record_time")
  2672. if patient_id <= 0 {
  2673. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2674. return
  2675. }
  2676. adminInfo := c.GetMobileAdminUserInfo()
  2677. timeLayout := "2006-01-02"
  2678. loc, _ := time.LoadLocation("Local")
  2679. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2680. record_time := theRecordTime.Unix()
  2681. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  2682. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  2683. consumables = RemoveRepeatedGood(consumables)
  2684. if record.IsOpen == 1 {
  2685. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  2686. if err == gorm.ErrRecordNotFound {
  2687. //没有记录,则创建出库单
  2688. timeStr := time.Now().Format("2006-01-02")
  2689. timeArr := strings.Split(timeStr, "-")
  2690. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  2691. total = total + 1
  2692. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  2693. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  2694. number = number + total
  2695. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  2696. creater := adminInfo.AdminUser.Id
  2697. warehouseOut := models.WarehouseOut{
  2698. WarehouseOutOrderNumber: warehousing_out_order,
  2699. OperationTime: time.Now().Unix(),
  2700. OrgId: adminInfo.Org.Id,
  2701. Creater: creater,
  2702. Ctime: time.Now().Unix(),
  2703. Status: 1,
  2704. WarehouseOutTime: record_time,
  2705. Dealer: 0,
  2706. Manufacturer: 0,
  2707. Type: 1,
  2708. IsSys: 1,
  2709. }
  2710. err := service.AddSigleWarehouseOut(&warehouseOut)
  2711. if err != nil {
  2712. utils.TraceLog("创建出库单失败 err = %v", err)
  2713. } else {
  2714. for _, item := range consumables {
  2715. if item.Count > 0 {
  2716. warehouseOutInfo := &models.WarehouseOutInfo{
  2717. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  2718. WarehouseOutId: warehouseOut.ID,
  2719. Status: 1,
  2720. Ctime: time.Now().Unix(),
  2721. Remark: "",
  2722. OrgId: adminInfo.Org.Id,
  2723. Type: 1,
  2724. Manufacturer: 0,
  2725. Dealer: 0,
  2726. IsSys: 1,
  2727. SysRecordTime: record_time,
  2728. GoodTypeId: item.GoodTypeId,
  2729. GoodId: item.GoodId,
  2730. }
  2731. warehouseOutInfo.Count = item.Count
  2732. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  2733. warehouseOutInfo.Price = stockInInfo.Price
  2734. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  2735. if err == nil {
  2736. details := &models.AutomaticReduceDetail{
  2737. WarehouseOutId: warehouseOutInfo.ID,
  2738. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  2739. PatientId: patient_id,
  2740. Ctime: time.Now().Unix(),
  2741. Mtime: time.Now().Unix(),
  2742. Status: 1,
  2743. RecordTime: record_time,
  2744. OrgId: adminInfo.Org.Id,
  2745. GoodId: item.GoodId,
  2746. GoodTypeId: item.GoodTypeId,
  2747. Count: item.Count,
  2748. }
  2749. service.AddSigleAutoReduceRecordInfo(details)
  2750. }
  2751. }
  2752. }
  2753. }
  2754. } else if err == nil {
  2755. for _, item := range consumables {
  2756. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  2757. if err == gorm.ErrRecordNotFound {
  2758. warehouseOutInfo := &models.WarehouseOutInfo{
  2759. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  2760. WarehouseOutId: out.ID,
  2761. Status: 1,
  2762. Ctime: time.Now().Unix(),
  2763. Remark: "",
  2764. OrgId: adminInfo.Org.Id,
  2765. Type: 1,
  2766. Manufacturer: 0,
  2767. Dealer: 0,
  2768. IsSys: 1,
  2769. SysRecordTime: record_time,
  2770. }
  2771. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  2772. warehouseOutInfo.Price = stockInInfo.Price
  2773. warehouseOutInfo.GoodId = item.GoodId
  2774. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  2775. warehouseOutInfo.Count = item.Count
  2776. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  2777. if err == nil {
  2778. details := &models.AutomaticReduceDetail{
  2779. WarehouseOutId: warehouseOutInfo.ID,
  2780. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  2781. PatientId: patient_id,
  2782. Ctime: time.Now().Unix(),
  2783. Mtime: time.Now().Unix(),
  2784. Status: 1,
  2785. RecordTime: record_time,
  2786. OrgId: adminInfo.Org.Id,
  2787. GoodId: item.GoodId,
  2788. GoodTypeId: item.GoodTypeId,
  2789. Count: item.Count,
  2790. }
  2791. service.AddSigleAutoReduceRecordInfo(details)
  2792. }
  2793. } else if err == nil { //记录存在,则将增加数量
  2794. if outInfo.ID > 0 {
  2795. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  2796. }
  2797. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  2798. if count == 0 {
  2799. details := &models.AutomaticReduceDetail{
  2800. WarehouseOutId: outInfo.ID,
  2801. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  2802. PatientId: patient_id,
  2803. Ctime: time.Now().Unix(),
  2804. Mtime: time.Now().Unix(),
  2805. Status: 1,
  2806. RecordTime: record_time,
  2807. OrgId: adminInfo.Org.Id,
  2808. GoodId: item.GoodId,
  2809. GoodTypeId: item.GoodTypeId,
  2810. Count: item.Count,
  2811. }
  2812. service.AddSigleAutoReduceRecordInfo(details)
  2813. } else if count == 1 {
  2814. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  2815. }
  2816. }
  2817. }
  2818. }
  2819. c.ServeSuccessJSON(map[string]interface{}{
  2820. "msg": "提交成功",
  2821. })
  2822. return
  2823. } else {
  2824. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  2825. return
  2826. }
  2827. }
  2828. func (c *DialysisAPIController) EditConsumables() {
  2829. patient_id, _ := c.GetInt64("patient_id", 0)
  2830. record_date := c.GetString("record_time")
  2831. if patient_id <= 0 {
  2832. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2833. return
  2834. }
  2835. adminInfo := c.GetMobileAdminUserInfo()
  2836. timeLayout := "2006-01-02"
  2837. loc, _ := time.LoadLocation("Local")
  2838. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  2839. record_time := theRecordTime.Unix()
  2840. dataBody := make(map[string]interface{}, 0)
  2841. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  2842. if err != nil {
  2843. utils.ErrorLog(err.Error())
  2844. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2845. return
  2846. }
  2847. var beforePrepares []*models.DialysisBeforePrepare
  2848. var newBeforePrepares []*models.DialysisBeforePrepare
  2849. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  2850. if record.IsOpen == 1 {
  2851. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  2852. goods, _ := dataBody["goods"].([]interface{})
  2853. if len(goods) > 0 {
  2854. for _, item := range goods {
  2855. items := item.(map[string]interface{})
  2856. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  2857. utils.ErrorLog("record_time")
  2858. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2859. return
  2860. }
  2861. record_time := int64(items["record_time"].(float64))
  2862. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  2863. utils.ErrorLog("id")
  2864. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2865. return
  2866. }
  2867. id := int64(items["id"].(float64))
  2868. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  2869. utils.ErrorLog("patient_id")
  2870. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2871. return
  2872. }
  2873. patient_id := int64(items["patient_id"].(float64))
  2874. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  2875. utils.ErrorLog("creater")
  2876. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2877. return
  2878. }
  2879. creater := int64(items["creater"].(float64))
  2880. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2881. utils.ErrorLog("good_id")
  2882. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2883. return
  2884. }
  2885. good_id := int64(items["good_id"].(float64))
  2886. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2887. utils.ErrorLog("good_type_id")
  2888. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2889. return
  2890. }
  2891. good_type_id := int64(items["good_type_id"].(float64))
  2892. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2893. utils.ErrorLog("count")
  2894. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2895. return
  2896. }
  2897. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2898. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  2899. utils.ErrorLog("ctime")
  2900. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2901. return
  2902. }
  2903. ctime := int64(items["ctime"].(float64))
  2904. adminUser := c.GetMobileAdminUserInfo()
  2905. prepare := &models.DialysisBeforePrepare{
  2906. ID: id,
  2907. UserOrgId: adminUser.Org.Id,
  2908. PatientId: patient_id,
  2909. RecordDate: record_time,
  2910. GoodId: good_id,
  2911. GoodTypeId: good_type_id,
  2912. Count: count,
  2913. Ctime: ctime,
  2914. Mtime: time.Now().Unix(),
  2915. Creater: creater,
  2916. Modifier: adminUser.AdminUser.Id,
  2917. Status: 1,
  2918. }
  2919. beforePrepares = append(beforePrepares, prepare)
  2920. }
  2921. }
  2922. }
  2923. consumables_source, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  2924. if dataBody["new_goods"] != nil && reflect.TypeOf(dataBody["new_goods"]).String() == "[]interface {}" {
  2925. goods, _ := dataBody["new_goods"].([]interface{})
  2926. if len(goods) > 0 {
  2927. for _, item := range goods {
  2928. items := item.(map[string]interface{})
  2929. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  2930. utils.ErrorLog("good_id")
  2931. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2932. return
  2933. }
  2934. good_id := int64(items["good_id"].(float64))
  2935. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  2936. utils.ErrorLog("good_type_id")
  2937. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2938. return
  2939. }
  2940. good_type_id := int64(items["good_type_id"].(float64))
  2941. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  2942. utils.ErrorLog("count")
  2943. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  2944. return
  2945. }
  2946. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  2947. adminUser := c.GetMobileAdminUserInfo()
  2948. prepare := &models.DialysisBeforePrepare{
  2949. UserOrgId: adminUser.Org.Id,
  2950. PatientId: patient_id,
  2951. RecordDate: record_time,
  2952. GoodId: good_id,
  2953. GoodTypeId: good_type_id,
  2954. Count: count,
  2955. Ctime: time.Now().Unix(),
  2956. Mtime: time.Now().Unix(),
  2957. Creater: adminUser.AdminUser.Id,
  2958. Modifier: 0,
  2959. }
  2960. newBeforePrepares = append(newBeforePrepares, prepare)
  2961. }
  2962. newBeforePrepares = RemoveRepeatedGood(newBeforePrepares)
  2963. }
  2964. service.CreateDialysisBeforePrepare(newBeforePrepares)
  2965. }
  2966. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  2967. if err == gorm.ErrRecordNotFound {
  2968. //没有记录,则创建出库单
  2969. timeStr := time.Now().Format("2006-01-02")
  2970. timeArr := strings.Split(timeStr, "-")
  2971. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  2972. total = total + 1
  2973. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  2974. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  2975. number = number + total
  2976. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  2977. creater := adminInfo.AdminUser.Id
  2978. warehouseOut := models.WarehouseOut{
  2979. WarehouseOutOrderNumber: warehousing_out_order,
  2980. OperationTime: time.Now().Unix(),
  2981. OrgId: adminInfo.Org.Id,
  2982. Creater: creater,
  2983. Ctime: time.Now().Unix(),
  2984. Status: 1,
  2985. WarehouseOutTime: record_time,
  2986. Dealer: 0,
  2987. Manufacturer: 0,
  2988. Type: 1,
  2989. IsSys: 1,
  2990. }
  2991. err := service.AddSigleWarehouseOut(&warehouseOut)
  2992. if err != nil {
  2993. utils.TraceLog("创建出库单失败 err = %v", err)
  2994. } else {
  2995. for _, item := range beforePrepares {
  2996. if item.Count > 0 {
  2997. warehouseOutInfo := &models.WarehouseOutInfo{
  2998. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  2999. WarehouseOutId: warehouseOut.ID,
  3000. Count: 1,
  3001. Status: 1,
  3002. Ctime: time.Now().Unix(),
  3003. Remark: "",
  3004. OrgId: adminInfo.Org.Id,
  3005. Type: 1,
  3006. Manufacturer: 0,
  3007. Dealer: 0,
  3008. IsSys: 1,
  3009. SysRecordTime: record_time,
  3010. GoodTypeId: item.GoodTypeId,
  3011. GoodId: item.GoodId,
  3012. }
  3013. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3014. warehouseOutInfo.Price = stockInInfo.Price
  3015. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3016. if err == nil {
  3017. details := &models.AutomaticReduceDetail{
  3018. WarehouseOutId: warehouseOutInfo.ID,
  3019. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3020. PatientId: patient_id,
  3021. Ctime: time.Now().Unix(),
  3022. Mtime: time.Now().Unix(),
  3023. Status: 1,
  3024. RecordTime: record_time,
  3025. OrgId: adminInfo.Org.Id,
  3026. GoodId: item.GoodId,
  3027. GoodTypeId: item.GoodTypeId,
  3028. }
  3029. service.AddSigleAutoReduceRecordInfo(details)
  3030. }
  3031. }
  3032. }
  3033. }
  3034. } else if err == nil {
  3035. if len(newBeforePrepares) > 0 { //新增
  3036. for _, item := range newBeforePrepares {
  3037. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  3038. if err == gorm.ErrRecordNotFound {
  3039. warehouseOutInfo := &models.WarehouseOutInfo{
  3040. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3041. WarehouseOutId: out.ID,
  3042. Status: 1,
  3043. Ctime: time.Now().Unix(),
  3044. Remark: "",
  3045. OrgId: adminInfo.Org.Id,
  3046. Type: 1,
  3047. Manufacturer: 0,
  3048. Dealer: 0,
  3049. IsSys: 1,
  3050. SysRecordTime: record_time,
  3051. }
  3052. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3053. warehouseOutInfo.Price = stockInInfo.Price
  3054. warehouseOutInfo.GoodId = item.GoodId
  3055. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  3056. warehouseOutInfo.Count = item.Count
  3057. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3058. if err == nil {
  3059. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  3060. if count == 0 {
  3061. details := &models.AutomaticReduceDetail{
  3062. WarehouseOutId: warehouseOutInfo.ID,
  3063. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3064. PatientId: patient_id,
  3065. Ctime: time.Now().Unix(),
  3066. Mtime: time.Now().Unix(),
  3067. Status: 1,
  3068. RecordTime: record_time,
  3069. OrgId: adminInfo.Org.Id,
  3070. GoodId: item.GoodId,
  3071. GoodTypeId: item.GoodTypeId,
  3072. Count: item.Count,
  3073. }
  3074. service.AddSigleAutoReduceRecordInfo(details)
  3075. } else if count == 1 {
  3076. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  3077. }
  3078. }
  3079. } else if err == nil { //记录存在,则将加数量
  3080. if outInfo.ID > 0 {
  3081. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  3082. }
  3083. count, _ := service.FindPatientAutomaticReduceRecord(adminInfo.Org.Id, record_time, item.GoodId, item.GoodTypeId, patient_id)
  3084. if count == 0 {
  3085. details := &models.AutomaticReduceDetail{
  3086. WarehouseOutId: outInfo.ID,
  3087. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3088. PatientId: patient_id,
  3089. Ctime: time.Now().Unix(),
  3090. Mtime: time.Now().Unix(),
  3091. Status: 1,
  3092. RecordTime: record_time,
  3093. OrgId: adminInfo.Org.Id,
  3094. GoodId: item.GoodId,
  3095. GoodTypeId: item.GoodTypeId,
  3096. Count: item.Count,
  3097. }
  3098. service.AddSigleAutoReduceRecordInfo(details)
  3099. } else if count == 1 {
  3100. service.UpdateUserInfoDetails(item.GoodTypeId, item.GoodId, record_time, adminInfo.Org.Id, patient_id, item.Count, &outInfo)
  3101. }
  3102. //details := &models.AutomaticReduceDetail{
  3103. // WarehouseOutId: outInfo.ID,
  3104. // WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3105. // PatientId: patient_id,
  3106. // Ctime: time.Now().Unix(),
  3107. // Mtime: time.Now().Unix(),
  3108. // Status: 1,
  3109. // RecordTime: record_time,
  3110. // OrgId: adminInfo.Org.Id,
  3111. // GoodId: item.GoodId,
  3112. // GoodTypeId: item.GoodTypeId,
  3113. // Count: item.Count,
  3114. //}
  3115. //service.AddSigleAutoReduceRecordInfo(details)
  3116. }
  3117. }
  3118. }
  3119. if len(beforePrepares) > 0 { //修改
  3120. for _, consumable := range consumables_source {
  3121. for _, before := range beforePrepares {
  3122. if consumable.GoodId == before.GoodId {
  3123. fmt.Println(consumable.Count)
  3124. fmt.Println(before.Count)
  3125. if consumable.Count != before.Count {
  3126. fmt.Println("111111111")
  3127. _, out := service.FindStockOutOrderNumberByTime(record_time, adminInfo.Org.Id)
  3128. //_, out := service.FindOldOrderInfoByGoodId(record_time, adminInfo.Org.Id)
  3129. //判断前端更改后的商品id的出库记录在数据库中是否存在
  3130. err, newOut := service.FindOrderInfoByGoodId(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id)
  3131. if err == gorm.ErrRecordNotFound { //不存在,则新增出库记录,并更改使用人商品信息
  3132. fmt.Println("222222222")
  3133. warehouseOutInfo := &models.WarehouseOutInfo{
  3134. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3135. WarehouseOutId: out.ID,
  3136. Count: before.Count,
  3137. Status: 1,
  3138. Ctime: time.Now().Unix(),
  3139. Remark: "",
  3140. OrgId: adminInfo.Org.Id,
  3141. Type: 1,
  3142. Manufacturer: 0,
  3143. Dealer: 0,
  3144. IsSys: 1,
  3145. SysRecordTime: record_time,
  3146. }
  3147. stockInInfo, _ := service.FindLastStockInInfoRecord(before.GoodId, adminInfo.Org.Id)
  3148. warehouseOutInfo.Price = stockInInfo.Price
  3149. warehouseOutInfo.GoodId = before.GoodId
  3150. warehouseOutInfo.GoodTypeId = before.GoodTypeId
  3151. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3152. if err == nil {
  3153. //可能存在商品使用人不存在的情况,需要先判断商品使用人是否存在
  3154. user, err := service.FindGoodUserById(before.GoodTypeId, before.GoodId, patient_id, adminInfo.Org.Id, out.WarehouseOutOrderNumber)
  3155. if err == gorm.ErrRecordNotFound {
  3156. details := &models.AutomaticReduceDetail{
  3157. WarehouseOutId: warehouseOutInfo.ID,
  3158. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3159. PatientId: patient_id,
  3160. Ctime: time.Now().Unix(),
  3161. Mtime: time.Now().Unix(),
  3162. Status: 1,
  3163. RecordTime: record_time,
  3164. OrgId: adminInfo.Org.Id,
  3165. GoodId: consumable.GoodId,
  3166. GoodTypeId: consumable.GoodTypeId,
  3167. Count: before.Count,
  3168. }
  3169. service.AddSigleAutoReduceRecordInfo(details)
  3170. } else if err == nil {
  3171. if user.ID > 0 {
  3172. //service.UpdateOrderInfoDetails( consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, a_liquid, warehouseOutInfo)
  3173. service.UpdateUserInfoDetails(consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, before.Count, warehouseOutInfo)
  3174. }
  3175. }
  3176. }
  3177. } else if err == nil { //存在,则更改使用人商品信息
  3178. fmt.Println("333333333")
  3179. //处理原来的数据
  3180. if newOut.ID > 0 {
  3181. if consumable.Count > before.Count { // 减少
  3182. num := int64(0)
  3183. if consumable.Count-before.Count > 0 {
  3184. num = consumable.Count - before.Count
  3185. } else {
  3186. num = before.Count - consumable.Count
  3187. }
  3188. service.UpdateOrderCountSub(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id, num)
  3189. } else if consumable.Count < before.Count { //增加
  3190. service.UpdateOrderCountAdd(consumable.GoodTypeId, consumable.GoodId, out.WarehouseOutOrderNumber, adminInfo.Org.Id, before.Count-consumable.Count)
  3191. }
  3192. user, err := service.FindGoodUserById(consumable.GoodTypeId, consumable.GoodId, patient_id, adminInfo.Org.Id, out.WarehouseOutOrderNumber)
  3193. if err == gorm.ErrRecordNotFound {
  3194. details := &models.AutomaticReduceDetail{
  3195. WarehouseOutId: newOut.ID,
  3196. WarehouseOutOrderNumber: newOut.WarehouseOutOrderNumber,
  3197. PatientId: patient_id,
  3198. Ctime: time.Now().Unix(),
  3199. Mtime: time.Now().Unix(),
  3200. Status: 1,
  3201. RecordTime: record_time,
  3202. OrgId: adminInfo.Org.Id,
  3203. GoodId: consumable.GoodId,
  3204. GoodTypeId: consumable.GoodTypeId,
  3205. Count: before.Count,
  3206. }
  3207. service.AddSigleAutoReduceRecordInfo(details)
  3208. } else if err == nil {
  3209. if user.ID > 0 {
  3210. service.UpdateUserInfoDetails(consumable.GoodTypeId, consumable.GoodId, record_time, adminInfo.Org.Id, patient_id, before.Count, &newOut)
  3211. }
  3212. }
  3213. }
  3214. }
  3215. fmt.Println("444444444")
  3216. }
  3217. }
  3218. }
  3219. }
  3220. }
  3221. }
  3222. fmt.Println("655555555")
  3223. var errs error
  3224. if len(beforePrepares) > 0 {
  3225. for _, item := range beforePrepares {
  3226. errs = service.UpdateDialysisBeforePrepareTwo(item)
  3227. }
  3228. }
  3229. if errs == nil {
  3230. c.ServeSuccessJSON(map[string]interface{}{
  3231. "msg": "修改成功",
  3232. })
  3233. return
  3234. } else {
  3235. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3236. return
  3237. }
  3238. } else {
  3239. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3240. goods, _ := dataBody["goods"].([]interface{})
  3241. if len(goods) > 0 {
  3242. for _, item := range goods {
  3243. items := item.(map[string]interface{})
  3244. if items["record_time"] == nil || reflect.TypeOf(items["record_time"]).String() != "float64" {
  3245. utils.ErrorLog("record_time")
  3246. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3247. return
  3248. }
  3249. record_time := int64(items["record_time"].(float64))
  3250. if items["id"] == nil || reflect.TypeOf(items["id"]).String() != "float64" {
  3251. utils.ErrorLog("id")
  3252. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3253. return
  3254. }
  3255. id := int64(items["id"].(float64))
  3256. if items["patient_id"] == nil || reflect.TypeOf(items["patient_id"]).String() != "float64" {
  3257. utils.ErrorLog("patient_id")
  3258. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3259. return
  3260. }
  3261. patient_id := int64(items["patient_id"].(float64))
  3262. if items["creater"] == nil || reflect.TypeOf(items["creater"]).String() != "float64" {
  3263. utils.ErrorLog("creater")
  3264. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3265. return
  3266. }
  3267. creater := int64(items["creater"].(float64))
  3268. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3269. utils.ErrorLog("good_id")
  3270. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3271. return
  3272. }
  3273. good_id := int64(items["good_id"].(float64))
  3274. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3275. utils.ErrorLog("good_type_id")
  3276. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3277. return
  3278. }
  3279. good_type_id := int64(items["good_type_id"].(float64))
  3280. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3281. utils.ErrorLog("count")
  3282. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3283. return
  3284. }
  3285. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3286. if items["ctime"] == nil || reflect.TypeOf(items["ctime"]).String() != "float64" {
  3287. utils.ErrorLog("ctime")
  3288. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3289. return
  3290. }
  3291. ctime := int64(items["ctime"].(float64))
  3292. adminUser := c.GetMobileAdminUserInfo()
  3293. prepare := &models.DialysisBeforePrepare{
  3294. ID: id,
  3295. UserOrgId: adminUser.Org.Id,
  3296. PatientId: patient_id,
  3297. RecordDate: record_time,
  3298. GoodId: good_id,
  3299. GoodTypeId: good_type_id,
  3300. Count: count,
  3301. Ctime: ctime,
  3302. Mtime: time.Now().Unix(),
  3303. Creater: creater,
  3304. Modifier: adminUser.AdminUser.Id,
  3305. Status: 1,
  3306. }
  3307. beforePrepares = append(beforePrepares, prepare)
  3308. }
  3309. }
  3310. }
  3311. if dataBody["new_goods"] != nil && reflect.TypeOf(dataBody["new_goods"]).String() == "[]interface {}" {
  3312. goods, _ := dataBody["new_goods"].([]interface{})
  3313. if len(goods) > 0 {
  3314. for _, item := range goods {
  3315. items := item.(map[string]interface{})
  3316. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3317. utils.ErrorLog("good_id")
  3318. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3319. return
  3320. }
  3321. good_id := int64(items["good_id"].(float64))
  3322. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3323. utils.ErrorLog("good_type_id")
  3324. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3325. return
  3326. }
  3327. good_type_id := int64(items["good_type_id"].(float64))
  3328. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3329. utils.ErrorLog("count")
  3330. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3331. return
  3332. }
  3333. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3334. adminUser := c.GetMobileAdminUserInfo()
  3335. prepare := &models.DialysisBeforePrepare{
  3336. UserOrgId: adminUser.Org.Id,
  3337. PatientId: patient_id,
  3338. RecordDate: record_time,
  3339. GoodId: good_id,
  3340. GoodTypeId: good_type_id,
  3341. Count: count,
  3342. Ctime: time.Now().Unix(),
  3343. Mtime: time.Now().Unix(),
  3344. Creater: adminUser.AdminUser.Id,
  3345. Modifier: 0,
  3346. }
  3347. newBeforePrepares = append(newBeforePrepares, prepare)
  3348. }
  3349. }
  3350. service.CreateDialysisBeforePrepare(newBeforePrepares)
  3351. }
  3352. var errs error
  3353. if len(beforePrepares) > 0 {
  3354. for _, item := range beforePrepares {
  3355. errs = service.UpdateDialysisBeforePrepareTwo(item)
  3356. }
  3357. }
  3358. if errs == nil {
  3359. c.ServeSuccessJSON(map[string]interface{}{
  3360. "msg": "修改成功",
  3361. })
  3362. return
  3363. } else {
  3364. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3365. return
  3366. }
  3367. }
  3368. }
  3369. func (c *DialysisAPIController) GetDialysisGoods() {
  3370. schedualDate := c.GetString("schedule_date")
  3371. schedule_type, _ := c.GetInt64("schedule_type")
  3372. partition_id, _ := c.GetInt64("partition_id")
  3373. page, _ := c.GetInt("page")
  3374. patient_id, _ := c.GetInt64("patient_id")
  3375. schedualEndDate := int64(0)
  3376. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", schedualDate)
  3377. if parseDateErr != nil && len(schedualDate) != 0 {
  3378. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3379. return
  3380. }
  3381. endDate, parseDateErr := utils.ParseTimeStringToTime("2006-01-02 15:04:05", schedualDate+" 23:59:59")
  3382. if parseDateErr != nil && len(schedualDate) != 0 {
  3383. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3384. return
  3385. }
  3386. schedualEndDate = endDate.Unix()
  3387. adminUser := c.GetMobileAdminUserInfo()
  3388. _, err := service.FindStockOutByIsSys(adminUser.Org.Id, 1, date.Unix())
  3389. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  3390. if err == gorm.ErrRecordNotFound {
  3391. dialysisGoods, _, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3392. if patient_id != 0 {
  3393. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3394. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3395. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3396. item.LastAutomaticReduceDetail = goodUser
  3397. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3398. }
  3399. }
  3400. c.ServeSuccessJSON(map[string]interface{}{
  3401. "dialysis_goods": dialysisGoods,
  3402. "good_type": goodTypes,
  3403. "total": total,
  3404. })
  3405. return
  3406. } else if err == nil {
  3407. //获取当天排班的每个患者的库存使用情况
  3408. dialysisGoods, err, total := service.MobileGetDialysisGoods(adminUser.Org.Id, date.Unix(), schedule_type, partition_id, page, 0, patient_id, "", schedualEndDate)
  3409. if patient_id != 0 {
  3410. for _, item := range dialysisGoods { //获取当天排班的每个患者的最后日期的库存使用情况
  3411. goodUser, _ := service.GetLastDialysisGoods(item.PatientId, adminUser.Org.Id, date.Unix())
  3412. lastGoodUserDetial, _ := service.GetLastDialysisBeforePrepare(item.PatientId, adminUser.Org.Id, date.Unix())
  3413. fmt.Println(goodUser)
  3414. fmt.Println(lastGoodUserDetial)
  3415. item.LastAutomaticReduceDetail = goodUser
  3416. item.LastDialysisBeforePrepare = lastGoodUserDetial
  3417. }
  3418. }
  3419. if err == nil {
  3420. c.ServeSuccessJSON(map[string]interface{}{
  3421. "dialysis_goods": dialysisGoods,
  3422. "good_type": goodTypes,
  3423. "total": total,
  3424. })
  3425. return
  3426. } else {
  3427. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3428. return
  3429. }
  3430. } else if err != nil {
  3431. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3432. return
  3433. }
  3434. }
  3435. func (c *DialysisAPIController) GetDialysisGoodsStatistics() {
  3436. start_time := c.GetString("start_time")
  3437. end_time := c.GetString("end_time")
  3438. timeLayout := "2006-01-02"
  3439. loc, _ := time.LoadLocation("Local")
  3440. var theStartTime int64
  3441. if len(start_time) > 0 {
  3442. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_time+" 00:00:00", loc)
  3443. if err != nil {
  3444. utils.ErrorLog(err.Error())
  3445. }
  3446. theStartTime = theTime.Unix()
  3447. }
  3448. var theEndtTime int64
  3449. if len(end_time) > 0 {
  3450. theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_time+" 23:59:59", loc)
  3451. if err != nil {
  3452. utils.ErrorLog(err.Error())
  3453. }
  3454. theEndtTime = theTime.Unix()
  3455. }
  3456. adminUser := c.GetMobileAdminUserInfo()
  3457. outInfo, err := service.MobileGetGoodsStatistics(adminUser.Org.Id, theStartTime, theEndtTime)
  3458. if err == nil {
  3459. c.ServeSuccessJSON(map[string]interface{}{
  3460. "stock_out": outInfo,
  3461. })
  3462. return
  3463. } else {
  3464. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
  3465. return
  3466. }
  3467. }
  3468. func (c *DialysisAPIController) GetStockInGoodInfo() {
  3469. patient_id, _ := c.GetInt64("patient_id", 0)
  3470. record_time := c.GetString("record_time")
  3471. adminUser := c.GetMobileAdminUserInfo()
  3472. date, parseDateErr := utils.ParseTimeStringToTime("2006-01-02", record_time)
  3473. if parseDateErr != nil && len(record_time) != 0 {
  3474. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3475. return
  3476. }
  3477. goodTypes, _ := service.FindAllGoodType(adminUser.Org.Id)
  3478. good_info, _ := service.FindAllGoodInfo(adminUser.Org.Id)
  3479. goodUser, _ := service.GetAllStockOutUserDetail(patient_id, adminUser.Org.Id, date.Unix())
  3480. lastGoodUserDetial, _ := service.GetLastDialysisGoods(patient_id, adminUser.Org.Id, date.Unix())
  3481. c.ServeSuccessJSON(map[string]interface{}{
  3482. "good_type": goodTypes,
  3483. "good_user": goodUser,
  3484. "good_info": good_info,
  3485. "last_good_user": lastGoodUserDetial,
  3486. })
  3487. return
  3488. }
  3489. func (c *DialysisAPIController) CreateOtherStockOutInfo() {
  3490. patient_id, _ := c.GetInt64("patient_id", 0)
  3491. record_date := c.GetString("record_time")
  3492. if patient_id <= 0 {
  3493. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3494. return
  3495. }
  3496. adminInfo := c.GetMobileAdminUserInfo()
  3497. timeLayout := "2006-01-02"
  3498. loc, _ := time.LoadLocation("Local")
  3499. theRecordTime, _ := time.ParseInLocation(timeLayout, record_date, loc)
  3500. record_time := theRecordTime.Unix()
  3501. dataBody := make(map[string]interface{}, 0)
  3502. err := json.Unmarshal(c.Ctx.Input.RequestBody, &dataBody)
  3503. if err != nil {
  3504. utils.ErrorLog(err.Error())
  3505. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3506. return
  3507. }
  3508. var beforePrepares []*models.DialysisBeforePrepare
  3509. if dataBody["goods"] != nil && reflect.TypeOf(dataBody["goods"]).String() == "[]interface {}" {
  3510. goods, _ := dataBody["goods"].([]interface{})
  3511. if len(goods) > 0 {
  3512. for _, item := range goods {
  3513. items := item.(map[string]interface{})
  3514. if items["good_id"] == nil || reflect.TypeOf(items["good_id"]).String() != "float64" {
  3515. utils.ErrorLog("good_id")
  3516. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3517. return
  3518. }
  3519. good_id := int64(items["good_id"].(float64))
  3520. if items["good_type_id"] == nil || reflect.TypeOf(items["good_type_id"]).String() != "float64" {
  3521. utils.ErrorLog("good_type_id")
  3522. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3523. return
  3524. }
  3525. good_type_id := int64(items["good_type_id"].(float64))
  3526. if items["count"] == nil || reflect.TypeOf(items["count"]).String() != "string" {
  3527. utils.ErrorLog("count")
  3528. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
  3529. return
  3530. }
  3531. count, _ := strconv.ParseInt(items["count"].(string), 10, 64)
  3532. adminUser := c.GetMobileAdminUserInfo()
  3533. prepare := &models.DialysisBeforePrepare{
  3534. UserOrgId: adminUser.Org.Id,
  3535. PatientId: patient_id,
  3536. RecordDate: record_time,
  3537. GoodId: good_id,
  3538. GoodTypeId: good_type_id,
  3539. Count: count,
  3540. Ctime: time.Now().Unix(),
  3541. Mtime: time.Now().Unix(),
  3542. Creater: adminUser.AdminUser.Id,
  3543. Modifier: 0,
  3544. }
  3545. record_count := service.FindDialysisBeforePrepare(prepare.PatientId, prepare.GoodId, prepare.GoodTypeId, adminUser.Org.Id, record_time)
  3546. if record_count == 0 {
  3547. beforePrepares = append(beforePrepares, prepare)
  3548. } else if record_count == 1 {
  3549. service.UpdateDialysisBeforePrepareTwo(prepare)
  3550. }
  3551. }
  3552. }
  3553. }
  3554. beforePrepares = RemoveRepeatedGood(beforePrepares)
  3555. if len(beforePrepares) > 0 {
  3556. service.CreateDialysisBeforePrepare(beforePrepares)
  3557. }
  3558. consumables, _ := service.FindConsumablesByDate(adminInfo.Org.Id, patient_id, record_time)
  3559. consumables = RemoveRepeatedGood(consumables)
  3560. _, record := service.FindAutomaticReduceRecordByOrgId(adminInfo.Org.Id)
  3561. if record.IsOpen == 1 {
  3562. out, err := service.FindStockOutByIsSys(adminInfo.Org.Id, 1, record_time)
  3563. if err == gorm.ErrRecordNotFound {
  3564. //没有记录,则创建出库单
  3565. timeStr := time.Now().Format("2006-01-02")
  3566. timeArr := strings.Split(timeStr, "-")
  3567. total, _ := service.FindAllWarehouseOut(adminInfo.Org.Id)
  3568. total = total + 1
  3569. warehousing_out_order := strconv.FormatInt(adminInfo.Org.Id, 10) + timeArr[0] + timeArr[1] + timeArr[2] + "000"
  3570. number, _ := strconv.ParseInt(warehousing_out_order, 10, 64)
  3571. number = number + total
  3572. warehousing_out_order = "CKD" + strconv.FormatInt(number, 10)
  3573. creater := adminInfo.AdminUser.Id
  3574. warehouseOut := models.WarehouseOut{
  3575. WarehouseOutOrderNumber: warehousing_out_order,
  3576. OperationTime: time.Now().Unix(),
  3577. OrgId: adminInfo.Org.Id,
  3578. Creater: creater,
  3579. Ctime: time.Now().Unix(),
  3580. Status: 1,
  3581. WarehouseOutTime: record_time,
  3582. Dealer: 0,
  3583. Manufacturer: 0,
  3584. Type: 1,
  3585. IsSys: 1,
  3586. }
  3587. err := service.AddSigleWarehouseOut(&warehouseOut)
  3588. if err != nil {
  3589. utils.TraceLog("创建出库单失败 err = %v", err)
  3590. } else {
  3591. for _, item := range consumables {
  3592. if item.Count > 0 {
  3593. warehouseOutInfo := &models.WarehouseOutInfo{
  3594. WarehouseOutOrderNumber: warehouseOut.WarehouseOutOrderNumber,
  3595. WarehouseOutId: warehouseOut.ID,
  3596. Status: 1,
  3597. Ctime: time.Now().Unix(),
  3598. Remark: "",
  3599. OrgId: adminInfo.Org.Id,
  3600. Type: 1,
  3601. Manufacturer: 0,
  3602. Dealer: 0,
  3603. IsSys: 1,
  3604. SysRecordTime: record_time,
  3605. GoodTypeId: item.GoodTypeId,
  3606. GoodId: item.GoodId,
  3607. }
  3608. warehouseOutInfo.Count = item.Count
  3609. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3610. warehouseOutInfo.Price = stockInInfo.Price
  3611. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3612. if err == nil {
  3613. details := &models.AutomaticReduceDetail{
  3614. WarehouseOutId: warehouseOutInfo.ID,
  3615. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3616. PatientId: patient_id,
  3617. Ctime: time.Now().Unix(),
  3618. Mtime: time.Now().Unix(),
  3619. Status: 1,
  3620. RecordTime: record_time,
  3621. OrgId: adminInfo.Org.Id,
  3622. GoodId: item.GoodId,
  3623. GoodTypeId: item.GoodTypeId,
  3624. Count: item.Count,
  3625. }
  3626. service.AddSigleAutoReduceRecordInfo(details)
  3627. }
  3628. }
  3629. }
  3630. }
  3631. } else if err == nil {
  3632. for _, item := range consumables {
  3633. outInfo, err := service.FindStockOutInfoByTypeId(adminInfo.Org.Id, item.GoodTypeId, item.GoodId, out.ID, out.WarehouseOutOrderNumber)
  3634. if err == gorm.ErrRecordNotFound {
  3635. warehouseOutInfo := &models.WarehouseOutInfo{
  3636. WarehouseOutOrderNumber: out.WarehouseOutOrderNumber,
  3637. WarehouseOutId: out.ID,
  3638. Status: 1,
  3639. Ctime: time.Now().Unix(),
  3640. Remark: "",
  3641. OrgId: adminInfo.Org.Id,
  3642. Type: 1,
  3643. Manufacturer: 0,
  3644. Dealer: 0,
  3645. IsSys: 1,
  3646. SysRecordTime: record_time,
  3647. }
  3648. stockInInfo, _ := service.FindLastStockInInfoRecord(item.GoodId, adminInfo.Org.Id)
  3649. warehouseOutInfo.Price = stockInInfo.Price
  3650. warehouseOutInfo.GoodId = item.GoodId
  3651. warehouseOutInfo.GoodTypeId = item.GoodTypeId
  3652. warehouseOutInfo.Count = item.Count
  3653. err := service.AddSigleWarehouseOutInfo(warehouseOutInfo)
  3654. if err == nil {
  3655. details := &models.AutomaticReduceDetail{
  3656. WarehouseOutId: warehouseOutInfo.ID,
  3657. WarehouseOutOrderNumber: warehouseOutInfo.WarehouseOutOrderNumber,
  3658. PatientId: patient_id,
  3659. Ctime: time.Now().Unix(),
  3660. Mtime: time.Now().Unix(),
  3661. Status: 1,
  3662. RecordTime: record_time,
  3663. OrgId: adminInfo.Org.Id,
  3664. GoodId: item.GoodId,
  3665. GoodTypeId: item.GoodTypeId,
  3666. Count: item.Count,
  3667. }
  3668. service.AddSigleAutoReduceRecordInfo(details)
  3669. }
  3670. } else if err == nil { //记录存在,则将增加数量
  3671. if outInfo.ID > 0 {
  3672. service.UpdateStockOutInfoCount2(adminInfo.Org.Id, outInfo.ID, item.Count)
  3673. }
  3674. details := &models.AutomaticReduceDetail{
  3675. WarehouseOutId: outInfo.ID,
  3676. WarehouseOutOrderNumber: outInfo.WarehouseOutOrderNumber,
  3677. PatientId: patient_id,
  3678. Ctime: time.Now().Unix(),
  3679. Mtime: time.Now().Unix(),
  3680. Status: 1,
  3681. RecordTime: record_time,
  3682. OrgId: adminInfo.Org.Id,
  3683. GoodId: item.GoodId,
  3684. GoodTypeId: item.GoodTypeId,
  3685. Count: item.Count,
  3686. }
  3687. service.AddSigleAutoReduceRecordInfo(details)
  3688. }
  3689. }
  3690. }
  3691. c.ServeSuccessJSON(map[string]interface{}{
  3692. "msg": "提交成功",
  3693. })
  3694. return
  3695. } else {
  3696. c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeOpenStocktWrong)
  3697. return
  3698. }
  3699. }
  3700. func RemoveRepeatedGood(arr []*models.DialysisBeforePrepare) (newArr []*models.DialysisBeforePrepare) {
  3701. newArr = make([]*models.DialysisBeforePrepare, 0)
  3702. for i := 0; i < len(arr); i++ {
  3703. repeat := false
  3704. for j := i + 1; j < len(arr); j++ {
  3705. if arr[i].GoodId == arr[j].GoodId && arr[i].GoodTypeId == arr[j].GoodTypeId {
  3706. repeat = true
  3707. break
  3708. }
  3709. }
  3710. if !repeat {
  3711. newArr = append(newArr, arr[i])
  3712. }
  3713. }
  3714. return
  3715. }