package airDrop

import (
	"context"

	"courseSign/server/global"
	"courseSign/server/model/airDrop"
	airDropReq "courseSign/server/model/airDrop/request"
	"courseSign/server/model/common/request"
	"courseSign/server/model/common/response"
	"courseSign/server/model/example"
	"courseSign/server/service"
	"courseSign/server/utils"
	"courseSign/server/utils/chain33"
	"github.com/33cn/chain33/types"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type RedPackageApi struct {
}

var redPackageService = service.ServiceGroupApp.AirDropServiceGroup.RedPackageService
var fileUploadAndDownloadService = service.ServiceGroupApp.ExampleServiceGroup.FileUploadAndDownloadService

// CreateRedPackage 创建RedPackage
// @Tags RedPackage
// @Summary 创建RedPackage
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body airDrop.RedPackage true "创建RedPackage"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /redPackage/createRedPackage [post]
func (redPackageApi *RedPackageApi) CreateRedPackage(c *gin.Context) {
	var redPackage airDrop.RedPackage
	err := c.ShouldBindJSON(&redPackage)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
    verify := utils.Rules{
        "Balance":{utils.NotEmpty()},
        "Num":{utils.NotEmpty()},
        "IpLimit":{utils.NotEmpty()},
        "Name":{utils.NotEmpty()},
    }
	if err := utils.Verify(redPackage, verify); err != nil {
    		response.FailWithMessage(err.Error(), c)
    		return
    	}
    	if redPackage.Balance * 1e8 / int64(redPackage.Num) < 1e7 {
			response.FailWithMessage("最小平均金额", c)
    		return
		}
	redPackage.Balance = redPackage.Balance * 1e8
	redPackage.Remain = redPackage.Balance
	redPackage.RemainNum = redPackage.Num
	if err := redPackageService.CreateRedPackage(redPackage); err != nil {
        global.GVA_LOG.Error("创建失败!", zap.Error(err))
		response.FailWithMessage("创建失败", c)
	} else {
		response.OkWithMessage("创建成功", c)
	}
}

// DeleteRedPackage 删除RedPackage
// @Tags RedPackage
// @Summary 删除RedPackage
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body airDrop.RedPackage true "删除RedPackage"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"删除成功"}"
// @Router /redPackage/deleteRedPackage [delete]
func (redPackageApi *RedPackageApi) DeleteRedPackage(c *gin.Context) {
	var redPackage airDrop.RedPackage
	err := c.ShouldBindJSON(&redPackage)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if err := redPackageService.DeleteRedPackage(redPackage); err != nil {
        global.GVA_LOG.Error("删除失败!", zap.Error(err))
		response.FailWithMessage("删除失败", c)
	} else {
		response.OkWithMessage("删除成功", c)
	}
}

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

// UpdateRedPackage 更新RedPackage
// @Tags RedPackage
// @Summary 更新RedPackage
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body airDrop.RedPackage true "更新RedPackage"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /redPackage/updateRedPackage [put]
func (redPackageApi *RedPackageApi) UpdateRedPackage(c *gin.Context) {
	var redPackage airDrop.RedPackage
	err := c.ShouldBindJSON(&redPackage)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
      verify := utils.Rules{
          "Balance":{utils.NotEmpty()},
          "Num":{utils.NotEmpty()},
          "IpLimit":{utils.NotEmpty()},
      }
    if err := utils.Verify(redPackage, verify); err != nil {
      	response.FailWithMessage(err.Error(), c)
      	return
     }
	if err := redPackageService.UpdateRedPackage(redPackage); err != nil {
        global.GVA_LOG.Error("更新失败!", zap.Error(err))
		response.FailWithMessage("更新失败", c)
	} else {
		response.OkWithMessage("更新成功", c)
	}
}

// GetWhiteList 获取RedPackage白名单
// @Tags RedPackageWhiteList
// @Summary 获取RedPackage白名单
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body airDrop.RedPackage true "获取RedPackage白名单"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /redPackage/getWhiteList [get]
func (redPackageApi *RedPackageApi) GetWhiteList(c *gin.Context) {
	var redPackage airDrop.RedPackage
	err := c.ShouldBindQuery(&redPackage)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}

	if list,err := redPackageService.GetWhiteList(redPackage.ID); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"list": list}, c)
	}
}

// ConvertWhiteList 导入推荐关系
// @Tags PackUser
// @Summary 导入推荐关系
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data body example.ExaFileUploadAndDownload true "导入推荐关系"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"更新成功"}"
// @Router /redPackage/convertWhiteList [post]
func (redPackageApi *RedPackageApi) ConvertWhiteList(c *gin.Context) {
	var file example.ExaFileUploadAndDownload
	noSave := c.DefaultQuery("noSave", "0")
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		global.GVA_LOG.Error("接收文件失败!", zap.Error(err))
		response.FailWithMessage("接收文件失败", c)
		return
	}
	file, err = fileUploadAndDownloadService.UploadFile(header, noSave) // 文件上传后拿到文件路径
	if err != nil {
		global.GVA_LOG.Error("修改数据库链接失败!", zap.Error(err))
		response.FailWithMessage("修改数据库链接失败", c)
		return
	}
	if list,err := redPackageService.ConvertWhiteList(file.Url); err != nil {
		global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"list": list}, c)
	}
}

// FindRedPackage 用id查询RedPackage
// @Tags RedPackage
// @Summary 用id查询RedPackage
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query airDrop.RedPackage true "用id查询RedPackage"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"查询成功"}"
// @Router /redPackage/findRedPackage [get]
func (redPackageApi *RedPackageApi) FindRedPackage(c *gin.Context) {
	var redPackage airDrop.RedPackage
	err := c.ShouldBindQuery(&redPackage)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if redPackage, err := redPackageService.GetRedPackage(redPackage.ID); err != nil {
        global.GVA_LOG.Error("查询失败!", zap.Error(err))
		response.FailWithMessage("查询失败", c)
	} else {
		response.OkWithData(gin.H{"redPackage": redPackage}, c)
	}
}

// GetRedPackageList 分页获取RedPackage列表
// @Tags RedPackage
// @Summary 分页获取RedPackage列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query airDropReq.RedPackageSearch true "分页获取RedPackage列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /redPackage/getRedPackageList [get]
func (redPackageApi *RedPackageApi) GetRedPackageList(c *gin.Context) {
	var pageInfo airDropReq.RedPackageSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := redPackageService.GetRedPackageInfoList(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)
    }
}

// QueryBalance 查询余额
// @Tags RedPackage
// @Summary 查询余额
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query airDropReq.RedPackageSearch true "分页获取RedPackage列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /redPackage/queryBalance [get]
func (redPackageApi *RedPackageApi) QueryBalance(c *gin.Context) {
	grpc := "cloud.bityuan.com"
	client,_ := chain33.NewGrpcClient(grpc)
	accounts,err := client.GetBalance(context.Background(),&types.ReqBalance{Addresses: []string{"1QBGDgy6CRPJj1mCFE1S2MYNfqDuGq3bJu"}})
	if err != nil {
		global.GVA_LOG.Error("余额获取失败!", zap.Error(err))
		response.FailWithMessage("余额获取失败", c)
		return
	}

	response.OkWithDetailed(accounts.Acc[0].Balance/1e8, "获取成功", c)

}

// GetRedPackageWebList 分页获取RedPackage列表
// @Tags RedPackage
// @Summary 分页获取RedPackage列表
// @Security ApiKeyAuth
// @accept application/json
// @Produce application/json
// @Param data query airDropReq.RedPackageSearch true "分页获取RedPackage列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /redPackage/getRedPackageList [get]
func (redPackageApi *RedPackageApi) GetRedPackageWebList(c *gin.Context) {
	var pageInfo airDropReq.RedPackageSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := redPackageService.GetRedPackageInfoWebList(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)
	}
}


// GetRedPackageTxList 分页获取RedPackage列表
// @Tags RedPackageTx
// @Summary 分页获取RedPackageTx列表
// @accept application/json
// @Produce application/json
// @Param data query airDropReq.RedPackageSearch true "分页获取RedPackage列表"
// @Success 200 {string} string "{"success":true,"data":{},"msg":"获取成功"}"
// @Router /redPackage/getRedPackageTxList [get]
func (redPackageApi *RedPackageApi) GetRedPackageTxList(c *gin.Context) {
	var pageInfo airDropReq.RedPackageSearch
	err := c.ShouldBindQuery(&pageInfo)
	if err != nil {
		response.FailWithMessage(err.Error(), c)
		return
	}
	if list, total, err := redPackageService.GetRedPackageTxList(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)
	}
}
