package twi

import (
	"time"

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

type TwiActFinishDetailApi struct {
}

var twiActFinishDetailService = service.ServiceGroupApp.TwiServiceGroup.TwiActFinishDetailService
//var templateService = service.ServiceGroupApp.TwiServiceGroup.TwiActTemplateService
var fileUploadAndDownloadService = service.ServiceGroupApp.ExampleServiceGroup.FileUploadAndDownloadService


// CreateTwiActFinishDetail 创建TwiActFinishDetail
// @Tags TwiActFinishDetail
// @Summary 创建TwiActFinishDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body twi.TwiActFinishDetail true "创建TwiActFinishDetail"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /twiActFinishDetail/createTwiActFinishDetail [post]
func (twiActFinishDetailApi *TwiActFinishDetailApi) CreateTwiActFinishDetail(c *gin.Context) {
	var twiActFinishDetail twi.TwiActFinishDetail
	err := c.ShouldBindJSON(&twiActFinishDetail)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := twiActFinishDetailService.CreateTwiActFinishDetail(twiActFinishDetail); err != nil {
        global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteTwiActFinishDetail 删除TwiActFinishDetail
// @Tags TwiActFinishDetail
// @Summary 删除TwiActFinishDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body twi.TwiActFinishDetail true "删除TwiActFinishDetail"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /twiActFinishDetail/deleteTwiActFinishDetail [delete]
func (twiActFinishDetailApi *TwiActFinishDetailApi) DeleteTwiActFinishDetail(c *gin.Context) {
	var twiActFinishDetail twi.TwiActFinishDetail
	err := c.ShouldBindJSON(&twiActFinishDetail)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := twiActFinishDetailService.DeleteTwiActFinishDetail(twiActFinishDetail); err != nil {
        global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

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

// UpdateTwiActFinishDetail 更新TwiActFinishDetail
// @Tags TwiActFinishDetail
// @Summary 更新TwiActFinishDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body twi.TwiActFinishDetail true "更新TwiActFinishDetail"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /twiActFinishDetail/updateTwiActFinishDetail [put]
func (twiActFinishDetailApi *TwiActFinishDetailApi) UpdateTwiActFinishDetail(c *gin.Context) {
	var twiActFinishDetail twi.TwiActFinishDetail
	err := c.ShouldBindJSON(&twiActFinishDetail)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := twiActFinishDetailService.UpdateTwiActFinishDetail(twiActFinishDetail); err != nil {
        global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// FindTwiActFinishDetail 用id查询TwiActFinishDetail
// @Tags TwiActFinishDetail
// @Summary 用id查询TwiActFinishDetail
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query twi.TwiActFinishDetail true "用id查询TwiActFinishDetail"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /twiActFinishDetail/findTwiActFinishDetail [get]
func (twiActFinishDetailApi *TwiActFinishDetailApi) FindTwiActFinishDetail(c *gin.Context) {
	var twiActFinishDetail twi.TwiActFinishDetail
	err := c.ShouldBindQuery(&twiActFinishDetail)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if retwiActFinishDetail, err := twiActFinishDetailService.GetTwiActFinishDetail(twiActFinishDetail.ID); err != nil {
        global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"retwiActFinishDetail": retwiActFinishDetail}, c)
	}
}

// GetTwiActFinishDetailList 分页获取TwiActFinishDetail列表
// @Tags TwiActFinishDetail
// @Summary 分页获取TwiActFinishDetail列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query twiReq.TwiActFinishDetailSearch true "分页获取TwiActFinishDetail列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /twiActFinishDetail/getTwiActFinishDetailList [get]
func (twiActFinishDetailApi *TwiActFinishDetailApi) GetTwiActFinishDetailList(c *gin.Context) {
	var pageInfo twiReq.TwiActFinishDetailSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := twiActFinishDetailService.GetTwiActFinishDetailInfoList(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)
    }
}

// Verify 创建TwiActFinishDetail
// @Tags TwiActFinishDetail
// @Summary 创建TwiActFinishDetail
// @accept application/json
// @Produce application/json
// @Param data  query  twiReq.FinishVerify true  "验证"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /twiActFinishDetail/verify [get]
func (twiActFinishDetailApi *TwiActFinishDetailApi) Verify(c *gin.Context) {
	var pageInfo twiReq.FinishVerify
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	// 查地址是否存在（绑定）
	addr := c.Request.Header.Get("address")
	if addr == "" {
		response.FailWithMessage("请重新登录", c)
		return
	}

	user,err := twiMetamaskService.GetTwiMetamaskByAddr(addr);
	if err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage(err.Error(), c)
		return
	}

	if _,isOk := global.BlackCache.Get(addr);isOk{
		response.FailWithMessage("请求频率过快",c)
		return
	} else {
		global.BlackCache.Set(addr,1,time.Second * 5)
	}

	// 查询对应任务是否存在
	if actionDetail,err := twiActTemplateService.GetTwiActTemplate(uint(pageInfo.Id)); err != nil {
		if err == gorm.ErrRecordNotFound {
			global.GVA_LOG.Error("GetTwiActTemplate err !", zap.Error(err))
			response.FailWithMessage("任务不存在", c)
			return
		} else {
			global.GVA_LOG.Error("GetTwiActTemplate err !", zap.Error(err))
			response.FailWithMessage("查询失败", c)
			return
		}

	} else {
		// 查询对于用户地址任务记录是否存在 没有新建一条记录
		if detail,err := twiActFinishDetailService.GetTwiActFinishDetailByOther(*actionDetail.ActId,actionDetail.ID,user.ID); err != nil {
			if err == gorm.ErrRecordNotFound {
				nd := twi.TwiActFinishDetail{
					ActId:        new (int),
					TemplateId:   new (int),
					Uid:          new (int),
					FinishTime:   new (time.Time),
					FinishStatus: new (bool),
					Ext:          "",
					//CommonInfo:   twi.UserCommonInfo{},
				}
				*nd.ActId = *actionDetail.ActId
				*nd.TemplateId = int(actionDetail.ID)
				*nd.FinishStatus = false
				*nd.FinishTime = time.Now()
				if pageInfo.Url != "" {
					nd.FinishPhoto = pageInfo.Url
				}

				err = twiActFinishDetailService.CreateTwiActFinishDetail(nd)
				if err != nil {
					global.GVA_LOG.Error("GetTwiActFinishDetailByOther err !", zap.Error(err))
					response.FailWithMessage("创建记录失败", c)
					return
				}
				response.OkWithMessage("用户任务创建成功，等待验证", c)
			} else {
				global.GVA_LOG.Error("GetTwiActFinishDetailByOther err !", zap.Error(err))
				response.FailWithMessage("查询记录失败", c)
				return
			}

		} else {
			if *detail.FinishStatus {
				response.OkWithMessage("任务已完成", c)
			} else {
				if detail.FinishPhoto == "" && pageInfo.Url != ""{
					detail.FinishPhoto = pageInfo.Url
					err = twiActFinishDetailService.UpdateTwiActFinishDetail(detail)
					if err != nil {
						global.GVA_LOG.Error("UpdateTwiActFinishDetail err !", zap.Error(err))
						response.FailWithMessage("上传截图失败", c)
						return
					} else {
						response.OkWithMessage("上传成功", c)
						return
					}
				} else {
					response.FailWithMessage("任务未完成，请等待", c)
				}
			}

		}
	}


}