package course

import (
	"time"

	"courseSign/server/global"
	"courseSign/server/model/common/request"
	"courseSign/server/model/common/response"
	"courseSign/server/model/course"
	courseReq "courseSign/server/model/course/request"
	"courseSign/server/service"
	"courseSign/server/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

type CourseActionUsersApi struct {
}

var courseActionUsersService = service.ServiceGroupApp.CourseServiceGroup.CourseActionUsersService


// CreateCourseActionUsers 创建CourseActionUsers
// @Tags CourseActionUsers
// @Summary 创建CourseActionUsers
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body course.CourseActionUsers true "创建CourseActionUsers"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /courseActionUsers/createCourseActionUsers [post]
func (courseActionUsersApi *CourseActionUsersApi) CreateCourseActionUsers(c *gin.Context) {
	var courseActionUsers course.CourseActionUsers
	err := c.ShouldBindJSON(&courseActionUsers)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := courseActionUsersService.CreateCourseActionUsers(courseActionUsers); err != nil {
        global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteCourseActionUsers 删除CourseActionUsers
// @Tags CourseActionUsers
// @Summary 删除CourseActionUsers
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body course.CourseActionUsers true "删除CourseActionUsers"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /courseActionUsers/deleteCourseActionUsers [delete]
func (courseActionUsersApi *CourseActionUsersApi) DeleteCourseActionUsers(c *gin.Context) {
	var courseActionUsers course.CourseActionUsers
	err := c.ShouldBindJSON(&courseActionUsers)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := courseActionUsersService.DeleteCourseActionUsers(courseActionUsers); err != nil {
        global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

// DeleteCourseActionUsersByIds 批量删除CourseActionUsers
// @Tags CourseActionUsers
// @Summary 批量删除CourseActionUsers
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body request.IdsReq true "批量删除CourseActionUsers"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"批量删除成功"}"
// @Router /courseActionUsers/deleteCourseActionUsersByIds [delete]
func (courseActionUsersApi *CourseActionUsersApi) DeleteCourseActionUsersByIds(c *gin.Context) {
	var IDS request.IdsReq
    err := c.ShouldBindJSON(&IDS)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := courseActionUsersService.DeleteCourseActionUsersByIds(IDS); err != nil {
        global.GVA_LOG.Error("批量删除失败!", zap.Error(err))
		response.FailWithMessage("批量删除失败", c)
	} else {
		response.OkWithMessage("批量删除成功", c)
	}
}

// UpdateCourseActionUsers 更新CourseActionUsers
// @Tags CourseActionUsers
// @Summary 更新CourseActionUsers
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body course.CourseActionUsers true "更新CourseActionUsers"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /courseActionUsers/updateCourseActionUsers [put]
func (courseActionUsersApi *CourseActionUsersApi) UpdateCourseActionUsers(c *gin.Context) {
	var courseActionUsers course.CourseActionUsers
	err := c.ShouldBindJSON(&courseActionUsers)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := courseActionUsersService.UpdateCourseActionUsers(courseActionUsers); err != nil {
        global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindCourseActionUsers 用id查询CourseActionUsers
// @Tags CourseActionUsers
// @Summary 用id查询CourseActionUsers
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query course.CourseActionUsers true "用id查询CourseActionUsers"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /courseActionUsers/findCourseActionUsers [get]
func (courseActionUsersApi *CourseActionUsersApi) FindCourseActionUsers(c *gin.Context) {
	var courseActionUsers course.CourseActionUsers
	err := c.ShouldBindQuery(&courseActionUsers)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if recourseActionUsers, err := courseActionUsersService.GetCourseActionUsers(courseActionUsers.ID); err != nil {
        global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"recourseActionUsers": recourseActionUsers}, c)
	}
}

// GetCourseActionUsersList 分页获取CourseActionUsers列表
// @Tags CourseActionUsers
// @Summary 分页获取CourseActionUsers列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query courseReq.CourseActionUsersSearch true "分页获取CourseActionUsers列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /courseActionUsers/getCourseActionUsersList [get]
func (courseActionUsersApi *CourseActionUsersApi) GetCourseActionUsersList(c *gin.Context) {
	var pageInfo courseReq.CourseActionUsersSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := courseActionUsersService.GetCourseActionUsersInfoList(pageInfo); err != nil {
	    global.GVA_LOG.Error("获取失败!", zap.Error(err))
        response.FailWithMessage("获取失败", c)
    } else {
        response.OkWithDetailed(response.PageResult{
            List:     list,
            Total:    total,
            Page:     pageInfo.Page,
            PageSize: pageInfo.PageSize,
        }, "获取成功", c)
    }
}

// SignAction 创建CourseActionUsers
// @Tags CourseActionUsers
// @Summary 创建CourseActionUsers
// @accept application/json
// @Produce application/json
// @Param data body course.CourseActionUsers true "创建CourseActionUsers"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /courseActionUsers/signAction [post]
func (courseActionUsersApi *CourseActionUsersApi) SignAction(c *gin.Context) {
	var courseActionUsers course.CourseActionUsers
	err := c.ShouldBindJSON(&courseActionUsers)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if *courseActionUsers.Aid == 0 || *courseActionUsers.Uid == 0 {
		response.FailWithMessage("参数为空", c)
		return
	}

	//检查活动是否已签到
	actionSign,err := courseActionUsersService.GetCourseActionUsersByUidAndAid(*courseActionUsers.Aid,*courseActionUsers.Uid)
	if err != nil && err != gorm.ErrRecordNotFound {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if actionSign.ID > 0 {
		response.FailWithMessage("已签到", c)
		return
	}


	// 检查课程活动 信息
	courseAction,err := courseActionService.GetCourseAction(uint(*courseActionUsers.Cid))
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if !*courseAction.IsShow {
		response.FailWithMessage("活动已下线", c)
		return
	}

	if courseAction.ActionEnd.Unix() < time.Now().Unix() {
		response.FailWithMessage("活动已结束", c)
		return
	}

	// 检查用户 信息
	user,err := courseUsersService.GetCourseUsers(uint(*courseActionUsers.Uid))
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if user.Invitor == "" {
		response.FailWithMessage("没有推荐者", c)
		return
	}

	courseSign,err := courseSignupService.GetCourseSignupByUidAndCid(uint(*courseActionUsers.Cid),uint(*courseActionUsers.Uid))
	if err != nil && err != gorm.ErrRecordNotFound {
		response.FailWithMessage(err.Error(), c)
		return
	} else if err != nil && err == gorm.ErrRecordNotFound {
		response.FailWithMessage("课程未报名", c)
		return
	}

	if courseSign.ID > 0 && !*courseSign.IsPass {
		response.FailWithMessage("报名审核未通过", c)
		return
	}
	if err := courseActionUsersService.CreateCourseActionUsers(courseActionUsers); err != nil {
		global.GVA_LOG.Error("签到失败!", zap.Error(err))
		response.FailWithMessage("签到失败", c)
	} else {
		response.OkWithMessage("签到成功", c)
	}
}

// GetMyAction 分页获取CourseActionUsers列表
// @Tags CourseActionUsers
// @Summary 分页获取CourseActionUsers列表
// @accept application/json
// @Produce application/json
// @Param data query courseReq.CourseActionUsersSearch true "分页获取CourseActionUsers列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /courseActionUsers/myAction [get]
func (courseActionUsersApi *CourseActionUsersApi) GetMyAction(c *gin.Context) {
	var pageInfo courseReq.CourseActionUsersSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	user,err := courseUsersService.GetCourseUsersByAddr(pageInfo.Addr)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	// courseInfo,err := courseListService.GetCourseList(uint(*pageInfo.Cid))
	// if err != nil {
	// 	response.FailWithMessage(err.Error(), c)
	// 	return
	// }
	//
	// actionInfo,err := courseActionUsersService.GetCourseActionUsers(uint(*pageInfo.Aid))
	// if err != nil {
	// 	response.FailWithMessage(err.Error(), c)
	// 	return
	// }

	if list, total, err := courseActionUsersService.GetMyCourseActionList(pageInfo,user.ID); err != nil {
		global.GVA_LOG.Error("获取失败!", zap.Error(err))
		response.FailWithMessage("获取失败", c)
	} else {
		response.OkWithDetailed(response.PageResult{
			List:     list,
			Total:    total,
			Page:     pageInfo.Page,
			PageSize: pageInfo.PageSize,
		}, "获取成功", c)
	}
}


// WebSignAction 设备码签到
// @Tags CourseActionUsers
// @Summary 设备码签到
// @accept application/json
// @Produce application/json
// @Param data body courseReq.ReqCode true "设备码签到"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /courseActionUsers/signActionWeb [post]
func (courseActionUsersApi *CourseActionUsersApi) WebSignAction(c *gin.Context) {
	var reqCode courseReq.ReqCode
	err := c.ShouldBindJSON(&reqCode)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if reqCode.DeviceCode == "" || reqCode.Aid == 0{
		response.FailWithMessage("invalid params", c)
		return
	}

	addr,err := jwtService.GetRedisJWT(reqCode.DeviceCode)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	global.GVA_LOG.Info("WebSignAction",zap.String("code",reqCode.DeviceCode))
	global.GVA_LOG.Info("WebSignAction",zap.String("addr",addr))
    token,err := jwtService.GetRedisJWT(addr)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	global.GVA_LOG.Info("WebSignAction",zap.String("token",token))
	j := utils.NewJWT()
	claims,err := j.ParseToken(token)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	actionInfo,err := courseActionService.GetCourseAction(uint(reqCode.Aid))
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	// 检查课程活动 信息
	if !*actionInfo.IsShow {
		response.FailWithMessage("活动已下线", c)
		return
	}

	if actionInfo.ActionEnd.Unix() < time.Now().Unix() {
		response.FailWithMessage("活动已结束", c)
		return
	}
	user,err := courseUsersService.GetCourseUsersByAddr(claims.Username)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if user.Invitor == "" {
		response.FailWithMessage("没有推荐者", c)
		return
	}

	//检查活动是否已签到
	actionSign,err := courseActionUsersService.GetCourseActionUsersByUidAndAid(reqCode.Aid,int(user.ID))
	if err != nil && err != gorm.ErrRecordNotFound {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if actionSign.ID > 0 {
		response.FailWithMessage("已签到", c)
		return
	}

	courseSign,err := courseSignupService.GetCourseSignupByUidAndCid(uint(*actionInfo.Cid),user.ID)
	if err != nil && err != gorm.ErrRecordNotFound {
		response.FailWithMessage(err.Error(), c)
		return
	} else if err != nil && err == gorm.ErrRecordNotFound {
		response.FailWithMessage("课程未报名", c)
		return
	}

	if courseSign.ID > 0 && !*courseSign.IsPass {
		response.FailWithMessage("报名审核未通过", c)
		return
	}
	signDate := utils.GetTodayTime(time.DateOnly)
	courseActionUsers := course.CourseActionUsers{}
	courseActionUsers.Cid = actionInfo.Cid
	courseActionUsers.SignDate = &signDate
	var uid,iid int
	uid = int(user.ID)
	iid = int(actionInfo.ID)
	courseActionUsers.Uid = &uid
	courseActionUsers.Aid = &iid

	if err := courseActionUsersService.CreateCourseActionUsers(courseActionUsers); err != nil {
		global.GVA_LOG.Error("签到失败!", zap.Error(err))
		response.FailWithMessage("签到失败", c)
	} else {
		response.OkWithMessage("签到成功", c)
	}
}


// WebSignActionSimple 简单签到
// @Tags CourseActionUsers
// @Summary 简单签到
// @accept application/json
// @Produce application/json
// @Param data body courseReq.ReqCode true "设备码签到"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /courseActionUsers/signActionSimple [post]
func (courseActionUsersApi *CourseActionUsersApi) WebSignActionSimple(c *gin.Context) {
	var reqCode courseReq.ReqCode
	err := c.ShouldBindJSON(&reqCode)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	address := c.Request.Header.Get("address")

	if reqCode.Aid == 0 {
		response.FailWithMessage("invalid params", c)
		return
	}

	actionInfo,err := courseActionService.GetCourseAction(uint(reqCode.Aid))
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	// 检查课程活动 信息

	if !*actionInfo.IsShow {
		response.FailWithMessage("活动已下线", c)
		return
	}

	if actionInfo.ActionEnd.Unix() < time.Now().Unix() {
		response.FailWithMessage("活动已结束", c)
		return
	}

	user,err := courseUsersService.GetCourseUsersByAddr(address)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if user.Invitor == "" {
		response.FailWithMessage("没有推荐者", c)
		return
	}

	//检查活动是否已签到
	actionSign,err := courseActionUsersService.GetCourseActionUsersByUidAndAid(reqCode.Aid,int(user.ID))
	if err != nil && err != gorm.ErrRecordNotFound {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if actionSign.ID > 0 {
		response.OkWithMessage("已签到", c)
		return
	}

	courseSign,err := courseSignupService.GetCourseSignupByUidAndCid(uint(*actionInfo.Cid),user.ID)
	if err != nil && err != gorm.ErrRecordNotFound {
		response.FailWithMessage(err.Error(), c)
		return
	} else if err != nil && err == gorm.ErrRecordNotFound {
		response.FailWithMessage("课程未报名", c)
		return
	}

	if courseSign.ID > 0 && !*courseSign.IsPass {
		response.FailWithMessage("报名审核未通过", c)
		return
	} else if courseSign.ID > 0 && *courseSign.IsFrozen {
		response.FailWithMessage("账户已冻结", c)
		return
	}
	signDate := utils.GetTodayTime(time.DateOnly)
	courseActionUsers := course.CourseActionUsers{}
	courseActionUsers.Cid = actionInfo.Cid
	courseActionUsers.SignDate = &signDate
	var uid,iid int
	uid = int(user.ID)
	iid = int(actionInfo.ID)
	courseActionUsers.Uid = &uid
	courseActionUsers.Aid = &iid

	if err := courseActionUsersService.CreateCourseActionUsers(courseActionUsers); err != nil {
		global.GVA_LOG.Error("签到失败!", zap.Error(err))
		response.FailWithMessage("签到失败", c)
	} else {
		response.OkWithMessage("签到成功", c)
	}
}