package controllers

import (
	"XT_New/enums"
	"XT_New/models"
	"XT_New/service"
	"XT_New/utils"
	"fmt"
	"github.com/astaxie/beego"
	"strconv"
	"strings"
	"time"
)

type StatisticsApiController struct {
	BaseAuthAPIController
}

func StatisticsApiRegistRouters() {
	beego.Router("/api/statistisc/index", &StatisticsApiController{}, "get:GetStatistics")
	beego.Router("/api/qc/statistiscall/get", &StatisticsApiController{}, "get:GetAllInspectionStatistisc")
	beego.Router("/api/qc/statistiscperson/get", &StatisticsApiController{}, "get:GetPersonInspectionStatistisc")
	beego.Router("/api/qc/statistiscperson/list", &StatisticsApiController{}, "get:GetInsepctionList")
	beego.Router("/api/qc/patientstatistiscall/get", &StatisticsApiController{}, "get:GetPatientInspectionStatistisc")
	beego.Router("/api/qc/patientinspectionstatistis/get", &StatisticsApiController{}, "get:GetFivePatientInspectionStatistisc")

	beego.Router("/api/commonqc/statistiscall/get", &StatisticsApiController{}, "get:GetAllCommonInspectionStatistisc")
	beego.Router("/api/commonqc/statistiscperson/get", &StatisticsApiController{}, "get:GetPersonCommonInspectionStatistisc")
	beego.Router("/api/commonqc/patientstatistiscall/get", &StatisticsApiController{}, "get:GetPatientCommonInspectionStatistisc")

	//透析总量统计
	beego.Router("/api/commonqc/dialysis/total", &StatisticsApiController{}, "get:GetDialysisTotal")
	beego.Router("/api/commonqc/dialysis/detail", &StatisticsApiController{}, "get:GetDialysisTotalDetail")
	beego.Router("/api/commonqc/dialysis/detailsinfo", &StatisticsApiController{}, "get:GetDialysisTotalDetailInfo")

	beego.Router("/api/commonqc/anticoagulant", &StatisticsApiController{}, "get:GetAnticoagulant")
	beego.Router("/api/commonqc/anticoagulant/detail", &StatisticsApiController{}, "get:GetAnticoagulantDetail")

	beego.Router("/api/commonqc/dialyzer", &StatisticsApiController{}, "get:GetDialyzer")
	beego.Router("/api/commonqc/dialyzer/config", &StatisticsApiController{}, "get:GetDialyzerConfig")
	beego.Router("/api/commonqc/dialyzer/detail", &StatisticsApiController{}, "get:GetDialyzerDetail")

	beego.Router("/api/commonqc/dialysistreat/finish", &StatisticsApiController{}, "get:GetDialysisTreatFinsh")
	beego.Router("/api/commonqc/dialysistreat/detail", &StatisticsApiController{}, "get:GetDialysisTreatDetail")

}

func (c *StatisticsApiController) GetDialysisTreatFinsh() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	data, _ := service.GetDialysisCompletionRate(c.GetAdminUserInfo().CurrentOrgId, startTime, endTime)
	total, _ := service.GetDialysisCompletionTotal(c.GetAdminUserInfo().CurrentOrgId, startTime, endTime)
	c.ServeSuccessJSON(map[string]interface{}{
		"data":  data,
		"total": total,
	})
}
func (c *StatisticsApiController) GetDialysisTreatDetail() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	mode, _ := c.GetInt64("mode")
	page, _ := c.GetInt64("page", 0)
	limit, _ := c.GetInt64("limit", 0)
	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	data, total, _ := service.GetDialysisCompletionDetail(c.GetAdminUserInfo().CurrentOrgId, startTime, endTime, mode, limit, page)
	c.ServeSuccessJSON(map[string]interface{}{
		"list":  data,
		"total": total,
	})
}

func (c *StatisticsApiController) GetDialysisTotal() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	mode, _ := c.GetInt64("mode")
	origin, _ := c.GetInt64("origin")
	time_way, _ := c.GetInt64("time_way")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	if mode == 0 { //统计透析模式不限
		//获取总人数
		p_total, _ := service.GetNewDialysiTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, origin)
		count_struct, _ := service.GetNewDialysisCountMode(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, origin, 0)
		c.ServeSuccessJSON(map[string]interface{}{
			"patient_count": p_total,
			"list":          count_struct,
		})
	} else { //固定某个模式
		// 拆分日期范围
		dates, err := splitDateRange(start_date, end_date)
		if err != nil {
			fmt.Println("Error:", err)
			return
		}

		var cuss []models.CustomDialysisData
		p_total, _ := service.GetNewDialysiTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, origin)
		switch time_way {
		case 1:
			// 按周统计
			weeks := groupByWeek(dates)
			fmt.Println(weeks)
			for _, week := range weeks {
				// 解析字符串时显式指定时区为 UTC
				t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", week[0].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}

				// 格式化时间时将时区设置为 UTC
				//fmt.Println(t.UTC().Format("2006-01-02 15:04:05"))

				var cus models.CustomDialysisData
				//week_date := week[0].Format("2006-01-02") + " 00:00:00"

				//date, err := time.Parse("2006-01-02 15:04:05", week_date)
				//if err != nil {
				//	fmt.Println("日期解析错误:", err)
				//	return
				//}

				// 将time.Time类型转换为时间戳(秒)
				//week_start := date.Unix()

				// 解析字符串时显式指定时区为 UTC
				t2, err := time.Parse("2006-01-02 15:04:05 -0700 MST", week[len(week)-1].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}

				//week_end_date := week[len(week)-1].Format("2006-01-02") + " 00:00:00"

				//end_date, err := time.Parse("2006-01-02 15:04:05", week_end_date)
				//if err != nil {
				//	fmt.Println("日期解析错误:", err)
				//	return
				//}
				//
				//// 将time.Time类型转换为时间戳(秒)
				//week_end := end_date.Unix()

				counts, _ := service.GetNewDialysisCountModeTwo(t.Unix(), t2.Unix(), c.GetAdminUserInfo().CurrentOrgId, origin, mode)
				cus.Date = strings.Split(week[0].String(), " ")[0] + "~" + strings.Split(week[len(week)-1].String(), " ")[0]
				cus.Count = counts.Count
				cus.Total = p_total
				cuss = append(cuss, cus)

			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": cuss,
			})
			break
		case 2:
			startDate, err := time.Parse("2006-01-02", start_date)
			if err != nil {
				fmt.Println("Error parsing start date:", err)
				return
			}

			endDate, err := time.Parse("2006-01-02", end_date)
			if err != nil {
				fmt.Println("Error parsing end date:", err)
				return
			}
			dailyDates := splitByDay(startDate, endDate)
			for _, date := range dailyDates {
				//fmt.Println(date)
				var cus models.CustomDialysisData
				counts, _ := service.GetNewDialysisCountModeTwo(date.Unix(), date.Unix(), c.GetAdminUserInfo().CurrentOrgId, origin, mode)
				cus.Date = date.Format("2006-01-02")
				cus.Count = counts.Count
				cus.Total = p_total
				cuss = append(cuss, cus)

			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": cuss,
			})
			break
		case 3:
			// 按月统计
			months := groupByMonth(dates)
			for _, month := range months {
				var cus models.CustomDialysisData
				counts, _ := service.GetNewDialysisCountModeTwo(month[0].Unix(), month[len(month)-1].Unix(), c.GetAdminUserInfo().CurrentOrgId, origin, mode)
				cus.Date = strings.Split(month[0].String(), " ")[0] + "~" + strings.Split(month[len(month)-1].String(), " ")[0]
				cus.Count = counts.Count
				cus.Total = p_total
				cuss = append(cuss, cus)

				//fmt.Println("Month:", month[0], "~", month[len(month)-1])
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": cuss,
			})
			break
		case 4:
			// 按年统计
			years := groupByYear(dates)
			for _, year := range years {
				var cus models.CustomDialysisData
				counts, _ := service.GetNewDialysisCountModeTwo(year[0].Unix(), year[len(year)-1].Unix(), c.GetAdminUserInfo().CurrentOrgId, origin, mode)
				cus.Date = strings.Split(strings.Split(year[0].String(), " ")[0], "-")[0]
				cus.Count = counts.Count
				cus.Total = p_total
				cuss = append(cuss, cus)

			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": cuss,
			})
			break
		}
	}

}
func (c *StatisticsApiController) GetDialysisTotalDetail() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	mode, _ := c.GetInt64("mode")
	origin, _ := c.GetInt64("origin")
	time_way, _ := c.GetInt64("time_way")
	//timeLayout := "2006-01-02"
	//loc, _ := time.LoadLocation("Local")
	//var startTime int64
	//if len(start_date) > 0 {
	//	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
	//	fmt.Println("err-----------", err)
	//	if err != nil {
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//		return
	//	}
	//	//startTime = theTime.Unix()
	//}
	//var endTime int64
	//if len(end_date) > 0 {
	//	theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
	//	if err != nil {
	//		utils.ErrorLog(err.Error())
	//		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
	//		return
	//	}
	//	//endTime = theTime.Unix()
	//}
	dates, err := splitDateRange(start_date, end_date)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	if origin == 1 {
		switch time_way {
		case 2:
			weeks := groupByWeek(dates)
			//var uniqueFields []map[string]interface{}
			var uniqueFields []map[string]interface{}

			for _, week := range weeks {
				// 解析字符串时显式指定时区为 UTC
				t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", week[0].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				// 解析字符串时显式指定时区为 UTC
				t2, err := time.Parse("2006-01-02 15:04:05 -0700 MST", week[len(week)-1].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				//dynamicFields := make([]map[string]interface{}, 0)
				list, _ := service.GetDialysisStats(t.Unix(), t2.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}
				//var uniqueFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})

			break
		case 1:
			startDate, err := time.Parse("2006-01-02", start_date)
			if err != nil {
				fmt.Println("Error parsing start date:", err)
				return
			}

			endDate, err := time.Parse("2006-01-02", end_date)
			if err != nil {
				fmt.Println("Error parsing end date:", err)
				return
			}
			dailyDates := splitByDay(startDate, endDate)
			var uniqueFields []map[string]interface{}
			for _, date := range dailyDates {
				list, _ := service.GetDialysisStats(date.Unix(), date.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})

			break
		case 3:
			months := groupByMonth(dates)
			var uniqueFields []map[string]interface{}
			for _, month := range months {
				// 解析字符串时显式指定时区为 UTC
				t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", month[0].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				// 解析字符串时显式指定时区为 UTC
				t2, err := time.Parse("2006-01-02 15:04:05 -0700 MST", month[len(month)-1].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				//dynamicFields := make([]map[string]interface{}, 0)
				list, _ := service.GetDialysisStats(t.Unix(), t2.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}
				//var uniqueFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})
			break
		case 4:
			years := groupByYear(dates)
			var uniqueFields []map[string]interface{}
			for _, year := range years {
				// 解析字符串时显式指定时区为 UTC
				t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", year[0].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				// 解析字符串时显式指定时区为 UTC
				t2, err := time.Parse("2006-01-02 15:04:05 -0700 MST", year[len(year)-1].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				//dynamicFields := make([]map[string]interface{}, 0)
				list, _ := service.GetDialysisStats(t.Unix(), t2.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}
				//var uniqueFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})
			break

		}

	} else {
		switch time_way {
		case 2:
			weeks := groupByWeek(dates)
			//var uniqueFields []map[string]interface{}
			var uniqueFields []map[string]interface{}

			for _, week := range weeks {
				// 解析字符串时显式指定时区为 UTC
				t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", week[0].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				// 解析字符串时显式指定时区为 UTC
				t2, err := time.Parse("2006-01-02 15:04:05 -0700 MST", week[len(week)-1].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				//dynamicFields := make([]map[string]interface{}, 0)
				list, _ := service.GetScheduleStats(t.Unix(), t2.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}
				//var uniqueFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})

			break
		case 1:
			startDate, err := time.Parse("2006-01-02", start_date)
			if err != nil {
				fmt.Println("Error parsing start date:", err)
				return
			}

			endDate, err := time.Parse("2006-01-02", end_date)
			if err != nil {
				fmt.Println("Error parsing end date:", err)
				return
			}
			dailyDates := splitByDay(startDate, endDate)
			var uniqueFields []map[string]interface{}
			for _, date := range dailyDates {
				list, _ := service.GetScheduleStats(date.Unix(), date.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})

			break
		case 3:
			months := groupByMonth(dates)
			var uniqueFields []map[string]interface{}
			for _, month := range months {
				// 解析字符串时显式指定时区为 UTC
				t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", month[0].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				// 解析字符串时显式指定时区为 UTC
				t2, err := time.Parse("2006-01-02 15:04:05 -0700 MST", month[len(month)-1].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				//dynamicFields := make([]map[string]interface{}, 0)
				list, _ := service.GetScheduleStats(t.Unix(), t2.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}
				//var uniqueFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})
			break
		case 4:
			years := groupByYear(dates)
			var uniqueFields []map[string]interface{}
			for _, year := range years {
				// 解析字符串时显式指定时区为 UTC
				t, err := time.Parse("2006-01-02 15:04:05 -0700 MST", year[0].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				// 解析字符串时显式指定时区为 UTC
				t2, err := time.Parse("2006-01-02 15:04:05 -0700 MST", year[len(year)-1].String())
				if err != nil {
					fmt.Println("解析时间出错:", err)
					return
				}
				//dynamicFields := make([]map[string]interface{}, 0)
				list, _ := service.GetScheduleStats(t.Unix(), t2.Unix(), mode, c.GetAdminUserInfo().CurrentOrgId, time_way)
				//fmt.Println(aa)
				var dynamicFields []map[string]interface{}
				//var uniqueFields []map[string]interface{}

				for _, result := range list {
					// 打印患者ID
					nb := result["日期"].([]byte)
					name := string(nb)

					// 创建动态字段的map
					dynamicField := make(map[string]interface{})
					// 将日期放在首位
					dynamicField["日期"] = name

					// 打印其他列的值,并添加到动态字段中
					for columnName, columnValue := range result {
						if columnName == "日期" {
							continue
						}
						if columnName == "合计" {
							continue
						}
						if columnValue == nil {
							dynamicField[columnName] = ""
							continue
						}

						byteValue, ok := columnValue.([]byte)
						if !ok {
							fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
							continue
						}

						strValue := string(byteValue)

						floatValue, err := strconv.ParseFloat(strValue, 64)
						if err != nil {
							fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
						} else {
							if floatValue == 0 {
								dynamicField[columnName] = ""
							} else {
								dynamicField[columnName] = floatValue
							}
						}
					}

					// 将合计放在末尾
					hj := result["合计"].(int64)
					dynamicField["合计"] = hj

					dynamicFields = append(dynamicFields, dynamicField)
				}

				// 将日期放在首位
				seen := make(map[interface{}]struct{})
				for _, field := range dynamicFields {
					value := field["日期"]
					if _, ok := seen[value]; !ok {
						seen[value] = struct{}{}
						uniqueFields = append(uniqueFields, field)
					}
				}
			}
			c.ServeSuccessJSON(map[string]interface{}{
				"list": uniqueFields,
			})
			break
		}
	}
}
func (c *StatisticsApiController) GetDialysisTotalDetailInfo() {
	date_str := c.GetString("date")
	mode, _ := c.GetInt64("mode")
	origin, _ := c.GetInt64("origin")
	page, _ := c.GetInt64("page")
	limit, _ := c.GetInt64("limit")
	start_date := strings.Split(date_str, "~")[0]
	end_date := strings.Split(date_str, "~")[1]
	if origin == 1 {
		qcp, total, _ := service.GetDialysisPrescriptionInfo(start_date, end_date, mode, c.GetAdminUserInfo().CurrentOrgId, page, limit)
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  qcp,
			"total": total,
		})
	} else {
		qcp, total, _ := service.GetScheduleInfo(start_date, end_date, mode, c.GetAdminUserInfo().CurrentOrgId, page, limit)
		c.ServeSuccessJSON(map[string]interface{}{
			"list":  qcp,
			"total": total,
		})
	}

}

func (c *StatisticsApiController) GetAnticoagulant() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	total, err2 := service.GetAnticoagulantTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId)
	if err2 != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	anticoagulantData, err := service.GetAnticoagulantData(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	type respData struct {
		Name       string  `json:"name"`
		Count      int     `json:"count"`
		Percentage float64 `json:"percentage"`
	}
	var respDatas []respData
	for anticoagulant, count := range anticoagulantData {
		var respData respData
		respData.Name = anticoagulant
		respData.Count = count
		respData.Percentage = float64(count) / float64(total) * 100
		respDatas = append(respDatas, respData)
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"data": respDatas,
	})

}
func (c *StatisticsApiController) GetAnticoagulantDetail() {
	anticoagulant, _ := c.GetInt64("anticoagulant")
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	timeLayout := "2006-01-02"
	page, _ := c.GetInt64("page", 0)
	limit, _ := c.GetInt64("limit", 0)
	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	prescriptions, total, _ := service.GetPrescriptionByAnticoagulant(page, limit, c.GetAdminUserInfo().CurrentOrgId, anticoagulant, startTime, endTime)

	c.ServeSuccessJSON(map[string]interface{}{
		"prescriptions": prescriptions,
		"total":         total,
	})

}

func (c *StatisticsApiController) GetDialyzer() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	total, err2 := service.GetDialyzerTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId)
	if err2 != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	dialyzers, err := service.GetDialyzerData(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId)
	if err != nil {
		c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
		return
	}
	type respData struct {
		Name       string  `json:"name"`
		Count      int     `json:"count"`
		Percentage float64 `json:"percentage"`
	}
	var respDatas []respData
	for _, item := range dialyzers {
		var respData respData
		respData.Name = item.Dialyzer
		respData.Count = item.Count
		respData.Percentage = float64(item.Count) / float64(total) * 100
		respDatas = append(respDatas, respData)
	}
	c.ServeSuccessJSON(map[string]interface{}{
		"data": respDatas,
	})

}
func (c *StatisticsApiController) GetDialyzerDetail() {
	dialyzer := c.GetString("dialyzer")
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	timeLayout := "2006-01-02"
	page, _ := c.GetInt64("page", 0)
	limit, _ := c.GetInt64("limit", 0)
	if page <= 0 {
		page = 1
	}
	if limit <= 0 {
		limit = 10
	}
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}
	prescriptions, total, _ := service.GetPrescriptionByDialyzer(page, limit, c.GetAdminUserInfo().CurrentOrgId, dialyzer, startTime, endTime)
	c.ServeSuccessJSON(map[string]interface{}{
		"prescriptions": prescriptions,
		"total":         total,
	})

}
func (c *StatisticsApiController) GetDialyzerConfig() {
	dialyzers, _ := service.GetDialyzerSummary(c.GetAdminUserInfo().CurrentOrgId)
	//Irrigation, _ := service.GetIrrigationSummary(c.GetAdminUserInfo().CurrentOrgId)
	//dialyzers = append(dialyzers, Irrigation...)
	c.ServeSuccessJSON(map[string]interface{}{
		"dialyzers": dialyzers,
	})
}

// 配置检验数据查询
func (this *StatisticsApiController) GetInsepctionList() {
	adminUser := this.GetAdminUserInfo()
	orgid := adminUser.CurrentOrgId
	configurationlist, err := service.GetInsepctionConfigurationList(orgid)
	if err != nil {
		this.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeSystemError)
		return
	}
	this.ServeSuccessJSON(map[string]interface{}{
		"configurationlist": configurationlist,
	})
}
func (c *StatisticsApiController) GetAllCommonInspectionStatistisc() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	project_id, _ := c.GetInt64("project_id")
	item_id, _ := c.GetInt64("item_id")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	//患者总数
	patientCount := service.GetPatientCount(c.GetAdminUserInfo().CurrentOrgId)
	//获取配置
	reference, _ := service.GetInspectionReferenceFour(project_id, item_id, c.GetAdminUserInfo().CurrentOrgId)
	//获取数值在正常范围内的总数
	config, _ := service.GetConfigurationById(project_id, item_id, c.GetAdminUserInfo().CurrentOrgId)
	max, _ := strconv.ParseFloat(config.LargeRange, 64)
	min, _ := strconv.ParseFloat(config.MinRange, 64)

	normalTotal, _ := service.GetNormalInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min)
	//获取数值异常的总数
	unusualTotal, _ := service.GetUnusualInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min)
	//获取没有检查的患者总数
	noCheckTotal, _ := service.GetPatientNotInspectionTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName)
	c.ServeSuccessJSON(map[string]interface{}{
		"patient_count":  patientCount,
		"normal_total":   normalTotal,
		"unusual_total":  unusualTotal,
		"no_check_total": noCheckTotal,
		"reference":      reference,
		"config":         config,
	})

}
func (c *StatisticsApiController) GetPersonCommonInspectionStatistisc() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	project_id, _ := c.GetInt64("project_id")
	item_id, _ := c.GetInt64("item_id")
	patient_id, _ := c.GetInt64("patient_id")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	patient, _ := service.GetFaPiaoPatientByID(c.GetAdminUserInfo().CurrentOrgId, patient_id)
	config, _ := service.GetConfigurationById(project_id, item_id, c.GetAdminUserInfo().CurrentOrgId)

	//获取配置
	reference, _ := service.GetInspectionReferenceFour(config.InspectionMajor, config.InspectionMinor, c.GetAdminUserInfo().CurrentOrgId)
	//获取数值在正常范围内的总数
	inspections, _ := service.GetPatientInspectionByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, patient_id, reference.ItemName)
	c.ServeSuccessJSON(map[string]interface{}{
		"patient":     patient,
		"reference":   reference,
		"inspections": inspections,
	})

}
func (c *StatisticsApiController) GetPatientCommonInspectionStatistisc() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	project_id, _ := c.GetInt64("project_id")
	item_id, _ := c.GetInt64("item_id")
	item_type, _ := c.GetInt64("item_type")
	keyword := c.GetString("keyword")
	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	//获取配置
	reference, _ := service.GetInspectionReferenceFour(project_id, item_id, c.GetAdminUserInfo().CurrentOrgId)
	//获取数值在正常范围内的总数

	config, _ := service.GetConfigurationById(project_id, item_id, c.GetAdminUserInfo().CurrentOrgId)
	max, _ := strconv.ParseFloat(config.LargeRange, 64)
	min, _ := strconv.ParseFloat(config.MinRange, 64)

	//max, _ := strconv.ParseFloat(reference.RangeMax, 64)
	//min, _ := strconv.ParseFloat(reference.RangeMin, 64)
	//config, _ := service.GetConfigurationById(project_id, item_id, c.GetAdminUserInfo().CurrentOrgId)

	switch item_type {
	case 1:
		list, _ := service.GetUnusualInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min, keyword)
		c.ServeSuccessJSON(map[string]interface{}{
			"list":      list,
			"reference": reference,
		})
		break
	case 2:
		list, _ := service.GetPatientNotInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, keyword)
		c.ServeSuccessJSON(map[string]interface{}{
			"list":      list,
			"reference": reference,
		})
		break
	case 3:
		list, _ := service.GetNormalInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min, keyword)
		c.ServeSuccessJSON(map[string]interface{}{
			"list":      list,
			"reference": reference,
		})
		break
	}
}

func (c *StatisticsApiController) GetFivePatientInspectionStatistisc() {
	//start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	//keyword := c.GetString("keyword")
	//timeLayout := "2006-01-02"
	//loc, _ := time.LoadLocation("Local")

	dynamicFields := make([]map[string]interface{}, 0)
	list, _ := service.GetLatestInspectionValues(c.GetAdminUserInfo().CurrentOrgId, strings.Split(end_date, "-")[0]+"-"+strings.Split(end_date, "-")[1])
	//fmt.Println(list)

	for _, result := range list {
		//fmt.Println(result)
		// 打印患者ID
		nb := result["姓名"].([]byte)
		name := string(nb)

		//ynamicFields := make([]map[string]interface{})

		//var dynamicFields DynamicData
		ynamicField := make(map[string]interface{})
		ynamicField["姓名"] = name
		// 打印其他列的值
		for columnName, columnValue := range result {

			fmt.Println("000000")
			fmt.Println(columnName)
			fmt.Println("000000")

			// 跳过患者ID列

			if columnName == "姓名" {
				continue
			}
			// 检查值是否为nil
			if columnValue == nil {
				fmt.Printf("Column: %s, Value: <nil>\n", columnName)
				continue
			}

			// 将字节切片转换为字符串
			byteValue, ok := columnValue.([]byte)
			if !ok {
				// 如果无法转换为[]byte,输出错误信息
				fmt.Printf("Error: Unable to convert value for column %s to []byte\n", columnName)
				continue
			}

			// 将字节切片转换为字符串
			strValue := string(byteValue)

			// 尝试将字符串转换为浮点数
			floatValue, err := strconv.ParseFloat(strValue, 64)
			if err != nil {
				// 如果转换失败,输出错误信息
				fmt.Printf("Error converting value for column %s: %v\n", columnName, err)
			} else {
				// 如果转换成功,输出列名和浮点数值
				fmt.Printf("Column: %s, Value: %f\n", columnName, floatValue)
			}
			ynamicField["年月"] = strings.Split(end_date, "-")[0] + "-" + strings.Split(end_date, "-")[1]
			if floatValue == 0 {
				ynamicField[columnName] = ""

			} else {
				ynamicField[columnName] = floatValue

			}
			fmt.Println(ynamicField)
			dynamicFields = append(dynamicFields, ynamicField)
		}
	}

	seen := make(map[interface{}]struct{})
	var uniqueFields []map[string]interface{}

	for _, field := range dynamicFields {
		value := field["姓名"]
		// 如果值未在map中出现过,则将其添加到新的切片中,并将其添加到map中
		if _, ok := seen[value]; !ok {
			seen[value] = struct{}{}
			uniqueFields = append(uniqueFields, field)
		}
	}

	c.ServeSuccessJSON(map[string]interface{}{
		"list": uniqueFields,
	})
	//list, _ := service.GetPatientFiveInspectionByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, keyword)
	//
	//var names []string
	//
	//for _, item := range list {
	//	names = append(names, item.ItemName)
	//}
	//
	//names = RemoveRepeatedNameElement(names)
	//fmt.Println(names)
	//
	//var tempList []models.InspectionTen
	//list_two := RemoveRepeatedInspectPatientElement(list)
	//for _, item := range list_two {
	//	var temp models.InspectionTen
	//	var temptwos []models.InspectionValue
	//	temp.PatientId = item.PatientId
	//	temp.Name = item.Name
	//	for _, subitem := range list {
	//		if item.PatientId == subitem.PatientId {
	//			var temptwo models.InspectionValue
	//			temptwo.Name = subitem.ItemName
	//			temptwo.Value = subitem.InspectValue
	//			temptwos = append(temptwos, temptwo)
	//		}
	//	}
	//	temp.Values = temptwos
	//	tempList = append(tempList, temp)
	//}
	//
	//var filtered []string
	//for _, item := range names {
	//	if item != "a" {
	//		filtered = append(filtered, item)
	//	}
	//}
	//
	//for _, item := range tempList {
	//	for _, subitem := range item.Values {
	//		for _, name := range filtered {
	//			if subitem.Name != name {
	//				filtered = append(filtered, name)
	//			}
	//		}
	//	}
	//}
	//
	////// 将剩余字符串填充到 Inspection 数组中
	////for _, name := range filtered {
	////	var temptwo models.InspectionValue
	////	temptwo.Name = subitem.ItemName
	////	temptwo.Value = subitem.InspectValue
	////	temptwos = append(temptwos, temptwo)
	////}
	//
	//for _, item := range tempList {
	//	//for _, subitem := range item.Values {
	//	var temptwo models.InspectionValue
	//	for _, name := range filtered {
	//		temptwo.Name = name
	//		temptwo.Value = ""
	//	}
	//	item.Values = append(item.Values, temptwo)
	//	//}
	//	fmt.Println(item.Values)
	//}

}
func (c *StatisticsApiController) GetPatientInspectionStatistisc() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	project_id, _ := c.GetInt64("project_id")
	item_id, _ := c.GetInt64("item_id")
	item_type, _ := c.GetInt64("item_type")
	//order_type,  _ := c.GetInt64("order_type")
	keyword := c.GetString("keyword")
	s_type, _ := c.GetInt64("type")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	//获取配置
	reference, _ := service.GetInspectionReferenceThree(project_id, item_id)
	//获取数值在正常范围内的总数

	max, _ := strconv.ParseFloat(reference.RangeMax, 64)
	min, _ := strconv.ParseFloat(reference.RangeMin, 64)

	switch item_type {
	case 0:

		break
	case 1:
		if s_type == 2 { //KTV
			list, _ := service.GetUnusualKTVORURRInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10950, 0, 1.2, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
		} else if s_type == 3 { //URR
			list, _ := service.GetUnusualKTVORURRInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10951, 0, 65, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
		} else {

			list, _ := service.GetUnusualInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list":      list,
				"reference": reference,
			})

		}

		break
	case 2:
		if s_type == 2 { //KTV
			list, _ := service.GetPatientNotKTVORURRInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10950, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
		} else if s_type == 3 { //URR
			list, _ := service.GetPatientNotKTVORURRInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10951, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
		} else {

			list, _ := service.GetPatientNotInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list":      list,
				"reference": reference,
			})
		}

		break
	case 3:
		if s_type == 2 { //KTV
			list, _ := service.GetNormalKTVORURRInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10950, 0, 1.2, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
		} else if s_type == 3 { //URR
			list, _ := service.GetNormalKTVORURRInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10951, 0, 65, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list": list,
			})
		} else {
			list, _ := service.GetNormalInspectionPatientList(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min, keyword)
			c.ServeSuccessJSON(map[string]interface{}{
				"list":      list,
				"reference": reference,
			})
		}

		break
	}
}
func (c *StatisticsApiController) GetAllInspectionStatistisc() {
	start_date := c.GetString("start_date")
	end_date := c.GetString("end_date")
	project_id, _ := c.GetInt64("project_id")
	item_id, _ := c.GetInt64("item_id")

	s_type, _ := c.GetInt64("type")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	//患者总数
	patientCount := service.GetPatientCount(c.GetAdminUserInfo().CurrentOrgId)
	//获取配置
	reference, _ := service.GetInspectionReferenceThree(project_id, item_id)
	//获取数值在正常范围内的总数

	max, _ := strconv.ParseFloat(reference.RangeMax, 64)
	min, _ := strconv.ParseFloat(reference.RangeMin, 64)

	if s_type == 2 {
		normalTotal, _ := service.GetNormalKTVORURRInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10950, 1.2)
		//获取数值异常的总数
		unusualTotal, _ := service.GetUnusualKTVORURRInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10950, 1.2)
		//获取没有检查的患者总数
		noCheckTotal, _ := service.GetPatientNotKTVORURRInspectionTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10950)
		c.ServeSuccessJSON(map[string]interface{}{
			"patient_count":  patientCount,
			"normal_total":   normalTotal,
			"unusual_total":  unusualTotal,
			"no_check_total": noCheckTotal,
		})

	} else if s_type == 3 {
		normalTotal, _ := service.GetNormalKTVORURRInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10951, 65)
		//获取数值异常的总数
		//unusualTotal, _ := service.GetUnusualKTVORURRInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1.2)
		unusualTotal, _ := service.GetUnusualKTVORURRInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10951, 65)
		//获取没有检查的患者总数
		noCheckTotal, _ := service.GetPatientNotKTVORURRInspectionTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10951)
		c.ServeSuccessJSON(map[string]interface{}{
			"patient_count":  patientCount,
			"normal_total":   normalTotal,
			"unusual_total":  unusualTotal,
			"no_check_total": noCheckTotal,
		})
	} else {
		normalTotal, _ := service.GetNormalInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min)
		//获取数值异常的总数
		unusualTotal, _ := service.GetUnusualInspectionTotalByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName, max, min)
		//获取没有检查的患者总数
		noCheckTotal, _ := service.GetPatientNotInspectionTotal(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, reference.ItemName)
		c.ServeSuccessJSON(map[string]interface{}{
			"patient_count":  patientCount,
			"normal_total":   normalTotal,
			"unusual_total":  unusualTotal,
			"no_check_total": noCheckTotal,
			"reference":      reference,
		})
	}

}
func (c *StatisticsApiController) GetPersonInspectionStatistisc() {
	start_date := c.GetString("start_time")
	end_date := c.GetString("end_time")
	project_id, _ := c.GetInt64("project_id")
	item_id, _ := c.GetInt64("item_id")
	patient_id, _ := c.GetInt64("patient_id")
	s_type, _ := c.GetInt64("type")

	timeLayout := "2006-01-02"
	loc, _ := time.LoadLocation("Local")
	var startTime int64
	if len(start_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", start_date+" 00:00:00", loc)
		fmt.Println("err-----------", err)
		if err != nil {
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		startTime = theTime.Unix()
	}
	var endTime int64
	if len(end_date) > 0 {
		theTime, err := time.ParseInLocation(timeLayout+" 15:04:05", end_date+" 23:59:59", loc)
		if err != nil {
			utils.ErrorLog(err.Error())
			c.ServeFailJSONWithSGJErrorCode(enums.ErrorCodeParamWrong)
			return
		}
		endTime = theTime.Unix()
	}

	if s_type == 2 {
		patient, _ := service.GetFaPiaoPatientByID(c.GetAdminUserInfo().CurrentOrgId, patient_id)
		//获取配置
		reference, _ := service.GetInspectionReferenceThree(1014, 10950)
		//获取数值在正常范围内的总数
		inspections, _ := service.GetPatientKTVORURRInspectionByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10950, patient_id)
		c.ServeSuccessJSON(map[string]interface{}{
			"patient":     patient,
			"reference":   reference,
			"inspections": inspections,
		})

	} else if s_type == 3 {
		patient, _ := service.GetFaPiaoPatientByID(c.GetAdminUserInfo().CurrentOrgId, patient_id)
		//获取配置
		reference, _ := service.GetInspectionReferenceThree(1014, 10951)
		//获取数值在正常范围内的总数
		inspections, _ := service.GetPatientKTVORURRInspectionByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, 1014, 10951, patient_id)
		c.ServeSuccessJSON(map[string]interface{}{
			"patient":     patient,
			"reference":   reference,
			"inspections": inspections,
		})

	} else {
		patient, _ := service.GetFaPiaoPatientByID(c.GetAdminUserInfo().CurrentOrgId, patient_id)
		//获取配置
		reference, _ := service.GetInspectionReferenceThree(project_id, item_id)
		//获取数值在正常范围内的总数
		inspections, _ := service.GetPatientInspectionByID(startTime, endTime, c.GetAdminUserInfo().CurrentOrgId, patient_id, reference.ItemName)
		c.ServeSuccessJSON(map[string]interface{}{
			"patient":     patient,
			"reference":   reference,
			"inspections": inspections,
		})
	}

}
func (c *StatisticsApiController) GetStatistics() {
	adminUserInfo := c.GetAdminUserInfo()

	// thisTime := time.Now()
	year, month, day := time.Now().Date()
	todayTime := time.Date(year, month, day, 0, 0, 0, 0, time.Local)
	startYearTime := time.Date(year, 1, 1, 0, 0, 0, 0, time.Local)
	endYearTime := time.Date(year+1, 1, 1, 0, 0, 0, 0, time.Local)

	todayWeek := int(todayTime.Weekday())
	if todayWeek == 0 {
		todayWeek = 7
	}

	weekEnd := 7 - todayWeek
	weekStart := weekEnd - 6
	// endDay := todayTime.AddDate(0, 0, weekEnd)
	startDay := todayTime.AddDate(0, 0, weekStart)
	//患者总数
	patientCount := service.GetPatientCount(adminUserInfo.CurrentOrgId)
	//今日透析
	todayDialysisCount := service.GetDayDialysisCount(adminUserInfo.CurrentOrgId, todayTime.Unix())

	//本周透析
	weekDaylysisCount := service.GetTimebetweenDialysisCount(adminUserInfo.CurrentOrgId, startDay.Unix(), todayTime.Unix())

	//传染病
	diseaseCounts := service.GetPatientContagionCounts(adminUserInfo.CurrentOrgId)

	//性别分布
	genderCounts := service.GetPatientGenderCounts(adminUserInfo.CurrentOrgId)

	//年龄分布
	ageCounts := service.GetPatiendAgeBetweenCount(adminUserInfo.CurrentOrgId)

	//透析模式
	modeCounts := service.GetPatientDialysisModeBetweenCount(adminUserInfo.CurrentOrgId, startYearTime.Unix(), endYearTime.Unix())

	c.ServeSuccessJSON(map[string]interface{}{
		"patient_count":        patientCount,
		"today_dialysis_count": todayDialysisCount,
		"week_daylysis_count":  weekDaylysisCount,
		"disease_counts":       diseaseCounts,
		"gender_counts":        genderCounts,
		"age_counts":           ageCounts,
		"mode_counts":          modeCounts,
	})

}

func RemoveRepeatedInspectPatientElement(arr []models.InspectionTenOne) (newArr []models.InspectionTenOne) {
	newArr = make([]models.InspectionTenOne, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i].PatientId == arr[j].PatientId {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}

func RemoveRepeatedNameElement(arr []string) (newArr []string) {
	newArr = make([]string, 0)
	for i := 0; i < len(arr); i++ {
		repeat := false
		for j := i + 1; j < len(arr); j++ {
			if arr[i] == arr[j] {
				repeat = true
				break
			}
		}
		if !repeat {
			newArr = append(newArr, arr[i])
		}
	}
	return
}

// 根据指定的日期范围拆分成周、月、年
func splitDateRange(startDate, endDate string) ([]time.Time, error) {
	startTime, err := time.Parse("2006-01-02", startDate)
	if err != nil {
		return nil, err
	}

	endTime, err := time.Parse("2006-01-02", endDate)
	if err != nil {
		return nil, err
	}

	var result []time.Time

	for date := startTime; date.Before(endTime) || date.Equal(endTime); date = date.AddDate(0, 0, 1) {
		result = append(result, date)
	}

	return result, nil
}

// 按周统计日期
func groupByWeek(dates []time.Time) [][]time.Time {
	var result [][]time.Time
	var currentWeek []time.Time

	for _, date := range dates {
		currentWeek = append(currentWeek, date)
		if date.Weekday() == time.Sunday {
			result = append(result, currentWeek)
			currentWeek = nil
		}
	}

	if len(currentWeek) > 0 {
		result = append(result, currentWeek)
	}

	return result
}

// 按月统计日期
func groupByMonth(dates []time.Time) [][]time.Time {
	var result [][]time.Time
	var currentMonth []time.Time
	lastMonth := dates[0].Month()

	for _, date := range dates {
		if date.Month() != lastMonth {
			result = append(result, currentMonth)
			currentMonth = nil
			lastMonth = date.Month()
		}
		currentMonth = append(currentMonth, date)
	}

	if len(currentMonth) > 0 {
		result = append(result, currentMonth)
	}

	return result
}

// 按年统计日期
func groupByYear(dates []time.Time) [][]time.Time {
	var result [][]time.Time
	var currentYear []time.Time
	lastYear := dates[0].Year()

	for _, date := range dates {
		if date.Year() != lastYear {
			result = append(result, currentYear)
			currentYear = nil
			lastYear = date.Year()
		}
		currentYear = append(currentYear, date)
	}

	if len(currentYear) > 0 {
		result = append(result, currentYear)
	}

	return result
}

// 将日期拆分为按天统计
func splitByDay(startDate, endDate time.Time) []time.Time {
	var dates []time.Time
	for d := startDate; !d.After(endDate); d = d.AddDate(0, 0, 1) {
		dates = append(dates, d)
	}
	return dates
}