package controller

import (
	"ai_xhs/common"
	"ai_xhs/service"
	"strconv"

	"github.com/gin-gonic/gin"
)
type EmployeeController struct {
	service *service.EmployeeService
}

func NewEmployeeController() *EmployeeController {
	return &EmployeeController{
		service: &service.EmployeeService{},
	}
}

// SendXHSCode 发送小红书验证码
func (ctrl *EmployeeController) SendXHSCode(c *gin.Context) {
	var req struct {
		XHSPhone string `json:"xhs_phone" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, common.CodeInvalidParams, "参数错误：手机号不能为空")
		return
	}

	err := ctrl.service.SendXHSCode(req.XHSPhone)
	if err != nil {
		common.Error(c, common.CodeInternalError, err.Error())
		return
	}

	common.SuccessWithMessage(c, "验证码已发送，请在小红书APP中查看", nil)
}

// GetProfile 获取员工个人信息
func (ctrl *EmployeeController) GetProfile(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	employee, err := ctrl.service.GetProfile(employeeID)
	if err != nil {
		common.Error(c, common.CodeNotFound, "员工不存在")
		return
	}

	// 获取用户显示名称（优先使用真实姓名，其次用户名）
	displayName := employee.RealName
	if displayName == "" {
		displayName = employee.Username
	}

	data := map[string]interface{}{
		"id":              employee.ID,
		"name":            displayName,
		"username":        employee.Username,
		"real_name":       employee.RealName,
		"phone":           employee.Phone,
		"role":            employee.Role,
		"enterprise_id":   employee.EnterpriseID,
		"enterprise_name": employee.Enterprise.Name,
		"is_bound_xhs":    employee.IsBoundXHS,
		"xhs_account":     employee.XHSAccount,
		"xhs_phone":       employee.XHSPhone,
		"has_xhs_cookie":  employee.XHSCookie != "", // 标识是否有Cookie，不返回完整Cookie
	}

	if employee.BoundAt != nil {
		data["bound_at"] = employee.BoundAt.Format("2006-01-02 15:04:05")
	}

	common.Success(c, data)
}

// BindXHS 绑定小红书账号
func (ctrl *EmployeeController) BindXHS(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	var req struct {
		XHSPhone string `json:"xhs_phone" binding:"required"`
		Code     string `json:"code" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, common.CodeInvalidParams, "参数错误")
		return
	}

	xhsAccount, err := ctrl.service.BindXHS(employeeID, req.XHSPhone, req.Code)
	if err != nil {
		common.Error(c, common.CodeBindXHSFailed, err.Error())
		return
	}

	common.SuccessWithMessage(c, "绑定成功", map[string]interface{}{
		"xhs_account": xhsAccount,
	})
}

// UnbindXHS 解绑小红书账号
func (ctrl *EmployeeController) UnbindXHS(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	if err := ctrl.service.UnbindXHS(employeeID); err != nil {
		common.Error(c, common.CodeInternalError, err.Error())
		return
	}

	common.SuccessWithMessage(c, "解绑成功", nil)
}

// GetAvailableCopies 获取可领取文案列表
func (ctrl *EmployeeController) GetAvailableCopies(c *gin.Context) {
	employeeID := c.GetInt("employee_id")
	productID, err := strconv.Atoi(c.Query("product_id"))
	if err != nil {
		common.Error(c, common.CodeInvalidParams, "产品ID参数错误")
		return
	}

	data, err := ctrl.service.GetAvailableCopies(employeeID, productID)
	if err != nil {
		common.Error(c, common.CodeInternalError, err.Error())
		return
	}

	common.Success(c, data)
}

// ClaimCopy 领取文案
func (ctrl *EmployeeController) ClaimCopy(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	var req struct {
		CopyID    int `json:"copy_id" binding:"required"`
		ProductID int `json:"product_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, common.CodeInvalidParams, "参数错误")
		return
	}

	data, err := ctrl.service.ClaimCopy(employeeID, req.CopyID, req.ProductID)
	if err != nil {
		common.Error(c, common.CodeAlreadyClaimed, err.Error())
		return
	}

	common.SuccessWithMessage(c, "领取成功", data)
}

// ClaimRandomCopy 随机领取文案
func (ctrl *EmployeeController) ClaimRandomCopy(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	var req struct {
		ProductID int `json:"product_id" binding:"required"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, common.CodeInvalidParams, "参数错误")
		return
	}

	data, err := ctrl.service.ClaimRandomCopy(employeeID, req.ProductID)
	if err != nil {
		common.Error(c, common.CodeCopyNotAvailable, err.Error())
		return
	}

	common.SuccessWithMessage(c, "领取成功", data)
}

// Publish 发布内容
func (ctrl *EmployeeController) Publish(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	var req service.PublishRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		common.Error(c, common.CodeInvalidParams, "参数错误")
		return
	}

	recordID, err := ctrl.service.Publish(employeeID, req)
	if err != nil {
		common.Error(c, common.CodeInternalError, err.Error())
		return
	}

	common.SuccessWithMessage(c, "发布成功", map[string]interface{}{
		"record_id": recordID,
	})
}

// GetMyPublishRecords 获取我的发布记录
func (ctrl *EmployeeController) GetMyPublishRecords(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	data, err := ctrl.service.GetMyPublishRecords(employeeID, page, pageSize)
	if err != nil {
		common.Error(c, common.CodeInternalError, err.Error())
		return
	}

	common.Success(c, data)
}

// GetPublishRecordDetail 获取发布记录详情
func (ctrl *EmployeeController) GetPublishRecordDetail(c *gin.Context) {
	employeeID := c.GetInt("employee_id")
	recordID, err := strconv.Atoi(c.Param("id"))
	if err != nil {
		common.Error(c, common.CodeInvalidParams, "记录ID参数错误")
		return
	}

	data, err := ctrl.service.GetPublishRecordDetail(employeeID, recordID)
	if err != nil {
		common.Error(c, common.CodeNotFound, err.Error())
		return
	}

	common.Success(c, data)
}

// CheckXHSStatus 检查小红书绑定与Cookie状态
func (ctrl *EmployeeController) CheckXHSStatus(c *gin.Context) {
	employeeID := c.GetInt("employee_id")

	status, err := ctrl.service.CheckXHSStatus(employeeID)
	if err != nil {
		common.Error(c, common.CodeInternalError, err.Error())
		return
	}

	common.Success(c, status)
}

// GetProducts 获取产品列表
func (ctrl *EmployeeController) GetProducts(c *gin.Context) {
	data, err := ctrl.service.GetProducts()
	if err != nil {
		common.Error(c, common.CodeInternalError, err.Error())
		return
	}

	common.Success(c, map[string]interface{}{
		"list": data,
	})
}
