package task

import (
	"context"
	"server/internal/dao"
	"server/internal/model"
	"server/internal/model/do"
	"server/internal/service"
	"server/utility/ecode"
)

type sTask struct {
}

func New() service.ITask {
	return &sTask{}
}
func init() {
	service.RegisterTask(New())
}
func (s *sTask) List(ctx context.Context, in *model.TaskListIn) (out *model.TaskListOut, err error) {
	out = &model.TaskListOut{}
	m := dao.Tasks.Ctx(ctx)
	if in.Title != "" {
		m = m.WhereLike("title", "%"+in.Title+"%")
	}
	if in.Status != 0 {
		m = m.Where("status", in.Status)
	}
	if err = m.Page(in.Page, in.Size).OrderDesc("id").ScanAndCount(&out.List, &out.Total, false); err != nil {
		return nil, ecode.Fail.Sub("task_query_failed")
	}
	return out, nil
}

func (s *sTask) Add(ctx context.Context, in *model.TaskAddIn) (out *model.TaskCRUDOut, err error) {
	_, err = dao.Tasks.Ctx(ctx).Data(do.Tasks{
		TaskType:     in.TaskType,
		Title:        in.Title,
		Description:  in.Description,
		RewardPoints: in.RewardPoints,
		Status:       in.Status,
	}).Insert()
	if err != nil {
		return nil, ecode.Fail.Sub("task_add_failed")
	}
	return &model.TaskCRUDOut{Success: true}, nil
}

func (s *sTask) Edit(ctx context.Context, in *model.TaskEditIn) (out *model.TaskCRUDOut, err error) {
	exist, err := dao.Tasks.Ctx(ctx).WherePri(in.Id).Exist()
	if err != nil {
		return nil, ecode.Fail.Sub("task_query_failed")
	}
	if !exist {
		return nil, ecode.NotFound.Sub("task_not_found")
	}
	_, err = dao.Tasks.Ctx(ctx).WherePri(in.Id).Data(do.Tasks{
		TaskType:     in.TaskType,
		Title:        in.Title,
		Description:  in.Description,
		RewardPoints: in.RewardPoints,
		Status:       in.Status,
	}).Update()
	if err != nil {
		return nil, ecode.Fail.Sub("task_edit_failed")
	}
	return &model.TaskCRUDOut{Success: true}, nil
}

func (s *sTask) Delete(ctx context.Context, in *model.TaskDelIn) (out *model.TaskCRUDOut, err error) {
	exist, err := dao.Tasks.Ctx(ctx).WherePri(in.Id).Exist()
	if err != nil {
		return nil, ecode.Fail.Sub("task_query_failed")
	}
	if !exist {
		return nil, ecode.NotFound.Sub("task_not_found")
	}
	_, err = dao.Tasks.Ctx(ctx).WherePri(in.Id).Delete()
	if err != nil {
		return nil, ecode.Fail.Sub("task_delete_failed")
	}
	return &model.TaskCRUDOut{Success: true}, nil
}

// AppList 获取任务列表（只返回任务类型和奖励积分）
func (s *sTask) AppList(ctx context.Context, in *model.TaskAppListIn) (out *model.TaskSimpleListOut, err error) {
	out = &model.TaskSimpleListOut{}

	// 只查询任务类型和奖励积分字段
	if err = dao.Tasks.Ctx(ctx).
		Fields("task_type, reward_points").
		Where("status", 1).
		OrderDesc("id").
		Scan(&out.List); err != nil {
		return nil, ecode.Fail.Sub("task_query_failed")
	}

	return out, nil
}
