package ai

import (
	"encoding/json"
	"eta/eta_api/controllers"
	"eta/eta_api/models"
	"eta/eta_api/models/aimod"
	"eta/eta_api/services/aiser"
	"eta/eta_api/utils"
	"fmt"
	"strconv"
	"time"
)

// AI
type AiController struct {
	controllers.BaseAuthController
}

// @Title 聊天接口
// @Description 聊天接口
// @Param	request	body aimod.ChatReq true "type json string"
// @Success 200 {object} response.ListResp
// @router /chat [post]
func (this *AiController) List() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	var req aimod.ChatReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	if req.Ask == "" {
		br.Msg = "请输入提问内容!"
		br.ErrMsg = "请输入提问内容"
		return
	}

	if utils.Re == nil {
		key := "CACHE_CHAT_" + strconv.Itoa(this.SysUser.AdminId)
		cacheVal, err := utils.Rc.RedisInt(key)
		fmt.Println("RedisString:", cacheVal, "err:", err)
		if err != nil && (err.Error() != "redigo: nil returned" && err.Error() != "redis: nil") {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "获取数据失败,Err:" + err.Error()
			return
		}
		putVal := 0
		if cacheVal <= 0 {
			putVal = utils.AiChatLimit
		} else {
			putVal = cacheVal - 1
		}

		if putVal <= 0 {
			br.Msg = "您今日" + strconv.Itoa(utils.AiChatLimit) + "次问答已达上限,请明天再来!"
			br.ErrMsg = "您今日" + strconv.Itoa(utils.AiChatLimit) + "次问答已达上限,请明天再来!"
			return
		}
		lastSecond := utils.GetTodayLastSecond()
		utils.Rc.Put(key, putVal, lastSecond)
	}

	//根据提问,获取信息
	askUuid := utils.MD5(req.Ask)
	chatMode, err := aimod.GetAiChatByAsk(askUuid)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "获取数据失败!"
		br.ErrMsg = "获取数据失败,GetAiChatByAsk,Err:" + err.Error()
		return
	}
	resp := new(aimod.ChatResp)
	var answer string
	//answerArr := []string{
	//	"周度数据显示,成品油现货市场价格跟随原油下跌,但近期相对抗跌,裂解价差走扩。批零价差方面汽油收窄,柴油走扩",
	//	"出口利润在原油下跌海外成品油矛盾更大的情况下汽柴油出口窗口完全关闭",
	//	"汽油需求在经历五一假期的一段高峰后将回归平稳,总体没有明显矛盾,后期我们担心更多的还是柴油。"}
	if chatMode != nil && chatMode.Answer != "" {
		answer = chatMode.Answer
	} else {
		//获取主题下的所有信息
		//AiChatTopicId
		historyList, err := aimod.GetAiChatList(req.AiChatTopicId)
		if err != nil && err.Error() != utils.ErrNoRow() {
			br.Msg = "获取主题历史数据失败!"
			br.ErrMsg = "获取主题历史数据失败,Err:" + err.Error()
			return
		}

		historyChatList := make([]aimod.HistoryChat, 0)
		for _, v := range historyList {
			historyChat := new(aimod.HistoryChat)
			historyChat.Ask = v.Ask
			historyChat.Answer = v.Answer
			historyChatList = append(historyChatList, *historyChat)
		}

		answer, err = aiser.ChatAutoMsg(req.Ask, historyChatList, req.Model)
		if err != nil {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "获取数据失败,ChatAutoMsg,Err:" + err.Error()
			return
		}
	}
	resp.Ask = req.Ask
	resp.Answer = answer
	resp.Model = req.Model

	if req.AiChatTopicId <= 0 { //新增
		topic := new(aimod.AiChatTopic)
		topic.TopicName = req.Ask
		topic.SysUserId = this.SysUser.AdminId
		topic.SysUserRealName = this.SysUser.RealName
		topic.CreateTime = time.Now()
		topic.ModifyTime = time.Now()
		topicId, err := aimod.AddAiChatTopic(topic)
		if err != nil {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "生成话题失败,Err:" + err.Error()
			return
		}
		resp.AiChatTopicId = int(topicId)
		chatItem := new(aimod.AiChat)
		chatItem.AiChatTopicId = resp.AiChatTopicId
		chatItem.Ask = req.Ask
		chatItem.AskUuid = utils.MD5(req.Ask)
		chatItem.Answer = answer
		chatItem.Model = EnabledModelsForMap[req.Model]
		chatItem.SysUserId = this.SysUser.AdminId
		chatItem.SysUserRealName = this.SysUser.RealName
		chatItem.CreateTime = time.Now()
		chatItem.ModifyTime = time.Now()
		_, err = aimod.AddAiChat(chatItem)
		if err != nil {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "生成话题记录失败,Err:" + err.Error()
			return
		}
	} else {
		resp.AiChatTopicId = req.AiChatTopicId
		chatItem := new(aimod.AiChat)
		chatItem.AiChatTopicId = resp.AiChatTopicId
		chatItem.Ask = req.Ask
		chatItem.AskUuid = utils.MD5(req.Ask)
		chatItem.Answer = answer
		chatItem.Model = EnabledModelsForMap[req.Model]
		chatItem.SysUserId = this.SysUser.AdminId
		chatItem.SysUserRealName = this.SysUser.RealName
		chatItem.CreateTime = time.Now()
		chatItem.ModifyTime = time.Now()
		_, err = aimod.AddAiChat(chatItem)
		if err != nil {
			br.Msg = "获取数据失败!"
			br.ErrMsg = "生成话题记录失败,Err:" + err.Error()
			return
		}
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取话题列表
// @Description 获取话题列表接口
// @Success 200 {object} aimod.AiChatTopicListResp
// @router /topic/list [get]
func (this *AiController) TopicList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	list, err := aimod.GetAiChatTopicList(sysUser.AdminId)
	if err != nil {
		br.Msg = "获取数据失败!"
		br.ErrMsg = "获取主题记录信息失败,Err:" + err.Error()
		return
	}
	resp := new(aimod.AiChatTopicListResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 获取话题详情
// @Description 获取话题详情接口
// @Param   AiChatTopicId   query   int  true       "主题id"
// @Success 200 {object} aimod.AiChatDetailResp
// @router /topic/detail [get]
func (this *AiController) TopicDetail() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	aiChatTopicId, _ := this.GetInt("AiChatTopicId")
	list, err := aimod.GetAiChatList(aiChatTopicId)
	if err != nil {
		br.Msg = "获取数据失败!"
		br.ErrMsg = "获取主题记录信息失败,Err:" + err.Error()
		return
	}
	for index := range list {
		list[index].Model = aimod.ModelViewMap[list[index].Model]
	}
	resp := new(aimod.AiChatDetailResp)
	resp.List = list
	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = resp
}

// @Title 删除话题接口
// @Description 删除话题接口
// @Param	request	body aimod.TopicDeleteReq true "type json string"
// @Success Ret=200 删除成功
// @router /topic/delete [post]
func (this *AiController) TopicDelete() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req aimod.TopicDeleteReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	if req.AiChatTopicId <= 0 {
		br.Msg = "参数错误!"
		br.ErrMsg = "参数错误!AiChatTopicId:" + strconv.Itoa(req.AiChatTopicId)
		return
	}
	err = aimod.DeleteTopic(req.AiChatTopicId)
	if err != nil {
		br.Msg = "删除失败!"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "删除成功"
	br.IsAddLog = true
}

// @Title 编辑话题接口
// @Description 编辑话题接口
// @Param	request	body aimod.TopicEditReq true "type json string"
// @Success Ret=200 编辑成功
// @router /topic/edit [post]
func (this *AiController) TopicEdit() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}

	var req aimod.TopicEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}

	if req.AiChatTopicId <= 0 {
		br.Msg = "参数错误!"
		br.ErrMsg = "参数错误!AiChatTopicId:" + strconv.Itoa(req.AiChatTopicId)
		return
	}
	topic, err := aimod.GetAiChatTopicByTopicName(req.TopicName)
	if err != nil && err.Error() != utils.ErrNoRow() {
		br.Msg = "编辑失败!"
		br.ErrMsg = "获取数据失败!Err:" + err.Error()
		return
	}
	if topic != nil && topic.AiChatTopicId != req.AiChatTopicId {
		br.Msg = "话题名称已存在,请重新修改!"
		return
	}

	err = aimod.EditTopic(req.AiChatTopicId, req.TopicName)
	if err != nil {
		br.Msg = "编辑失败!"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}