package talent_service

import (
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"youngmini_server/app/dao"
	"youngmini_server/app/model/talent_model"
)

func SearchByTaskName(r *ghttp.Request) *TalentHttpResult {
	taskOrBrandName := r.GetRequestString("task_name", "nil")
	if taskOrBrandName == "nil" {
		return &TalentHttpResult{Code: -1, Msg: "input task_name param"}
	}

	taskOrBrandName = "%" + taskOrBrandName + "%"
	var searchResult talent_model.SearchByNameResult
	err := g.DB().Model(dao.TaskBaseInfo.Table).WithAll().
		Where(dao.TaskBaseInfo.Columns.TaskStatus, taskStatusInProgress).
		Where("(task_name like ? or brand_name like ?)", taskOrBrandName, taskOrBrandName).
		Scan(&searchResult.SearchResult)
	if err != nil {
		return &TalentHttpResult{Code: -2, Msg: "query task info failed"}
	}

	// 如果搜索结果位空则推荐任务
	if len(searchResult.SearchResult) <= 0 {
		err = g.DB().Model("task_base_info").WithAll().
			Where(dao.TaskBaseInfo.Columns.TaskStatus, taskStatusInProgress).
			Order("task_id").Limit(6).Scan(&searchResult.RecommendResult)
		if err != nil {
			return &TalentHttpResult{Code: -3, Msg: "query commend task info failed"}
		}
	}

	return &TalentHttpResult{Code: 0, Msg: "success", Data: searchResult}
}