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 Script *script

type script struct {
}

// ScriptOpinion 在上传脚本表上提交修改意见
func (*script) ScriptOpinion(ctx context.Context, request http_model.ScriptOpinionRequest) (*http_model.ScriptOpinionData, error) {
	Script := gorm_model.YounggeeScriptInfo{
		TaskID:        request.TaskID,
		ReviseOpinion: request.ScriptOpinion,
	}
	err := db.ScriptOpinion(ctx, Script.TaskID, Script.ReviseOpinion)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Script service] call CreateScript error,err:%+v", err)
		return nil, err
	}
	// 记录任务日志
	err = db.CreateTaskLog(ctx, Script.TaskID, "脚本驳回")
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Script service] call CreateTaskLog error,err:%+v", err)
		return nil, err
	}

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

	res := &http_model.ScriptOpinionData{
		TaskID: Script.TaskID,
	}
	return res, nil
}

// AcceptScript
func (*script) AcceptScript(ctx context.Context, request http_model.AcceptScriptRequest) (*http_model.AcceptScriptData, 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.AcceptScript(ctx, TaskIDList)
	if err != nil {
		logrus.WithContext(ctx).Errorf("[Script service] call CreateScript error,err:%+v", err)
		return nil, err
	}
	// 记录任务日志
	for _, taskId := range TaskIDList {
		err = db.CreateTaskLog(ctx, taskId, "脚本通过")
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Script service] call CreateTaskLog error,err:%+v", err)
			return nil, err
		}
		err = db.CreateMessageByTaskId(ctx, 2, 1, taskId)
		if err != nil {
			logrus.WithContext(ctx).Errorf("[Script service] call CreateTaskLog error,err:%+v", err)
			return nil, err
		}
	}

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