package v1

import (
	"context"
	"designs/app/common/request"
	"designs/global"
	"designs/model"
	"designs/response"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/tencentyun/cos-go-sdk-v5"
	"net/http"
	"net/url"
	"path/filepath"
	"time"
)

func FileList(c *gin.Context) {
	form := request.Check(c, &struct {
		Offset *int   `form:"offset" binding:"required"`
		Limit  *int   `form:"limit" binding:"required"`
		Search string `form:"search" binding:""`
	}{})

	query := global.App.DB.Table("file")
	if form.Search != "" {
		query = query.Where("fileName", "like", "%"+form.Search+"%")
	}
	var count int64
	err := query.Count(&count).Error
	if err != nil {
		response.Fail(c, 1001, err.Error())
		return
	}

	var files []model.File
	err = query.Offset(*form.Offset).Limit(*form.Limit).Scan(&files).Error
	if err != nil {
		response.Fail(c, 1002, err.Error())
		return
	}

	response.Success(c, gin.H{
		"count": count,
		"data":  files,
	})
}

func FileDelete(c *gin.Context) {
	form := request.Check(c, &struct {
		FileId int `form:"fileId" json:"fileId" binding:"required"`
	}{})
	var d interface{}
	err := global.App.DB.Table("file").Where("id", form.FileId).Delete(d).Error
	if err != nil {
		response.Fail(c, 2001, err.Error())
		return
	}

	//删除本地文件和云端文件

	response.Success(c, gin.H{})

}

func LocalFileToService(c *gin.Context) {
	form := request.Check(c, &struct {
		FilePath string `form:"filePath" json:"filePath" binding:"required"`
	}{})

	path, err := FileToService(form.FilePath)
	if err != nil {
		response.Fail(c, 1004, err.Error())
		return
	}

	now := model.XTime{
		Time: time.Now(),
	}

	//存储到mysql
	err = global.App.DB.Table("file").Create(&model.File{
		CreatedAt: now,
		UpdatedAt: now,
		FileName:  filepath.Base(form.FilePath),
		LocalPath: form.FilePath,
		CosPath:   path,
	}).Error
	if err != nil {
		response.Fail(c, 2001, err.Error())
		return
	}

	response.Success(c, gin.H{
		"file_path": path,
	})
}

func FileToService(filePath string) (string, error) {
	// 将 examplebucket-1250000000 和 COS_REGION 修改为用户真实的信息
	// 存储桶名称，由 bucketname-appid 组成，appid 必须填入，可以在 COS 控制台查看存储桶名称。https://console.cloud.tencent.com/cos5/bucket
	// COS_REGION 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket, 关于地域的详情见 https://cloud.tencent.com/document/product/436/6224
	u, _ := url.Parse("https://chunhao-1257323087.cos.ap-shanghai.myqcloud.com")
	// 用于 Get Service 查询，默认全地域 service.cos.myqcloud.com
	su, _ := url.Parse("https://service.cos.myqcloud.com")
	b := &cos.BaseURL{BucketURL: u, ServiceURL: su}
	// 1.永久密钥
	client := cos.NewClient(b, &http.Client{
		Transport: &cos.AuthorizationTransport{
			SecretID:  "AKIDgQ2TzTq381nQrAJKBC8tSqCNM9lBQTQB", // 用户的 SecretId，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考 https://cloud.tencent.com/document/product/598/37140
			SecretKey: "gBVWO4dzCD5qeKoy30phTBi7NXYYM2b0",     // 用户的 SecretKey，建议使用子账号密钥，授权遵循最小权限指引，降低使用风险。子账号密钥获取可参考 https://cloud.tencent.com/document/product/598/37140
		},
	})

	key := filepath.Base(filePath)
	res, _, err := client.Object.Upload(
		context.Background(), key, filePath, nil,
	)
	fmt.Println(res)
	if err != nil {
		return "", err
	}

	ourl := client.Object.GetObjectURL(key)

	return ourl.Host + ourl.Path, nil
}
