package api

import (
	"box-cost/db/model"
	"box-cost/db/repo"
	"box-cost/log"
	"errors"
	"fmt"
	"io"
	"os"
	"path"
	"strings"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

// 签名管理
func Signature(r *GinRouter) {

	// 创建签名
	r.POST("/signature/create", SignatureAdd)

	// 获取签名详情
	r.GET("/signature/detail/:id", SignatureDetail)

	// 获取签名列表
	r.GET("/signature/list", SignatureList)

	// 更新签名
	r.POST("/signature/update", SignatureUpdate)

	// 删除签名
	r.POST("/signature/delete/:id", SignatureDel)

	r.POST("/signature/upload/image", SignatureUpload)
}

// 创建签名
func SignatureAdd(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	var signature model.Signature

	err := c.ShouldBindJSON(&signature)
	if err != nil {
		fmt.Println(err)
		return nil, errors.New("参数错误！")
	}

	// if signature.UserId.IsZero() {
	// 	return nil, errors.New("签名用户为空")
	// }
	signature.Format = `{"autofit":true,"print_obj":true,"lock_aspect_ratio":false,"locked":false,"positioning":"oncell"}`

	signature.CreateTime = time.Now()
	signature.UpdateTime = time.Now()

	return repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionSignature, &signature)
}

// 获取签名详情
func SignatureDetail(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	signatureId := c.Param("id")
	id, err := primitive.ObjectIDFromHex(signatureId)
	if err != nil {
		return nil, errors.New("非法id")
	}
	var signature model.Signature
	option := &repo.DocSearchOptions{
		CollectName: repo.CollectionSignature,
		Query:       repo.Map{"_id": id},
	}

	found, err := repo.RepoSeachDoc(apictx.CreateRepoCtx(), option, &signature)
	if !found || err != nil {
		log.Info(err)
		return nil, errors.New("数据未找到")
	}

	return signature, nil
}

// 获取签名列表
func SignatureList(c *gin.Context, apictx *ApiSession) (interface{}, error) {

	page, size, query := UtilQueryPageSize(c)

	option := &repo.PageSearchOptions{
		CollectName: repo.CollectionSignature,
		Query:       query,
		Page:        page,
		Size:        size,
		Sort:        bson.M{"sort": 1},
	}
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), option)
}

// 更新签名
func SignatureUpdate(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	var signature model.Signature
	err := c.ShouldBindJSON(&signature)

	if err != nil {
		return nil, errors.New("参数错误")
	}
	if signature.Id.IsZero() {
		return nil, errors.New("id的为空")
	}
	signature.UpdateTime = time.Now()
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionSignature, signature.Id.Hex(), &signature)
}

// 删除签名
func SignatureDel(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	signatureId := c.Param("id")
	if signatureId == "" {
		return nil, errors.New("id为空")
	}

	return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionSignature, signatureId)
}

// 本地上传图片
func SignatureUpload(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	handle, err := c.FormFile("image")
	// 上传图像接口
	if err != nil {
		return nil, err
	}
	uploadFile, err := handle.Open()
	if err != nil {
		return nil, err
	}

	ext := strings.ToLower(path.Ext(handle.Filename))
	if ext != ".jpg" && ext != ".png" {
		return nil, errors.New("只支持jpg/png图片上传")
	}
	// 保存图片
	os.Mkdir("signature/", 0777)
	pathFileName := fmt.Sprintf("%s%s", randName(6), handle.Filename)
	saveFile, err := os.OpenFile(fmt.Sprintf("signature/%s", pathFileName), os.O_WRONLY|os.O_CREATE, 0666)
	if err != nil {
		return nil, err
	}
	io.Copy(saveFile, uploadFile)
	defer uploadFile.Close()
	defer saveFile.Close()

	// http://127.0.0.1:18088/boxcost/public/
	out := map[string]string{
		"url":  fmt.Sprintf("%s%s", SignatureDir, pathFileName),
		"path": fmt.Sprintf("signature/%s", pathFileName),
	}
	return out, nil
}
