package service

import (
	"encoding/json"
	"errors"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	imm20200930 "github.com/alibabacloud-go/imm-20200930/v4/client"
	openapiutil "github.com/alibabacloud-go/openapi-util/service"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	"net/url"
	"strings"
)

type Conversion struct {
	AccessKeyId     string
	AccessKeySecret string
	Endpoint        string
	Bucket          string
}

func NewConversion() *Conversion {
	return &Conversion{
		Endpoint:        "imm.cn-shenzhen.aliyuncs.com",
		AccessKeyId:     "LTAI5tFsFNAoCngNdX9g4CMW",
		AccessKeySecret: "otz3kkD0s3SWhVitKP2cqiZdCkTCJd",
		Bucket:          "test-bucket-v1",
	}
}

func (o *Conversion) CreateClient() (_result *openapi.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(o.AccessKeyId),
		AccessKeySecret: tea.String(o.AccessKeySecret),
	}
	config.Endpoint = tea.String(o.Endpoint) //imm.cn-shenzhen.aliyuncs.com
	_result = &openapi.Client{}
	_result, _err = openapi.NewClient(config)
	return _result, _err
}

// CreateApiInfo API 相关
func (o *Conversion) CreateApiInfo() (_result *openapi.Params) {
	params := &openapi.Params{
		Action:      tea.String("CreateOfficeConversionTask"),
		Version:     tea.String("2020-09-30"),
		Protocol:    tea.String("HTTPS"),
		Method:      tea.String("POST"),
		AuthType:    tea.String("AK"),
		Style:       tea.String("RPC"),
		Pathname:    tea.String("/"),
		ReqBodyType: tea.String("json"),
		BodyType:    tea.String("json"),
	}
	return params
}

// GetBucket 获取bucket信息
func (o *Conversion) GetBucket(isPrivate bool) string {
	if isPrivate {
		return "oss://" + "test-bucket-v1"
	}
	return "oss://" + "test-bucket-v1-pub"
}

type ConversionRequest struct {
	ProjectName string
	SourceType  string
	TargetType  string
	SourceURI   string
	TargetURI   string
	IsPrivate   bool
}

type GetTaskRequest struct {
	ProjectName       string
	TaskType          string
	TaskId            string
	RequestDefinition bool
}

func (o *Conversion) checkParam(arg ConversionRequest) error {
	if arg.SourceURI == "" {
		return errors.New("SourceURI 不能为空")
	}
	//if arg.TargetURI == "" {
	//	return errors.New("TargetURI 不能为空")
	//}
	if arg.ProjectName == "" {
		return errors.New("ProjectName 不能为空")
	}
	if arg.SourceType == "" {
		return errors.New("SourceType 不能为空")
	}
	if arg.TargetType == "" {
		return errors.New("TargetType 不能为空")
	}
	return nil
}

// DoConversion 文件转换
func (o *Conversion) DoConversion(arg ConversionRequest) (string, error) {
	//校验参数
	checkErr := o.checkParam(arg)
	if checkErr != nil {
		return "", checkErr
	}

	client := NewConversion()
	params := client.CreateApiInfo()

	sourceParseUrl, parseErr := url.Parse(arg.SourceURI)
	if parseErr != nil {
		return "", parseErr
	}
	targetParseUrl, parseTargetErr := url.Parse(arg.TargetURI)
	if parseTargetErr != nil {
		return "", parseTargetErr
	}
	// query params
	queries := map[string]interface{}{}
	queries["ProjectName"] = arg.ProjectName
	queries["SourceURI"] = o.GetBucket(arg.IsPrivate) + sourceParseUrl.Path
	queries["TargetURI"] = o.GetBucket(arg.IsPrivate) + targetParseUrl.Path
	//queries["TargetURIPrefix"] = arg.TargetURIPrefix
	queries["SourceType"] = arg.SourceType
	queries["TargetType"] = arg.TargetType
	// runtime options
	runtime := &util.RuntimeOptions{}
	request := &openapi.OpenApiRequest{
		Query: openapiutil.Query(queries),
	}

	ossClient, _err := client.CreateClient()
	if _err != nil {
		return "", _err
	}

	fmt.Println("DoConversion request", queries)
	// 返回值为 Map 类型，可从 Map 中获得三类数据：响应体 body、响应头 headers、HTTP 返回的状态码 statusCode。
	res, err := ossClient.CallApi(params, request, runtime)
	fmt.Println("DoConversion result", res)
	if err != nil {
		return "", err
	}
	return "", err
}

func (o *Conversion) CreateImClient() (_result *imm20200930.Client, _err error) {
	config := &openapi.Config{
		AccessKeyId:     tea.String(o.AccessKeyId),
		AccessKeySecret: tea.String(o.AccessKeySecret),
	}
	config.Endpoint = tea.String(o.Endpoint)

	_result = &imm20200930.Client{}
	_result, _err = imm20200930.NewClient(config)
	return _result, _err
}

// CreateProject 创建项目
func (o *Conversion) CreateProject() (_err error) {
	client, createError := o.CreateImClient()
	if createError != nil {
		return createError
	}

	createProjectRequest := &imm20200930.CreateProjectRequest{}
	var ProjectName = "DOC_TO_PDF"
	createProjectRequest.ProjectName = &ProjectName
	runtime := &util.RuntimeOptions{}

	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		createdResp, _err := client.CreateProjectWithOptions(createProjectRequest, runtime)
		if _err != nil {
			return _err
		}
		fmt.Println("创建项目返回参数", createdResp)
		return nil
	}()

	if tryErr != nil {
		var sdkErr = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			sdkErr = _t
		} else {
			sdkErr.Message = tea.String(tryErr.Error())
		}
		// 诊断地址
		var data interface{}
		d := json.NewDecoder(strings.NewReader(tea.StringValue(sdkErr.Data)))
		decodeError := d.Decode(&data)
		if decodeError != nil {
			return decodeError
		}
		if m, ok := data.(map[string]interface{}); ok {
			fmt.Println("创建项目出现异常", m["Code"])
			resultCode, assertCodeError := util.AssertAsString(m["Code"])
			if assertCodeError != nil {
				return assertCodeError
			}
			if *resultCode == "ResourceAlreadyExists" {
				return nil
			}
			return errors.New(*resultCode)
		}
		errMsg, assertError := util.AssertAsString(sdkErr.Message)
		if assertError != nil {
			return assertError
		}
		fmt.Println("创建项目出现异常", &errMsg)
	}
	return nil
}

func (o *Conversion) GetTaskProject(args GetTaskRequest) (string, error) {
	client, _err := o.CreateImClient()
	if _err != nil {
		return "", _err
	}

	getTaskRequest := &imm20200930.GetTaskRequest{}
	getTaskRequest.TaskId = &args.TaskId
	getTaskRequest.TaskType = &args.TaskType
	runtime := &util.RuntimeOptions{}
	tryErr := func() (_e error) {
		defer func() {
			if r := tea.Recover(recover()); r != nil {
				_e = r
			}
		}()
		// 复制代码运行请自行打印 API 的返回值
		_, _err = client.GetTaskWithOptions(getTaskRequest, runtime)
		if _err != nil {
			return _err
		}

		return nil
	}()

	if tryErr != nil {
		var error = &tea.SDKError{}
		if _t, ok := tryErr.(*tea.SDKError); ok {
			error = _t
		} else {
			error.Message = tea.String(tryErr.Error())
		}
		// 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
		// 错误 message
		fmt.Println(tea.StringValue(error.Message))
		// 诊断地址
		var data interface{}
		d := json.NewDecoder(strings.NewReader(tea.StringValue(error.Data)))
		d.Decode(&data)
		if m, ok := data.(map[string]interface{}); ok {
			recommend, _ := m["Recommend"]
			fmt.Println(recommend)
		}
		_, _err = util.AssertAsString(error.Message)
		if _err != nil {
			return "", _err
		}
	}
	return "", _err
}
