package service

import (
	"context"
	"fmt"
	"strings"
	"youngee_b_api/db"
	"youngee_b_api/model/gorm_model"
	"youngee_b_api/model/http_model"

	"github.com/sirupsen/logrus"
)

var Link *link

type link struct {
}

// LinkOpinion 在上传脚本表上提交修改意见
func (*link) LinkOpinion(ctx context.Context, request http_model.LinkOpinionRequest) (*http_model.LinkOpinionData, error) {
	Link := gorm_model.YounggeeLinkInfo{
		TaskID:        request.TaskID,
		ReviseOpinion: request.LinkOpinion,
	}
	err := db.LinkOpinion(ctx, Link.TaskID, Link.ReviseOpinion)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link service] call CreateLink error,err:%+v", err)
		return nil, err
	}
	// 记录任务日志
	err = db.CreateTaskLog(ctx, Link.TaskID, "链接驳回")
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link service] call CreateTaskLog error,err:%+v", err)
		return nil, err
	}

	err = db.CreateMessageByTaskId(ctx, 18, 3, Link.TaskID)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link service] call CreateMessageByTaskId error,err:%+v", err)
		return nil, err
	}

	res := &http_model.LinkOpinionData{
		TaskID: Link.TaskID,
	}
	return res, nil
}

// AcceptLink
func (*link) AcceptLink(ctx context.Context, request http_model.AcceptLinkRequest) (*http_model.AcceptLinkData, error) {
	var TaskIDList []string
	TaskIDs := strings.Split(request.TaskIds, ",")
	for _, taskId := range TaskIDs {
		TaskIDList = append(TaskIDList, taskId)
	}
	fmt.Printf("acc request %+v", TaskIDList)
	err := db.AcceptLink(ctx, TaskIDList)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Link service] call CreateLink error,err:%+v", err)
		return nil, err
	}
	// 记录任务日志
	for _, taskId := range TaskIDList {
		err = db.CreateTaskLog(ctx, taskId, "链接通过")
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Link service] call CreateTaskLog error,err:%+v", err)
			return nil, err
		}
		err = db.CreateMessageByTaskId(ctx, 4, 1, taskId)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Script service] call CreateTaskLog error,err:%+v", err)
			return nil, err
		}
	}

	res := &http_model.AcceptLinkData{
		TaskIds: TaskIDList,
	}
	return res, nil
}
