package ai

import (
	"encoding/json"
	"errors"
	"eta/eta_api/models"
	"eta/eta_api/models/ai_summary"
	"eta/eta_api/models/system"
	aiSummaryService "eta/eta_api/services/ai_summary"
	"eta/eta_api/utils"
	"time"
)

// AiPromptList
// @Title 获取所有ai纪要分类接口-包含沙盘
// @Description 获取所有ai纪要分类接口-包含沙盘
// @Success 200 {object} data_manage.ChartClassifyListResp
// @router /prompt/list [get]
func (this *AiController) AiPromptList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()

	list, err := ai_summary.GetAiPromptList(this.SysUser.AdminId, 0)
	if err != nil {
		br.Msg = "获取失败"
		br.ErrMsg = "获取数据失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = list
}

// PromptGroupList
// @Title 获取可见的目录列表
// @Description 获取可见的目录列表接口
// @Success 200 {object} ppt_english.RespGroupList
// @router /prompt/groups [get]
func (this *AiController) PromptGroupList() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	list, err := ai_summary.GetAiPromptShareList()
	if err != nil {
		br.Msg = err.Error()
		return
	}
	resp := make([]*ai_summary.RespGroupListItem, 0)
	publicAdminIdList := make([]int, 0)
	publicPromptListMap := make(map[int][]*ai_summary.AiPromptItem)
	systemAdminMap := make(map[int]*system.Admin)

	for _, v := range list {
		publicPromptList, ok := publicPromptListMap[v.SysAdminId]
		if !ok {
			publicPromptList = make([]*ai_summary.AiPromptItem, 0)
			publicAdminIdList = append(publicAdminIdList, v.SysAdminId)

		}
		systemAdminMap[v.SysAdminId] = &system.Admin{
			AdminId:  v.SysAdminId,
			RealName: v.SysAdminName,
		}
		publicPromptList = append(publicPromptList, v)
		publicPromptListMap[v.SysAdminId] = publicPromptList
	}
	for _, v := range publicAdminIdList {
		systemAdmin, ok := systemAdminMap[v]
		if !ok {
			continue
		}
		respGroupPptNameListItemList, ok := publicPromptListMap[v]
		if !ok {
			respGroupPptNameListItemList = make([]*ai_summary.AiPromptItem, 0)
		}

		//  分组信息
		tmpRespGroupListItem := &ai_summary.RespGroupListItem{
			GroupId:    int64(systemAdmin.AdminId),
			GroupName:  systemAdmin.RealName,
			AdminId:    systemAdmin.AdminId,
			IsShare:    1,
			PromptList: respGroupPptNameListItemList,
		}
		resp = append(resp, tmpRespGroupListItem)
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "查询成功"
	br.Data = resp
	return
}

// AddPpt
// @Title 新增提示词
// @Description 新增提示词接口
// @Param	request	body ppt_english.AddPptEnglishReq true "type json string"
// @Success 200 Ret=200 新增成功
// @router /prompt/add [post]
func (this *AiController) AddPrompt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req ai_summary.AiPromptAddReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.Title == "" {
		br.Msg = "标题不能为空"
		return
	}

	var msg string
	//获取该层级下最大的排序数
	maxSort, err := ai_summary.GetAiPromptMaxSort(this.SysUser.AdminId)

	prompt := &ai_summary.AiPrompt{
		CreateTime:    time.Now(),
		ModifyTime:    time.Now(),
		PromptContent: req.PromptContent,
		SysAdminId:    this.SysUser.AdminId,
		SysAdminName:  this.SysUser.RealName,
		Title:         req.Title,
		Sort:          maxSort + 1,
	}
	_, err = ai_summary.AddPropmt(prompt)
	if err != nil {
		br.Msg = "新增失败"
		br.ErrMsg = "新增失败,Err:" + err.Error()
		return
	}

	msg = "新增成功"

	br.Ret = 200
	br.Success = true
	br.Msg = msg
}

// EditPpt
// @Title 编辑提示词
// @Description 编辑提示词接口
// @Param	request	body ppt_english.AddPptEnglishReq true "type json string"
// @Success 200 Ret=200 编辑成功
// @router /prompt/edit [post]
func (this *AiController) EditPrompt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req ai_summary.AiPromptEditReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.Title == "" {
		br.Msg = "标题不能为空"
		return
	}

	promptItem := &ai_summary.AiPrompt{
		AiPromptId:    req.AiPromptId,
		PromptContent: req.PromptContent,
		Title:         req.Title,
		CreateTime:    time.Time{},
		ModifyTime:    time.Now(),
	}

	err = promptItem.Update([]string{"ModifyTime", "PromptContent", "Title"})
	if err != nil {
		br.Msg = "编辑失败"
		br.ErrMsg = "编辑失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "编辑成功"
	br.IsAddLog = true
}

// DeletePpt
// @Title 删除提示词
// @Description 删除ppt接口
// @Param	request	body ppt_english.DeletePptEnglishReq true "type json string"
// @Success 200 Ret=200 删除成功
// @router /prompt/delete [post]
func (this *AiController) DeletePrompt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req ai_summary.DeleteAipromptReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.AiPromptId <= 0 {
		br.Msg = "参数错误"
		return
	}
	promptInfo, err := ai_summary.GetAiPromptById(req.AiPromptId)
	if err != nil {
		br.Msg = "提示词不存在"
		return
	}
	if promptInfo.SysAdminId != this.SysUser.AdminId {
		br.Msg = "无权删除"
		return
	}
	err = ai_summary.DelAiPromptyId(req.AiPromptId)
	if err != nil {
		br.Msg = "删除失败"
		br.ErrMsg = "删除失败,Err:" + err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.IsAddLog = true
	br.Msg = "删除成功"
}

// DetailPrompt
// @Title 获取提示词详情
// @Description 获取提示词详情接口
// @Param   AiPromptId   query   int  true       "提示词id"
// @Success 200 {object} ppt_english.PptEnglish
// @router /prompt/detail [get]
func (this *AiController) DetailPrompt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		if br.ErrMsg == "" {
			br.IsSendEmail = false
		}
		this.Data["json"] = br
		this.ServeJSON()
	}()
	sysUser := this.SysUser
	if sysUser == nil {
		br.Msg = "请登录"
		br.ErrMsg = "请登录,SysUser Is Empty"
		br.Ret = 408
		return
	}
	aiPromptId, _ := this.GetInt("AiPromptId")

	promptInfo, err := ai_summary.GetAiPromptById(aiPromptId)
	if err != nil {
		br.Msg = "提示词不存在"
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "获取成功"
	br.Data = promptInfo
}

// MoveAiPrompt
// @Title 移动提示词
// @Description 移动提示词接口
// @Param	request	body models.ReqMoveGroupPpt true "type json string"
// @Success 200 Ret=200 移动成功
// @router /prompt/move [post]
func (this *AiController) MoveAiPrompt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req ai_summary.ReqMovePrompt
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.AiPromptId <= 0 {
		br.Msg = "请输入提示词ID"
		return
	}

	prompt, err := ai_summary.GetAiPromptById(req.AiPromptId)
	if err != nil {
		if err.Error() == utils.ErrNoRow() {
			br.Msg = "当前提示词不存在"
			br.ErrMsg = "当前提示词不存在"
			return
		}
		br.Msg = "提示词查询出错"
		br.ErrMsg = "提示词查询出错:" + err.Error()
		return
	}
	var updateStr []string

	var currentSort, prevSort, nextSort int
	currentSort = prompt.Sort

	var prevPrompt *ai_summary.AiPrompt
	var nextPrompt *ai_summary.AiPrompt
	if req.PrevAiPromptId > 0 {
		prevPrompt, err = ai_summary.GetAiPromptById(req.PrevAiPromptId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				err = errors.New("目录下的提示词不存在")
				return
			}
			err = errors.New("目录下的提示词查询出错:" + err.Error())
			return
		}
		prevSort = prevPrompt.Sort
	}

	if req.NextAiPromptId > 0 {
		nextPrompt, err = ai_summary.GetAiPromptById(req.NextAiPromptId)
		if err != nil {
			if err.Error() == utils.ErrNoRow() {
				err = errors.New("目录下的提示词不存在")
				return
			}
			err = errors.New("目录下的提示词查询出错:" + err.Error())
			return
		}
		nextSort = nextPrompt.Sort
	}

	updateStr = append(updateStr, "sort")

	//移到两个排序值中间操作
	if prevSort >= currentSort {
		//往下移动
		err = ai_summary.MoveDownPromptBySort(this.SysUser.AdminId, prevSort, currentSort)
		if err != nil {
			err = errors.New("向下移动提示词出错:" + err.Error())
			return
		}
		prompt.Sort = prevSort
	} else if nextSort <= currentSort && nextSort != 0 {
		//往上移动
		err = ai_summary.MoveUpPromptBySort(this.SysUser.AdminId, nextSort, currentSort)
		if err != nil {
			err = errors.New("向上移动提示词出错:" + err.Error())
			return
		}
		prompt.Sort = nextSort
	}
	//更新当前排序
	err = prompt.Update(updateStr)
	if err != nil {
		err = errors.New("移动提示词出错:" + err.Error())
		return
	}
	br.Ret = 200
	br.Success = true
	br.Msg = "移动成功"
}

// SharePrompt
// @Title 共享/取消共享单个提示词
// @Description 共享/取消共享单个提示词接口
// @Param	request	body models.ReqPptShare true "type json string"
// @Success 200 {object} models.RespPptShare
// @router /prompt/share [post]
func (this *AiController) SharePrompt() {
	br := new(models.BaseResponse).Init()
	defer func() {
		this.Data["json"] = br
		this.ServeJSON()
	}()
	var req ai_summary.DeleteAipromptReq
	err := json.Unmarshal(this.Ctx.Input.RequestBody, &req)
	if err != nil {
		br.Msg = "参数解析异常!"
		br.ErrMsg = "参数解析失败,Err:" + err.Error()
		return
	}
	if req.AiPromptId <= 0 {
		br.Msg = "请输入提示词序号"
		return
	}

	err = aiSummaryService.SharePrompt(req.AiPromptId, this.SysUser.AdminId)
	if err != nil {
		br.Msg = err.Error()
		return
	}

	br.Ret = 200
	br.Success = true
	br.Msg = "操作成功"

	return
}