package models

import (
	"fmt"
	"strconv"
	"strings"
)

// DeviationDetail 表示一个评估结果中的偏差值和百分比
type DeviationDetail struct {
	Value   string `json:"value"`   // 偏差值，如 "9.31"
	Percent string `json:"percent"` // 百分比，如 "104.7%"

}

// FatherAvgDeviationDetail 表示一个平均偏差结果，包含多个评估指标
type FatherAvgDeviationDetail struct {
	Emotional      DeviationDetail `json:"Emotional"`
	Overreach      DeviationDetail `json:"Overreach"`
	RejectDeny     DeviationDetail `json:"RejectDeny"`
	Punishment     DeviationDetail `json:"Punishment"`
	Preferred      DeviationDetail `json:"Preferred"`
	Overprotection DeviationDetail `json:"OverProtection"` // 可选字段，仅父亲评估结果中存在
}

// MotherAvgDeviationDetail 表示一个平均偏差结果，包含多个评估指标
type MotherAvgDeviationDetail struct {
	Emotional  DeviationDetail `json:"Emotional"`
	Overreach  DeviationDetail `json:"Overreach"`
	RejectDeny DeviationDetail `json:"RejectDeny"`
	Punishment DeviationDetail `json:"Punishment"`
	Preferred  DeviationDetail `json:"Preferred"`
}

// EvaluateResult 表示最终的评估结果，包括母亲和父亲的平均偏差评估
type EvaluateResultVal struct {
	MotherAvgDev MotherAvgDeviationDetail `json:"MotherAvgDev"`
	FatherAvgDev FatherAvgDeviationDetail `json:"FatherAvgDev"`
	Summary      EvaluationSummary        `json:"Summary"` // 新增字段

}

// 计算偏差百分比的函数
func CalculateDeviation(userValue, standardValue, standardDeviation float64) DeviationDetail {
	diff := userValue - standardValue
	percent := (diff / standardDeviation) * 100
	return DeviationDetail{
		Value:   fmt.Sprintf("%.2f", diff),
		Percent: fmt.Sprintf("%.1f%%", percent),
	}
}

// 核心处理函数的完整实现
func ProcessEvaluation(testData TestResultData, configData map[string]interface{}) (EvaluateResultVal, error) {
	var evaluateResult EvaluateResultVal

	fatherStandard, ok := configData["FatherStandard"].(map[string]interface{})
	if !ok {
		return evaluateResult, fmt.Errorf("FatherStandard data format incorrect or missing")
	}
	motherStandard, ok := configData["MotherStandard"].(map[string]interface{})
	if !ok {
		return evaluateResult, fmt.Errorf("MotherStandard data format incorrect or missing")
	}

	// 解析测试数据
	fatherAvg := testData.FatherAverage
	motherAvg := testData.MotherAverage

	// 处理父亲的评估结果
	evaluateResult.FatherAvgDev = CalculateAvgDeviation(fatherAvg, fatherStandard)

	// 处理母亲的评估结果
	evaluateResult.MotherAvgDev = CalculateAvgDeviationMother(motherAvg, motherStandard)

	// 计算评估结果之后，调用 SummarizeEvaluation 来生成总结性评价
	evaluateResult.Summary = SummarizeEvaluation(evaluateResult)

	return evaluateResult, nil
}

// 计算平均偏差的函数，针对父亲
func CalculateAvgDeviation(testResult FatherTestResultDetail, standardData map[string]interface{}) FatherAvgDeviationDetail {
	avgDev := FatherAvgDeviationDetail{}

	averageValues, ok := standardData["Average"].(map[string]interface{})
	if !ok {
		return avgDev
	}
	avgDevValues, ok := standardData["AvgDev"].(map[string]interface{})
	if !ok {
		return avgDev
	}

	avgDev.Emotional = CalculateDeviationHelper(testResult.Emotional, averageValues["Emotional"], avgDevValues["Emotional"])
	avgDev.Overreach = CalculateDeviationHelper(testResult.Overreach, averageValues["Overreach"], avgDevValues["Overreach"])
	avgDev.RejectDeny = CalculateDeviationHelper(testResult.RejectDeny, averageValues["RejectDeny"], avgDevValues["RejectDeny"])
	avgDev.Punishment = CalculateDeviationHelper(testResult.Punishment, averageValues["Punishment"], avgDevValues["Punishment"])
	avgDev.Preferred = CalculateDeviationHelper(testResult.Preferred, averageValues["Preferred"], avgDevValues["Preferred"])
	avgDev.Overprotection = CalculateDeviationHelper(testResult.OverProtection, averageValues["OverProtection"], avgDevValues["OverProtection"])

	return avgDev
}

// 计算平均偏差的函数，针对母亲
func CalculateAvgDeviationMother(testResult MotherTestResultDetail, standardData map[string]interface{}) MotherAvgDeviationDetail {
	avgDev := MotherAvgDeviationDetail{}

	averageValues, ok := standardData["Average"].(map[string]interface{})
	if !ok {
		return avgDev
	}
	avgDevValues, ok := standardData["AvgDev"].(map[string]interface{})
	if !ok {
		return avgDev
	}

	avgDev.Emotional = CalculateDeviation(StrToFloat64(testResult.Emotional), StrToFloat64(averageValues["Emotional"].(string)), StrToFloat64(avgDevValues["Emotional"].(string)))
	avgDev.Overreach = CalculateDeviation(StrToFloat64(testResult.Overreach), StrToFloat64(averageValues["Overreach"].(string)), StrToFloat64(avgDevValues["Overreach"].(string)))
	avgDev.RejectDeny = CalculateDeviation(StrToFloat64(testResult.RejectDeny), StrToFloat64(averageValues["RejectDeny"].(string)), StrToFloat64(avgDevValues["RejectDeny"].(string)))
	avgDev.Punishment = CalculateDeviation(StrToFloat64(testResult.Punishment), StrToFloat64(averageValues["Punishment"].(string)), StrToFloat64(avgDevValues["Punishment"].(string)))
	avgDev.Preferred = CalculateDeviation(StrToFloat64(testResult.Preferred), StrToFloat64(averageValues["Preferred"].(string)), StrToFloat64(avgDevValues["Preferred"].(string)))

	return avgDev
}

// 辅助函数，用于计算单个指标的偏差和百分比
func CalculateDeviationHelper(userValueStr, standardValueStr, standardDeviationStr interface{}) DeviationDetail {
	userValue, _ := strconv.ParseFloat(userValueStr.(string), 64)
	standardValue, _ := strconv.ParseFloat(standardValueStr.(string), 64)
	standardDeviation, _ := strconv.ParseFloat(standardDeviationStr.(string), 64)

	return CalculateDeviation(userValue, standardValue, standardDeviation)
}

// StrToFloat64 将字符串转换为float64
func StrToFloat64(s string) float64 {
	val, err := strconv.ParseFloat(s, 64)
	if err != nil {
		fmt.Printf("Error converting string to float64: %v\n", err)
		return 0.0
	}
	return val
}

type EvaluationSummary struct {
	MotherEvaluateResult map[string]string `json:"MotherEvaluateResult"`
	FatherEvaluateResult map[string]string `json:"FatherEvaluateResult"`
}

func SummarizeEvaluation(evalResult EvaluateResultVal) EvaluationSummary {
	summary := EvaluationSummary{
		MotherEvaluateResult: make(map[string]string),
		FatherEvaluateResult: make(map[string]string),
	}
	// 评估母亲的指标
	summary.MotherEvaluateResult = EvaluateDeviationDetails(evalResult.MotherAvgDev)
	// 评估父亲的指标
	summary.FatherEvaluateResult = EvaluateDeviationDetailsFather(evalResult.FatherAvgDev)

	return summary

}

/*
   评估母亲指标的帮助函数
*/

// 评估母亲指标的帮助函数
func EvaluateDeviationDetails(motherAvgDev MotherAvgDeviationDetail) map[string]string {
	result := make(map[string]string)

	result["Emotional"] = EvaluateCategory(motherAvgDev.Emotional.Percent)
	result["Overreach"] = EvaluateCategory(motherAvgDev.Overreach.Percent)
	result["RejectDeny"] = EvaluateCategory(motherAvgDev.RejectDeny.Percent)
	result["Punishment"] = EvaluateCategory(motherAvgDev.Punishment.Percent)
	result["Preferred"] = EvaluateCategory(motherAvgDev.Preferred.Percent)

	return result
}

// 评估父亲指标的帮助函数
func EvaluateDeviationDetailsFather(fatherAvgDev FatherAvgDeviationDetail) map[string]string {
	result := make(map[string]string)

	result["Emotional"] = EvaluateCategory(fatherAvgDev.Emotional.Percent)
	result["Overreach"] = EvaluateCategory(fatherAvgDev.Overreach.Percent)
	result["RejectDeny"] = EvaluateCategory(fatherAvgDev.RejectDeny.Percent)
	result["Punishment"] = EvaluateCategory(fatherAvgDev.Punishment.Percent)
	result["Preferred"] = EvaluateCategory(fatherAvgDev.Preferred.Percent)
	if fatherAvgDev.Overprotection.Value != "" { // 只有在有值的情况下才评估
		result["OverProtection"] = EvaluateCategory(fatherAvgDev.Overprotection.Percent)
	}

	return result
}

// 根据百分比评估指标类别的函数
func EvaluateCategory(percentStr string) string {
	percent, err := strconv.ParseFloat(strings.TrimSuffix(percentStr, "%"), 64)
	if err != nil {
		fmt.Printf("Error parsing percent string to float64: %v\n", err)
		return "Error"
	}
	if percent > 100 {
		return "过度"
	} else if percent < -100 {
		return "缺乏"
	} else {
		return "正常" // 可能需要调整逻辑以匹配具体需求
	}

}
