patient_service.go 63KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. package service
  2. import (
  3. "Xcx_New/models"
  4. "strconv"
  5. "strings"
  6. "time"
  7. "fmt"
  8. "github.com/jinzhu/gorm"
  9. )
  10. //GetPatientList 返回患者的列表
  11. func GetPatientList(orgID int64, keywords string, page, limit, schedulType, bindingState, lapseto, source, startTime, endTime, contagion, reimbursementWay, isscheduling, isprescription int64, isStartTime, isEndTime bool) (patients []*models.Patients, total int64, err error) {
  12. db := readDb.Table("xt_patients as p").Where("p.status=1")
  13. if orgID > 0 {
  14. db = db.Where("p.user_org_id=?", orgID)
  15. }
  16. if len(keywords) > 0 {
  17. likeKey := "%" + keywords + "%"
  18. db = db.Where("p.name LIKE ? OR p.dialysis_no LIKE ?", likeKey, likeKey)
  19. }
  20. if schedulType > 0 {
  21. db = db.Joins("JOIN xt_schedule as s ON s.patient_id=p.id")
  22. db = db.Where("s.status=1 and s.schedule_type=?", schedulType)
  23. }
  24. if contagion > 0 {
  25. db = db.Joins("JOIN xt_patients_infectious_diseases as xpid ON xpid.patient_id=p.id")
  26. db = db.Where("xpid.disease_id=? and xpid.status=1", contagion)
  27. }
  28. if isscheduling == 1 {
  29. db = db.Where("EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.status=1").QueryExpr())
  30. } else if isscheduling == 2 {
  31. db = db.Where("NOT EXISTS (?)", readDb.Table("xt_schedule as iss").Where("iss.patient_id=p.id and iss.status=1").QueryExpr())
  32. }
  33. if isprescription == 1 {
  34. db = db.Where("EXISTS (?)", readDb.Table("xt_dialysis_prescription as xdp").Where("xdp.patient_id=p.id and xdp.status=1").QueryExpr())
  35. } else if isprescription == 2 {
  36. db = db.Where("NOT EXISTS (?)", readDb.Table("xt_dialysis_prescription as xdp").Where("xdp.patient_id=p.id and xdp.status=1").QueryExpr())
  37. }
  38. if bindingState > 0 {
  39. db = db.Where("p.binding_state=?", bindingState)
  40. }
  41. if lapseto > 0 {
  42. db = db.Where("p.lapseto=?", lapseto)
  43. }
  44. if source > 0 {
  45. db = db.Where("p.source=?", source)
  46. }
  47. if reimbursementWay > 0 {
  48. db = db.Where("p.reimbursement_way_id = ?", reimbursementWay)
  49. }
  50. if isStartTime {
  51. db = db.Where("p.created_time>=?", startTime)
  52. }
  53. if isEndTime {
  54. db = db.Where("p.created_time<=?", endTime)
  55. }
  56. offset := (page - 1) * limit
  57. err = db.Order("p.id desc").Select(" p.id, p.user_org_id, p.user_id, p.patient_type, p.dialysis_no, p.admission_number, p.source, p.lapseto, p.partition_id, p.bed_id, p.name, p.alias, p.gender, p.marital_status, p.id_card_no, p.birthday, p.reimbursement_way_id, p.health_care_type, p.health_care_no, p.health_care_due_date, p.height, p.blood_type, p.rh, p.health_care_due_alert_date, p.education_level, p.profession, p.phone, p.home_telephone, p.relative_phone, p.relative_relations, p.home_address, p.work_unit, p.unit_address, p.children, p.receiving_date, p.is_hospital_first_dialysis, p.first_dialysis_date, p.first_dialysis_hospital, p.induction_period, p.initial_dialysis, p.total_dialysis, p.attending_doctor_id, p.head_nurse_id, p.evaluate, p.diagnose, p.remark, p.registrars_id, p.registrars, p.qr_code, p.binding_state, p.status, p.created_time, p.updated_time,p.user_sys_before_count,p.out_reason,p.death_time").Group("p.id").Count(&total).Offset(offset).Limit(limit).Find(&patients).Error
  58. return
  59. }
  60. //GetAllPatientList 返回全部患者的列表
  61. func GetAllPatientList(orgID int64) (patients []*models.Patients, total int64, err error) {
  62. db := readDb.Table("xt_patients as p").Where("p.user_org_id=? and p.status=1 and p.lapseto = 1", orgID)
  63. err = db.Select(" p.id, p.user_org_id, p.user_id, p.patient_type, p.dialysis_no, p.admission_number, p.source, p.lapseto, p.partition_id, p.bed_id, p.name, p.alias, p.gender, p.marital_status, p.id_card_no, p.birthday, p.reimbursement_way_id, p.health_care_type, p.health_care_no, p.health_care_due_date, p.height, p.blood_type, p.rh, p.health_care_due_alert_date, p.education_level, p.profession, p.phone, p.home_telephone, p.relative_phone, p.relative_relations, p.home_address, p.work_unit, p.unit_address, p.children, p.receiving_date, p.is_hospital_first_dialysis, p.first_dialysis_date, p.first_dialysis_hospital, p.induction_period, p.initial_dialysis, p.total_dialysis, p.attending_doctor_id, p.head_nurse_id, p.evaluate, p.diagnose, p.remark, p.registrars_id, p.registrars, p.qr_code, p.binding_state, p.status, p.created_time, p.updated_time").Count(&total).Find(&patients).Error
  64. return
  65. }
  66. func GetPatientListByUpdateTime(orgID int64, syncTime int64) (patients []*models.PatientListForFaceList, total int64, err error) {
  67. db := readDb.Model(&models.PatientListForFaceList{}).Where("user_org_id=? AND status=1 AND avatar <> 'https://images.shengws.com/201809182128222.png' AND avatar <> 'https://images.shengws.com/201809182128111.png' AND avatar <> ''", orgID)
  68. db = db.Where("updated_time >= ?", syncTime)
  69. err = db.Count(&total).Find(&patients).Error
  70. return
  71. }
  72. func GetPatientListBySchedules(orgID int64, syncTime int64) (patients []*models.SchedulePatients, total int64, err error) {
  73. db := readDb.Model(&models.SchedulePatients{}).Where("user_org_id=? AND status=1 AND schedule_date = ?", orgID, syncTime).Preload("Patient", "status = 1 AND user_org_id = ? ", orgID)
  74. err = db.Count(&total).Find(&patients).Error
  75. return
  76. }
  77. func GetPatientListBySchedulesFind(orgID int64, syncTime int64, patient_name string) (patients []*models.SchedulePatients, total int64, err error) {
  78. db := readDb.Model(&models.SchedulePatients{}).Where("user_org_id=? AND status=1 AND schedule_date = ?", orgID, syncTime).Preload("Patient", "status = 1 AND user_org_id = ? and name like ? ", orgID, "%"+patient_name+"%")
  79. err = db.Count(&total).Find(&patients).Error
  80. return
  81. }
  82. func GetPatientListById(orgID int64, patientId int64) (patients models.PatientListForFace, err error) {
  83. err = readDb.Model(&models.PatientListForFaceList{}).Where("user_org_id=? and id = ? and status=1", orgID, patientId).First(&patients).Error
  84. return
  85. }
  86. func GetPatientCount(orgID int64) (total int64) {
  87. readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1", orgID).Count(&total)
  88. return
  89. }
  90. func GetLapsetoPatientCount(orgID int64, lapseto int64) (total int64) {
  91. readDb.Model(&models.Patients{}).Where("user_org_id=? and lapseto=? and status=1", orgID, lapseto).Count(&total)
  92. return
  93. }
  94. func ChechLastDialysisNo(orgID int64) (dialysisNo int64) {
  95. var patient models.Patients
  96. err := readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=?", orgID).Order("dialysis_no desc").First(&patient).Error
  97. if err != nil {
  98. return
  99. }
  100. if patient.ID == 0 {
  101. return
  102. }
  103. dialysisNo, _ = strconv.ParseInt(patient.DialysisNo, 10, 64)
  104. return
  105. }
  106. func FindPatientByDialysisNo(orgID int64, dialysisNo string) (patient models.Patients, err error) {
  107. err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and dialysis_no=?", orgID, dialysisNo).First(&patient).Error
  108. return
  109. }
  110. func FindPatientByIdCardNo(orgID int64, idCardNo string) (patient models.Patients, err error) {
  111. err = readDb.Model(&models.Patients{}).Where("status=1 and user_org_id=? and id_card_no=?", orgID, idCardNo).First(&patient).Error
  112. return
  113. }
  114. func FindPatientByMobile(orgID int64, mobile string) (patient models.Patients, err error) {
  115. err = readDb.Model(&models.Patients{}).Where("phone=? and user_org_id=? and status=1", mobile, orgID).First(&patient).Error
  116. return
  117. }
  118. func FindPatientById(orgID int64, id int64) (patient models.Patients, err error) {
  119. err = readDb.Model(&models.Patients{}).Where("id = ? and user_org_id=? and status=1", id, orgID).First(&patient).Error
  120. return
  121. }
  122. func FindPatientByIdTwo(orgID int64, id int64) (patient models.XtPatientsNew, err error) {
  123. err = readDb.Model(&models.XtPatientsNew{}).Where("blood_id = ? and user_org_id = ? and status =1", id, orgID).First(&patient).Error
  124. return
  125. }
  126. func FindPatientByIdWithDiseases(orgID int64, id int64) (patient models.Patients, err error) {
  127. err = readDb.Model(&models.Patients{}).Preload("Contagions", "status = 1").Preload("Diseases", "status = 1").Where("id = ? and user_org_id=? and status=1", id, orgID).First(&patient).Error
  128. return
  129. }
  130. func FindPatientWithDeviceByNo(orgID int64, no string, time int64) (patient models.SchedualPatient2, err error) {
  131. err = readDb.Preload("DialysisSchedule", func(db *gorm.DB) *gorm.DB {
  132. return db.Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
  133. Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
  134. Where("user_org_id = ? AND schedule_date = ? ", orgID, time)
  135. }).Preload("InfectiousDiseases", "status = 1").Where("user_org_id=? and dialysis_no = ? and status=1", orgID, no).First(&patient).Error
  136. return
  137. }
  138. func CreatePatient(patient *models.Patients, contagions []int64, diseases []int64) (err error) {
  139. user, _ := GetSgjUserByMobild(patient.Phone)
  140. customer, _ := GetSgjCoustomerByMobile(patient.UserOrgId, patient.Phone)
  141. utx := writeDb.Begin()
  142. btx := writeUserDb.Begin()
  143. if user.ID == 0 {
  144. user.Mobile = patient.Phone
  145. user.Avatar = patient.Avatar
  146. user.AvatarThumb = patient.Avatar
  147. user.Birthday = patient.Birthday
  148. user.Username = patient.Name
  149. user.Gender = patient.Gender
  150. user.Sources = 11
  151. user.Introduce = patient.Remark
  152. user.Status = 1
  153. user.UpdatedTime = patient.UpdatedTime
  154. user.CreatedTime = patient.CreatedTime
  155. err = btx.Create(&user).Error
  156. if err != nil {
  157. utx.Rollback()
  158. btx.Rollback()
  159. return
  160. }
  161. }
  162. patient.UserId = user.ID
  163. if customer == nil {
  164. err = btx.Create(&models.SgjCustomer{
  165. UserOrgId: patient.UserOrgId,
  166. UserId: user.ID,
  167. Mobile: patient.Phone,
  168. Name: patient.Name,
  169. Gender: patient.Gender,
  170. Birthday: patient.Birthday,
  171. Sources: 11,
  172. Status: 1,
  173. CreatedTime: patient.CreatedTime,
  174. UpdatedTime: patient.UpdatedTime,
  175. Avatar: patient.Avatar,
  176. Remark: patient.Remark,
  177. }).Error
  178. if err != nil {
  179. utx.Rollback()
  180. btx.Rollback()
  181. return
  182. }
  183. }
  184. err = utx.Create(patient).Error
  185. if err != nil {
  186. utx.Rollback()
  187. btx.Rollback()
  188. return
  189. }
  190. var lapseto models.PatientLapseto
  191. lapseto.PatientId = patient.ID
  192. lapseto.LapsetoType = patient.Lapseto
  193. lapseto.CreatedTime = patient.CreatedTime
  194. lapseto.UpdatedTime = patient.CreatedTime
  195. lapseto.Status = 1
  196. lapseto.LapsetoTime = patient.CreatedTime
  197. err = utx.Create(&lapseto).Error
  198. if err != nil {
  199. utx.Rollback()
  200. btx.Rollback()
  201. return
  202. }
  203. if len(contagions) > 0 {
  204. thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  205. insertParams := make([]string, 0)
  206. insertData := make([]interface{}, 0)
  207. for _, contagion := range contagions {
  208. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  209. insertData = append(insertData, patient.ID)
  210. insertData = append(insertData, contagion)
  211. insertData = append(insertData, 1)
  212. insertData = append(insertData, patient.CreatedTime)
  213. insertData = append(insertData, patient.UpdatedTime)
  214. }
  215. thisSQL += strings.Join(insertParams, ", ")
  216. err = utx.Exec(thisSQL, insertData...).Error
  217. if err != nil {
  218. utx.Rollback()
  219. btx.Rollback()
  220. return
  221. }
  222. }
  223. if len(diseases) > 0 {
  224. thisSQL := "INSERT INTO xt_patients_chronic_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  225. insertParams := make([]string, 0)
  226. insertData := make([]interface{}, 0)
  227. for _, disease := range diseases {
  228. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  229. insertData = append(insertData, patient.ID)
  230. insertData = append(insertData, disease)
  231. insertData = append(insertData, 1)
  232. insertData = append(insertData, patient.CreatedTime)
  233. insertData = append(insertData, patient.UpdatedTime)
  234. }
  235. thisSQL += strings.Join(insertParams, ", ")
  236. err = utx.Exec(thisSQL, insertData...).Error
  237. if err != nil {
  238. utx.Rollback()
  239. btx.Rollback()
  240. return
  241. }
  242. }
  243. utx.Commit()
  244. btx.Commit()
  245. return
  246. }
  247. func GetLastPatientData(orgid int64) (models.Patients, error) {
  248. patients := models.Patients{}
  249. err := XTReadDB().Model(&patients).Where("user_org_id = ? and status = 1", orgid).Last(&patients).Error
  250. return patients, err
  251. }
  252. func CreatePatientsNew(patientsNew *models.XtPatientsNew) error {
  253. err := XTWriteDB().Model(&patientsNew).Create(&patientsNew).Error
  254. return err
  255. }
  256. func EditPatientLapseto(patient *models.Patients, lapseto *models.PatientLapseto) (err error) {
  257. utx := writeDb.Begin()
  258. err = utx.Model(&models.Patients{}).Where("id=?", patient.ID).Update(map[string]interface{}{"lapseto": patient.Lapseto, "out_reason": patient.OutReason, "death_time": patient.DeathTime}).Error
  259. //err = utx.Model(&models.PatientLapseto{}).Where("id=?", patient.ID).Update(map[string]interface{}{"lapseto_type": patient.Lapseto, "lapseto_time": time.Now().Unix(), "updated_time": time.Now().Unix()}).Error
  260. if err != nil {
  261. utx.Rollback()
  262. return
  263. }
  264. err = utx.Create(lapseto).Error
  265. if err != nil {
  266. utx.Rollback()
  267. return
  268. }
  269. // 删除排班和排班模板信息
  270. if lapseto.LapsetoType == 2 {
  271. now := time.Now()
  272. deleteScheduleErr := utx.Model(&models.PatientSchedule{}).Where("patient_id = ? AND schedule_date >= ? AND status = 1", patient.ID, lapseto.LapsetoTime).Updates(map[string]interface{}{
  273. "status": 0,
  274. "updated_time": now.Unix(),
  275. }).Error
  276. if deleteScheduleErr != nil {
  277. utx.Rollback()
  278. err = deleteScheduleErr
  279. return
  280. }
  281. deleteSchTempItemErr := utx.Model(&models.PatientScheduleTemplateItem{}).Where("patient_id = ? AND status = 1", patient.ID).Updates(map[string]interface{}{
  282. "status": 0,
  283. "mtime": now.Unix(),
  284. }).Error
  285. if deleteSchTempItemErr != nil {
  286. utx.Rollback()
  287. err = deleteSchTempItemErr
  288. return
  289. }
  290. }
  291. utx.Commit()
  292. return
  293. }
  294. func UpdatePatient(patient *models.Patients, contagions []int64, diseases []int64) (err error) {
  295. // if len(contagions) > 0 || len(diseases) > 0 {
  296. utx := writeDb.Begin()
  297. err = utx.Save(patient).Error
  298. if err != nil {
  299. utx.Rollback()
  300. return
  301. }
  302. err = utx.Model(&models.InfectiousDiseases{}).Where("patient_id=?", patient.ID).Update(map[string]interface{}{"Status": 2, "UpdatedTime": patient.UpdatedTime}).Error
  303. fmt.Println("err", err)
  304. if err != nil {
  305. utx.Rollback()
  306. return
  307. }
  308. if len(contagions) > 0 && patient.IsInfectious == 2 {
  309. thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  310. insertParams := make([]string, 0)
  311. insertData := make([]interface{}, 0)
  312. for _, contagion := range contagions {
  313. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  314. insertData = append(insertData, patient.ID)
  315. insertData = append(insertData, contagion)
  316. insertData = append(insertData, 1)
  317. insertData = append(insertData, time.Now().Unix())
  318. insertData = append(insertData, time.Now().Unix())
  319. }
  320. thisSQL += strings.Join(insertParams, ", ")
  321. err = utx.Exec(thisSQL, insertData...).Error
  322. if err != nil {
  323. utx.Rollback()
  324. return
  325. }
  326. }
  327. err = utx.Model(&models.ChronicDiseases{}).Where("patient_id=?", patient.ID).Update(map[string]interface{}{"Status": 2, "UpdatedTime": patient.UpdatedTime}).Error
  328. if err != nil {
  329. utx.Rollback()
  330. return
  331. }
  332. if len(diseases) > 0 {
  333. thisSQL := "INSERT INTO xt_patients_chronic_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  334. insertParams := make([]string, 0)
  335. insertData := make([]interface{}, 0)
  336. for _, disease := range diseases {
  337. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  338. insertData = append(insertData, patient.ID)
  339. insertData = append(insertData, disease)
  340. insertData = append(insertData, 1)
  341. insertData = append(insertData, time.Now().Unix())
  342. insertData = append(insertData, time.Now().Unix())
  343. }
  344. thisSQL += strings.Join(insertParams, ", ")
  345. err = utx.Exec(thisSQL, insertData...).Error
  346. if err != nil {
  347. utx.Rollback()
  348. return
  349. }
  350. }
  351. utx.Commit()
  352. // } else {
  353. // err = writeDb.Save(patient).Error
  354. // }
  355. return
  356. }
  357. func UpdatePatientLapseto(patientid int64, lapseto models.PatientLapseto) error {
  358. err := XTWriteDB().Model(&lapseto).Where("patient_id = ?", patientid).Updates(map[string]interface{}{"lapseto_type": lapseto.LapsetoType, "lapseto_time": time.Now().Unix(), "updated_time": time.Now().Unix()}).Error
  359. return err
  360. }
  361. func UpdatepatientTwo(patientsNew *models.XtPatientsNew, id int64) error {
  362. err := XTWriteDB().Model(&patientsNew).Where("blood_id = ?", id).Update(map[string]interface{}{"user_org_id": patientsNew.UserOrgId, "user_id": patientsNew.UserId, "avatar": patientsNew.Avatar, "patient_type": patientsNew.Avatar, "dialysis_no": patientsNew.DialysisNo, "admission_number": patientsNew.AdmissionNumber, "source": patientsNew.Source, "lapseto": patientsNew.Lapseto, "partition_id": patientsNew.PartitionId, "bed_id": patientsNew.BedId, "name": patientsNew.Name, "alias": patientsNew.Alias, "gender": patientsNew.Gender, "marital_status": patientsNew.MaritalStatus, "id_card_no": patientsNew.IdCardNo, "birthday": patientsNew.Birthday, "reimbursement_way_id": patientsNew.ReimbursementWayId, "health_care_type": patientsNew.HealthCareType, "health_care_no": patientsNew.HealthCareType, "health_care_due_date": patientsNew.HealthCareType, "height": patientsNew.Height, "blood_type": patientsNew.BloodType, "rh": patientsNew.Rh, "health_care_due_alert_date": patientsNew.HealthCareDueAlertDate, "education_level": patientsNew.EducationLevel, "profession": patientsNew.Profession, "phone": patientsNew.Phone, "home_telephone": patientsNew.HomeTelephone, "relative_phone": patientsNew.RelativePhone, "relative_relations": patientsNew.RelativeRelations, "home_address": patientsNew.HomeAddress, "work_unit": patientsNew.WorkUnit, "unit_address": patientsNew.UnitAddress, "children": patientsNew.Children, "receiving_date": patientsNew.ReceivingDate, "is_hospital_first_dialysis": patientsNew.IsHospitalFirstDialysis, "first_dialysis_date": patientsNew.FirstDialysisDate, "first_dialysis_hospital": patientsNew.FirstDialysisHospital, "predialysis_condition": patientsNew.PredialysisCondition, "pre_hospital_dialysis_frequency": patientsNew.PreHospitalDialysisFrequency, "pre_hospital_dialysis_times": patientsNew.PreHospitalDialysisFrequency, "hospital_first_dialysis_date": patientsNew.HospitalFirstDialysisDate, "induction_period": patientsNew.InductionPeriod, "initial_dialysis": patientsNew.InitialDialysis, "total_dialysis": patientsNew.TotalDialysis, "attending_doctor_id": patientsNew.AttendingDoctorId, "head_nurse_id": patientsNew.HeadNurseId, "evaluate": patientsNew.Evaluate, "diagnose": patientsNew.Diagnose, "remark": patientsNew.Remark, "registrars_id": patientsNew.RegistrarsId, "registrars": patientsNew.Registrars, "qr_code": patientsNew.QrCode, "binding_state": patientsNew.BindingState, "patient_complains": patientsNew.PatientComplains, "present_history": patientsNew.PresentHistory, "past_history": patientsNew.PastHistory, "temperature": patientsNew.Temperature,
  363. "pulse": patientsNew.Pulse, "respiratory": patientsNew.Respiratory, "sbp": patientsNew.Sbp, "dbp": patientsNew.Dbp, "nation": patientsNew.Nation, "native_place": patientsNew.NativePlace, "age": patientsNew.Age, "infectious_next_record_time": patientsNew.InfectiousNextRecordTime, "is_infectious": patientsNew.IsInfectious, "remind_cycle": patientsNew.RemindCycle, "response_result": patientsNew.ResponseResult, "is_open_remind": patientsNew.IsOpenRemind, "first_treatment_date": patientsNew.FirstTreatmentDate, "dialysis_age": patientsNew.DialysisAge, "expense_kind": patientsNew.ExpenseKind, "tell_phone": patientsNew.ExpenseKind, "contact_name": patientsNew.ContactName, "blood_patients": patientsNew.BloodPatients, "slow_patients": patientsNew.SlowPatients, "member_patients": patientsNew.MemberPatients, "ecommer_patients": patientsNew.EcommerPatients}).Error
  364. return err
  365. }
  366. func GetLastInfectionRecord(id int64, org_id int64, project_id int64, date int64) (inspection models.Inspection, err error) {
  367. err = readDb.Model(&models.Inspection{}).Where("patient_id=? and status=1 and org_id = ? and project_id = ? AND inspect_date = ? ", id, org_id, project_id, date).Last(&inspection).Error
  368. return
  369. }
  370. func GetAllInfectionRecord(date int64, org_id int64, patient_id int64, project_id int64) (inspection []*models.Inspection, err error) {
  371. err = readDb.Model(&models.Inspection{}).Where("patient_id=? and status=1 and org_id = ? and project_id = ? and inspect_date = ?", patient_id, org_id, project_id, date).Find(&inspection).Error
  372. return
  373. }
  374. func GetPatientDiseases(id int64) []int64 {
  375. var dis []models.ChronicDiseases
  376. ids := make([]int64, 0)
  377. err := readDb.Model(&models.ChronicDiseases{}).Where("patient_id=? and status=1", id).Find(&dis).Error
  378. if err != nil || len(dis) == 0 {
  379. return ids
  380. }
  381. for _, item := range dis {
  382. ids = append(ids, item.DiseaseId)
  383. }
  384. return ids
  385. }
  386. func GetPatientContagions(id int64) []int64 {
  387. var cis []models.InfectiousDiseases
  388. ids := make([]int64, 0)
  389. err := readDb.Model(&models.InfectiousDiseases{}).Where("patient_id=? and status=1", id).Find(&cis).Error
  390. if err != nil || len(cis) == 0 {
  391. return ids
  392. }
  393. for _, item := range cis {
  394. ids = append(ids, item.DiseaseId)
  395. }
  396. return ids
  397. }
  398. func FindPatientDialysisSolutionByMode(orgID int64, patientID, modeId int64) (solution models.DialysisSolution, err error) {
  399. err = readDb.Model(&models.DialysisSolution{}).Where("user_org_id=? and patient_id=? and mode_id=? and parent_id=0 and status=1", orgID, patientID, modeId).First(&solution).Error
  400. return
  401. }
  402. func FindPatientDialysisSolution(orgID int64, id int64) (solution models.DialysisSolution, err error) {
  403. err = readDb.Model(&models.DialysisSolution{}).Where("id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
  404. return
  405. }
  406. func FindPatientDialysisSolutionChild(orgID int64, id int64) (solution models.DialysisSolution, err error) {
  407. err = readDb.Model(&models.DialysisSolution{}).Where("parent_id = ? and status=1 and user_org_id=?", id, orgID).First(&solution).Error
  408. return
  409. }
  410. func CreatePatientDialysisSolution(solution *models.DialysisSolution) (err error) {
  411. err = writeDb.Create(solution).Error
  412. return
  413. }
  414. func UpdatePatientDialysisSolution(solution *models.DialysisSolution) (err error) {
  415. err = writeDb.Save(solution).Error
  416. return
  417. }
  418. //GetPatientDialysisSolutionList 返回患者透析方案的列表
  419. func GetPatientDialysisSolutionList(orgID int64, patientID int64, page, limit int64) (solutions []*models.DialysisSolution, total int64, err error) {
  420. offset := (page - 1) * limit
  421. db := readDb.Table("xt_dialysis_solution as ds").Where("ds.status=1")
  422. if orgID > 0 {
  423. db = db.Where("ds.user_org_id=?", orgID)
  424. }
  425. if patientID > 0 {
  426. db = db.Where("ds.patient_id=?", patientID)
  427. }
  428. db = db.Count(&total).Offset(offset).Limit(limit)
  429. err = db.Order("id desc").Find(&solutions).Error
  430. if err != nil {
  431. return
  432. }
  433. if len(solutions) > 0 {
  434. nilNameIds := make([]int64, 0)
  435. for _, solution := range solutions {
  436. if len(solution.ModeName) == 0 {
  437. nilNameIds = append(nilNameIds, solution.ModeId)
  438. }
  439. }
  440. if len(nilNameIds) > 0 {
  441. var modes []*models.TreatmentMode
  442. err = readDb.Model(&models.TreatmentMode{}).Where("id IN (?)", nilNameIds).Find(&modes).Error
  443. if err != nil {
  444. return
  445. }
  446. modesMap := make(map[int64]models.TreatmentMode, 0)
  447. for _, mode := range modes {
  448. modesMap[mode.ID] = *mode
  449. }
  450. for index, solution := range solutions {
  451. if _, exixt := modesMap[solution.ModeId]; exixt && len(solution.ModeName) == 0 {
  452. solutions[index].ModeName = modesMap[solution.ModeId].Name
  453. }
  454. }
  455. }
  456. }
  457. return
  458. }
  459. //GetPatientDryWeightAdjustList 返回患者调整干体重的列表
  460. func GetPatientDryWeightAdjustList(orgID int64, patientID int64, page int64, limit int64) (weights []*models.DryWeightAdjust, total int64, err error) {
  461. db := readDb.Table("xt_dry_weight_adjust as dwa").Where("dwa.status=1")
  462. if orgID > 0 {
  463. db = db.Where("dwa.user_org_id=?", orgID)
  464. }
  465. if patientID > 0 {
  466. db = db.Where("dwa.patient_id=?", patientID)
  467. }
  468. db = db.Select("dwa.id, dwa.user_org_id, dwa.patient_id, dwa.weight, dwa.adjusted_value, dwa.doctor, dwa.registrars_id, dwa.remark, dwa.status, dwa.created_time, dwa.updated_time").Count(&total).Order("id desc")
  469. if page > 0 && limit > 0 {
  470. offset := (page - 1) * limit
  471. db = db.Offset(offset).Limit(limit)
  472. }
  473. err = db.Find(&weights).Error
  474. return
  475. }
  476. func CreateDryWeightAdjust(m *models.DryWeightAdjust) (err error) {
  477. err = writeDb.Create(m).Error
  478. return
  479. }
  480. func FindPatientLastDryWeightAdjust(orgID int64, id int64) (weight models.DryWeightAdjust, err error) {
  481. err = readDb.Model(&models.DryWeightAdjust{}).Where("user_org_id=? and patient_id=? and status=1", orgID, id).Order("id desc").First(&weight).Error
  482. return
  483. }
  484. func CreateDoctorAdvice(m *models.DoctorAdvice) (err error) {
  485. return writeDb.Create(m).Error
  486. }
  487. func GetMaxAdviceGroupID(orgId int64) (group int64) {
  488. var advice models.DoctorAdvice
  489. err := readDb.Table("xt_doctor_advice").Where("user_org_id=?", orgId).Select("max(groupno) as groupno").First(&advice).Error
  490. if err != nil {
  491. fmt.Println(err)
  492. group = 0
  493. }
  494. group = advice.GroupNo
  495. return
  496. }
  497. func CreateGroupAdvice(orgId int64, group int64, advices []*models.GroupAdvice) (err error) {
  498. if group == 0 {
  499. group = GetMaxAdviceGroupID(orgId) + 1
  500. }
  501. tx := writeDb.Begin()
  502. defer func() {
  503. if r := recover(); r != nil {
  504. tx.Rollback()
  505. }
  506. }()
  507. for _, advice := range advices {
  508. advice.GroupNo = group
  509. if err = tx.Create(advice).Error; err != nil {
  510. tx.Rollback()
  511. return
  512. }
  513. }
  514. tx.Commit()
  515. return
  516. }
  517. func CreateMGroupAdvice(orgId int64, advices []*models.GroupAdvice, groupNo int64) (list []*models.GroupAdvice, err error) {
  518. if groupNo <= 0 {
  519. group := GetMaxAdviceGroupID(orgId)
  520. groupNo = group + 1
  521. }
  522. tx := writeDb.Begin()
  523. defer func() {
  524. if r := recover(); r != nil {
  525. tx.Rollback()
  526. }
  527. }()
  528. for _, advice := range advices {
  529. advice.GroupNo = groupNo
  530. if err = tx.Create(advice).Error; err != nil {
  531. tx.Rollback()
  532. return
  533. }
  534. list = append(list, advice)
  535. if len(advice.Children) > 0 {
  536. for _, child := range advice.Children {
  537. child.GroupNo = groupNo
  538. child.ParentId = advice.ID
  539. fmt.Println(child)
  540. if err = tx.Create(&child).Error; err != nil {
  541. tx.Rollback()
  542. return
  543. }
  544. list = append(list, child)
  545. }
  546. }
  547. }
  548. tx.Commit()
  549. return
  550. }
  551. func UpdateDoctorAdvice(m *models.DoctorAdvice) (err error) {
  552. return writeDb.Save(m).Error
  553. }
  554. func StopGroupAdvice(orgId int64, groupNo int64, m *models.DoctorAdvice) (err error) {
  555. err = writeDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? and groupno=?", orgId, groupNo).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "StopState": 1, "StopReason": m.StopReason, "StopDoctor": m.StopDoctor, "StopTime": m.StopTime}).Error
  556. if err != nil {
  557. return
  558. }
  559. return
  560. }
  561. func StopDoctorAdvice(m *models.DoctorAdvice) (err error) {
  562. ut := writeDb.Begin()
  563. err = ut.Save(m).Error
  564. if err != nil {
  565. ut.Rollback()
  566. return
  567. }
  568. err = ut.Model(&models.DoctorAdvice{}).Where("parent_id=?", m.ID).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "StopState": 1, "StopReason": m.StopReason, "StopDoctor": m.StopDoctor, "StopTime": m.StopTime, "Modifier": m.Modifier}).Error
  569. if err != nil {
  570. ut.Rollback()
  571. return
  572. }
  573. ut.Commit()
  574. return
  575. }
  576. func DeleteSolution(m *models.DialysisSolution) (err error) {
  577. if m.ParentId > 0 {
  578. return writeDb.Save(m).Error
  579. } else {
  580. ut := writeDb.Begin()
  581. err = ut.Save(m).Error
  582. if err != nil {
  583. ut.Rollback()
  584. return
  585. }
  586. err = ut.Model(&models.DialysisSolution{}).Where("parent_id=?", m.ID).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "Status": 0}).Error
  587. if err != nil {
  588. ut.Rollback()
  589. return
  590. }
  591. ut.Commit()
  592. }
  593. return
  594. }
  595. func DeleteDoctorAdvice(m *models.DoctorAdvice) (err error) {
  596. if m.ParentId > 0 {
  597. return writeDb.Save(m).Error
  598. } else {
  599. ut := writeDb.Begin()
  600. err = ut.Save(m).Error
  601. if err != nil {
  602. ut.Rollback()
  603. return
  604. }
  605. err = ut.Model(&models.DoctorAdvice{}).Where("parent_id=? AND user_org_id = ?", m.ID, m.UserOrgId).Update(map[string]interface{}{"UpdatedTime": m.UpdatedTime, "Status": 0, "Modifier": m.Modifier}).Error
  606. if err != nil {
  607. ut.Rollback()
  608. return
  609. }
  610. ut.Commit()
  611. }
  612. return
  613. }
  614. func DeleteGroupAdvice(orgId int64, groupNo int64, admin_user_id int64) (err error) {
  615. err = writeDb.Model(&models.DoctorAdvice{}).Where("user_org_id = ? and groupno = ?", orgId, groupNo).Update(map[string]interface{}{"UpdatedTime": time.Now().Unix(), "Status": 0, "Modifier": admin_user_id}).Error
  616. if err != nil {
  617. return
  618. }
  619. return
  620. }
  621. func FindDoctorAdvice(orgID, id int64) (advice models.DoctorAdvice, err error) {
  622. err = readDb.Model(&models.DoctorAdvice{}).Where("id = ? and user_org_id=? and status = 1", id, orgID).First(&advice).Error
  623. return
  624. }
  625. func FindHisDoctorAdvice(orgID, id int64) (advice models.HisDoctorAdviceInfo, err error) {
  626. err = readDb.Model(&models.HisDoctorAdviceInfo{}).Where("id = ? and user_org_id=? and status = 1", id, orgID).First(&advice).Error
  627. return
  628. }
  629. func FindDoctorAdviceByGroupNo(orgID, groupNo int64) (advice models.DoctorAdvice, err error) {
  630. err = readDb.Model(&models.DoctorAdvice{}).Where("groupno = ? and user_org_id=? and status = 1", groupNo, orgID).First(&advice).Error
  631. return
  632. }
  633. func GetDoctorAdviceList(orgID, patientID, advice_type, stop, start, end int64, keywords string) (advices []*models.DoctorAdvices, total int64, err error) {
  634. db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
  635. table := UserReadDB().Table("sgj_user_admin_role as r")
  636. fmt.Print("table", table)
  637. if orgID > 0 {
  638. db = db.Where("x.user_org_id=?", orgID)
  639. }
  640. if patientID > 0 {
  641. db = db.Where("x.patient_id = ?", patientID)
  642. }
  643. if advice_type > 0 {
  644. db = db.Where("x.advice_type = ?", advice_type)
  645. } else if advice_type == 0 {
  646. db = db.Where("x.advice_type in (?)", []int{1, 3})
  647. }
  648. if stop == 1 {
  649. db = db.Where("(x.stop_state=? or x.execution_state=?)", stop, stop)
  650. } else if stop == 2 {
  651. db = db.Where("x.stop_state=? and x.execution_state=?", stop, stop)
  652. }
  653. if start != 0 {
  654. db = db.Where("x.start_time>=?", start)
  655. }
  656. if end != 0 {
  657. db = db.Where("start_time<=?", end)
  658. }
  659. if len(keywords) > 0 {
  660. likeKey := "%" + keywords + "%"
  661. db = db.Where("x.advice_name LIKE ?", likeKey)
  662. }
  663. err = db.Group("x.id").Count(&total).Select("x.id, x.user_org_id, x.patient_id, x.advice_type, x.advice_date, x.record_date, x.start_time, x.advice_name,x.advice_desc, x.reminder_date, x.drug_spec, x.drug_spec_unit, x.single_dose, x.single_dose_unit, x.prescribing_number, x.prescribing_number_unit, x.delivery_way, x.execution_frequency, x.advice_doctor, x.status, x.created_time,x.updated_time, x.advice_affirm, x.remark, x.stop_time, x.stop_reason, x.stop_doctor, x.stop_state, x.parent_id, x.execution_time, x.execution_staff, x.execution_state, x.checker, x.check_state, x.check_time, x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Order("start_time desc, groupno desc, advice_order desc, id asc").Scan(&advices).Error
  664. fmt.Print("err", err)
  665. return
  666. }
  667. func GetDoctorAdviceListOne(orgID, patientID, advice_type, stop, start, end int64, keywords string, page int64, limit int64) (advices []*models.DoctorAdvices, total int64, err error) {
  668. db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
  669. table := UserReadDB().Table("sgj_user_admin_role as r")
  670. fmt.Print("table", table)
  671. if orgID > 0 {
  672. db = db.Where("x.user_org_id=?", orgID)
  673. }
  674. if patientID > 0 {
  675. db = db.Where("x.patient_id = ?", patientID)
  676. }
  677. if advice_type == 1 && advice_type > 0 {
  678. db = db.Where("x.advice_type = ?", advice_type)
  679. }
  680. if advice_type == 3 && advice_type > 0 {
  681. db = db.Where("x.advice_type = 2 or x.advice_type = 3")
  682. }
  683. if advice_type == 4 && advice_type > 0 {
  684. db = db.Where("x.advice_type = 4")
  685. }
  686. if stop == 1 {
  687. db = db.Where("(x.stop_state=? or x.execution_state=?)", stop, stop)
  688. } else if stop == 2 {
  689. db = db.Where("x.stop_state=? and x.execution_state=?", stop, stop)
  690. }
  691. if start != 0 {
  692. db = db.Where("x.start_time>=?", start)
  693. }
  694. if end != 0 {
  695. db = db.Where("start_time<=?", end)
  696. }
  697. if len(keywords) > 0 {
  698. likeKey := "%" + keywords + "%"
  699. db = db.Where("x.advice_name LIKE ?", likeKey)
  700. }
  701. offset := (page - 1) * limit
  702. err = db.Group("x.id").Count(&total).Offset(offset).Limit(limit).Select("x.id, x.user_org_id, x.patient_id, x.advice_type, x.advice_date, x.record_date, x.start_time, x.advice_name,x.advice_desc, x.reminder_date, x.drug_spec, x.drug_spec_unit, x.single_dose, x.single_dose_unit, x.prescribing_number, x.prescribing_number_unit, x.delivery_way, x.execution_frequency, x.advice_doctor, x.status, x.created_time,x.updated_time, x.advice_affirm, x.remark, x.stop_time, x.stop_reason, x.stop_doctor, x.stop_state, x.parent_id, x.execution_time, x.execution_staff, x.execution_state, x.checker, x.check_state, x.check_time, x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Order("start_time desc, groupno desc, advice_order desc, id asc").Scan(&advices).Error
  703. fmt.Print("err", err)
  704. return
  705. }
  706. func GetDoctorAdviceListTwo(orgID int64, patientID int64, advice_type int64, stop int64, start int64, end int64, keywords string, limit int64, page int64) (advices []*models.DoctorAdvices, total int64, err error) {
  707. db := readDb.Table("xt_doctor_advice as x").Where("x.status = 1")
  708. table := UserReadDB().Table("sgj_user_admin_role as r")
  709. fmt.Println(table)
  710. if orgID > 0 {
  711. db = db.Where("x.user_org_id=?", orgID)
  712. }
  713. if patientID > 0 {
  714. db = db.Where("x.patient_id = ?", patientID)
  715. }
  716. if advice_type == 1 {
  717. db = db.Where("x.advice_type = ?", advice_type)
  718. }
  719. if advice_type == 3 && advice_type > 0 {
  720. db = db.Where("x.advice_type = 2 or x.advice_type = 3")
  721. }
  722. if advice_type == 4 && advice_type > 0 {
  723. db = db.Where("x.advice_type = 4")
  724. }
  725. if stop == 1 {
  726. db = db.Where("(x.stop_state=? or x.execution_state=?)", stop, stop)
  727. } else if stop == 2 {
  728. db = db.Where("x.stop_state=? and x.execution_state=?", stop, stop)
  729. }
  730. if start != 0 {
  731. db = db.Where("x.start_time>=?", start)
  732. }
  733. if end != 0 {
  734. db = db.Where("start_time<=?", end)
  735. }
  736. if len(keywords) > 0 {
  737. likeKey := "%" + keywords + "%"
  738. db = db.Where("x.advice_name LIKE ?", likeKey)
  739. }
  740. offset := (page - 1) * limit
  741. err = db.Order("x.start_time desc").Group("x.start_time").Count(&total).Offset(offset).Limit(limit).Select("x.id, x.user_org_id, x.patient_id, x.advice_type, x.advice_date, x.record_date, x.start_time, x.advice_name,x.advice_desc, x.reminder_date, x.drug_spec, x.drug_spec_unit, x.single_dose, x.single_dose_unit, x.prescribing_number, x.prescribing_number_unit, x.delivery_way, x.execution_frequency, x.advice_doctor, x.status, x.created_time,x.updated_time, x.advice_affirm, x.remark, x.stop_time, x.stop_reason, x.stop_doctor, x.stop_state, x.parent_id, x.execution_time, x.execution_staff, x.execution_state, x.checker, x.check_state, x.check_time, x.groupno,x.remind_type,x.frequency_type,x.day_count,x.week_day,x.parent_id,r.user_name, IF(x.parent_id > 0, x.parent_id, x.id) as advice_order").Joins("Left join sgj_users.sgj_user_admin_role as r on r.admin_user_id = x.advice_doctor").Scan(&advices).Error
  742. fmt.Print("错误是什么", err)
  743. return
  744. }
  745. func GetDoctorAdvicePageList(orgID, patientID, advice_type, stop, start, end int64, keywords string, page, limit int64) (advices []*models.DoctorAdvice, total int64, err error) {
  746. offset := (page - 1) * limit
  747. db := readDb.Model(&models.DoctorAdvice{}).Where("status=1")
  748. if orgID > 0 {
  749. db = db.Where("user_org_id=?", orgID)
  750. }
  751. if patientID > 0 {
  752. db = db.Where("patient_id = ?", patientID)
  753. }
  754. if advice_type > 0 {
  755. db = db.Where("advice_type = ?", advice_type)
  756. }
  757. if stop == 1 {
  758. db = db.Where("(stop_state=? or execution_state=?) and parent_id=0", stop, stop)
  759. } else if stop == 2 {
  760. db = db.Where("stop_state=? and execution_state=?", stop, stop)
  761. }
  762. if start != 0 {
  763. db = db.Where("start_time>=?", start)
  764. }
  765. if end != 0 {
  766. db = db.Where("start_time<=?", end)
  767. }
  768. if len(keywords) > 0 {
  769. likeKey := "%" + keywords + "%"
  770. db = db.Where("advice_name LIKE ?", likeKey)
  771. }
  772. err = db.Count(&total).Select("id,user_org_id,patient_id,advice_type,advice_date,start_time,advice_name,advice_desc,reminder_date,single_dose,single_dose_unit,prescribing_number,prescribing_number_unit,delivery_way,execution_frequency,advice_doctor,status,created_time,updated_time,advice_affirm,remark,stop_time,stop_reason,stop_doctor,stop_state,parent_id,execution_time,execution_staff,execution_state,checker IF(parent_id>0, parent_id, id) as advice_order").Order("advice_order desc, id").Offset(offset).Limit(limit).Scan(&advices).Error
  773. return
  774. }
  775. func CreateSubDoctorAdvice(advices []*models.DoctorAdvice) (err error) {
  776. if len(advices) > 0 {
  777. utx := writeDb.Begin()
  778. if len(advices) > 0 {
  779. thisSQL := "INSERT INTO xt_doctor_advice (single_dose_unit, prescribing_number, prescribing_number_unit, advice_name, advice_desc,single_dose,created_time,updated_time,patient_id,parent_id,user_org_id,record_date,advice_type,drug_spec_unit) VALUES "
  780. insertParams := make([]string, 0)
  781. insertData := make([]interface{}, 0)
  782. for _, advice := range advices {
  783. insertParams = append(insertParams, "(?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
  784. insertData = append(insertData, advice.SingleDoseUnit)
  785. insertData = append(insertData, advice.PrescribingNumber)
  786. insertData = append(insertData, advice.PrescribingNumberUnit)
  787. insertData = append(insertData, advice.AdviceName)
  788. insertData = append(insertData, advice.AdviceDesc)
  789. insertData = append(insertData, advice.SingleDose)
  790. insertData = append(insertData, advice.CreatedTime)
  791. insertData = append(insertData, advice.UpdatedTime)
  792. insertData = append(insertData, advice.PatientId)
  793. insertData = append(insertData, advice.ParentId)
  794. insertData = append(insertData, advice.UserOrgId)
  795. insertData = append(insertData, advice.RecordDate)
  796. insertData = append(insertData, 2)
  797. insertData = append(insertData, advice.DrugSpecUnit)
  798. }
  799. thisSQL += strings.Join(insertParams, ", ")
  800. err = utx.Exec(thisSQL, insertData...).Error
  801. if err != nil {
  802. utx.Rollback()
  803. return
  804. }
  805. }
  806. utx.Commit()
  807. }
  808. return
  809. }
  810. func GetPatientDialysisRecord(orgID, patientID int64, page, limit, start, end, mode_id int64) ([]*models.PatientDialysisRecord, int64, error) {
  811. offset := (page - 1) * limit
  812. var total int64
  813. var err error
  814. var orders []*models.PatientDialysisRecord
  815. // err = readDb.Table("xt_dialysis_order as do").
  816. // Preload("DialysisPrescription", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  817. // Preload("PredialysisEvaluation", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  818. // Preload("AssessmentAfterDislysis", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  819. // Preload("TreatmentSummary", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  820. // Joins("JOIN xt_schedule as s ON s.patient_id=? and FROM_UNIXTIME(s.schedule_date, '%Y-%m-%d')=FROM_UNIXTIME(do.dialysis_date, '%Y-%m-%d')", patientID).
  821. // Joins("JOIN xt_device_zone as dz ON dz.org_id = ? and dz.id=s.partition_id", orgID).
  822. // Where("do.patient_id=? and do.user_org_id=? and do.stage = 2 and do.status=1", patientID, orgID).Count(&total).Offset(offset).Limit(limit).Order("do.dialysis_date desc").Select(" do.id, do.dialysis_date, do.user_org_id, do.patient_id, do.prescription_id, do.stage, do.remark, do.status, do.created_time, do.updated_time, s.schedule_type, s.partition_id, dz.name as partition_name").Find(&orders).Error
  823. db := readDb.Table("xt_dialysis_order as do").
  824. Preload("DialysisPrescription", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  825. Preload("PredialysisEvaluation", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  826. Preload("DialysisPrescription", func(db *gorm.DB) *gorm.DB {
  827. return readDb.Where("patient_id=? and user_org_id=? and status=1", patientID, orgID).Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  828. return readUserDb.Where("status = 1")
  829. })
  830. }).
  831. Preload("AssessmentAfterDislysis", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  832. Preload("TreatmentSummary", "patient_id=? and user_org_id=? and status=1", patientID, orgID).
  833. Preload("Device", "org_id=? and status=1", orgID).
  834. Preload("UserAdminRole", func(db *gorm.DB) *gorm.DB {
  835. return readUserDb.Where("org_id=? and status = 1", orgID)
  836. }).
  837. Joins("JOIN xt_schedule as s ON s.patient_id=? and FROM_UNIXTIME(s.schedule_date, '%Y-%m-%d')=FROM_UNIXTIME(do.dialysis_date, '%Y-%m-%d')", patientID).
  838. Joins("JOIN xt_device_zone as dz ON dz.org_id = ? and dz.id=s.partition_id", orgID).
  839. Where("do.patient_id=? and do.user_org_id=? and do.stage = 2 and do.status=1", patientID, orgID).Group("s.schedule_date")
  840. if start != 0 {
  841. db = db.Where("do.dialysis_date>=?", start)
  842. }
  843. if end != 0 {
  844. db = db.Where("do.dialysis_date<=?", end)
  845. }
  846. if mode_id > 0 {
  847. db = db.Joins("JOIN xt_dialysis_prescription as dp ON dp.patient_id=do.patient_id and dp.user_org_id = do.user_org_id and dp.record_date = do.dialysis_date")
  848. db = db.Where("dp.mode_id=?", mode_id)
  849. }
  850. err = db.Count(&total).Offset(offset).Limit(limit).Order("do.dialysis_date desc").Select("do.bed_id, do.id, do.dialysis_date, do.user_org_id, do.patient_id, do.prescription_id, do.stage, do.remark, do.status, do.created_time, do.updated_time,do.start_nurse,do.finish_nurse ,s.schedule_type, s.partition_id, dz.name as partition_name").Find(&orders).Error
  851. if len(orders) > 0 {
  852. ids := make([]int64, 0)
  853. for _, order := range orders {
  854. dialyzer := order.DialysisPrescription.Dialyzer
  855. ids = append(ids, dialyzer)
  856. }
  857. if len(ids) > 0 {
  858. var dialyzers []*models.DeviceNumber
  859. err = readDb.Model(&models.DeviceNumber{}).Where("id IN (?) and org_id=? and status=1", ids, orgID).Find(&dialyzers).Error
  860. if err != nil {
  861. return nil, 0, err
  862. }
  863. dialyzerMap := make(map[int64]models.DeviceNumber, 0)
  864. for _, item := range dialyzers {
  865. dialyzerMap[item.ID] = *item
  866. }
  867. for orderIndex, order := range orders {
  868. if _, exist := dialyzerMap[order.DialysisPrescription.Dialyzer]; exist {
  869. orders[orderIndex].DeviceNumber = dialyzerMap[order.DialysisPrescription.Dialyzer].Number
  870. }
  871. }
  872. }
  873. }
  874. return orders, total, err
  875. }
  876. func GetPatientTreatmentSummaryList(orgID, patientID, page, limit, start, end int64) (list []*models.TreatmentSummary, total int, err error) {
  877. offset := (page - 1) * limit
  878. fmt.Println(offset)
  879. fmt.Println(limit)
  880. db := readDb.Model(&models.TreatmentSummary{}).Where("user_org_id = ? and patient_id=?", orgID, patientID)
  881. if start != 0 {
  882. db = db.Where("assessment_date >= ?", start)
  883. }
  884. if end != 0 {
  885. db = db.Where("assessment_date <= ?", end)
  886. }
  887. db = db.Where("status=1")
  888. err = db.Count(&total).Offset(offset).Limit(limit).Order("assessment_date desc, id desc").Find(&list).Error
  889. return
  890. }
  891. func GetPatientScheduleList(orgID int64, patientID int64, page int64, limit int64, start int64) (schedules []*models.PatientSchedule, err error) {
  892. offset := (page - 1) * limit
  893. err = readDb.Table("xt_schedule as s").
  894. Preload("DeviceZone", "org_id=? and status=1", orgID).
  895. Preload("DeviceNumber", "org_id=? and status=1", orgID).
  896. Preload("TreatmentMode", "status=1").
  897. Where("s.patient_id =? and s.user_org_id=? and s.schedule_date>=? and s.status=1", patientID, orgID, start).
  898. Limit(limit).Offset(offset).Find(&schedules).Error
  899. return
  900. }
  901. func GetMonitorRecord(orgID int64, date int64, partition int64, patientId int64) ([]*models.NewVMMonitorDialysisSchedule, error) {
  902. var mds []*models.NewVMMonitorDialysisSchedule
  903. if patientId == 0 {
  904. db := readDb.
  905. Model(&models.NewVMMonitorDialysisSchedule{}).
  906. Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
  907. Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
  908. Preload("TreatmentMode", "status = 1").
  909. Preload("Prescription", "status = 1 AND user_org_id = ? AND record_date = ?", orgID, date).
  910. Preload("AssessmentBeforeDislysis", "status = 1 AND user_org_id = ? AND assessment_date = ?", orgID, date).
  911. Preload("AssessmentAfterDislysis", "status = 1 AND user_org_id = ? AND assessment_date = ? ", orgID, date).
  912. Preload("MonitoringRecord", "status = 1 AND user_org_id = ? AND monitoring_date = ?", orgID, date).
  913. Preload("DialysisOrder", "status = 1 AND user_org_id = ? AND dialysis_date = ?", orgID, date).
  914. Preload("DialysisOrder.DeviceNumber", "status = 1 AND org_id = ?", orgID).
  915. Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID).
  916. Where("status = 1 AND user_org_id = ?", orgID)
  917. if date != 0 {
  918. db = db.Where("schedule_date = ? ", date)
  919. }
  920. if partition != 0 {
  921. db = db.Where("partition_id = ? ", partition)
  922. }
  923. err := db.Find(&mds).Error
  924. fmt.Println("err", err)
  925. }
  926. if patientId > 0 {
  927. db := readDb.Table("xt_schedule as x").Where("x.status = 1")
  928. db = db.
  929. Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
  930. Preload("TreatmentMode", "status = 1").
  931. Preload("Prescription", "status = 1 AND user_org_id = ? AND patient_id = ?", orgID, patientId).
  932. Preload("AssessmentBeforeDislysis", "status = 1 AND user_org_id = ? AND patient_id = ?", orgID, patientId).
  933. Preload("AssessmentAfterDislysis", "status = 1 AND user_org_id = ? AND patient_id = ? ", orgID, patientId).
  934. Preload("MonitoringRecord", "status = 1 AND user_org_id = ? AND patient_id = ?", orgID, patientId).
  935. Preload("DialysisOrder", "status = 1 AND user_org_id = ? AND patient_id = ?", orgID, patientId).
  936. Preload("DialysisOrder.DeviceNumber", "status = 1 AND org_id = ?", orgID).
  937. Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID).
  938. Where("status = 1 AND user_org_id = ?", orgID)
  939. if partition != 0 {
  940. db = db.Where("partition_id = ? ", partition)
  941. }
  942. db = db.Where("schedule_date <= ? ", time.Now().Unix())
  943. db = db.Where("patient_id = ?", patientId)
  944. db = db.Order("schedule_date desc")
  945. err := db.Find(&mds).Error
  946. fmt.Println("err", err)
  947. }
  948. return mds, err
  949. }
  950. func MobileGetMonitorsWithPatient(orgID int64, keyword string, page int) ([]*models.MonitorDialysisSchedule, error) {
  951. var patients []*models.Patients
  952. getPatientErr := readDb.Model(&models.Patients{}).Where("status = 1 AND user_org_id = ? AND (name like ? OR dialysis_no like ?)", orgID, "%"+keyword+"%", "%"+keyword+"%").Find(&patients).Error
  953. if getPatientErr != nil {
  954. return nil, getPatientErr
  955. }
  956. patientIDs := make([]int64, len(patients))
  957. for index, patient := range patients {
  958. patientIDs[index] = patient.ID
  959. }
  960. db := readDb.
  961. Model(&models.MonitorDialysisSchedule{}).
  962. Preload("DeviceNumber", "status = 1 AND org_id = ?", orgID).
  963. Preload("DeviceZone", "status = 1 AND org_id = ?", orgID).
  964. Preload("TreatmentMode", "status = 1").
  965. Preload("Prescription", "status = 1 AND user_org_id = ?", orgID).
  966. Preload("AssessmentBeforeDislysis", "status = 1 AND user_org_id = ?", orgID).
  967. Preload("AssessmentAfterDislysis", "status = 1 AND user_org_id = ?", orgID).
  968. Preload("MonitoringRecord", "status = 1 AND user_org_id = ?", orgID).
  969. Preload("DialysisOrder", "status = 1 AND user_org_id = ?", orgID).
  970. Preload("MonitorPatients", "status = 1 AND user_org_id = ?", orgID).
  971. Where("status = 1 AND user_org_id = ? AND patient_id in (?)", orgID, patientIDs)
  972. var schedules []*models.MonitorDialysisSchedule
  973. err := db.Offset(20 * (page - 1)).Limit(20).Order("schedule_date desc").Find(&schedules).Error
  974. return schedules, err
  975. }
  976. func GetPatientByKeyWord(orgID int64, keywords string) (patient []*models.Patients, err error) {
  977. db := readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1", orgID)
  978. if len(keywords) > 0 {
  979. likekey := "%" + keywords + "%"
  980. err = db.Where("name LIKE ? OR dialysis_no LIKE ? ", likekey, likekey).Find(&patient).Error
  981. } else {
  982. err = db.Find(&patient).Error
  983. }
  984. return
  985. }
  986. func FindDoctorAdviceByGoroupNo(orgID int64, groupno int64) (advice models.DoctorAdvice, err error) {
  987. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? AND groupno = ? AND status = 1", orgID, groupno).First(&advice).Error
  988. return
  989. }
  990. func FindOldDoctorAdvice(orgID int64, advice_id int64) (advice models.DoctorAdvice, err error) {
  991. err = readDb.Model(&models.DoctorAdvice{}).Where("id = ? AND user_org_id=? AND status = 1", advice_id, orgID).First(&advice).Error
  992. return
  993. }
  994. func UpdateAdviceGroupStartTime(orgID int64, groupNO int64, startTime int64, admin_user_id int64) error {
  995. now := time.Now().Unix()
  996. err := writeDb.Model(&models.DoctorAdvice{}).Where("user_org_id = ? AND status = 1 AND execution_state <> 1 AND check_state <> 1 AND groupno = ? AND admin_user_id = ?", orgID, groupNO, admin_user_id).Updates(map[string]interface{}{
  997. "start_time": startTime,
  998. "updated_time": now,
  999. "modifier": admin_user_id,
  1000. }).Error
  1001. return err
  1002. }
  1003. func QueryPatientById(id int64) *models.Patients {
  1004. var pat models.Patients
  1005. err := readDb.Model(&models.Patients{}).Where("id=?", id).First(&pat).Error
  1006. if err != nil {
  1007. }
  1008. return &pat
  1009. }
  1010. func FindAllDoctorAdviceByGoroupNo(orgID int64, groupno int64) (advice []models.DoctorAdvice, err error) {
  1011. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? AND groupno = ? AND status = 1", orgID, groupno).Find(&advice).Error
  1012. return
  1013. }
  1014. func FindDoctorAdviceByIds(orgID int64, ids []string) (advice []models.DoctorAdvice, err error) {
  1015. err = readDb.Model(&models.DoctorAdvice{}).Where("id IN (?) AND user_org_id = ? AND status = 1", ids, orgID).Find(&advice).Error
  1016. return
  1017. }
  1018. func BatchDeleteDoctorAdvice(ids []string, user_id int64) (err error) {
  1019. ut := writeDb.Begin()
  1020. err = ut.Model(&models.DoctorAdvice{}).Where("status = 1 AND id IN (?)", ids).Updates(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix(), "modifier": user_id}).Error
  1021. if err != nil {
  1022. ut.Rollback()
  1023. return
  1024. }
  1025. err = ut.Model(&models.DoctorAdvice{}).Where("status = 1 AND parent_id IN (?)", ids).Updates(map[string]interface{}{"status": 0, "updated_time": time.Now().Unix(), "modifier": user_id}).Error
  1026. if err != nil {
  1027. ut.Rollback()
  1028. return
  1029. }
  1030. ut.Commit()
  1031. return err
  1032. }
  1033. func FindAdviceByGoroupNo(orgID int64, groupno int64) (advice []models.DoctorAdvice, err error) {
  1034. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? AND groupno = ? AND status = 1 AND parent_id = 0", orgID, groupno).Find(&advice).Error
  1035. return
  1036. }
  1037. func UpdateDoctorAdviceAndSubAdvice(m *models.DoctorAdvice) (err error) {
  1038. ut := writeDb.Begin()
  1039. err = ut.Save(m).Error
  1040. if err != nil {
  1041. ut.Rollback()
  1042. return
  1043. }
  1044. err = ut.Model(&models.DoctorAdvice{}).Where("status = 1 AND parent_id IN (?)", m.ID).Updates(map[string]interface{}{"start_time": m.StartTime, "groupno": m.GroupNo, "mtime": time.Now().Unix()}).Error
  1045. if err != nil {
  1046. ut.Rollback()
  1047. return
  1048. }
  1049. ut.Commit()
  1050. return err
  1051. }
  1052. func GetAllWaitRemindPatient(org_id int64, page int64, limit int64) (total int64, patient []*models.Patients, err error) {
  1053. type Total struct {
  1054. Count int64
  1055. }
  1056. var totals Total
  1057. offset := (page - 1) * limit
  1058. err = readDb.Raw("select * from xt_patients where user_org_id = ? AND lapseto = 1 AND infectious_next_record_time > 0 AND status = 1 AND date_sub(DATE_FORMAT(date(from_unixtime(`xt_patients`.`infectious_next_record_time`)),'%Y-%m-%d'), interval 7 day) <= now() Order by infectious_next_record_time", org_id).Offset(offset).Limit(limit).Scan(&patient).Error
  1059. readDb.Raw("select Count(id) as count from xt_patients where user_org_id = ? AND lapseto = 1 AND infectious_next_record_time > 0 AND status = 1 AND date_sub(DATE_FORMAT(date(from_unixtime(`xt_patients`.`infectious_next_record_time`)),'%Y-%m-%d'), interval 7 day) <= now() Order by infectious_next_record_time", org_id).Scan(&totals)
  1060. return totals.Count, patient, err
  1061. }
  1062. func UpdatePatientRemindStatus(patient_id int64, remind int64, org_id int64) (err error) {
  1063. err = writeDb.Model(&models.Patients{}).Where("status = 1 AND id = ? AND user_org_id = ?", patient_id, org_id).Updates(map[string]interface{}{"is_open_remind": remind}).Error
  1064. return
  1065. }
  1066. func CreatePatientWeightAdjust(m *models.SgjPatientDryweight) (err error) {
  1067. err = writeDb.Create(m).Error
  1068. return
  1069. }
  1070. func FindLastDryWeightAdjust(orgID int64, id int64) (weight models.SgjPatientDryweight, err error) {
  1071. err = readDb.Model(&models.SgjPatientDryweight{}).Where("user_org_id=? and patient_id=? and status=1", orgID, id).Order("id desc").First(&weight).Error
  1072. return
  1073. }
  1074. func GetSchedualPatientByKeyWord(orgID int64, keywords string, date int64) (patient []*models.Patients, err error) {
  1075. db := readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1 and lapseto = 1 ", orgID)
  1076. if len(keywords) > 0 {
  1077. likekey := "%" + keywords + "%"
  1078. err = db.Where("(name LIKE ? OR dialysis_no LIKE ?) AND NOT EXISTS (Select * FROM `xt_dialysis_order` as d Where d.`dialysis_date` = ? AND d.`status` = 1 AND d.`patient_id` = xt_patients.id AND d.user_org_id = xt_patients.user_org_id)", likekey, likekey, date).Find(&patient).Error
  1079. } else {
  1080. err = db.Find(&patient).Error
  1081. }
  1082. return
  1083. }
  1084. func GetPatientScheduleOne(patientid int64, nowdate int64, orgid int64) (models.XtSchedule, error) {
  1085. schedule := models.XtSchedule{}
  1086. err := XTReadDB().Model(&schedule).Where("patient_id = ? and schedule_date = ? and user_org_id = ? and status =1", patientid, nowdate, orgid).Find(&schedule).Error
  1087. return schedule, err
  1088. }
  1089. func CreateExportPatient(patient *models.Patients, contagions []int64, org_creator int64) (err error) {
  1090. user, _ := GetSgjUserByMobild(patient.Phone)
  1091. customer, _ := GetSgjCoustomerByMobile(patient.UserOrgId, patient.Phone)
  1092. utx := writeDb.Begin()
  1093. btx := writeUserDb.Begin()
  1094. if user.ID == 0 {
  1095. user.Mobile = patient.Phone
  1096. user.Avatar = patient.Avatar
  1097. user.AvatarThumb = patient.Avatar
  1098. user.Birthday = patient.Birthday
  1099. user.Username = patient.Name
  1100. user.Gender = patient.Gender
  1101. user.Sources = 11
  1102. user.Introduce = patient.Remark
  1103. user.Status = 1
  1104. user.UpdatedTime = patient.UpdatedTime
  1105. user.CreatedTime = patient.CreatedTime
  1106. err = btx.Create(&user).Error
  1107. if err != nil {
  1108. utx.Rollback()
  1109. btx.Rollback()
  1110. return
  1111. }
  1112. }
  1113. patient.UserId = user.ID
  1114. if customer == nil {
  1115. err = btx.Create(&models.SgjCustomer{
  1116. UserOrgId: patient.UserOrgId,
  1117. UserId: user.ID,
  1118. Mobile: patient.Phone,
  1119. Name: patient.Name,
  1120. Gender: patient.Gender,
  1121. Birthday: patient.Birthday,
  1122. Sources: 11,
  1123. Status: 1,
  1124. CreatedTime: patient.CreatedTime,
  1125. UpdatedTime: patient.UpdatedTime,
  1126. Avatar: patient.Avatar,
  1127. Remark: patient.Remark,
  1128. }).Error
  1129. if err != nil {
  1130. utx.Rollback()
  1131. btx.Rollback()
  1132. return
  1133. }
  1134. }
  1135. err = utx.Create(patient).Error
  1136. if err != nil {
  1137. utx.Rollback()
  1138. btx.Rollback()
  1139. return
  1140. }
  1141. if patient.DryWeight > 0 {
  1142. var dryWeight models.SgjPatientDryweight
  1143. dryWeight.PatientId = patient.ID
  1144. dryWeight.UserOrgId = patient.UserOrgId
  1145. dryWeight.Status = 1
  1146. dryWeight.AdjustedValue = "/"
  1147. dryWeight.Creator = org_creator
  1148. dryWeight.UserId = org_creator
  1149. dryWeight.Ctime = time.Now().Unix()
  1150. dryWeight.Mtime = time.Now().Unix()
  1151. dryWeight.DryWeight = patient.DryWeight
  1152. dryWeight.Remakes = ""
  1153. err = utx.Create(&dryWeight).Error
  1154. }
  1155. var lapseto models.PatientLapseto
  1156. lapseto.PatientId = patient.ID
  1157. lapseto.LapsetoType = patient.Lapseto
  1158. lapseto.CreatedTime = patient.CreatedTime
  1159. lapseto.UpdatedTime = patient.CreatedTime
  1160. lapseto.Status = 1
  1161. lapseto.LapsetoTime = patient.CreatedTime
  1162. err = utx.Create(&lapseto).Error
  1163. if err != nil {
  1164. utx.Rollback()
  1165. btx.Rollback()
  1166. return
  1167. }
  1168. if len(contagions) > 0 {
  1169. thisSQL := "INSERT INTO xt_patients_infectious_diseases (patient_id, disease_id, status, created_time, updated_time) VALUES "
  1170. insertParams := make([]string, 0)
  1171. insertData := make([]interface{}, 0)
  1172. for _, contagion := range contagions {
  1173. insertParams = append(insertParams, "(?, ?, ?, ?, ?)")
  1174. insertData = append(insertData, patient.ID)
  1175. insertData = append(insertData, contagion)
  1176. insertData = append(insertData, 1)
  1177. insertData = append(insertData, patient.CreatedTime)
  1178. insertData = append(insertData, patient.UpdatedTime)
  1179. }
  1180. thisSQL += strings.Join(insertParams, ", ")
  1181. err = utx.Exec(thisSQL, insertData...).Error
  1182. if err != nil {
  1183. utx.Rollback()
  1184. btx.Rollback()
  1185. return
  1186. }
  1187. }
  1188. patientsNew := models.XtPatientsNew{
  1189. Name: patient.Name,
  1190. Gender: patient.Gender,
  1191. Phone: patient.Phone,
  1192. IdCardNo: patient.IdCardNo,
  1193. FirstDialysisDate: patient.FirstDialysisDate,
  1194. Source: patient.Source,
  1195. Lapseto: patient.Lapseto,
  1196. IsInfectious: patient.IsInfectious,
  1197. DialysisNo: patient.DialysisNo,
  1198. Height: patient.Height,
  1199. HomeAddress: patient.HomeAddress,
  1200. IsExcelExport: 1,
  1201. BloodPatients: 1,
  1202. Status: 1,
  1203. CreatedTime: time.Now().Unix(),
  1204. UserOrgId: patient.UserOrgId,
  1205. BloodId: patient.ID,
  1206. Avatar: "https://images.shengws.com/201809182128111.png",
  1207. }
  1208. err = utx.Create(&patientsNew).Error
  1209. if err != nil {
  1210. utx.Rollback()
  1211. btx.Rollback()
  1212. return
  1213. }
  1214. utx.Commit()
  1215. btx.Commit()
  1216. return
  1217. }
  1218. func FindPatientPhoneIsExist(phone string, org_id int64) (count int64) {
  1219. readDb.Model(&models.Patients{}).Where("user_org_id = ? AND phone = ? AND status = 1", org_id, phone).Count(&count)
  1220. return
  1221. }
  1222. func FindPatientIdCardNoIsExist(id_card_no string, org_id int64) (count int64) {
  1223. readDb.Model(&models.Patients{}).Where("user_org_id = ? AND id_card_no = ? AND status = 1", org_id, id_card_no).Count(&count)
  1224. return
  1225. }
  1226. func CreateExportErrLog(log *models.ExportErrLog) {
  1227. writeDb.Create(&log)
  1228. return
  1229. }
  1230. func FindPatientExportLog(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
  1231. err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 1", org_id, export_time).Find(&errLogs).Error
  1232. return
  1233. }
  1234. func FindPatientExportLogOne(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
  1235. err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 4", org_id, export_time).Find(&errLogs).Error
  1236. return
  1237. }
  1238. func FindPatientExportLogTwo(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
  1239. err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 5", org_id, export_time).Find(&errLogs).Error
  1240. return
  1241. }
  1242. func FindPatientExportLogThree(org_id int64, export_time int64) (errLogs []*models.ExportErrLog, err error) {
  1243. err = readDb.Model(&models.ExportErrLog{}).Where("user_org_id = ? AND export_time = ? AND log_type = 6", org_id, export_time).Find(&errLogs).Error
  1244. return
  1245. }
  1246. func CreateExportLog(log *models.ExportLog) {
  1247. writeDb.Create(&log)
  1248. }
  1249. func UpdateDoctorEditAdvice(advice models.XtDoctorAdvice, orgid int64, groupno int64, date int64, patientid int64) error {
  1250. err := XTWriteDB().Model(&advice).Where("user_org_id = ? and groupno = ? and advice_date = ? and patient_id = ?", orgid, groupno, date, patientid).Update(map[string]interface{}{"start_time": advice.StartTime, "updated_time": advice.UpdatedTime}).Error
  1251. return err
  1252. }
  1253. func GetPatientsByKey(orgID int64, keywords string) (patient []*models.Patients, err error) {
  1254. db := readDb.Model(&models.Patients{}).Where("user_org_id=? and status=1 and lapseto = 1 ", orgID)
  1255. if len(keywords) > 0 {
  1256. likekey := "%" + keywords + "%"
  1257. err = db.Where("(name LIKE ? OR dialysis_no LIKE ?)", likekey, likekey).Find(&patient).Error
  1258. } else {
  1259. err = db.Find(&patient).Error
  1260. }
  1261. return
  1262. }
  1263. func FindAllDoctorAdviceByGoroupNoTwo(orgID int64, groupno int64) (advice []models.DoctorAdvice, err error) {
  1264. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id=? AND groupno = ? AND status = 1 AND execution_state = 2", orgID, groupno).Find(&advice).Error
  1265. return
  1266. }
  1267. func FindDoctorAdviceByIdsTwo(orgID int64, ids []string) (advice []models.DoctorAdvice, err error) {
  1268. err = readDb.Model(&models.DoctorAdvice{}).Where("user_org_id = ? AND status = 1 AND execution_state = 2 AND (id IN (?) OR parent_id IN (?))", orgID, ids, ids).Find(&advice).Error
  1269. return
  1270. }
  1271. func CreateHisGroupAdvice(orgId int64, advices []*models.HisGroupAdvice, groupNo int64) (list []*models.HisGroupAdvice, err error) {
  1272. if groupNo <= 0 {
  1273. group := GetMaxAdviceGroupID(orgId)
  1274. groupNo = group + 1
  1275. }
  1276. tx := writeDb.Begin()
  1277. defer func() {
  1278. if r := recover(); r != nil {
  1279. tx.Rollback()
  1280. }
  1281. }()
  1282. for _, advice := range advices {
  1283. advice.Groupno = groupNo
  1284. if err = tx.Create(advice).Error; err != nil {
  1285. tx.Rollback()
  1286. return
  1287. }
  1288. list = append(list, advice)
  1289. if len(advice.Children) > 0 {
  1290. for _, child := range advice.Children {
  1291. child.Groupno = groupNo
  1292. child.ParentId = advice.ID
  1293. fmt.Println(child)
  1294. if err = tx.Create(&child).Error; err != nil {
  1295. tx.Rollback()
  1296. return
  1297. }
  1298. list = append(list, child)
  1299. }
  1300. }
  1301. }
  1302. tx.Commit()
  1303. return
  1304. }
  1305. func GetDialysisCount(orgid int64, partitionid int64) (order []*models.BloodDialysisOrderCount, err error) {
  1306. db := XTReadDB().Table("xt_dialysis_order as o")
  1307. if partitionid == 0 {
  1308. db.Raw("select count(o.id) as count,o.patient_id from xt_dialysis_order as o left join xt_schedule as x on x.patient_id = o.patient_id where o.status =1 and o.user_org_id = ? and x.schedule_date = o.dialysis_date and x.status = 1", orgid).Group("o.patient_id").Scan(&order)
  1309. }
  1310. if partitionid > 0 {
  1311. db.Raw("select count(o.id) as count,o.patient_id from xt_dialysis_order as o left join xt_schedule as x on x.patient_id = o.patient_id where o.status =1 and o.user_org_id = ? and x.partition_id = ? and x.schedule_date = o.dialysis_date and x.status = 1", orgid, partitionid).Group("o.patient_id").Scan(&order)
  1312. }
  1313. return order, err
  1314. }
  1315. func UpdatePatientDialysisSolutionOne(patientid int64, orgid int64, prescription *models.DialysisPrescription, timenow int64) error {
  1316. err = XTWriteDB().Model(&prescription).Where("patient_id = ? and user_org_id = ? and record_date = ? ", patientid, orgid, timenow).Updates(map[string]interface{}{"dialyzer": prescription.Dialyzer, "anticoagulant": prescription.Anticoagulant, "mode_id": prescription.ModeId, "dialysis_duration_hour": prescription.DialysisDurationHour, "anticoagulant_shouji": prescription.AnticoagulantShouji, "anticoagulant_weichi": prescription.AnticoagulantWeichi, "anticoagulant_zongliang": prescription.AnticoagulantZongliang, "kalium": prescription.Kalium, "sodium": prescription.Sodium, "calcium": prescription.Calcium, "dialyzer_perfusion_apparatus": prescription.DialyzerPerfusionApparatus, "blood_access": prescription.BloodAccess, "dialysate_flow": prescription.DialysateFlow, "dialysate_temperature": prescription.DialysateTemperature, "dialysis_dialyszers": prescription.DialysisDialyszers, "dialysis_irrigation": prescription.DialysisIrrigation, "plasma_separator": prescription.PlasmaSeparator, "bilirubin_adsorption_column": prescription.BilirubinAdsorptionColumn, "oxygen_uptake": prescription.OxygenUptake, "oxygen_flow": prescription.OxygenFlow, "oxygen_time": prescription.OxygenTime}).Error
  1317. return err
  1318. }
  1319. //func FindRemindAdvice(user_org_id int64, advice_name string, advice_desc string, template_id string, fre_type int64, patient_id int64, record_date int64) (advice models.DoctorAdvice, err error) {
  1320. // err = XTWriteDB().Model(&models.DoctorAdvice{}).Where("patient_id = ? and user_org_id = ? and record_date = ? and advice_name = ? and advice_desc = ? and template_id = ? and frequency_type = ? ", patient_id, user_org_id, record_date, advice_name, advice_desc, template_id, fre_type).First(&advice).Error
  1321. // return
  1322. //}
  1323. func FindRemindAdvice(user_org_id int64, advice_name string, advice_desc string, template_id string, fre_type int64, patient_id int64, record_date int64) (advice models.DoctorAdvice, err error) {
  1324. err = XTWriteDB().Model(&models.DoctorAdvice{}).Where("patient_id = ? and user_org_id = ? and record_date = ? and advice_name = ? and advice_desc = ? and template_id = ? and frequency_type = ? AND advice_type = 2 ", patient_id, user_org_id, record_date, advice_name, advice_desc, template_id, fre_type).First(&advice).Error
  1325. return
  1326. }
  1327. func UpdateScheduleByDeathTime(patientid int64, shcheduledate int64) error {
  1328. err := XTWriteDB().Model(models.XtSchedule{}).Where("patient_id = ? and schedule_date>?", patientid, shcheduledate).Updates(map[string]interface{}{"status": 0}).Error
  1329. return err
  1330. }
  1331. func UpdateScheduleItemByPatientId(id int64) error {
  1332. err := XTWriteDB().Model(models.PatientScheduleTemplateItem{}).Where("patient_id = ? and status = 1", id).Updates(map[string]interface{}{"status": 0}).Error
  1333. return err
  1334. }