package models

import (
	"database/sql/driver"
	"encoding/json"
	"errors"
	"time"
)

// DetectionTask 检测任务模型
type DetectionTask struct {
	ID            uint      `gorm:"primaryKey" json:"id"`
	TaskNo        string    `gorm:"type:varchar(32);uniqueIndex" json:"task_no"`
	ClassID       uint      `json:"class_id"`
	TeacherID     uint      `json:"teacher_id"`
	StartTime     time.Time `json:"start_time"`
	EndTime       *time.Time `json:"end_time"`
	StudentCount  int       `json:"student_count"`
	DetectionType string    `gorm:"type:varchar(32)" json:"detection_type"`
	Status        int       `gorm:"default:0" json:"status"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

// Detection 检测记录模型
type Detection struct {
	ID            uint      `gorm:"primaryKey" json:"id"`
	TaskID        uint      `json:"task_id"`
	StudentID     uint      `json:"student_id"`
	DetectionTime time.Time `json:"detection_time"`
	VisionLeft    float64   `json:"vision_left"`
	VisionRight   float64   `json:"vision_right"`
	FatigueScore  float64   `json:"fatigue_score"`
	AlertLevel    int       `gorm:"default:0" json:"alert_level"`
	DeviceID      *uint     `json:"device_id"`
	RawDataURL    string    `gorm:"type:text" json:"raw_data_url"`
	AIAnalysis    JSONMap   `gorm:"type:json" json:"ai_analysis"`
	Status        int       `gorm:"default:1" json:"status"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
}

// DetectionReport 检测报告
type DetectionReport struct {
	ID           uint      `gorm:"primaryKey" json:"id"`
	StudentID    uint      `json:"student_id"`
	DetectionID  uint      `json:"detection_id"`
	VisionLeft   float64   `gorm:"column:vision_left" json:"vision_left"`
	VisionRight  float64   `gorm:"column:vision_right" json:"vision_right"`
	LeftEyeX     float64   `gorm:"column:left_eye_x" json:"left_eye_x"`
	LeftEyeY     float64   `gorm:"column:left_eye_y" json:"left_eye_y"`
	RightEyeX    float64   `gorm:"column:right_eye_x" json:"right_eye_x"`
	RightEyeY    float64   `gorm:"column:right_eye_y" json:"right_eye_y"`
	GazePointX   float64   `gorm:"column:gaze_point_x" json:"gaze_point_x"`
	GazePointY   float64   `gorm:"column:gaze_point_y" json:"gaze_point_y"`
	FatigueScore float64   `json:"fatigue_score"`
	AlertLevel   string    `gorm:"type:varchar(16)" json:"alert_level"`
	AIAnalysis   JSONMap   `gorm:"type:json" json:"ai_analysis"`
	CreatedAt    time.Time `json:"created_at"`
}

// VisionData 视力数据 (简化)
type VisionData struct {
	VisionLeft  float64 `gorm:"-" json:"vision_left"`
	VisionRight float64 `gorm:"-" json:"vision_right"`
	Confidence  string  `gorm:"-" json:"confidence"`
}

// EyeMovementData 眼动数据 (简化)
type EyeMovementData struct {
	LeftEyeX   float64 `gorm:"-" json:"left_eye_x"`
	LeftEyeY   float64 `gorm:"-" json:"left_eye_y"`
	RightEyeX  float64 `gorm:"-" json:"right_eye_x"`
	RightEyeY  float64 `gorm:"-" json:"right_eye_y"`
	Timestamp  int64   `gorm:"-" json:"timestamp"`
}

// ResponseData 响应数据
type ResponseData struct {
	Accuracy     float64 `gorm:"-" json:"accuracy"`
	ResponseType float64 `gorm:"-" json:"response_time"`
	Errors       int     `gorm:"-" json:"errors"`
}

// JSONMap 自定义 JSON 类型
type JSONMap map[string]interface{}

func (j JSONMap) Value() (driver.Value, error) {
	if len(j) == 0 {
		return nil, nil
	}
	return json.Marshal(j)
}

func (j *JSONMap) Scan(value interface{}) error {
	if value == nil {
		*j = make(JSONMap)
		return nil
	}
	data, ok := value.([]byte)
	if !ok {
		return errors.New("type assertion to []byte failed")
	}
	return json.Unmarshal(data, j)
}

// DetectionHistory 检测历史
type DetectionHistory struct {
	ID           uint      `gorm:"primaryKey" json:"id"`
	StudentID    uint      `json:"student_id"`
	ClassID      uint      `json:"class_id"`
	VisionLeft   float64   `json:"vision_left"`
	VisionRight  float64   `json:"vision_right"`
	FatigueScore float64   `json:"fatigue_score"`
	AlertLevel   string    `gorm:"type:varchar(16)" json:"alert_level"`
	DetectionTime time.Time `json:"detection_time"`
	CreatedAt    time.Time `json:"created_at"`
}

// VisionChangeTrend 视力变化趋势
type VisionChangeTrend struct {
	ID          uint      `gorm:"primaryKey" json:"id"`
	StudentID   uint      `json:"student_id"`
	VisionLeft  float64   `json:"vision_left"`
	VisionRight float64   `json:"vision_right"`
	ChangeValue float64   `json:"change_value"`
	Trend       string    `gorm:"type:varchar(16)" json:"trend"`
	RecordedAt  time.Time `json:"recorded_at"`
	CreatedAt   time.Time `json:"created_at"`
}
