package api

import (
	"errors"
	"fmt"
	"spu3d/log"
	"strings"

	"github.com/huaweicloud/huaweicloud-sdk-go-v3/core/auth/basic"
	mpc "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/mpc/v1"
	hwmodel "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/mpc/v1/model"
	region "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/mpc/v1/region"
)

var (
	Ak                = "RA1D7CFVCVKUFX1FHHPB"
	Endpoint          = "mpc.cn-east-3.myhuaweicloud.com"
	Sk                = "cDrR2NgAF2KaA4MRkcK19r93P3P6hLKOPhHvPu9p"
	SourceObjectUrl   = "https://sku3d-test.obs.cn-east-3.myhuaweicloud.com/queenshow/"
	VideoThumbnailUrl = "https://sku3d-test.obs.cn-east-3.myhuaweicloud.com/thumb-video/"
)

func NewHwClient() *mpc.MpcClient {
	ak := Ak
	sk := Sk

	auth := basic.NewCredentialsBuilder().
		WithAk(ak).
		WithSk(sk).
		Build()

	return mpc.NewMpcClient(
		mpc.MpcClientBuilder().
			WithRegion(region.ValueOf("cn-east-3")).
			WithCredential(auth).
			Build())

}

func VideoThumbnails(videoURL string) (string, error) {
	request := &hwmodel.CreateThumbnailsTaskRequest{}
	var listDotsThumbnailPara = []int32{
		int32(2),
	}
	_thum := strings.Split(videoURL, "/")
	videoFileName := _thum[len(_thum)-1]
	thumImageName := fmt.Sprintf("%s%s", strings.Split(videoFileName, ".")[0], ".jpg")
	fmt.Println(videoFileName)
	outputFilenameThumbnailPara := thumImageName

	typeThumbnailPara := hwmodel.GetThumbnailParaTypeEnum().DOTS
	thumbnailParabody := &hwmodel.ThumbnailPara{
		Type:           &typeThumbnailPara,
		Dots:           &listDotsThumbnailPara,
		OutputFilename: &outputFilenameThumbnailPara,
	}
	outputbody := &hwmodel.ObsObjInfo{
		Bucket:   "sku3d-test",
		Location: "cn-east-3",
		Object:   "thumb-video", // jpg
	}
	outPutImageUrl := fmt.Sprintf("%s%s", VideoThumbnailUrl, thumImageName)

	inputbody := &hwmodel.ObsObjInfo{
		Bucket:   "sku3d-test",
		Location: "cn-east-3",
		Object:   "queenshow/" + videoFileName, // mp4地址
	}
	request.Body = &hwmodel.CreateThumbReq{
		ThumbnailPara: thumbnailParabody,
		Output:        outputbody,
		Input:         inputbody,
	}
	client := NewHwClient()
	if client != nil {
		res, err := client.CreateThumbnailsTask(request)
		if err != nil {
			log.Error(err)
			fmt.Println(err)
			return "", errors.New("视频截图失败!")
		}
		log.Infof("视频截图[%s]=>taskId:", videoURL, *res.TaskId)

	} else {
		return "", errors.New("获取华为客户端错误")
	}
	return outPutImageUrl, nil
}

type VideoCutParams struct {
	SourceVideoUrl string
	DestVideoName  string
	Start          string
	End            string
}

type VideoCutOutRes struct {
	Url   string `json:"url"`
	JobId string `json:"jobId"`
}

func VideoCutOut(params *VideoCutParams) (VideoCutOutRes, error) {
	_thum := strings.Split(params.SourceVideoUrl, "/")
	sourceVideoName := _thum[len(_thum)-1]
	request := &hwmodel.CreateEditingJobRequest{}
	// 不带后缀
	fileNameOutput := params.DestVideoName
	outputOutputSetting := &hwmodel.ObsObjInfo{
		Bucket:   "sku3d-test",
		Location: "cn-east-3",
		Object:   "queenshow",
		FileName: &fileNameOutput,
	}
	outputSettingbody := &hwmodel.OutputSetting{
		Output: outputOutputSetting,
	}
	inputClips := &hwmodel.ObsObjInfo{
		Bucket:   "sku3d-test",
		Location: "cn-east-3",
		Object:   "queenshow/" + sourceVideoName,
	}
	timelineStartClips := params.Start
	timelineEndClips := params.End
	var listClipsbody = []hwmodel.ClipInfo{
		{
			Input:         inputClips,
			TimelineStart: &timelineStartClips,
			TimelineEnd:   &timelineEndClips,
		},
	}
	var listEditTypebody = []string{
		"CLIP",
	}
	request.Body = &hwmodel.CreateEditingJobReq{
		OutputSetting: outputSettingbody,
		Clips:         &listClipsbody,
		EditType:      &listEditTypebody,
	}
	outPutVideoUrl := fmt.Sprintf("%s%s.mp4", SourceObjectUrl, fileNameOutput)
	client := NewHwClient()
	jobId := ""
	if client != nil {
		res, err := client.CreateEditingJob(request)
		if err != nil {
			log.Error(err)
			fmt.Println(err)
			return VideoCutOutRes{}, errors.New("视频裁剪失败!")
		}
		jobId = *res.JobId
		log.Infof("视频裁剪[%s]=>jobId:", params.SourceVideoUrl, *res.JobId)

	} else {
		return VideoCutOutRes{}, errors.New("获取华为客户端错误!")
	}
	return VideoCutOutRes{Url: outPutVideoUrl, JobId: jobId}, nil
}

// 查询裁剪任务
func QueryByJobId(jobId string) (*hwmodel.ListEditingJobResponse, error) {
	client := NewHwClient()
	if client == nil {
		return nil, errors.New("获取华为客户端错误!")
	}
	request := &hwmodel.ListEditingJobRequest{}
	var listJobId = []string{
		jobId,
	}
	request.JobId = &listJobId
	return client.ListEditingJob(request)
}