package service

import (
	"context"
	service "convert-server/domain/repository"

	"convert-server/infra/db"
	"time"
)

// 发起文件转换
func DoConversion(c context.Context, req *service.ConversionRequest) (resp *service.ConversionResponse, err error) {
	/*ret := make(map[string]interface{}, 0)
	ret["errcode"] = 0
	ret["errmsg"] = nil
	ret["base64"] = nil*/
	req.IsPrivate = true

	//创建项目
	createErr := service.NewConversion().CreateProject()
	if createErr != nil {
		resp.Msg = createErr.Error()
		resp.Code = "100010"
		resp.Data = nil
		return resp, err
	}

	//执行转换
	result, errs := service.NewConversion().Conversion(req)
	if errs != nil {
		resp.Msg = createErr.Error()
		resp.Code = "100010"
		resp.Data = nil
		return resp, err
	}
	taskId := result["body"].(map[string]interface{})["TaskId"].(string)

	//入库
	save, errset := db.GetServerSiteMicrosDB().DocServerProject.Create().
		SetProjectName(req.ProjectName).
		SetCreatedAt(time.Now()).
		SetSourceURL(req.SourceURI).
		SetSourceType(req.SourceType).
		SetTargetURL(req.TargetURI).
		SetTaskID(taskId).Save(c)

	if errset != nil {
		resp.Msg = errset.Error()
		resp.Code = "100010"
		resp.Data = nil
		return resp, errset
	}

	resp.Msg = ""
	resp.Code = "200"
	resp.Data = save
	return resp, nil
}

// 获取转换结果
func GetTaskProject(c context.Context, req *service.GetTaskRequest) (resp *service.ConversionResponse, err error) {
	ret := make(map[string]interface{}, 0)
	req.RequestDefinition = true

	ret["ProjectId"] = req.ProjectId
	if ret["ProjectId"] != "" {
		projectData, infoErr := db.GetServerSiteMicrosDB().DocServerProject.Get(c, ret["ProjectId"].(int32))
		if infoErr != nil {
			resp.Msg = err.Error()
			resp.Code = "100010"
			resp.Data = nil
			return resp, err
		}
		req.ProjectName = projectData.ProjectName
		req.TaskId = projectData.TaskID
		req.TaskType = projectData.TargetType
	}

	result, errs := service.NewConversion().GetTaskProject(*req)
	if errs != nil {
		resp.Msg = err.Error()
		resp.Code = "100010"
		resp.Data = nil
		return resp, err
	}

	resp.Msg = ""
	resp.Code = "200"
	resp.Data = result
	return resp, nil
}
