package utils

import (
	"bytes"
	"crypto/rand"
	"encoding/base64"
	"github.com/disintegration/imaging"
	"image"
	"image/jpeg"
	"math/big"
	"os"
	"strconv"
)

/*  图形验证码部分*/

func GetRandInt(max int) int {
	num, _ := rand.Int(rand.Reader, big.NewInt(int64(max-1)))
	return int(num.Int64())
}

var dataBase64 = "data:image/png;base64,"

func CreateCode() (string, string, int, int) {
	//生成随机数
	nums := GetRandInt(8)
	//maskImg := GetUuid()
	//var maskImg = "./static/images/hkmb.png"
	var bg = "./static/images/" + strconv.Itoa(nums) + ".jpg"
	f, _ := os.Open(bg)
	defer f.Close()
	//testImg, _ := os.Open(maskImg)
	//defer testImg.Close()
	//获取随机x坐标
	imageRandX := GetRandInt(260 - 100)
	if imageRandX < 100 {
		imageRandX += 100
	}
	//获取随机y坐标
	imageRandY := GetRandInt(146 - 40)
	if imageRandY < 40 {
		imageRandY += 40
	}
	//转化为image对象
	m, _, err := image.Decode(f)
	if err != nil {
		panic(err)
	}
	//转化为image对象
	//testImg1, _, err := image.Decode(testImg)
	if err != nil {
		panic(err)
	}
	//设置截取的最大坐标值和最小坐标值
	maxPotion := image.Point{
		X: imageRandX,
		Y: imageRandY,
	}
	minPotion := image.Point{ //x，y坐标取遮罩图的大小
		X: imageRandX - 40,
		Y: imageRandY - 40,
	}
	subimg := image.Rectangle{
		Max: maxPotion,
		Min: minPotion,
	}
	//var createImg = "./static/images/code/" + maskImg + ".png"
	//var testImg3 = "./static/images/code/" + uuid.New().String() + ".png"
	//f, err = os.Create(createImg) //截出来的图片
	//defer f.Close()
	//截取图像
	data := imaging.Crop(m, subimg)
	jpeg.Encode(f, data, nil)
	byteTest := new(bytes.Buffer)
	jpeg.Encode(byteTest, data, nil)
	// base64 压缩
	toString := base64.StdEncoding.EncodeToString(byteTest.Bytes())
	maskBase64 := dataBase64 + toString
	//设置遮罩
	bgBase64 := createCodeImg(bg, minPotion)
	return maskBase64, bgBase64, imageRandX, imageRandY
}

/*func GetUuid() string {
	return uuid.New().String()
}*/
func createCodeImg(path string, minPotion image.Point) string {
	bg, err := os.Open(path)
	defer bg.Close()

	if err != nil {
		panic(err)
	}

	maskFile, err := os.Open("./static/images/hkmb.png")
	defer maskFile.Close()
	if err != nil {
		panic(err)
	}
	bgimg, _, err := image.Decode(bg)
	maskimg, _, err := image.Decode(maskFile)

	data := imaging.Overlay(bgimg, maskimg, minPotion, 1.0)
	//newUuid := uuid.New().String()
	//f, err := os.Create("./static/images/code/" + newUuid + ".png") // 截出来后的背景图
	//defer f.Close()
	byteTest := new(bytes.Buffer)
	jpeg.Encode(byteTest, data, nil)
	// base64 压缩
	bgBase64 := dataBase64 + base64.StdEncoding.EncodeToString(byteTest.Bytes())
	//jpeg.Encode(f, data, nil)
	return bgBase64
}
