package recyclecardmanage

import (
	"errors"
	"fmt"
	"github.com/codinl/go-logger"
	"github.com/gin-gonic/gin"
	"go-admin/app/admin/apis/pay"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/pkg/jwtauth"
	"go-admin/tools/app"
	"net/http"
	"time"
)

// RecycleCardOrderList 查询小程序回收订单
// @Summary 查询小程序回收订单
// @Tags 租卡系统-订单管理
// @Produce json
// @Accept json
// @Param request body models.RecycleCardOrderListReq true "查询小程序回收订单"
// @Success 200 {object} models.RecycleCardOrderListRsp
// @Router /api/v1/recycle_card/order/list [post]
func RecycleCardOrderList(c *gin.Context) {
	req := models.RecycleCardOrderListReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Error("ShouldBindJSON err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)

	//data, _ := c.Get(jwtauth.JwtPayloadKey)
	//fmt.Println("data:", data)
	//sysUid, ok := data.(jwtauth.MapClaims)["identity"]
	//if !ok {
	//	logger.Error("sys uid err")
	//	app.Error(c, http.StatusInternalServerError, errors.New("sys uid err"), "查询失败")
	//	return
	//}
	//sysUser, err := models.GetSysUser(sysUid)
	//if err != nil {
	//	logger.Error("sys user err:", err)
	//	app.Error(c, http.StatusInternalServerError, err, "查询失败")
	//	return
	//}
	req.CooperativeBusinessId = sysUser.CooperativeBusinessId

	//uc = &auth.UserClaims{Uid: 8588420}
	rsp, err := req.List(c)
	if err != nil {
		logger.Error("game cassette err", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败"+err.Error())
		return
	}

	//ret := map[string]interface{}{
	//	"list":     orders,
	//	"cur_page": req.PageIdx,
	//	"count":    count,
	//}

	app.OK(c, rsp, "")
	return
}

func RecycleCardOrderDetail(c *gin.Context) {
	req := struct {
		OrderId uint32 `json:"order_id" binding:"required"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Error("ShouldBindJSON err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	//uc = &auth.UserClaims{Uid: 8588420}

	var order models.RecycleCardOrder
	err := orm.Eloquent.Table("recycle_card_order").Where("id=?", req.OrderId).Find(&order).Error
	//err := model.NewRecycleCardOrderQuerySet(model.DB).IDEq(req.OrderId).One(&order)
	if err != nil {
		logger.Error("game cassette err", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	user, err := models.GetUserInfoByUid(order.Uid)
	if err != nil {
		logger.Error("user err", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	order.UserInfo = &user
	store, err := models.GetStore(order.StoreId)
	if err != nil {
		logger.Error("order store err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	order.Store = store
	app.OK(c, order, "")
	return
}

func RecycleCardOrderCheck(c *gin.Context) {
	req := struct {
		OrderId   uint32 `json:"order_id" binding:"required"`
		CheckType uint32 `json:"check_type"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Error("ShouldBindJSON err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	//uc = &auth.UserClaims{Uid: 8588420}
	var order models.RecycleCardOrder
	err := orm.Eloquent.Table("recycle_card_order").Where("id=?", req.OrderId).Find(&order).Error
	if err != nil {
		logger.Error("recycle card order err:", err)
		return
	}
	if order.State != 1 {
		logger.Error("order state err")
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	if req.CheckType == 1 {
		err := orm.Eloquent.Table("recycle_card_order").Where("id=?", req.OrderId).Updates(map[string]interface{}{
			"state":      3,
			"check_time": time.Now(),
		}).Error
		//err := model.NewRecycleCardOrderQuerySet(model.DB).IDEq(req.OrderId).GetUpdater().SetState(3).Update()
		if err != nil {
			logger.Error("recycle card order err:", err)
			app.Error(c, http.StatusInternalServerError, err, "操作失败")
			return
		}
	}

	app.OK(c, nil, "操作成功")
	return
}

func RecycleCardOrderImageUpdate(c *gin.Context) {
	req := struct {
		OrderId uint32 `json:"order_id" binding:"required"`
		Images  string `json:"images" binding:"required"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Error("ShouldBindJSON err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	data, _ := c.Get(jwtauth.JwtPayloadKey)
	mapClaims := data.(jwtauth.MapClaims)
	sysUid := float64(0)
	if v, ok := mapClaims["identity"]; ok {
		sysUid = v.(float64)
	}
	fmt.Println("sysUid:", sysUid)

	//req.SysUid = fmt.Sprintf("%.0f", sysUid)
	var sysUser models.SysUser
	err := orm.Eloquent.Table("sys_user").Where("user_id=?", uint32(sysUid)).Find(&sysUser).Error
	if err != nil {
		logger.Error("sys user err:", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	var order models.RecycleCardOrder
	err = orm.Eloquent.Table("recycle_card_order").Where("id=?", req.OrderId).Find(&order).Error
	//err := models.NewRecycleCardOrderQuerySet(model.DB).IDEq(req.OrderId).One(&order)
	if err != nil {
		logger.Error("order err:%#v", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	if order.State != 1 {
		logger.Error("order state err")
		app.Error(c, http.StatusInternalServerError, err, "状态错误")
		return
	}
	userInfo, err := models.GetUserInfoByUid(order.Uid)
	if err != nil {
		logger.Error("user info err:", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	//order.Price = 40 // TODO

	transfer, err := pay.Transfer(order.Price, userInfo.WxOpenID, "回收卡带")
	if err != nil {
		logger.Error("transfer err:", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	err = orm.Eloquent.Table("recycle_card_order").Where("id=?", req.OrderId).Updates(map[string]interface{}{
		"images":         req.Images,
		"state":          2,
		"check_time":     time.Now(),
		"retrieve_state": 1,
	}).Error
	//err = model.NewRecycleCardOrderQuerySet(model.DB).IDEq(req.OrderId).GetUpdater().
	//	SetImages(req.Images).Update()
	if err != nil {
		logger.Error("game cassette err", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	fundRecord := &models.FundRecord{
		Uid:        order.Uid,
		FundType:   models.FundTypeRecycleCard,
		Amount:     int64(order.Price) * (-1),
		OutTradeNo: transfer.PartnerTradeNo,
		PaymentNo:  transfer.PaymentNo,
		Status:     2,
		Remark:     "回收卡带",
		//TransactionId: ,
	}
	err = orm.Eloquent.Create(fundRecord).Error
	if err != nil {
		logger.Error("create fund record err:", err)
	}

	operationLog := &models.OperationLog{
		//Uid:                   assistant.Uid,
		SysUid:                uint32(sysUser.UserId),
		Description:           "回收卡带转款",
		OperationType:         models.OperationTypeRecycleCardOrderImageUpdate,
		CorrelationId:         order.ID,
		CorrelationName:       models.LogCorrelationRecycleCardOrderId,
		StoreId:               uint32(sysUser.StoreId),
		StoreName:             sysUser.StoreName,
		CooperativeName:       sysUser.CooperativeName,
		CooperativeBusinessId: sysUser.CooperativeBusinessId,
	}
	operationLog.AddLog()
	app.OK(c, nil, "操作成功")
	return
}

func RecycleCardConfigUpdate(c *gin.Context) {
	req := models.RecycleCardConfig{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Error("ShouldBindJSON err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	if req.RebateRate < 0 || req.RebateRate > 10000 {
		logger.Error("rebate rate err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	config, err := models.RecycleCardConfigUpdate(req)
	if err != nil {
		logger.Error("update config err:%#v", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
	}
	app.OK(c, config, "操作成功")
	return
}

func RecycleCardConfigInfo(c *gin.Context) {
	//req := struct {
	//	OrderId uint32 `json:"order_id" binding:"required"`
	//	Images  string `json:"images" binding:"required"`
	//}{}
	//if c.ShouldBindJSON(&req) != nil {
	//	logger.Error("ShouldBindJSON err")
	//	app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
	//	return
	//}

	config, err := models.RecycleCardConfigInfo()
	if err != nil {
		logger.Error("update config err:%#v", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
	}
	app.OK(c, config, "操作成功")
	return
}

func RecycleCardOrderRetrieve(c *gin.Context) {
	req := struct {
		OrderId uint32 `json:"order_id" binding:"required"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Error("ShouldBindJSON err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	var order models.RecycleCardOrder
	err := orm.Eloquent.Table("recycle_card_order").Where("id=?", req.OrderId).Find(&order).Error
	if err != nil {
		logger.Error("order err:%#v", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}
	if order.State != 2 {
		logger.Error("order state err")
		app.Error(c, http.StatusInternalServerError, err, "状态错误")
		return
	}

	err = orm.Eloquent.Table("recycle_card_order").Where("id=?", req.OrderId).Updates(map[string]interface{}{
		"retrieve_state": 2,
		"retrieve_time":  time.Now(),
	}).Error
	if err != nil {
		logger.Error("recycle card order err:", err)
		app.Error(c, http.StatusInternalServerError, err, "操作失败")
		return
	}

	app.OK(c, nil, "操作成功")
	return
}
