package filterPoly

import (
	log "app.yhyue.com/moapp/jylog"
	"bp.jydev.jianyu360.cn/BaseService/gateway/core/util"
	"encoding/json"
	"fmt"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/util/gconv"
	"math"
	"strings"
)

// VerifyHandle 验证码处理
func (a *ReqFilterPoly) VerifyHandle(r *ghttp.Request, key string, hasLogin bool) map[string]interface{} {
	//_ = req.ParseForm()
	util.CopyReqAndFormData(r.Request, false)
	vc := r.Request.Form.Get("antiVerifyCheck")
	if vc == "" {
		vc = r.Request.Header.Get("antiVerifyCheck")
	}
	vKey := fmt.Sprintf(VerifyRedisKey, key)
	result := map[string]interface{}{
		"error_code": 0,
		"hasLogin":   hasLogin,
	}
	if vc != "" {
		ok := func() bool {
			va := AllRedis.GetBytes(vKey)
			if va == nil {
				return true
			}
			var result = [][]int{}
			if err := json.Unmarshal(va, &result); err != nil {
				log.WithContext(r.Context()).Errorf("%s Unmarshal 出错 %v\n", key, err)
				return false
			}
			vcArr := strings.Split(vc, ";")
			if len(vcArr) != len(result) {
				log.WithContext(r.Context()).Infof("用户%s验证码校验失败 选择数量不足 \n正确坐标:%v\n输入坐标%v \n", key, result, vcArr)
				return false
			}

			imgWidth := gconv.Int(r.Request.Form.Get("imgw")) //app端图片宽度改变
			for index, pos := range vcArr {
				p := strings.Split(pos, ",")
				if len(p) != 2 {
					return false
				}
				px := gconv.Int(p[0])
				py := gconv.Int(p[1])
				if imgWidth != 0 { //320 100
					px = px * 320 / imgWidth
					py = py * 320 / imgWidth
				}

				if d := Distance(px, py, result[index][0], result[index][1]); d > 15 {
					log.WithContext(r.Context()).Infof("用户%s验证码校验失败 w:%d 第(%d)校验结果%f\n正确坐标:%v\n输入坐标%v \n", key, imgWidth, index, d, result, vcArr)
					return false
				}
			}
			log.WithContext(r.Context()).Infof("用户%s验证码校验通过\n", key)
			return true
		}()
		if ok {
			a.ClearWaitVerify(key)
			result["antiVerify"] = 1
		} else {
			result["antiVerify"] = -1
			//统计验证码错误次数
			go a.VerifyErrDetail(key)
		}

	} else {
		result["antiVerify"] = -1
	}
	if result["antiVerify"] == -1 {
		checkVerify := <-vCodeChan
		AllRedis.Set(vKey, checkVerify.CheckArr, 60*5)
		result["imgData"] = checkVerify.imgBase64
		result["textVerify"] = checkVerify.Key
	}
	r.Response.Header().Add("antiVerify", gconv.String(result["antiVerify"]))
	return result
}

func Distance(sx, sy, dx, dy int) float64 {
	x := math.Abs(float64(sx - dx))
	y := math.Abs(float64(sy - dy))
	h := math.Hypot(x, y)
	return h
}
