package api

import (
	"easyaudioencode/internal/core/audioencode"
	"fmt"
	"git.lnton.com/lnton/pkg/reason"
	"github.com/gin-gonic/gin"
	"strconv"
)

func (a AudioEncodeAPI) findAudioTask(c *gin.Context, in *audioencode.FindAudioTaskInput) (any, error) {
	items, total, err := a.core.FindAudioTask(c.Request.Context(), in)
	rows := make([]map[string]interface{}, 0)

	for _, item := range items {
		//row := structs.Map(item)
		row := make(map[string]interface{})

		row["audio_id"] = item.AudioID
		row["audio_name"] = item.AudioName
		row["channel_id"] = item.ChannelID
		row["channel_name"] = item.ChannelName
		row["size"] = item.Size
		row["duration"] = item.Duration
		row["id"] = item.ID
		row["mode"] = item.Mode
		row["created_at"] = item.CreatedAt
		row["updated_at"] = item.UpdatedAt
		row["task_status"] = item.TaskStatus
		row["error_msg"] = item.ErrorMsg
		task, errs := a.transcodeCore.GetTaskInfo(item.ID)
		if errs == nil {
			row["task_status"] = task.Status
			row["end_time"] = task.EndTime
			row["create_time"] = task.CreateTime
			row["start_time"] = task.StartTime
		} else {
			if item.TaskStatus == 1 || item.TaskStatus == 0 {
				row["task_status"] = 2
			}
		}
		rows = append(rows, row)
	}

	return gin.H{"items": rows, "total": total}, err
}

func (a AudioEncodeAPI) addAudioTask(c *gin.Context, in *audioencode.AddAudioTaskInput) (any, error) {
	if len(in.Items) == 0 {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`add audioencode Items is empty`))
	}
	var outputList []audioencode.AddErrorOutput
	for _, item := range in.Items {
		audioInfo, err := a.core.GetAudioEncode(c.Request.Context(), item.AudioID)
		if err != nil {
			list := audioencode.AddErrorOutput{
				AudioID:     item.AudioID,
				ChannelID:   item.ChannelID,
				ErrorMsg:    fmt.Sprintf(`find audioencode [%d] err [%s]`, item.AudioID, err.Error()),
				ChannelName: item.ChannelName,
			}
			outputList = append(outputList, list)
			continue
		}
		inAdd := &audioencode.AddAudioTask{
			AudioID:     item.AudioID,
			ChannelID:   item.ChannelID,
			ChannelName: item.ChannelName,
			Size:        audioInfo.Size,
			Duration:    audioInfo.Duration,
			AudioName:   audioInfo.Name,
			Mode:        audioInfo.Mode,
		}
		info, err := a.core.AddAudioTask(c.Request.Context(), inAdd)
		if err != nil {
			list := audioencode.AddErrorOutput{
				AudioID:     item.AudioID,
				ChannelID:   item.ChannelID,
				ErrorMsg:    fmt.Sprintf(`find audioencode [%d] err [%s]`, item.AudioID, err.Error()),
				ChannelName: item.ChannelName,
			}
			outputList = append(outputList, list)
			continue
		}

		err = a.transcodeCore.AddTask(info.ID, info.ChannelID, audioInfo.EncodeUrl, audioInfo.Duration)
		if err != nil {
			list := audioencode.AddErrorOutput{
				AudioID:     item.AudioID,
				ChannelID:   item.ChannelID,
				ErrorMsg:    fmt.Sprintf(`find audioencode [%d] err [%s]`, item.AudioID, err.Error()),
				ChannelName: item.ChannelName,
			}
			outputList = append(outputList, list)
			continue
		}
	}
	if len(outputList) == 0 {
		return gin.H{"data": "ok", "msg": "下发成功"}, nil
	}
	return gin.H{"data": outputList, "msg": "下发失败通道!"}, nil
}

func (a AudioEncodeAPI) cancelAudioTask(c *gin.Context, _ *struct{}) (any, error) {
	ID, _ := strconv.Atoi(c.Param("id"))
	err := a.transcodeCore.CancelTask(ID)
	if err != nil {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`add CancelTask err [%s]`, err.Error()))
	}
	return gin.H{"data": "OK!"}, err
}

func (a AudioEncodeAPI) delAudioTask(c *gin.Context, _ *struct{}) (any, error) {
	ID, _ := strconv.Atoi(c.Param("id"))
	_, err := a.core.DelAudioTask(c.Request.Context(), ID)
	if err != nil {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`del audioencode [%d] err [%s]`, ID, err.Error()))
	}
	return gin.H{"data": "OK!"}, err
}

func (a AudioEncodeAPI) delAudioTaskAll(c *gin.Context, in *audioencode.DelAudioTaskInput) (any, error) {
	if len(in.IDs) == 0 {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`del audioencode ids is empty`))
	}
	_, err := a.core.DelAudioTaskAll(c.Request.Context(), in.IDs)
	if err != nil {
		return nil, reason.ErrServer.SetMsg(fmt.Sprintf(`del audioencode [%d] err [%s]`, in.IDs, err.Error()))
	}
	return gin.H{"data": "OK!"}, err
}
