package api

import (
	"fmt"
	"licserver/internal/service"
	"net/http"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

type LicenseHandler struct {
	licenseService *service.LicenseService
}

func NewLicenseHandler(licenseService *service.LicenseService) *LicenseHandler {
	return &LicenseHandler{licenseService: licenseService}
}

// 创建授权码
func (h *LicenseHandler) CreateLicenses(c *gin.Context) {
	var input service.LicenseCreateInput
	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	userID := c.GetUint("userID")
	licenses, err := h.licenseService.CreateLicenses(&input, userID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "授权码创建成功",
		"data":    licenses,
	})
}

// 使用授权码
func (h *LicenseHandler) UseLicense(c *gin.Context) {
	var input struct {
		Code      string `json:"code" binding:"required"`
		DeviceUID string `json:"device_uid" binding:"required"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	license, err := h.licenseService.UseLicense(input.Code, input.DeviceUID, c.ClientIP())
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "授权码使用成功",
		"data":    license,
	})
}

// 获取授权码列表
func (h *LicenseHandler) GetLicenses(c *gin.Context) {
	status := c.Query("status")
	licenseType := c.Query("license_type")
	batchNo := c.Query("batch_no")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("limit", "10"))

	licenses, total, err := h.licenseService.GetLicenses(status, licenseType, batchNo, page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 确保返回格式符合 layui table 的要求
	c.JSON(http.StatusOK, gin.H{
		"code":  0,
		"msg":   "",
		"count": total,
		"data":  licenses,
	})
}

// 获取授权码使用日志
func (h *LicenseHandler) GetLicenseLogs(c *gin.Context) {
	licenseID, err := strconv.ParseUint(c.Param("id"), 10, 32)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的授权码ID"})
		return
	}

	// 检查是否为导出请求
	if c.Query("export") == "1" {
		data, err := h.licenseService.ExportLogs(uint(licenseID))
		if err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
			return
		}

		// 设置响应头
		filename := fmt.Sprintf("license_logs_%d_%s.csv", licenseID, time.Now().Format("20060102150405"))
		c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
		c.Data(http.StatusOK, "text/csv", data)
		return
	}

	// 常规日志查询
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "10"))

	logs, total, err := h.licenseService.GetLicenseLogs(uint(licenseID), page, pageSize)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "获取授权码使用日志成功",
		"count":   total,
		"data":    logs,
	})
}

// 添加撤销授权码的处理方法
func (h *LicenseHandler) RevokeLicense(c *gin.Context) {
	code := c.Param("code")
	userID := c.GetUint("userID")

	if err := h.licenseService.RevokeLicense(code, userID); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "授权码撤销成功",
	})
}

// 添加批量撤销处理方法
func (h *LicenseHandler) RevokeLicenses(c *gin.Context) {
	var input struct {
		Codes []string `json:"codes" binding:"required"`
	}

	if err := c.ShouldBindJSON(&input); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	userID := c.GetUint("userID")
	if err := h.licenseService.RevokeLicenses(input.Codes, userID); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "授权码批量撤销成功",
	})
}
