package midware

import (
	"encoding/json"
	"net/http"
	"strings"
	"time"

	"be.ems/lib/dborm"
	"be.ems/lib/services"
)

// 登录策略限制登录时间和访问ip范围
func ArrowIPAddr(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ipAddr := strings.Split(r.RemoteAddr, ":")[0]

		// 读取配置信息 登录策略设置
		result, err := dborm.XormGetConfig("Security", "loginSecurity")
		if err != nil {
			next.ServeHTTP(w, r)
			return
		}
		data := make(map[string]any)
		err = json.Unmarshal([]byte(result["value_json"].(string)), &data)
		if err != nil {
			next.ServeHTTP(w, r)
			return
		}

		// 开关
		switchStr := data["switch"].(string)
		if switchStr == "0" {
			next.ServeHTTP(w, r)
			return
		}

		ipRange := data["ipRange"].(string)
		logintimeRange := data["logintime_range"].(string)

		// 检查ip
		ips := strings.Split(ipRange, "/")
		hasIP := false
		for _, ip := range ips {
			if ipAddr == ip {
				hasIP = true
			}
		}
		if !hasIP {
			services.ResponseErrorWithJson(w, 502, "网关登录策略-IP限制: "+ipAddr)
			return
		}

		// 检查开放时间
		logintimeRangeArr := strings.Split(logintimeRange, " - ")

		// 加载中国时区
		loc, _ := time.LoadLocation("Asia/Shanghai")
		// 获取当前时间
		currentTime := time.Now().In(loc)

		// 获取当前日期
		currentDate := time.Date(currentTime.Year(), currentTime.Month(), currentTime.Day(), 0, 0, 0, 0, currentTime.Location())
		ymd := currentDate.Format("2006-01-02")

		// 定义开始时间和结束时间
		startTime, _ := time.ParseInLocation("2006-01-02 15:04:05", ymd+" "+logintimeRangeArr[0], loc)
		endTime, _ := time.ParseInLocation("2006-01-02 15:04:05", ymd+" "+logintimeRangeArr[1], loc)

		// 判断当前时间是否在范围内
		if currentTime.After(startTime) && currentTime.Before(endTime) {
			next.ServeHTTP(w, r)
		} else {
			services.ResponseErrorWithJson(w, 502, "网关登录策略-不在开放时间范围内")
		}
	})
}
