package ctx

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"ems.agt/lib/core/vo"
	"github.com/gorilla/mux"
)

// Param 地址栏参数{id}
func Param(r *http.Request, key string) string {
	vars := mux.Vars(r)
	v, ok := vars[key]
	if ok {
		return v
	}
	return ""
}

// GetQuery 查询参数
func GetQuery(r *http.Request, key string) string {
	return r.URL.Query().Get(key)
}

// QueryMap 查询参数转换Map
func QueryMap(r *http.Request) map[string]any {
	queryValues := r.URL.Query()
	queryParams := make(map[string]any)
	for key, values := range queryValues {
		queryParams[key] = values[0]
	}
	return queryParams
}

// 读取json请求结构团体
func ShouldBindJSON(r *http.Request, args any) error {
	body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 设置较大的长度，例如 1<<20 (1MB)
	if err != nil {
		return err
	}
	err = json.Unmarshal(body, args)
	return err
}

// JSON 相应json数据
func JSON(w http.ResponseWriter, code int, data any) {
	// 跨域响应头
	// To solve cross domain issue
	w.Header().Set("Access-Control-Allow-Origin", "*")
	//	w.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
	w.Header().Set("Access-Control-Allow-Methods", "*")
	w.Header().Set("Access-Control-Allow-Headers", "*")
	//	w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
	//	w.Header().Set("Access-Control-Allow-Headers", "AccessToken")
	w.Header().Set("Access-Control-Expose-Headers", "Access-Control-Allow-Headers, Token")
	w.Header().Set("Access-Control-Allow-Credentials", "true")
	w.Header().Set("Content-Type", "application/json;charset=UTF-8")

	response, err := json.Marshal(data)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte(err.Error()))
	} else {
		w.WriteHeader(code)
		w.Write(response)
	}
}

/// ==== 登录用户信息， 通过中间件后预置入

// 定义自定义类型作为键
type ContextKey string

// LoginUser 登录用户信息需要Authorize中间件
func LoginUser(r *http.Request) (vo.LoginUser, error) {
	// 上下文
	v := r.Context().Value(ContextKey("LoginUser"))
	if v != nil {
		return v.(vo.LoginUser), nil
	}
	return vo.LoginUser{}, fmt.Errorf("无用户信息")
}

// LoginUserToUserID 登录用户信息-用户ID
func LoginUserToUserID(r *http.Request) string {
	loginUser, err := LoginUser(r)
	if err != nil {
		return ""
	}
	return loginUser.UserID
}

// LoginUserToUserName 登录用户信息-用户名称
func LoginUserToUserName(r *http.Request) string {
	loginUser, err := LoginUser(r)
	if err != nil {
		return ""
	}
	return loginUser.UserName
}
