package midware

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	"be.ems/lib/core/datasource"
	"be.ems/lib/core/utils/ctx"
	"be.ems/lib/core/utils/date"
	"be.ems/lib/dborm"
	"be.ems/lib/log"
)

// LogMML mml操作日志搜集
func LogMML(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 读取请求体内容
		body, err := io.ReadAll(r.Body)
		if err != nil {
			http.Error(w, "Internal Server Error", http.StatusInternalServerError)
			return
		}
		// 解析json内参数
		var bodyArgs map[string]any
		_ = json.Unmarshal(bytes.Clone(body), &bodyArgs)
		// 将请求体内容存储在临时缓冲区中
		buffer := bytes.NewBuffer(body)
		r.Body = io.NopCloser(buffer)

		next.ServeHTTP(w, r)

		// 收尾存入数据库的参数
		mmlCmd := bodyArgs["mml"].([]any)[0]
		ipAddr := strings.Split(r.RemoteAddr, ":")[0]
		neType := ctx.Param(r, "elementTypeValue")
		neId := ctx.GetQuery(r, "ne_id")
		timeStr := date.ParseDateToStr(time.Now(), date.YYYY_MM_DD_HH_MM_SS)

		// 响应内容长度和状态码作为结果
		str := strings.TrimSuffix(fmt.Sprintf("%v", w), "}")
		strArr := strings.Split(str, " ")
		size := strArr[1]
		status := strArr[2]
		contentType := w.Header().Get("Content-Type")
		resultStr := fmt.Sprintf(`{"status":"%s","size":"%s","content-type":"%s"}`, status, size, contentType)

		// 用户名
		username := "-"
		accessToken := r.Header.Get("AccessToken")
		if accessToken != "" {
			// 验证令牌 == 这里直接查数据库session
			se, _ := dborm.XormUpdateSessionShakeTime(accessToken)
			username = se.AccountId
		}

		// 执行插入
		sql := "insert into mml_log (user,ip,ne_type,ne_id,mml,result,log_time)values(?,?,?,?,?,?,?)"
		_, sqlerr := datasource.ExecDB("", sql, []any{username, ipAddr, neType, neId, mmlCmd, resultStr, timeStr})
		if sqlerr != nil {
			log.Errorf("insert row : %v", err.Error())
		}
	})
}
