package biz

import (
	"ai_scheduler/internal/data/constants"
	errors "ai_scheduler/internal/data/error"
	"ai_scheduler/internal/data/impl"
	"ai_scheduler/internal/data/model"
	"ai_scheduler/internal/entitys"
	"ai_scheduler/internal/pkg/l_request"
	"context"
	"encoding/json"
	"net/http"
	"strconv"

	"gorm.io/gorm/utils"

	"xorm.io/builder"

	"ai_scheduler/internal/config"
)

type TaskBiz struct {
	taskRepo *impl.TaskImpl
	conf     *config.Config
}

func NewTaskBiz(conf *config.Config, taskRepo *impl.TaskImpl) *TaskBiz {
	return &TaskBiz{
		taskRepo: taskRepo,
		conf:     conf,
	}
}

// taskList 功能列表
func (t *TaskBiz) TaskList(ctx context.Context, req *entitys.TaskRequest, auth string) (list []model.AiTask, err error) {
	tasks := make([]model.AiTask, 0)
	cond := builder.NewCond()
	cond = cond.And(builder.Eq{"status": constants.Enable})
	cond = cond.And(builder.Eq{"sys_id": req.SysId})
	cond = cond.And(builder.Eq{"is_show": constants.IsSHOW})
	err = t.taskRepo.GetRangeToMapStruct(&cond, &tasks)

	codes, err := t.GetUserPermission(req, auth)
	if err != nil {
		return
	}

	// 检查用户是否有权限
	for _, task := range tasks {
		if utils.Contains(codes, task.Index) {
			list = append(list, task)
		}
	}

	return
}

// 从统一登录平台获取用户权限
func (t *TaskBiz) GetUserPermission(req *entitys.TaskRequest, auth string) (codes []string, err error) {

	request := l_request.Request{
		Method: "GET",
		Url:    t.conf.PermissionConfig.PermissionURL + strconv.Itoa(int(req.SysId)),
		Headers: map[string]string{
			"User-Agent":    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
			"Accept":        "application/json, text/plain, */*",
			"Authorization": auth,
		},
	}
	// 发送请求
	res, err := request.Send()
	if err != nil {
		err = errors.SysErrf("请求用户权限失败")
		return
	}

	// 检查响应状态码
	if res.StatusCode != http.StatusOK {
		err = errors.SysErrf("获取用户权限失败")
		return
	}

	type resp struct {
		Codes []string `json:"codes"`
	}
	// 解析响应体s
	var respBody resp
	err = json.Unmarshal([]byte(res.Text), &respBody)
	if err != nil {
		return
	}

	return respBody.Codes, nil
}
