package entitys

import (
	"ai_scheduler/internal/data/constants"
	"ai_scheduler/internal/data/model"
	"encoding/json"
	"log"
)

type ChatHistory struct {
	SessionID string           `json:"session_id"`
	Role      constants.Caller `json:"role"`
	Content   string           `json:"content"`
	Prologue  string           `json:"prologue"`
}

type ChatHisLog struct {
	HisId int64 `json:"his_id"`
}

type ChatHistQuery struct {
	HisID     int64  `json:"his_id"`
	SessionID string `json:"session_id"`
	Page      int    `json:"page"`
	PageSize  int    `json:"page_size"`
}

type ChatHisQueryResponse struct {
	HisID     int64    `gorm:"column:his_id;primaryKey;autoIncrement:true" json:"his_id"`
	SessionID string   `gorm:"column:session_id;not null" json:"session_id"`
	Ques      string   `gorm:"column:ques;not null" json:"ques"`
	Ans       string   `gorm:"column:ans;not null" json:"ans"`
	Files     string   `gorm:"column:files;not null" json:"files"`
	Useful    int32    `gorm:"column:useful;not null;comment:0不评价,1有用，其他为无用" json:"useful"` // 0不评价,1有用，其他为无用
	CreateAt  string   `gorm:"column:create_at;default:CURRENT_TIMESTAMP" json:"create_at"`
	TaskID    int32    `gorm:"column:task_id;not null" json:"task_id"`       // 任务ID
	TaskName  string   `gorm:"column:task_name;not null" json:"task_name"`   // 任务名称
	Contents  []string `gorm:"column:contents" json:"contents"`              // 前端回传数据
	TaskIndex string   `gorm:"column:task_index;not null" json:"task_index"` // 任务索引
}

func (c *ChatHisQueryResponse) FromModel(chat model.AiChatHi, task model.AiTask) {
	c.HisID = chat.HisID
	c.SessionID = chat.SessionID
	c.Ques = chat.Ques
	c.Ans = chat.Ans
	c.Files = chat.Files
	c.Useful = chat.Useful
	c.CreateAt = chat.CreateAt.Format("2006-01-02 15:04:05")
	c.TaskID = chat.TaskID
	c.TaskName = task.Name
	c.Contents = make([]string, 0)
	c.TaskIndex = c.parseTaskIndex(task.Index)

	// 解析Content
	if "" != chat.Content {
		err := json.Unmarshal([]byte(chat.Content), &c.Contents)
		if err != nil {
			c.Contents = append(c.Contents, chat.Content)
			log.Println("解析Content失败 error: ", err)
		}
	}
}

func (c *ChatHisQueryResponse) parseTaskIndex(taskIndex string) string {
	// 反转 IrregularTaskToolIndexMap
	reverseMap := make(map[string]string)
	for k, v := range constants.IrregularTaskToolIndexMap {
		reverseMap[v] = k
	}

	if _, ok := reverseMap[taskIndex]; ok {
		return reverseMap[taskIndex]
	}

	return taskIndex
}

type UpdateContentRequest struct {
	HisID   int64  `json:"his_id" validate:"required"`
	Content string `json:"content" validate:"required"`
}
