package new_mobile_api_controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"crypto/md5"
	"encoding/json"
	"fmt"
	"github.com/jinzhu/gorm"
	"strconv"
	"strings"
	"time"
)

type NewDialysisApiController struct {
	NewMobileBaseAPIAuthController
}

func (this *NewDialysisApiController) GetIllnesslist() {

	illnesslist, err := service.GetIllnessListTwo()
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"illnesslist": illnesslist,
	})
}

func (this *NewDialysisApiController) GetPatient() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	page, _ := this.GetInt64("page")
	limit, _ := this.GetInt64("limit")
	patient, total, err := service.GetBloodDialysisPatient(orgid, page, limit)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
		"total":   total,
	})
}

func (this *NewDialysisApiController) GetAllPatient() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	patient, err := service.GetAllPatient(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
	})
}

func (this *NewDialysisApiController) GetGeneratedialysisno() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	dialysisNo := service.ChechLastDialysisNoTwo(orgid)
	//fmt.Print("机构ID",adminUserInfo.CurrentOrgId)
	if dialysisNo == 0 {
		dialysisNo = 1
	} else {
		dialysisNo++
	}
	no := strconv.FormatInt(dialysisNo, 10)

	rep := 3 - len(no)

	if rep > 0 {
		no = strings.Repeat("0", rep) + no
	}

	this.ServeSuccessJSON(map[string]interface{}{
		"no": no,
	})
	return
}

func (this *NewDialysisApiController) GetBloodPatientInfo() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgId := adminInfo.Org.Id
	fmt.Print("机构ID", orgId)
	phone := this.GetString("phone")
	_, errcode := service.GetBloodPatientInfo(orgId, phone)
	fmt.Print("errcode", errcode)
	if errcode == gorm.ErrRecordNotFound {
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
		return
	} else if errcode == nil {
		return
	} else {

	}
}

func (this *NewDialysisApiController) GetSlowPatientInfo() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgId := adminInfo.Org.Id
	fmt.Print("机构ID", orgId)
	phone := this.GetString("phone")
	fmt.Print("phone", phone)
	_, errcode := service.GetSlowPatientInfo(orgId, phone)
	fmt.Print("errcode", errcode)
	if errcode == gorm.ErrRecordNotFound {
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
		return
	} else if errcode == nil {
		return
	} else {

	}

}

func (this *NewDialysisApiController) GetMemberpatientInfo() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgId := adminInfo.Org.Id
	fmt.Print("机构ID", orgId)
	phone := this.GetString("phone")
	fmt.Print("phone", phone)
	_, errcode := service.GetMemberPatientInfo(orgId, phone)
	fmt.Print("errcode", errcode)
	if errcode == gorm.ErrRecordNotFound {
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "ok"
		this.ServeSuccessJSON(returnData)
		return
	} else if errcode == nil {
		return
	} else {

	}
}

func (this *NewDialysisApiController) SavePatient() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	fmt.Print("err", err)
	name := dataBody["name"].(string)
	fmt.Println("姓名", name)
	sex := int64(dataBody["sex"].(float64))
	fmt.Print("性别", sex)
	idCard := dataBody["idCard"].(string)
	fmt.Print("身份证", idCard)
	birthday := dataBody["birthday"].(string)
	births := strings.Split(birthday, "-")
	fmt.Print("生日", birthday)
	birYear, _ := strconv.Atoi(births[0])
	age := time.Now().Year() - birYear
	ages := int64(age)
	fmt.Println("age是多少", ages)
	timeLayout := "2006-01-02 15:04:05"
	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
	birth := theTime.Unix()
	fmt.Print(birth)
	phone := dataBody["phone"].(string)
	fmt.Print("电话号码", phone)
	patientType := dataBody["result"].([]interface{})
	fmt.Print("患者标签", patientType)
	dialysis := dataBody["dialysis"].(string)
	fmt.Print("透析号", dialysis)
	patientsoure := int64(dataBody["patientsoure"].(float64))
	fmt.Print("患者来源", patientsoure)
	lapseto := int64(dataBody["lapseto"].(float64))
	fmt.Print("留置状态", lapseto)
	contagions := dataBody["resultTwo"].([]interface{})
	fmt.Print("传染病", contagions)
	ids := make([]int64, 0)
	for _, contagion := range contagions {
		id, _ := strconv.ParseInt(contagion.(string), 10, 64)
		ids = append(ids, id)
	}
	fmt.Print("传染病2", contagions)
	is_infectious := int64(dataBody["is_infectious"].(float64))
	fmt.Print("传染病", is_infectious)
	adminssionNumber := dataBody["admissionNumber"].(string)
	fmt.Print("住院号", adminssionNumber)

	fistdate := dataBody["fistDate"].(string)
	fmt.Print("首次透析日期", fistdate)
	timeLayouts := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	times, err := time.ParseInLocation(timeLayouts+" 15:04:05", fistdate+" 00:00:00", loc)
	//times, err := utils.ParseTimeStringToTime(timeLayout, fistdate+"00:00:00")
	fisttime := times.Unix()
	fmt.Print(fisttime)

	diagonse := dataBody["diagnose"].(string)
	fmt.Print("诊断", diagonse)
	avatar := dataBody["avatar"].(string)
	fmt.Print("头像", avatar)
	//慢性病
	requipmentId := dataBody["requipmentId"].(string)
	fmt.Print("设备ID", requipmentId)
	slowContagions := dataBody["resultThree"].([]interface{})
	fmt.Print("慢性传染病", slowContagions)
	idss := make([]int64, 0)
	for _, contagion := range slowContagions {
		id, _ := strconv.ParseInt(contagion.(string), 10, 64)
		idss = append(ids, id)
	}
	slowDiseases := dataBody["resultFour"].([]interface{})
	idsss := make([]int64, 0)
	for _, contagion := range slowDiseases {
		id, _ := strconv.ParseInt(contagion.(string), 10, 64)
		idsss = append(ids, id)
	}
	fmt.Print("慢性病", slowDiseases)

	bloodPatient := int64(dataBody["bloodPatient"].(float64))
	fmt.Print("血透病人", bloodPatient)
	slowpatient := int64(dataBody["slowPatient"].(float64))
	fmt.Print("慢病病人", slowpatient)
	memberpatient := int64(dataBody["memberPatient"].(float64))
	fmt.Print("会员病人", memberpatient)
	//会员
	memberFistDate := dataBody["memberFistDate"].(string)
	fmt.Print("首次透析日期", memberFistDate)
	//membertimes, err := utils.ParseTimeStringToTime(timeLayout, memberFistDate+"00:00:00")
	membertimes, _ := time.ParseInLocation(timeLayouts+" 15:04:05", memberFistDate+" 00:00:00", loc)
	memtime := membertimes.Unix()
	fmt.Print("会员透析日期", memtime)
	patient_type := int64(dataBody["patientType"].(float64))
	fmt.Print("病种", patient_type)
	treatmentmethod := int64(dataBody["treatmentMethod"].(float64))
	fmt.Print("治疗方式", treatmentmethod)

	//查询身份证号码是否存在
	thisPatientOne, _ := service.FindPatientByIdCardNoFive(orgid, idCard)
	if thisPatientOne.ID > 0 {
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "身份证号码已存在"
		this.ServeSuccessJSON(returnData)
		return
	}

	//查询手机号码是否存在
	thisPatient, err := service.FindPatientByMobileFive(phone, orgid)
	if thisPatient.ID > 0 {
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "手机号码已存在"
		this.ServeSuccessJSON(returnData)
		return
	}
	//如果是血透病人
	if bloodPatient == 1 {
		//查询透析号是否存在
		thisPatientTwo, _ := service.FindPatientByDialysisNoFive(orgid, dialysis)
		if thisPatientTwo.ID > 0 {
			returnData := make(map[string]interface{}, 0)
			returnData["msg"] = "透析号已存在"
			this.ServeSuccessJSON(returnData)
			return
		}

		patients := models.Patients{
			Name:              name,
			Gender:            sex,
			Birthday:          birth,
			Age:               ages,
			Phone:             phone,
			Lapseto:           lapseto,
			AdmissionNumber:   adminssionNumber,
			FirstDialysisDate: fisttime,
			Diagnose:          diagonse,
			Source:            patientsoure,
			DialysisNo:        dialysis,
			UserOrgId:         orgid,
			Status:            1,
			CreatedTime:       time.Now().Unix(),
			Avatar:            avatar,
			IdCardNo:          idCard,
			IsInfectious:      is_infectious,
		}
		err = service.CreateOldPatient(&patients)
		fmt.Print("报错", err)
		patient, err := service.GetLastOldPatient(orgid)
		fmt.Print("病人ID", patient.ID)
		err = service.AddContagions(patient.ID, patient.CreatedTime, patient.UpdatedTime, ids)
		fmt.Println("添加传染病失败", err)

		patientsNew := models.XtPatientsNew{
			Name:              name,
			Gender:            sex,
			Birthday:          birth,
			Age:               ages,
			Phone:             phone,
			Lapseto:           lapseto,
			AdmissionNumber:   adminssionNumber,
			FirstDialysisDate: fisttime,
			Diagnose:          diagonse,
			Source:            patientsoure,
			DialysisNo:        dialysis,
			UserOrgId:         orgid,
			Status:            1,
			CreatedTime:       time.Now().Unix(),
			Avatar:            avatar,
			MemberPatients:    memberpatient,
			BloodPatients:     bloodPatient,
			SlowPatients:      slowpatient,
			BloodId:           patient.ID,
			IsInfectious:      is_infectious,
			IdCardNo:          idCard,
		}
		err = service.CreateNewPatient(&patientsNew)
		fmt.Print("报错", err)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"patient": patientsNew,
		})
	}

	fmt.Print("slowpatient", slowpatient)
	//如果是慢病病人
	if slowpatient == 1 {
		_, errcodetwo := service.GetSlowPatientData(phone, orgid)
		fmt.Print("查询慢慢是吧", errcodetwo)
		if errcodetwo == gorm.ErrRecordNotFound {
			patients := models.CdmPatients{
				Name:        name,
				Gender:      sex,
				Birthday:    birth,
				Phone:       phone,
				Diagnose:    diagonse,
				Source:      patientsoure,
				UserOrgId:   orgid,
				Status:      1,
				CreatedTime: time.Now().Unix(),
				Avatar:      avatar,
				IdCardNo:    idCard,
			}
			errcodetwo := service.CreateCdmPatient(&patients)
			fmt.Print("报错", errcodetwo)
			slowPatient, errcodetwo := service.GetOldCdmPatient(orgid)
			errcodetwo = service.AddSlowContagions(slowPatient.ID, slowPatient.CreatedTime, slowPatient.UpdatedTime, idss, orgid)
			fmt.Print("添加慢病传染病失败", errcodetwo)
			errcodethree := service.AddSlowDiseases(slowPatient.ID, slowPatient.CreatedTime, slowPatient.UpdatedTime, idsss, orgid)
			fmt.Print("添加慢性病失败", errcodethree)

			_, errcodefour := service.GetLastNewSlowPatient(phone, orgid)
			if errcodefour == gorm.ErrRecordNotFound {
				patientsNew := models.XtPatientsNew{
					Name:              name,
					Gender:            sex,
					Birthday:          birth,
					Age:               ages,
					Phone:             phone,
					Lapseto:           lapseto,
					AdmissionNumber:   adminssionNumber,
					FirstDialysisDate: fisttime,
					Diagnose:          diagonse,
					Source:            patientsoure,
					DialysisNo:        dialysis,
					UserOrgId:         orgid,
					Status:            1,
					CreatedTime:       time.Now().Unix(),
					Avatar:            avatar,
					MemberPatients:    memberpatient,
					BloodPatients:     bloodPatient,
					SlowPatients:      slowpatient,
					SlowId:            slowPatient.ID,
					IsInfectious:      is_infectious,
					IdCardNo:          idCard,
					EquitmentId:       requipmentId,
				}
				err = service.CreateNewPatient(&patientsNew)
				if err != nil {
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
					return
				}
				this.ServeSuccessJSON(map[string]interface{}{
					"patient": patientsNew,
				})
			} else if errcodetwo == nil {
				fmt.Print("病人已存在")
				if memberpatient == 1 {
					fmt.Print("进来没有", memberpatient)
					_, errmembercode := service.GetMemberPatientInfo(orgid, phone)
					if errmembercode == gorm.ErrRecordNotFound {
						customer := models.SgjUserCustomer{
							Name:        name,
							UserOrgId:   orgid,
							Mobile:      phone,
							Gender:      sex,
							Birthday:    birth,
							IllDate:     memtime,
							Status:      1,
							CreatedTime: time.Now().Unix(),
							Avatar:      avatar,
							IllnessId:   patient_type,
							TreatType:   treatmentmethod,
						}
						errmembercode := service.CreateMemberPatient(&customer)
						fmt.Print("创建会员病人失败", errmembercode)
						_, errmembercodetwo := service.GetMemberNewPatient(phone, orgid)
						fmt.Print("错误", errmembercodetwo)
						//获取机构的最后一条数据
						memberPatient, errmembercode := service.GetLastMemberPatient(orgid)
						if errmembercodetwo == gorm.ErrRecordNotFound {
							patientsNew := models.XtPatientsNew{
								Name:              name,
								Gender:            sex,
								Birthday:          birth,
								Age:               ages,
								Phone:             phone,
								Lapseto:           lapseto,
								AdmissionNumber:   adminssionNumber,
								FirstDialysisDate: fisttime,
								Diagnose:          diagonse,
								Source:            patientsoure,
								DialysisNo:        dialysis,
								UserOrgId:         orgid,
								Status:            1,
								CreatedTime:       time.Now().Unix(),
								Avatar:            avatar,
								MemberPatients:    memberpatient,
								BloodPatients:     bloodPatient,
								SlowPatients:      slowpatient,
								MemberId:          memberPatient.ID,
								IsInfectious:      is_infectious,
								IdCardNo:          idCard,
								MemberFistdate:    memtime,
								MemberPatienttype: patient_type,
								MemberTreatement:  treatmentmethod,
							}
							err = service.CreateNewPatient(&patientsNew)
							fmt.Print("报错", err)
							if err != nil {
								this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
								return
							}
							this.ServeSuccessJSON(map[string]interface{}{
								"patient": patientsNew,
							})
						} else if errmembercode == nil {
							fmt.Print("病人已存在")
							return
						} else {

						}
					} else if errmembercode == nil {
						fmt.Print("病人已存在")
						return
					} else {

					}
				}
				return
			} else {

			}

		} else if errcodetwo == nil {
			fmt.Print("病人已存在")
			return
		} else {

		}

	}

	if memberpatient == 1 {
		fmt.Print("进来没有", memberpatient)
		_, errmembercode := service.GetMemberPatientInfo(orgid, phone)
		if errmembercode == gorm.ErrRecordNotFound {
			customer := models.SgjUserCustomer{
				Name:        name,
				UserOrgId:   orgid,
				Mobile:      phone,
				Gender:      sex,
				Birthday:    birth,
				IllDate:     memtime,
				Status:      1,
				CreatedTime: time.Now().Unix(),
				Avatar:      avatar,
				IllnessId:   patient_type,
				TreatType:   treatmentmethod,
			}
			errmembercode := service.CreateMemberPatient(&customer)
			fmt.Print("创建会员病人失败", errmembercode)
			_, errmembercodetwo := service.GetMemberNewPatient(phone, orgid)
			fmt.Print("错误", errmembercodetwo)
			//获取机构的最后一条数据
			memberPatient, errmembercode := service.GetLastMemberPatient(orgid)
			if errmembercodetwo == gorm.ErrRecordNotFound {
				patientsNew := models.XtPatientsNew{
					Name:              name,
					Gender:            sex,
					Birthday:          birth,
					Age:               ages,
					Phone:             phone,
					Lapseto:           lapseto,
					AdmissionNumber:   adminssionNumber,
					FirstDialysisDate: fisttime,
					Diagnose:          diagonse,
					Source:            patientsoure,
					DialysisNo:        dialysis,
					UserOrgId:         orgid,
					Status:            1,
					CreatedTime:       time.Now().Unix(),
					Avatar:            avatar,
					MemberPatients:    memberpatient,
					BloodPatients:     bloodPatient,
					SlowPatients:      slowpatient,
					MemberId:          memberPatient.ID,
					IsInfectious:      is_infectious,
					IdCardNo:          idCard,
					MemberFistdate:    memtime,
					MemberPatienttype: patient_type,
					MemberTreatement:  treatmentmethod,
				}
				err = service.CreateNewPatient(&patientsNew)
				fmt.Print("报错", err)
				if err != nil {
					this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
					return
				}
				this.ServeSuccessJSON(map[string]interface{}{
					"patient": patientsNew,
				})
			} else if errmembercode == nil {
				fmt.Print("病人已存在")
				return
			} else {

			}
		} else if errmembercode == nil {
			fmt.Print("病人已存在")
			return
		} else {

		}
	}

}

func (this *NewDialysisApiController) GetPatientDetail() {
	id, _ := this.GetInt64("id")
	//获取病人详情信息
	detail, err := service.GetPatientDetailTwo(id)
	//获取传染病详情
	diseases := service.GetPatientDiseasesTwo(detail.BloodId)
	//获取慢病传染病
	slowDiseases, err := service.GetSlowPatientDiseases(detail.SlowId)
	//获取慢病慢性病
	cronicDiseases, err := service.GetCronicDiseases(detail.SlowId)
	//获取血透医嘱管理
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patientDetail":  detail,
		"diseases":       diseases,
		"slowDiseases":   slowDiseases,
		"cronicDiseases": cronicDiseases,
	})
}

func (this *NewDialysisApiController) GetDoctorAdvices() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	id, _ := this.GetInt64("id")
	appid := adminInfo.App.Id
	fmt.Print("id", id)
	//跟据新表id获取老表id
	newPatientInfo, _ := service.GetPatientDetailTwo(id)
	//获取病人ID
	doctor_type, _ := this.GetInt64("type")
	fmt.Print("医嘱内型", doctor_type)
	start := this.GetString("startime")
	fmt.Print("start", start)
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("开始时间", startime)
	end := this.GetString("endtime")
	fmt.Print("end", end)
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 23:59:59", loc)
	endtime := endTimes.Unix()
	fmt.Print("结束时间", endtime)
	limit, _ := this.GetInt64("limit")
	page, _ := this.GetInt64("page")
	fmt.Println("病人ID", newPatientInfo.BloodId)
	advice, _, err := service.GetNewDoctorAdvice(newPatientInfo.BloodId, doctor_type, startime, endtime, limit, page, orgid)
	one, total, err := service.GetNewDoctorAdviceOne(newPatientInfo.BloodId, doctor_type, startime, endtime, limit, page, orgid)
	fmt.Println("err------------------------", err)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	doctor, err := service.GetAllDoctorTwo(orgid, appid)
	this.ServeSuccessJSON(map[string]interface{}{
		"advice": advice,
		"total":  total,
		"doctor": doctor,
		"one":    one,
	})
}

func (this *NewDialysisApiController) GetDryWeight() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 23:59:59", loc)

	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	dryweight, total, err := service.GetDryWeight(patient.BloodId, startime, endtime, limit, page, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"dryweight": dryweight,
		"total":     total,
	})
}

func (this *NewDialysisApiController) ToSearch() {
	adminUser := this.GetMobileAdminUserInfo()
	orgId := adminUser.Org.Id
	name := this.GetString("name")
	search, err := service.ToSearch(orgId, name)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"search": search,
	})
}

func (this *NewDialysisApiController) GetCourseManagement() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 23:59:59", loc)
	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	management, total, err := service.GetCourseManagement(patient.BloodId, startime, endtime, limit, page, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"coursemanagement": management,
		"total":            total,
	})
}

func (this *NewDialysisApiController) DeleteCourseManagement() {
	id, _ := this.GetInt64("id")
	err := service.DeleteCouseManagement(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) GetCouseManagentDetail() {
	id, _ := this.GetInt64("id")
	detail, err := service.GetCouseManagentDetail(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"couseDetail": detail,
	})
}

func (this *NewDialysisApiController) GetAllBloodDialysisPatient() {
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	lapseto, _ := this.GetInt64("patientstatus")
	source, _ := this.GetInt64("source")
	adminUserInfo := this.GetMobileAdminUserInfo()
	orgid := adminUserInfo.Org.Id
	patient, total, err := service.GetAllBloodDialysisPatient(orgid, page, limit, lapseto, source)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"bloodpatient": patient,
		"total":        total,
	})
}

func (this *NewDialysisApiController) GetAllSlowPatent() {
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	adminUserInfo := this.GetMobileAdminUserInfo()
	orgid := adminUserInfo.Org.Id
	patient, total, err := service.GetAllSlowPatient(orgid, page, limit)
	fmt.Print("err", err)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"slowpatient": patient,
		"total":       total,
	})
}

func (this *NewDialysisApiController) GetAllMemberPatient() {
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	adminUserInfo := this.GetMobileAdminUserInfo()
	orgid := adminUserInfo.Org.Id
	patient, total, err := service.GetAllMemberPatient(orgid, page, limit)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"memberpatient": patient,
		"total":         total,
	})
}

func (this *NewDialysisApiController) DeleteDryWeight() {
	id, _ := this.GetInt64("id")
	err := service.DeleteDryWeight(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) GetDryWeightDetail() {
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	drydetail, err := service.GetDryWeightDetail(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"drydetail": drydetail,
	})
}

func (this *NewDialysisApiController) GetlongDialysisrecord() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 00:00:00", loc)
	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	dialysisrecord, total, err := service.GetlongDialysisrecord(patient.BloodId, startime, endtime, limit, page, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"dialysisrecord": dialysisrecord,
		"total":          total,
	})
}

func (this *NewDialysisApiController) GetRescuerecord() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 23:59:59", loc)
	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	rescuerecord, total, err := service.GetRescuerecord(patient.BloodId, startime, endtime, limit, page, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"rescuerecord": rescuerecord,
		"total":        total,
	})
}

func (this *NewDialysisApiController) GetScheduling() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 00:00:00", loc)
	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	mode_type, _ := this.GetInt64("mode_types")
	fmt.Print("透析模式", mode_type)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	scheduling, total, err := service.GetScheduling(patient.BloodId, startime, endtime, limit, page, orgid, mode_type)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"scheduling": scheduling,
		"total":      total,
	})
}

func (this *NewDialysisApiController) GetEducation() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 00:00:00", loc)
	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	education, total, err := service.GetEducation(patient.BloodId, startime, endtime, limit, page, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"education": education,
		"total":     total,
	})
}

func (this *NewDialysisApiController) GetSchedulingDetail() {
	id, _ := this.GetInt64("id")
	detail, err := service.GetSchedulingDetail(id)
	patient, err := service.GetSchedulingTwo(id)
	fmt.Print("errr", err)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"schedulingDetail": detail,
		"patient":          patient,
	})
}

func (this *NewDialysisApiController) DeleteScheduling() {
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	err := service.DeleteScheduling(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) GetEducationDetail() {
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	education, err := service.GetEducationDetailOne(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"education": education,
	})
}

func (this *NewDialysisApiController) DeleteEducation() {
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	err := service.DeleteEducation(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) GetRescueRecordDetail() {
	id, _ := this.GetInt64("id")
	recordDetail, err := service.GetRescueRecordDetail(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"recordDetail": recordDetail,
	})
}

func (this *NewDialysisApiController) DeleteRescueRecord() {
	id, _ := this.GetInt64("id")
	err := service.DeleteRescueRecord(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) ToSearchePatient() {
	keyword := this.GetString("keyword")
	fmt.Print("关键字", keyword)
	adminUserinfo := this.GetMobileAdminUserInfo()
	orgid := adminUserinfo.Org.Id
	fmt.Println(orgid)
	patient, err := service.ToSearchePatient(keyword, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
	})
}

func (this *NewDialysisApiController) SearchallPatient() {
	keyword := this.GetString("keyword")
	fmt.Print("关键字", keyword)
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	patient, err := service.SearchallPatient(keyword, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
	})
}

func (this *NewDialysisApiController) GetSearchallBlood() {
	keyword := this.GetString("keyword")
	fmt.Print("关键字", keyword)
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	bloodPatient, err := service.GetSearchallBlood(keyword, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"bloodPatient": bloodPatient,
	})
}

func (this *NewDialysisApiController) GetSlowSearchePatient() {
	keyword := this.GetString("keyword")
	fmt.Print("关键字", keyword)
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	slowPatient, err := service.GetSlowSearchePatient(keyword, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"slowPatient": slowPatient,
	})
}

func (this *NewDialysisApiController) GetMemberSearchPatent() {
	keyword := this.GetString("keyword")
	fmt.Print("关键字", keyword)
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	memberPatient, err := service.GetMemberSearchPatient(keyword, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"memberPatient": memberPatient,
	})
}

func (this *NewDialysisApiController) GetLongDialysisDetail() {
	id, err := this.GetInt64("id")
	longDialysisDetail, err := service.GetLongDialysisDetail(id)
	patient, err := service.GetPatientName(longDialysisDetail.PatientId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"longDialysisDetail": longDialysisDetail,
		"patient":            patient,
	})
}

func (this *NewDialysisApiController) DeleteLongDialysis() {
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	err := service.DeleteLongDialysis(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) GetDialysisrecord() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 00:00:00", loc)
	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	appid := adminInfo.App.Id
	dislystype, _ := this.GetInt64("dislysType")
	fmt.Print("透析模式", dislystype)
	dialysisrecord, total, err := service.GetDialysisrecord(patient.BloodId, startime, endtime, limit, page, orgid, dislystype)
	doctor, err := service.GetAllDoctorTwo(orgid, appid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"dialysisrecord": dialysisrecord,
		"total":          total,
		"doctor":         doctor,
	})
}

func (this *NewDialysisApiController) GetDoctorAdviceDetail() {

	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	appid := adminUser.App.Id
	id, _ := this.GetInt64("id")
	bloodTwo, _ := service.GetPatientDetailTwo(id)
	fmt.Println("id", bloodTwo.BloodId)
	date, _ := this.GetInt64("date")
	doctorAdvicedetail, err := service.GetDoctorAdviceDetail(date, bloodTwo.BloodId, orgid)
	fmt.Println("err-------------------------------", err)
	doctorDetail, err := service.GetAllDoctorTwo(orgid, appid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"doctorAdvicedetail": doctorAdvicedetail,
		"doctorDetail":       doctorDetail,
	})
}

func (this *NewDialysisApiController) DeleteManagement() {
	groupno, _ := this.GetInt64("id")
	fmt.Print("id是什么", groupno)
	orgId := this.GetMobileAdminUserInfo().Org.Id
	fmt.Print("机构ID", orgId)
	err := service.DeleteManagement(groupno, orgId)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) DeleteChild() {
	id, _ := this.GetInt64("id")
	err := service.DeleteChild(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) DeletePatient() {
	id, _ := this.GetInt64("id")
	err := service.DeletePatient(id)
	fmt.Println("错误是什么", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "ok"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) UpdatedPatient() {

	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	fmt.Print("机构ID", orgid)
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	fmt.Print("err", err)
	id := int64(dataBody["id"].(float64))
	fmt.Print("id", id)
	name := dataBody["name"].(string)
	fmt.Println("姓名", name)
	sex := int64(dataBody["sex"].(float64))
	fmt.Print("性别", sex)
	idCard := dataBody["idCard"].(string)
	fmt.Print("身份证", idCard)
	birthday := dataBody["birthday"].(string)
	births := strings.Split(birthday, "-")
	fmt.Print("生日", birthday)
	birYear, _ := strconv.Atoi(births[0])
	age := time.Now().Year() - birYear
	ages := int64(age)
	fmt.Println("age是多少", ages)
	timeLayout := "2006-01-02 15:04:05"
	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
	birth := theTime.Unix()
	fmt.Print(birth)
	phone := dataBody["phone"].(string)
	fmt.Print("电话号码", phone)
	patientType := dataBody["result"].([]interface{})
	fmt.Print("患者标签", patientType)
	dialysis := dataBody["dialysis"].(string)
	fmt.Print("透析号", dialysis)
	patientsoure := int64(dataBody["patientsoure"].(float64))
	fmt.Print("患者来源", patientsoure)
	lapseto := int64(dataBody["lapseto"].(float64))
	fmt.Print("留置状态", lapseto)
	contagions := dataBody["resultTwo"].([]interface{})
	fmt.Print("传染病", contagions)
	ids := make([]int64, 0)
	for _, contagion := range contagions {
		id, _ := strconv.ParseInt(contagion.(string), 10, 64)
		ids = append(ids, id)
	}
	fmt.Print("传染病2", contagions)
	is_infectious := int64(dataBody["is_infectious"].(float64))
	fmt.Print("传染病", is_infectious)
	adminssionNumber := dataBody["admissionNumber"].(string)
	fmt.Print("住院号", adminssionNumber)

	fistdate := dataBody["fistDate"].(string)
	fmt.Print("首次透析日期", fistdate)
	timeLayouts := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	times, err := time.ParseInLocation(timeLayouts+" 15:04:05", fistdate+" 00:00:00", loc)
	//times, err := utils.ParseTimeStringToTime(timeLayout, fistdate+"00:00:00")
	fisttime := times.Unix()
	fmt.Print(fisttime)

	diagonse := dataBody["diagnose"].(string)
	fmt.Print("诊断", diagonse)
	avatar := dataBody["avatar"].(string)
	fmt.Print("头像", avatar)
	//慢性病
	requipmentId := dataBody["requipmentId"].(string)
	fmt.Print("设备ID", requipmentId)
	slowContagions := dataBody["resultThree"].([]interface{})
	fmt.Print("慢性传染病", slowContagions)
	idss := make([]int64, 0)
	for _, contagion := range slowContagions {
		id, _ := strconv.ParseInt(contagion.(string), 10, 64)
		idss = append(ids, id)
	}
	fmt.Print(idss)
	slowDiseases := dataBody["resultFour"].([]interface{})
	idsss := make([]int64, 0)
	for _, contagion := range slowDiseases {
		id, _ := strconv.ParseInt(contagion.(string), 10, 64)
		idsss = append(ids, id)
	}
	fmt.Print("idsss", idsss)
	fmt.Print("慢性病", slowDiseases)
	bloodPatient := int64(dataBody["bloodPatient"].(float64))
	fmt.Print("血透病人", bloodPatient)
	slowpatient := int64(dataBody["slowPatient"].(float64))
	fmt.Print("慢病病人", slowpatient)
	memberpatient := int64(dataBody["memberPatient"].(float64))
	fmt.Print("会员病人", memberpatient)
	//会员
	memberFistDate := dataBody["memberFistDate"].(string)
	fmt.Print("首次透析日期", memberFistDate)
	//membertimes, err := utils.ParseTimeStringToTime(timeLayout, memberFistDate+"00:00:00")
	membertimes, _ := time.ParseInLocation(timeLayouts+" 15:04:05", memberFistDate+" 00:00:00", loc)
	memtime := membertimes.Unix()
	fmt.Print("会员透析日期", memtime)
	patient_type := int64(dataBody["patientType"].(float64))
	fmt.Print("病种", patient_type)
	treatmentmethod := int64(dataBody["treatmentMethod"].(float64))
	fmt.Print("治疗方式", treatmentmethod)

	//如果是血透病人
	if bloodPatient == 1 {
		//根据新表ID获取老表病人ID
		patient, _ := service.GetNewPatient(id)

		//判断身份证号是否相同
		thisPatient, _ := service.FindPatientByIdCardNoOne(orgid, idCard, id)
		if thisPatient.ID > 0 && thisPatient.ID != patient.BloodId {
			returnData := make(map[string]interface{}, 0)
			returnData["msg"] = "身份证号码已存在"
			this.ServeSuccessJSON(returnData)
			return
		}

		//查询手机号码是否存在
		thisPatientOne, err := service.FindPatientByMobileOne(phone, orgid, id)
		if thisPatientOne.ID > 0 && thisPatientOne.ID != patient.BloodId {
			returnData := make(map[string]interface{}, 0)
			returnData["msg"] = "手机号码已存在"
			this.ServeSuccessJSON(returnData)
			return
		}

		//查询号透析号是否相同
		thisPatientother, _ := service.FindPatientByDialysisNoOne(orgid, dialysis, id)
		if thisPatientother.ID > 0 && thisPatientother.ID != patient.BloodId {
			fmt.Println("进来没有---------------------------------")
			returnData := make(map[string]interface{}, 0)
			returnData["msg"] = "透析号码已存在"
			this.ServeSuccessJSON(returnData)
			return
		}

		patients := models.Patients{
			Name:              name,
			Gender:            sex,
			Birthday:          birth,
			Age:               ages,
			Phone:             phone,
			Lapseto:           lapseto,
			AdmissionNumber:   adminssionNumber,
			FirstDialysisDate: fisttime,
			Diagnose:          diagonse,
			Source:            patientsoure,
			DialysisNo:        dialysis,
			UserOrgId:         orgid,
			Status:            1,
			CreatedTime:       time.Now().Unix(),
			Avatar:            avatar,
			IdCardNo:          idCard,
			IsInfectious:      is_infectious,
		}
		err = service.UpdatedPatient(patients, patient.BloodId)
		patientsNew := models.XtPatientsNew{
			ID:                id,
			Name:              name,
			Gender:            sex,
			Birthday:          birth,
			Age:               ages,
			Phone:             phone,
			Lapseto:           lapseto,
			AdmissionNumber:   adminssionNumber,
			FirstDialysisDate: fisttime,
			Diagnose:          diagonse,
			Source:            patientsoure,
			DialysisNo:        dialysis,
			UserOrgId:         orgid,
			Status:            1,
			CreatedTime:       time.Now().Unix(),
			Avatar:            avatar,
			IdCardNo:          idCard,
			IsInfectious:      is_infectious,
		}
		err = service.UpdateXtPatientNew(patientsNew, id)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"patients": patientsNew,
		})
		//更改传染病
		updateContagions, err := service.UpdateContagions(patient.BloodId)
		fmt.Print("更新传染病失败", err)
		fmt.Print("up", updateContagions)
		err = service.AddContagions(patient.BloodId, patient.CreatedTime, patient.UpdatedTime, ids)
		fmt.Println("添加传染病失败", err)
	}
	if slowpatient == 1 {
		patient, _ := service.GetNewPatient(id)
		patients := models.CdmPatients{
			Name:        name,
			Gender:      sex,
			Birthday:    birth,
			Phone:       phone,
			Diagnose:    diagonse,
			Source:      patientsoure,
			UserOrgId:   orgid,
			Status:      1,
			CreatedTime: time.Now().Unix(),
			Avatar:      avatar,
			IdCardNo:    idCard,
		}
		err := service.UpdateCustomer(patients, patient.SlowId)
		fmt.Print("更新慢病患者失败", err)
		xtPatientsNew := models.XtPatientsNew{
			ID:                id,
			Name:              name,
			Gender:            sex,
			Birthday:          birth,
			Age:               ages,
			Phone:             phone,
			Lapseto:           lapseto,
			AdmissionNumber:   adminssionNumber,
			FirstDialysisDate: fisttime,
			Diagnose:          diagonse,
			Source:            patientsoure,
			DialysisNo:        dialysis,
			UserOrgId:         orgid,
			Status:            1,
			CreatedTime:       time.Now().Unix(),
			Avatar:            avatar,
			MemberPatients:    memberpatient,
			BloodPatients:     bloodPatient,
			SlowPatients:      slowpatient,
			IsInfectious:      is_infectious,
			IdCardNo:          idCard,
			EquitmentId:       requipmentId,
		}
		err = service.UpdateXtPatientNew(xtPatientsNew, id)
		fmt.Print("更新失败", err)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"patients": xtPatientsNew,
		})
	}

	if memberpatient == 1 {
		patient, _ := service.GetNewPatient(id)
		customer := models.SgjUserCustomer{
			Name:        name,
			UserOrgId:   orgid,
			Mobile:      phone,
			Gender:      sex,
			Birthday:    birth,
			IllDate:     memtime,
			Status:      1,
			CreatedTime: time.Now().Unix(),
			Avatar:      avatar,
			IllnessId:   patient_type,
			TreatType:   treatmentmethod,
		}
		err := service.UpdatedCustomer(customer, patient.MemberId)

		fmt.Print("更新失败", err)
		patientsNew := models.XtPatientsNew{
			ID:                id,
			Name:              name,
			Gender:            sex,
			Birthday:          birth,
			Age:               ages,
			Phone:             phone,
			Lapseto:           lapseto,
			AdmissionNumber:   adminssionNumber,
			FirstDialysisDate: fisttime,
			Diagnose:          diagonse,
			Source:            patientsoure,
			DialysisNo:        dialysis,
			UserOrgId:         orgid,
			Status:            1,
			CreatedTime:       time.Now().Unix(),
			Avatar:            avatar,
			MemberPatients:    memberpatient,
			BloodPatients:     bloodPatient,
			SlowPatients:      slowpatient,
			IsInfectious:      is_infectious,
			IdCardNo:          idCard,
			MemberFistdate:    memtime,
			MemberPatienttype: patient_type,
			MemberTreatement:  treatmentmethod,
		}
		err = service.UpdateXtPatientNewOne(patientsNew, id)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"patients": patientsNew,
		})
	}
}

func (this *NewDialysisApiController) GetAllDoctor() {
	orgid := this.GetMobileAdminUserInfo().Org.Id
	id := this.GetMobileAdminUserInfo().App.Id
	doctor, err := service.GetAllDoctorTwo(orgid, id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"doctor": doctor,
	})
}

func (this *NewDialysisApiController) GetAllProjectName() {
	id := this.GetString("date")
	fmt.Println("id是", id)
	ids, _ := strconv.ParseInt(id, 10, 64)
	patientid := this.GetString("patientid")
	fmt.Println("patient", patientid)
	paientids, _ := strconv.ParseInt(patientid, 10, 64)
	patient, _ := service.GetNewPatient(paientids)
	orgid := this.GetMobileAdminUserInfo().Org.Id
	projectName, err := service.GetAllProjectName(ids, orgid, patient.BloodId)
	fmt.Println("projectname----------------------------------", err)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"projectName": projectName,
	})
}

func (this *NewDialysisApiController) GetAllInspection() {

	//查询该机构是否存在检验检测项目
	orgid := this.GetMobileAdminUserInfo().Org.Id
	fmt.Print("orgid", orgid)
	_, errcode := service.GetInspectionByOrgId(orgid)
	if errcode == gorm.ErrRecordNotFound {
		inspection, err := service.GetAllInspection(0)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"inspection": inspection,
		})
	} else if errcode == nil {
		inspection, err := service.GetAllInspection(orgid)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"inspection": inspection,
		})
	} else {

	}

}

func (this *NewDialysisApiController) GetInspection() {
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	id, _ := this.GetInt64("id")
	fmt.Print("id", id)
	patient, _ := service.GetPatientDetailTwo(id)
	start := this.GetString("startime")
	startTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", start+" 00:00:00", loc)
	startime := startTimes.Unix()
	fmt.Print("startime", startime)
	end := this.GetString("endtime")
	endTimes, _ := time.ParseInLocation(timeLayout+" 15:04:05", end+" 00:00:00", loc)
	endtime := endTimes.Unix()
	fmt.Print("endtime", endtime)
	limit, _ := this.GetInt64("limit")
	fmt.Print("limit", limit)
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	projectid, _ := this.GetInt64("projectid")
	fmt.Print("projectid", projectid)
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	fmt.Print("patient", patient)
	fmt.Print("orgid", orgid)

	//查询该机构是否存在
	//inspection, _ := service.GetInspectionById(patient.BloodId, startime, endtime, orgid)
	//if len(inspection) == 0 {
	//
	//}
	inspection, total, err := service.GetInspection(patient.BloodId, startime, endtime, limit, page, orgid, projectid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"inspection": inspection,
		"total":      total,
	})
}

func (this *NewDialysisApiController) GetMyInformation() {
	id, _ := this.GetInt64("id")
	roleInfo, err := service.GetPosition(id)

	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"roleInfo": roleInfo,
	})
	return
}

func (this *NewDialysisApiController) GetMyInformationThree() {
	id, _ := this.GetInt64("id")
	roleInfo, err := service.GetPositionOne(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"roleInfo": roleInfo,
	})
	return
}

func (this *NewDialysisApiController) GetPatientName() {
	id, _ := this.GetInt64("id")
	patients, _ := service.GetPatientDetailTwo(id)
	fmt.Print("paitents", patients.ID)
	patientName, err := service.GetPatientName(patients.BloodId)
	fmt.Print("err", err)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patientName": patientName,
	})
}

func (this *NewDialysisApiController) GetInspectionDetail() {

	patientid, _ := this.GetInt64("patientid")
	fmt.Print("patientid", patientid)
	patients, _ := service.GetPatientDetailTwo(patientid)
	date, _ := this.GetInt64("date")
	fmt.Print("date", date)
	projectid, _ := this.GetInt64("projectid")
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	InspectionDetail, err := service.GetInspectionDetail(patients.BloodId, date, orgid, projectid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"InspectionDetail": InspectionDetail,
	})
}

func (this *NewDialysisApiController) SaveFeed() {

	question, _ := this.GetInt64("question")
	fmt.Print("question", question)
	title := this.GetString("title")
	fmt.Print("title", title)
	content := this.GetString("content")
	fmt.Print("content", content)
	phone := this.GetString("phone")
	fmt.Print("phone", phone)
	times, _ := this.GetInt64("time")
	fmt.Print("time", times)
	adminuserid, _ := this.GetInt64("admin_user_id")
	fmt.Println("admin", adminuserid)
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	appid := adminUser.App.Id
	feedback := models.XtPatientFeedback{
		ProblemType: question,
		Title:       title,
		Content:     content,
		Phone:       phone,
		TimeQuantum: times,
		UserOrgId:   orgid,
		Ctime:       time.Now().Unix(),
		Status:      1,
		AdminUserId: adminuserid,
		AppId:       appid,
	}
	err := service.CreateFeedBack(&feedback)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"feedback": feedback,
	})
}

func (this *NewDialysisApiController) DeleteInspection() {
	admininfo := this.GetMobileAdminUserInfo()
	orgid := admininfo.Org.Id
	date, _ := this.GetInt64("date")
	fmt.Println("date", date)
	err := service.DeleteInspection(date, orgid)
	fmt.Println("删除失败", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "手机号码已存在"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) DeleteChildInspection() {
	admininfo := this.GetMobileAdminUserInfo()
	orgid := admininfo.Org.Id
	name := this.GetString("name")
	fmt.Println("name", name)
	date, _ := this.GetInt64("date")
	fmt.Println("date", date)
	err := service.DeleteChildInspection(name, date, orgid)
	fmt.Println("删除失败", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "手机号码已存在"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) SaveMessage() {
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
	message := this.GetString("message")
	fmt.Println("message", message)
	orgid, _ := this.GetInt64("orgid")
	role := models.SgjUserAdminRole{
		Message: message,
	}
	err := service.SaveMessage(id, orgid, &role)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"role": role,
	})
}

func (this *NewDialysisApiController) SaveSex() {
	sex, _ := this.GetInt64("sex")
	fmt.Println("sex", sex)
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
	orgid, _ := this.GetInt64("orgid")
	role := models.SgjUserAdminRole{
		Sex:   sex,
		OrgId: orgid,
	}
	err := service.SaveSex(id, &role)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"role": role,
	})
}

func (this *NewDialysisApiController) SaveBirthday() {
	dataBody := make(map[string]interface{}, 0)
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &dataBody)
	fmt.Println(err)
	id := dataBody["id"].(string)
	ids, err := strconv.ParseInt(id, 10, 64)
	fmt.Print("id", id)
	birthday := dataBody["birth"].(string)
	timeLayout := "2006-01-02 15:04:05"
	theTime, err := utils.ParseTimeStringToTime(timeLayout, birthday+" 00:00:00")
	birth := theTime.Unix()
	orgid := dataBody["orgid"].(string)
	orgids, err := strconv.ParseInt(orgid, 10, 64)
	role := models.SgjUserAdminRole{
		Birthday: birth,
		OrgId:    orgids,
	}
	err = service.SaveBirthday(ids, &role)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"role": role,
	})
}

func (this *NewDialysisApiController) GetOrgName() {

	id, _ := this.GetInt64("id")
	name, err := service.GetOrgName(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"name": name,
	})
}

func (this *NewDialysisApiController) GetRoleName() {
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
	orgid, _ := this.GetInt64("orgid")
	fmt.Println("orgid", orgid)
	//跟剧机构ID获取APPID
	app, _ := service.GetAppId(orgid)
	name, err := service.GetRoleName(id, orgid, app.Id)

	//获取管理员
	admin, err := service.GetAdmin(id)
	positionName, err := service.GetPositionName(id, orgid, app.Id)
	role_ids := strings.Split(positionName.RoleIds, ",")
	var names = ""
	for _, item := range role_ids {
		id, _ := strconv.ParseInt(item, 10, 64)
		role, _ := service.GetRole(id)
		if len(role.RoleName) != 0 {
			names = role.RoleName + "," + names
		}
	}
	//fmt.Println("role_ids--------------", role_ids)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"name":         name,
		"positionName": positionName,
		"admin":        admin,
		"names":        names,
	})
}

func (this *NewDialysisApiController) SavePartition() {
	adminInfo := this.GetMobileAdminUserInfo()
	name := this.GetString("name")
	fmt.Println("分区名称", name)
	zonetype, _ := this.GetInt64("type")
	fmt.Println("分区型号", zonetype)
	strInt64 := strconv.FormatInt(zonetype, 10)
	typeid, _ := strconv.Atoi(strInt64)
	zone := models.DeviceZone{
		Name:       name,
		Type:       typeid,
		OrgID:      adminInfo.Org.Id,
		Status:     1,
		CreateTime: time.Now().Unix(),
	}
	err := service.CreatedZone(&zone)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"zone": zone,
	})
}

func (this *NewDialysisApiController) GetAllZone() {

	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	page, _ := this.GetInt64("page")
	limit, _ := this.GetInt64("limit")
	zone, total, err := service.GetAllZone(orgid, page, limit)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"zone":  zone,
		"total": total,
	})
}

func (this *NewDialysisApiController) DeleteZone() {
	id, _ := this.GetInt64("id")
	err := service.DeleteZoneById(id)
	fmt.Println("删除失败", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "删除失败"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) SaveGroup() {
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	name := this.GetString("name")
	fmt.Println("name", name)
	group := models.DeviceGroup{
		Name:       name,
		Status:     1,
		CreateTime: time.Now().Unix(),
		OrgID:      orgid,
	}
	err := service.SaveGroup(&group)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"group": group,
	})
}

func (this *NewDialysisApiController) GetAllGroup() {
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	page, _ := this.GetInt64("page")
	fmt.Println("page", page)
	limit, _ := this.GetInt64("limit")
	fmt.Println("limit", limit)
	group, total, err := service.GetAllGroup(orgid, page, limit)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"group": group,
		"total": total,
	})
}

func (this *NewDialysisApiController) DeleteGroup() {
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
	err := service.DeleteGroup(id)
	fmt.Println("删除失败", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "删除失败"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) GetAllGroupOne() {
	admininfo := this.GetMobileAdminUserInfo()
	orgid := admininfo.Org.Id
	zone, _ := service.GetAllZoneOne(orgid)
	group, err := service.GetAllGroupOne(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"zone":  zone,
		"group": group,
	})
}

func (this *NewDialysisApiController) SaveBed() {
	adminuser := this.GetMobileAdminUserInfo()
	orgid := adminuser.Org.Id
	name := this.GetString("name")
	fmt.Println("name", name)
	zone, _ := this.GetInt64("zone")
	fmt.Print("zone", zone)
	group, _ := this.GetInt64("group")
	fmt.Println("group", group)
	number := models.DeviceNumber{
		Number:     name,
		ZoneID:     zone,
		GroupID:    group,
		OrgID:      orgid,
		Status:     1,
		CreateTime: time.Now().Unix(),
	}
	err := service.CreateNumber(&number)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"number": number,
	})
}

func (this *NewDialysisApiController) GetAllNumber() {
	admininfo := this.GetMobileAdminUserInfo()
	orgid := admininfo.Org.Id
	page, _ := this.GetInt64("page")
	fmt.Print("page", page)
	limit, _ := this.GetInt64("limit")
	fmt.Println("limit", limit)
	number, total, err := service.GetAllNumber(page, limit, orgid)
	zone, _ := service.GetAllZoneOne(orgid)
	group, _ := service.GetAllGroupOne(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"number": number,
		"total":  total,
		"zone":   zone,
		"group":  group,
	})
}

func (this *NewDialysisApiController) DeleteBed() {
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
	nowDateTime := time.Now()
	nowDate := nowDateTime.Format("2006-01-02")
	nowDate += " 00:00:00"
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	theTime, _ := time.ParseInLocation(timeLayout+" 15:04:05", nowDate, loc)
	fmt.Println(theTime.Unix())
	adminInfo := this.GetMobileAdminUserInfo()
	orgid := adminInfo.Org.Id
	_, errcode := service.GetSchedu(id, theTime.Unix(), orgid)
	fmt.Println("errcode", errcode)
	if errcode == gorm.ErrRecordNotFound {
		err := service.DeleteBed(id)
		fmt.Println("删除失败", err)
		returnData := make(map[string]interface{}, 0)
		returnData["msg"] = "删除失败"
		this.ServeSuccessJSON(returnData)
		return
	} else if errcode == nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}

}

func (this *NewDialysisApiController) LoginOut() {
	this.Ctx.SetCookie("logout_cookie", "1")
	this.Ctx.SetCookie("token_cookie", "")
	id, _ := this.GetInt64("id")
	loginLog := models.SgjUserAdminLoginLog{
		AdminUserId: id,
		OrgId:       0,
		AppId:       0,
		Ip:          utils.GetIP(this.Ctx.Request),
		OperateType: 2,
		AppType:     0,
		Ctime:       time.Now().Unix(),
	}
	err := service.CreateLoginLod(&loginLog)
	fmt.Println("err--------", err)
	returnData := make(map[string]interface{}, 0)
	returnData["msg"] = "删除失败"
	this.ServeSuccessJSON(returnData)
	return
}

func (this *NewDialysisApiController) GetMemberPatient() {

	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	patient, err := service.GetMemberPatient(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
	})
}

func (this *NewDialysisApiController) GetSlowPatient() {
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	patient, err := service.GetSlowPatient(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
	})
}

func (this *NewDialysisApiController) GetBloodPatient() {
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	patient, err := service.GetBloodPatient(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"patient": patient,
	})
}

func (this *NewDialysisApiController) SaveName() {
	id := this.GetString("id")
	ids, _ := strconv.ParseInt(id, 10, 64)
	fmt.Println("id", ids)
	name := this.GetString("name")
	fmt.Println("name", name)
	admin := models.SgjUserAdmin{
		Name: name,
	}
	err := service.SaveName(ids, &admin)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"admin": admin,
	})
}

func (this *NewDialysisApiController) GetAllOrganization() {

	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
}

func (this *NewDialysisApiController) GetMyOrganazition() {
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
	role, _ := service.GetAdminUserId(id)
	organaziton, err := service.GetMyOrganaziton(role.AdminUserId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"organaziton": organaziton,
	})
}

func (this *NewDialysisApiController) GetOrgInformation() {
	id, _ := this.GetInt64("id")
	information, err := service.GetOrgInformation(id)
	name, err := service.GetShortName(information.OrgType)
	typeName, err := service.GetTypeName(name.Pid)
	//获取省
	province, err := service.GetOrgProvince(information.Province)
	cityes, err := service.GetOrgProvince(information.City)
	district, err := service.GetOrgProvince(information.District)
	fmt.Print("err", err)
	//if err != nil {
	//	this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
	//	return
	//}
	this.ServeSuccessJSON(map[string]interface{}{
		"information": information,
		"name":        name,
		"typeName":    typeName,
		"province":    province,
		"city":        cityes,
		"district":    district,
	})
}

func (this *NewDialysisApiController) GetAllOrgType() {

	orgType, _ := service.GetAllOrgType()
	returnData := make(map[string]interface{}, 0)
	returnData["orgType"] = orgType
	this.ServeSuccessJSON(returnData)
}

func (this *NewDialysisApiController) EditOrg() {
	id, _ := this.GetInt64("id")
	fmt.Println("id", id)
	name := this.GetString("org_name")
	fmt.Println("name", name)
	provinceName := this.GetString("provinces_name")
	fmt.Println("provinceName", provinceName)
	cityName := this.GetString("city_name")
	fmt.Println("cityName", cityName)
	districtName := this.GetString("district_name")
	fmt.Println("districtName", districtName)
	address := this.GetString("address")
	fmt.Println("address", address)
	org_type := this.GetString("org_type")
	fmt.Println("org_type", org_type)
	contactName := this.GetString("contact_name")
	fmt.Println("contactName", contactName)
	orgPhone := this.GetString("telephone")
	fmt.Println("orgPhone", orgPhone)
	provinceID := 0
	cityID := 0
	districtID := 0
	province, getProvinceErr := service.GetProvinceWithName(provinceName)
	if getProvinceErr != nil {
		utils.ErrorLog("查询省名失败：%v", getProvinceErr)
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else if province != nil {
		provinceID = int(province.ID)
		city, getCityErr := service.GetCityWithName(province.ID, cityName)
		if getCityErr != nil {
			utils.ErrorLog("查询城市名失败：%v", getCityErr)
			this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
			this.ServeJSON()
			return
		} else if city != nil {
			cityID = int(city.ID)
			district, getDistrictErr := service.GetDistrictWithName(city.ID, districtName)
			if getDistrictErr != nil {
				utils.ErrorLog("查询区县名失拜：%v", getDistrictErr)
				this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
				this.ServeJSON()
				return
			} else if district != nil {
				districtID = int(district.ID)
			}
		}
	}

	orgType := service.GetOrgTypeByName(org_type)
	fmt.Println(provinceID, cityID, districtID)
	org := models.SgjUserOrg{
		OrgName:      name,
		OrgShortName: name,
		Province:     int64(provinceID),
		City:         int64(cityID),
		District:     int64(districtID),
		Address:      address,
		OrgType:      orgType.ID,
		Telephone:    orgPhone,
		ContactName:  contactName,
	}

	fmt.Println("org", org)
	err := service.UpdateOrg(id, org)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"org": org,
	})
}

func (this *NewDialysisApiController) GetMyInforName() {
	id, _ := this.GetInt64("id")
	orgid, _ := this.GetInt64("orgid")
	Username, err := service.GetAdminName(id, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"Username": Username,
	})
}

func (this *NewDialysisApiController) GetMyInformationFour() {
	adminUserInfo := this.GetMobileAdminUserInfo()
	//creatId := adminUserInfo.AdminUser.Id
	//fmt.Println("创建者ID", creatId)
	orgid := adminUserInfo.Org.Id
	//跟剧机构ID获取创建者ID
	fmt.Println("orgid", orgid)
	//OrgId, _ := service.GetCreatByOrgId(orgid)
	//fmt.Println("创建者ID", OrgId.Creator)
	creatId := adminUserInfo.AdminUser.Id
	//fmt.Println("creatid", creatId)
	fmt.Println("当前机构ID信息", orgid)
	Username, err := service.GetMyOrgInformationFour(creatId, orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"Username": Username,
	})
}

func (this *NewDialysisApiController) GetPartionDetail() {
	id, _ := this.GetInt64("id")
	partionDetail, err := service.GetPartionDetail(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"partionDetail": partionDetail,
	})
}

func (this *NewDialysisApiController) UpdatePartition() {
	id, _ := this.GetInt64("id")
	name := this.GetString("name")
	zoneType, _ := this.GetInt64("type")
	strInt64 := strconv.FormatInt(zoneType, 10)
	typeid, _ := strconv.Atoi(strInt64)
	zone := models.DeviceZone{
		Name: name,
		Type: typeid,
	}
	err := service.UpdatePartition(id, &zone)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"zone": zone,
	})
}

func (this *NewDialysisApiController) GetGroupDetail() {
	id, _ := this.GetInt64("id")
	groupDetail, err := service.GetGroupDetail(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"groupDetail": groupDetail,
	})

}

func (this *NewDialysisApiController) UpdateGroup() {
	id, _ := this.GetInt64("id")
	name := this.GetString("name")
	group := models.DeviceGroup{Name: name}
	err := service.UpdateGroup(id, &group)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"group": group,
	})
}

func (this *NewDialysisApiController) GetBedDetail() {
	adminUser := this.GetMobileAdminUserInfo()
	orgid := adminUser.Org.Id
	id, _ := this.GetInt64("id")
	zone, _ := service.GetAllZoneOne(orgid)
	group, err := service.GetAllGroupOne(orgid)
	bedDetail, err := service.GetBedDetail(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"zone":      zone,
		"group":     group,
		"bedDetail": bedDetail,
	})
}

func (this *NewDialysisApiController) UpdatedBed() {
	id, _ := this.GetInt64("id")
	name := this.GetString("name")
	fmt.Println("name", name)
	zone, _ := this.GetInt64("zone")
	fmt.Println("zone", zone)
	group, _ := this.GetInt64("group")
	fmt.Println("group", group)
	number := models.DeviceNumber{
		Number:  name,
		ZoneID:  zone,
		GroupID: group,
	}
	err := service.UpdatedBed(id, &number)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"number": number,
	})
}

func (this *NewDialysisApiController) GetMyOrgInformation() {
	creator, _ := this.GetInt64("creator")
	fmt.Println("cretor", creator)
	adminInfo := this.GetMobileAdminUserInfo()
	appId := adminInfo.App.Id
	information, err := service.GetMyOrgInformation(creator, appId)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"information": information,
	})
}

func (this *NewDialysisApiController) SaveNameTwo() {
	id, _ := this.GetInt64("id")
	name := this.GetString("name")
	orgid, _ := this.GetInt64("orgid")
	role := models.SgjUserAdminRole{
		UserName: name,
	}
	err := service.SaveNameTwo(id, orgid, &role)
	fmt.Println("err", err)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"role": role,
	})
}

func (this *NewDialysisApiController) GetCurrentOrg() {
	nowTime := time.Now().Unix()
	adminInfo := this.GetMobileAdminUserInfo()
	orgId := adminInfo.Org.Id

	var key = "kN*5&AHqLP7&IGRKvHoElJm*2YY6Nw*QSScJ4ff&DH&ofGnbfQIks1A1NT9AbIDB"
	stringA := fmt.Sprintf("org_id=%d&time=%d", orgId, nowTime)
	data := []byte(stringA)
	has := md5.Sum(data)
	md5str := fmt.Sprintf("%x", has)
	stringB := fmt.Sprintf("string=%s&key=%s", md5str, key)
	data = []byte(stringB)
	has = md5.Sum(data)
	signToken := fmt.Sprintf("%x", has)
	name, err := service.GetOrgName(orgId)
	//var fxlink = signToken + fmt.Sprintf("&fxtoken=%s&fxorgid=%d&timestamp=%d&fxadmin=%d", signToken, orgId, nowTime, name.Creator)
	//fmt.Println(fxlink)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"org":       name,
		"nowTime":   nowTime,
		"signToken": signToken,
	})
}

func (this *NewDialysisApiController) GetMyMobile() {
	id, _ := this.GetInt64("id")
	mobile, err := service.GetMyMobile(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"mobile": mobile,
	})
}

func (this *NewDialysisApiController) SumitForm() {

	name := this.GetString("name")
	fmt.Println("姓名", name)
	mobile := this.GetString("mobile")
	fmt.Println("mobile", mobile)
	address := this.GetString("address")
	fmt.Println("address", address)
	positon, _ := this.GetInt64("position")
	fmt.Println("职位", positon)
	hospitalName := this.GetString("hospitalName")
	fmt.Println("医院名称", hospitalName)
	systemName := this.GetString("systemName")
	fmt.Println("系统名称", systemName)
	isUser, _ := this.GetInt64("isUser")
	fmt.Println("是否使用", isUser)
	isThink, _ := this.GetInt64("isThink")
	fmt.Println("是否考虑", isThink)
	result := this.GetString("result")
	fmt.Println("result", result)
	otherRemark := this.GetString("otherRemark")
	fmt.Println("result", otherRemark)
	otherMessage := this.GetString("otherMessage")
	fmt.Println("otherMessage", otherMessage)
	gift, _ := this.GetInt64("gift")
	fmt.Println("gift", gift)
	admininfo := this.GetMobileAdminUserInfo()
	creator := admininfo.AdminUser.Id
	fmt.Println("创建者", creator)
	_, errcode := service.GetActivtyCreator(creator)
	if errcode == gorm.ErrRecordNotFound {
		table := models.KyActivityTable{
			Name:         name,
			Phone:        mobile,
			Address:      address,
			Position:     positon,
			HospitalName: hospitalName,
			SystemName:   systemName,
			IsUser:       isUser,
			IsThink:      isThink,
			OtherMode:    result,
			OtherRemark:  otherRemark,
			OtherMessage: otherMessage,
			Gift:         gift,
			AdminUserId:  creator,
			Status:       1,
			Ctime:        time.Now().Unix(),
		}
		err := service.CreateTable(&table)
		if err != nil {
			this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
			return
		}
		this.ServeSuccessJSON(map[string]interface{}{
			"table": table,
		})
	} else if errcode == nil {
		this.Data["json"] = enums.MakeFailResponseJSONWithSGJErrorCode(enums.ErrorCodeDataException)
		this.ServeJSON()
		return
	} else {
		return
	}
}

func (this *NewDialysisApiController) GetMobile() {
	adminInfo := this.GetMobileAdminUserInfo()
	id := adminInfo.AdminUser.Id

	mobile, err := service.GetMobile(id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"mobile": mobile,
	})
}

func (this *NewDialysisApiController) GetRolePosition() {

	adminInfo := this.GetMobileAdminUserInfo()
	cretor := adminInfo.AdminUser.Id
	orgid := adminInfo.Org.Id

	//去查角色
	role, err := service.GetAdminUserRole(cretor, orgid)
	fmt.Println("role----------------", role.RoleIds)
	role_ids := strings.Split(role.RoleIds, ",")
	var names = ""
	for _, item := range role_ids {
		id, _ := strconv.ParseInt(item, 10, 64)
		role, _ := service.GetRole(id)
		if len(role.RoleName) != 0 {
			names = role.RoleName + "," + names
		}
	}
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"names": names,
	})
}

func (this *NewDialysisApiController) GetOrgs() {
	adminInfo := this.GetMobileAdminUserInfo()
	orgs, err := service.GetOrgs(adminInfo.AdminUser.Id)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"orgs": orgs,
	})
}
