package cooperativemanage

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

// CooperativeBusinessList 查看供应商列表
// @Summary 查看供应商列表
// @Tags 合作商, v1.2.0
// @Produce json
// @Accept json
// @Param request body models.CooperativeBusinessListReq true "查看供应商列表模型"
// @Success 200 {object} models.CooperativeBusinessListResp
// @Router /api/v1/cooperative/list [post]
func CooperativeBusinessList(c *gin.Context) {
	req := &models.CooperativeBusinessListReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := models.CooperativeBusinessListResp{
		Count:     count,
		List:      list,
		PageIndex: req.Page,
		TotalPage: req.PageSize,
	}

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

type CooperativeMemberDeductReq struct {
	CooperativeBusinessId uint32 `json:"cooperative_business_id" binding:"required"`
	GoldDeduct            uint32 `json:"gold_deduct" binding:"required"`       // 黄金会员提成
	PlatinumDeduct        uint32 `json:"platinum_deduct" binding:"required"`   // 白金会员提成
	BlackGoldDeduct       uint32 `json:"black_gold_deduct" binding:"required"` // 黑金金会员提成
	// cooperative_member_deduct
}

// CooperativeAdd 新增供应商
// @Summary 新增供应商
// @Tags 合作商, v1.2.0
// @Produce json
// @Accept json
// @Param request body models.CooperativeBusiness true "新增供应商模型"
// @Success 200 {object} app.Response
// @Router /api/v1/cooperative/add [post]
func CooperativeAdd(c *gin.Context) {
	req := &models.CooperativeBusiness{}
	if err := c.ShouldBindJSON(req); err != nil {
		logger.Errorf("para err", err)
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	req.AddTime = time.Now()
	err := orm.Eloquent.Create(req).Error
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "添加失败")
		return
	}
	deduct := &models.CooperativeMemberDeduct{
		CooperativeBusinessId:  req.ID,
		GoldDeduct:             req.CooperativeMemberDeduct.GoldDeduct,
		PlatinumDeduct:         req.CooperativeMemberDeduct.PlatinumDeduct,
		BlackGoldDeduct:        req.CooperativeMemberDeduct.BlackGoldDeduct,
		RenewalGoldDeduct:      req.CooperativeMemberDeduct.RenewalGoldDeduct,
		RenewalPlatinumDeduct:  req.CooperativeMemberDeduct.RenewalPlatinumDeduct,
		RenewalBlackGoldDeduct: req.CooperativeMemberDeduct.RenewalBlackGoldDeduct,
	}
	err = orm.Eloquent.Create(deduct).Error
	if err != nil {
		logger.Errorf("create cooperative member deduct err:", err)
		app.Error(c, http.StatusInternalServerError, err, "添加失败")
		return
	}

	app.OK(c, nil, "添加成功")
	return
}

// CooperativeEdit 编辑供应商
// @Summary 编辑供应商
// @Tags 合作商, v1.2.0
// @Produce json
// @Accept json
// @Param request body models.CooperativeBusiness true "编辑供应商模型"
// @Success 200 {object} app.Response
// @Router /api/v1/cooperative/edit [post]
func CooperativeEdit(c *gin.Context) {
	req := &models.CooperativeBusiness{}
	if err := c.ShouldBindJSON(req); err != nil {
		logger.Errorf("para err", err)
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	req.AddTime = time.Now()
	err := orm.Eloquent.Model(&models.CooperativeBusiness{}).Where("id = ?", req.ID).Updates(req).Error
	if err != nil {
		logger.Errorf("edit cooperative err:", err)
		app.Error(c, http.StatusInternalServerError, err, "更新失败")
		return
	}

	app.OK(c, nil, "添加成功")
	return
}

func CooperativeMemberPromotionList(c *gin.Context) {
	req := &models.CooperativeMemberPromotionReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
	return
}

func CooperativeMemberPromotionStoreList(c *gin.Context) {
	req := &models.CooperativeMemberPromotionStoreReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
	return
}

func CooperativeMemberPromotionDayList(c *gin.Context) {
	req := &models.CooperativeMemberPromotionDayReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
	return
}

func CooperativeMemberPromotionStoreDayList(c *gin.Context) {
	req := &models.CooperativeMemberPromotionStoreDayReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
	return
}

// CooperativeMemberPromotionStatisticList 租卡会员统计
// @Summary 租卡会员统计
// @Tags 会员管理, V1.2.0
// @Produce json
// @Accept json
// @Param request body models.CooperativeMemberPromotionStatisticReq true "租卡会员统计模型"
// @Success 200 {object} models.CooperativeMemberPromotionStatisticListResp
// @Router /api/v1/cooperative/member_promotion_statistic/list [post]
func CooperativeMemberPromotionStatisticList(c *gin.Context) {
	req := &models.CooperativeMemberPromotionStatisticReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	ret, err := req.List(c)
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

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

func CooperativeMemberPromotionSettleInfo(c *gin.Context) {
	req := &struct {
		CooperativeMemberPromotionId uint32 `json:"cooperative_member_promotion_id"`
		CooperativeBusinessId        uint32 `json:"cooperative_business_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	var memberPromotion models.CooperativeMemberPromotion
	err := orm.Eloquent.Table("").Where("id=?", req.CooperativeMemberPromotionId).Find(&memberPromotion).Error
	if err != nil {
		logger.Errorf("cooperative member promotion err:", err)
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	if memberPromotion.CooperativeBusinessId != req.CooperativeBusinessId {
		logger.Errorf("cooperative business id err:")
		app.Error(c, http.StatusInternalServerError, errors.New("cooperative business id err"), "结算错误")
		return
	}
	cooperative := new(models.CooperativeBusiness)
	cooperative.ID = memberPromotion.CooperativeBusinessId
	cooperative.SetMemberDeductConfig()

	if memberPromotion.State != models.PromotionStateUnSettlement {
		logger.Errorf("cooperative member promotion state err:")
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}

	if cooperative.CooperativeMemberDeduct == nil {
		logger.Errorf("cooperative member deduct nil:")
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	memberPromotion.GoldDeduct = cooperative.CooperativeMemberDeduct.GoldDeduct
	memberPromotion.PlatinumDeduct = cooperative.CooperativeMemberDeduct.PlatinumDeduct
	memberPromotion.BlackGoldDeduct = cooperative.CooperativeMemberDeduct.BlackGoldDeduct

	memberPromotion.RenewalGoldDeduct = cooperative.CooperativeMemberDeduct.RenewalGoldDeduct
	memberPromotion.RenewalPlatinumDeduct = cooperative.CooperativeMemberDeduct.RenewalPlatinumDeduct
	memberPromotion.RenewalBlackGoldDeduct = cooperative.CooperativeMemberDeduct.RenewalBlackGoldDeduct

	memberPromotion.DeductAmount += memberPromotion.GoldCount * memberPromotion.GoldDeduct
	memberPromotion.DeductAmount += memberPromotion.PlatinumCount * memberPromotion.PlatinumDeduct
	memberPromotion.DeductAmount += memberPromotion.BlackGoldCount * memberPromotion.BlackGoldDeduct

	memberPromotion.DeductAmount += memberPromotion.RenewalGoldCount * memberPromotion.RenewalGoldDeduct
	memberPromotion.DeductAmount += memberPromotion.RenewalPlatinumCount * memberPromotion.RenewalPlatinumDeduct
	memberPromotion.DeductAmount += memberPromotion.RenewalBlackGoldCount * memberPromotion.RenewalBlackGoldDeduct

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

func CooperativeMemberPromotionSettleConfirm(c *gin.Context) {
	req := &struct {
		CooperativeMemberPromotionId uint32 `json:"cooperative_member_promotion_id"`
		CooperativeBusinessId        uint32 `json:"cooperative_business_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	var memberPromotion models.CooperativeMemberPromotion
	err := orm.Eloquent.Table("").Where("id=?", req.CooperativeMemberPromotionId).Find(&memberPromotion).Error
	if err != nil {
		logger.Errorf("cooperative member promotion err:", err)
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	if memberPromotion.CooperativeBusinessId != req.CooperativeBusinessId {
		logger.Errorf("cooperative business id err:")
		app.Error(c, http.StatusInternalServerError, errors.New("cooperative business id err"), "结算错误")
		return
	}
	// TODO
	//if memberPromotion.Date != models.MonthDateAdd(-1) {
	//	logger.Errorf("settle date err:")
	//	app.Error(c, http.StatusInternalServerError, errors.New("settle date err"), "结算错误")
	//	return
	//}

	cooperative := new(models.CooperativeBusiness)
	cooperative.ID = memberPromotion.CooperativeBusinessId
	cooperative.SetMemberDeductConfig()

	if memberPromotion.State != models.PromotionStateUnSettlement {
		logger.Errorf("cooperative member promotion state err:")
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}

	if cooperative.CooperativeMemberDeduct == nil {
		logger.Errorf("cooperative member deduct nil:")
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	memberPromotion.GoldDeduct = cooperative.CooperativeMemberDeduct.GoldDeduct
	memberPromotion.PlatinumDeduct = cooperative.CooperativeMemberDeduct.PlatinumDeduct
	memberPromotion.BlackGoldDeduct = cooperative.CooperativeMemberDeduct.BlackGoldDeduct

	memberPromotion.RenewalGoldDeduct = cooperative.CooperativeMemberDeduct.RenewalGoldDeduct
	memberPromotion.RenewalPlatinumDeduct = cooperative.CooperativeMemberDeduct.RenewalPlatinumDeduct
	memberPromotion.RenewalBlackGoldDeduct = cooperative.CooperativeMemberDeduct.RenewalBlackGoldDeduct

	memberPromotion.DeductAmount += memberPromotion.GoldCount * memberPromotion.GoldDeduct
	memberPromotion.DeductAmount += memberPromotion.PlatinumCount * memberPromotion.PlatinumDeduct
	memberPromotion.DeductAmount += memberPromotion.BlackGoldCount * memberPromotion.BlackGoldDeduct

	memberPromotion.DeductAmount += memberPromotion.RenewalGoldCount * memberPromotion.RenewalGoldDeduct
	memberPromotion.DeductAmount += memberPromotion.RenewalPlatinumCount * memberPromotion.RenewalPlatinumDeduct
	memberPromotion.DeductAmount += memberPromotion.RenewalBlackGoldCount * memberPromotion.RenewalBlackGoldDeduct

	begin := orm.Eloquent.Begin()
	deductSettle := &models.CooperativeDeductSettle{
		CooperativeMemberPromotionId: req.CooperativeMemberPromotionId,
		CooperativeBusinessId:        memberPromotion.CooperativeBusinessId,
		CooperativeName:              memberPromotion.CooperativeName,
		DeductAmount:                 memberPromotion.DeductAmount,
		Date:                         memberPromotion.Date,
		State:                        models.PromotionStateFinancePay,
		GoldCount:                    memberPromotion.GoldCount,
		PlatinumCount:                memberPromotion.PlatinumCount,
		BlackGoldCount:               memberPromotion.BlackGoldCount,
		GoldDeduct:                   memberPromotion.GoldDeduct,
		PlatinumDeduct:               memberPromotion.PlatinumDeduct,
		BlackGoldDeduct:              memberPromotion.BlackGoldDeduct,

		RenewalGoldCount:       memberPromotion.RenewalGoldCount,
		RenewalPlatinumCount:   memberPromotion.RenewalPlatinumCount,
		RenewalBlackGoldCount:  memberPromotion.RenewalBlackGoldCount,
		RenewalGoldDeduct:      memberPromotion.RenewalGoldDeduct,
		RenewalPlatinumDeduct:  memberPromotion.RenewalPlatinumDeduct,
		RenewalBlackGoldDeduct: memberPromotion.RenewalBlackGoldDeduct,
	}
	err = begin.Create(deductSettle).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("create cooperative deduct settle err:", err)
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	err = begin.Table("cooperative_member_promotion").Where("id=?", memberPromotion.ID).
		Updates(map[string]interface{}{
			"state": models.PromotionStateFinancePay,
		}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("update cooperative_member_promotion state err:", err)
		app.Error(c, http.StatusInternalServerError,
			errors.New("update cooperative_member_promotion state err"), "结算错误")
		return
	}
	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("commit err:", err)
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	app.OK(c, memberPromotion, "")
	return
}

func CooperativeMemberPromotionSettleList(c *gin.Context) {
	req := &models.CooperativeMemberPromotionSettleReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
	return
}

func CooperativeMemberPromotionSettleRemit(c *gin.Context) {
	req := &struct {
		CooperativeDeductSettleId uint32 `json:"cooperative_deduct_settle_id"`
		CooperativeBusinessId     uint32 `json:"cooperative_business_id"`
	}{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	var deductSettle models.CooperativeDeductSettle
	err := orm.Eloquent.Table("").Where("id=?", req.CooperativeDeductSettleId).Find(&deductSettle).Error
	if err != nil {
		logger.Errorf("cooperative member promotion err:", err)
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	if deductSettle.CooperativeBusinessId != req.CooperativeBusinessId {
		logger.Errorf("cooperative business id err:")
		app.Error(c, http.StatusInternalServerError, errors.New("cooperative business id err"), "操作失败")
		return
	}
	if deductSettle.State != models.PromotionStateFinancePay {
		logger.Errorf("deduct settle state err:")
		app.Error(c, http.StatusInternalServerError, errors.New("deduct settle state err"), "操作失败")
		return
	}

	begin := orm.Eloquent.Begin()
	err = begin.Table("cooperative_member_promotion").
		Where("id=?", deductSettle.CooperativeMemberPromotionId).Updates(map[string]interface{}{
		"state": models.PromotionStateSettled,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("update cooperative_member_promotion state err:", err)
		app.Error(c, http.StatusInternalServerError, errors.New("update cooperative_member_promotion state err"), "操作失败")
		return
	}
	err = begin.Table("cooperative_deduct_settle").Where("id=?", deductSettle.ID).Updates(map[string]interface{}{
		"state": models.PromotionStateSettled,
	}).Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("update cooperative_member_promotion state err:", err)
		app.Error(c, http.StatusInternalServerError, errors.New("update cooperative_member_promotion state err"), "操作失败")
		return
	}
	err = begin.Commit().Error
	if err != nil {
		begin.Rollback()
		logger.Errorf("commit err:", err)
		app.Error(c, http.StatusInternalServerError, err, "结算错误")
		return
	}
	app.OK(c, nil, "")
	return
}

func CooperativePromotionMemberList(c *gin.Context) {
	req := &models.CooperativePromotionMemberReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
	return
}

func UpdateCooperativeMemberDeduct(c *gin.Context) {
	req := &models.CooperativeMemberDeduct{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	err := orm.Eloquent.Save(req).Error
	if err != nil {
		logger.Errorf("update cooperative member deduct err:", err)
		app.Error(c, http.StatusInternalServerError, err, "修改失败")
		return
	}

	app.OK(c, nil, "修改成功")
	return
}

type CooperativeAssistantMemberDeductReq struct {
	CooperativeBusinessId  uint32 `json:"cooperative_business_id" binding:"required"`
	StoreId                uint32 `json:"store_id"  binding:"required"`                  //
	GoldDeduct             uint32 `json:"gold_deduct"  binding:"required"`               // 黄金会员提成
	PlatinumDeduct         uint32 `json:"platinum_deduct"  binding:"required"`           // 白金会员提成
	BlackGoldDeduct        uint32 `json:"black_gold_deduct"  binding:"required"`         // 黑金金会员提成
	RenewalGoldDeduct      uint32 `json:"renewal_gold_deduct"  binding:"required"`       // 续费黄金会员提成
	RenewalPlatinumDeduct  uint32 `json:"renewal_platinum_deduct"  binding:"required"`   // 续费白金会员提成
	RenewalBlackGoldDeduct uint32 `json:"renewal_black_gold_deduct"  binding:"required"` // 续费黑金金会员提成
	// cooperative_assistant_member_deduct
}

func UpdateCooperativeMemberStoreDeduct(c *gin.Context) {
	req := &CooperativeAssistantMemberDeductReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	memberDeduct := &models.CooperativeAssistantMemberDeduct{
		CooperativeBusinessId:  req.CooperativeBusinessId,
		StoreId:                req.StoreId,
		GoldDeduct:             req.GoldDeduct,
		PlatinumDeduct:         req.PlatinumDeduct,
		BlackGoldDeduct:        req.BlackGoldDeduct,
		RenewalGoldDeduct:      req.RenewalGoldDeduct,
		RenewalPlatinumDeduct:  req.RenewalPlatinumDeduct,
		RenewalBlackGoldDeduct: req.RenewalBlackGoldDeduct,
	}
	if memberDeduct.CooperativeBusinessId == 0 {
		var store models.Store
		err := orm.Eloquent.Table("store").Where("id=?", memberDeduct.StoreId).Find(&store).Error
		if err != nil {
			logger.Errorf("store err:", store)
			app.Error(c, http.StatusInternalServerError, err, "修改失败")
			return
		}
		memberDeduct.CooperativeBusinessId = store.CooperativeBusinessId
	}
	err := orm.Eloquent.Save(memberDeduct).Error
	if err != nil {
		logger.Errorf("update cooperative member deduct err:", err)
		app.Error(c, http.StatusInternalServerError, err, "修改失败")
		return
	}

	app.OK(c, nil, "修改成功")
	return
}

func CooperativeOrderList(c *gin.Context) {
	req := &models.CooperativeOrderReq{}
	if c.ShouldBindJSON(req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	//reqJson, _ := json.Marshal(req)
	//fmt.Println("reqJson:", string(reqJson))

	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	ret := map[string]interface{}{
		"count":     count,
		"list":      list,
		"pageIndex": req.Page,
	}
	app.OK(c, ret, "")
}

// AssistantInviteMemberReportList 店员绩效
// @Summary 店员绩效
// @Tags 门店管理, v1.2.0
// @Produce json
// @Accept json
// @Param request body models.AssistantInviteMemberReportReq true "店员绩效模型"
// @Success 200 {object} models.AssistantInviteMemberReportListResp
// @Router /api/v1/cooperative/member_promotion/assistant_report [post]
func AssistantInviteMemberReportList(c *gin.Context) {
	req := models.AssistantInviteMemberReportReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("parameter err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

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

	ret, err := req.List(c)
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

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

func CooperativeStoreList(c *gin.Context) {
	req := &models.GetCooperativeStoreReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para 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)
	list, count, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	ret := map[string]interface{}{
		"count":      count,
		"list":       list,
		"pageIndex":  req.Page,
		"total_page": req.PageSize,
	}

	app.OK(c, ret, "")
}

func CooperativeGameCardStockList(c *gin.Context) {
	req := models.CooperativeGameCardStockReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("parameter err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

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

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

func CooperativeGameCardGoodsList(c *gin.Context) {
	req := models.CooperativeGameCardGoodsReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	businessId, err := models.GetCooperativeBusinessId(c)
	if err != nil {
		logger.Errorf("get cooperative business id err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	req.CooperativeBusinessId = businessId
	resp, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}

	app.OK(c, resp, "")
}

// 5.调拨任务列表
func CooperativeCannibalizeTaskList(c *gin.Context) {
	req := models.CooperativeCannibalizeTaskReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	businessId, err := models.GetCooperativeBusinessId(c)
	if err != nil {
		logger.Errorf("cannibalize task get cooperative business id err:", err)
		app.Error(c, http.StatusInternalServerError, err, "查询失败")
		return
	}
	req.CooperativeBusinessId = businessId
	resp, err := req.List()
	if err != nil {
		logger.Errorf("err:", err)
		app.Error(c, http.StatusInternalServerError, err, "任务列表错误")
		return
	}

	app.OK(c, resp, "")
}

func CooperativeStockExport(c *gin.Context) {
	req := struct {
		StoreId uint32 `json:"store_id"`
	}{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}
	businessId, err := models.GetCooperativeBusinessId(c)
	if err != nil {
		logger.Errorf("cannibalize task get cooperative business id err:", err)
		app.Error(c, http.StatusInternalServerError, err, "导出失败")
		return
	}
	//req.CooperativeBusinessId = businessId
	var cooperativeBusiness models.CooperativeBusiness
	err = orm.Eloquent.Table("cooperative_business").Where("id=?", businessId).Find(&cooperativeBusiness).Error
	if err != nil {
		logger.Errorf("cooperative business err:", err)
		app.Error(c, http.StatusInternalServerError, err, "导出失败")
		return
	}
	storeIds := []uint32{req.StoreId}
	if req.StoreId == 0 {
		ids, err := models.GetStoreIdsByCooperativeBusinessId(businessId)
		if err != nil {
			logger.Errorf("store id cooperative business err:", err)
			app.Error(c, http.StatusInternalServerError, err, "导出失败")
			return
		}
		storeIds = ids
	}

	goodsStock := models.CooperativeExportGoodsStock(storeIds, cooperativeBusiness)

	ret := &map[string]interface{}{
		"goods_stock_url": goodsStock,
	}
	app.OK(c, ret, "数据导出成功")
	return
}

func CooperativeMemberPromotionExport(c *gin.Context) {
	req := models.CooperativeExportMemberPromotionReq{}
	if c.ShouldBindJSON(&req) != nil {
		logger.Errorf("para err")
		app.Error(c, http.StatusBadRequest, errors.New("para err"), "参数错误")
		return
	}

	businessId, err := models.GetCooperativeBusinessId(c)
	if err != nil {
		logger.Errorf("cannibalize task get cooperative business id err:", err)
		app.Error(c, http.StatusInternalServerError, err, "导出失败")
		return
	}
	req.CooperativeBusinessId = businessId
	//var cooperativeBusiness models.CooperativeBusiness
	//err = orm.Eloquent.Table("cooperative_business").Where("id=?", businessId).Find(&cooperativeBusiness).Error
	//if err != nil {
	//	logger.Errorf("cooperative business err:", err)
	//	app.Error(c, http.StatusInternalServerError, err, "导出失败")
	//	return
	//}
	//storeIds := []uint32{req.StoreId}
	//if req.StoreId == 0 {
	//	ids, err := models.GetStoreIdsByCooperativeBusinessId(businessId)
	//	if err != nil {
	//		logger.Errorf("store id cooperative business err:", err)
	//		app.Error(c, http.StatusInternalServerError, err, "导出失败")
	//		return
	//	}
	//	storeIds = ids
	//}

	memberPromotion := req.Export()
	if memberPromotion == "" {
		logger.Errorf("member promotion url nil:")
		app.Error(c, http.StatusInternalServerError, errors.New("member promotion url nil"), "导出失败")
		return
	}

	ret := &map[string]interface{}{
		"member_promotion_url": memberPromotion,
	}
	app.OK(c, ret, "数据导出成功")
}

// CooperativeSetPayInfo 设置支付信息
// @Summary 设置支付信息
// @Tags 合作商, v1.2.0
// @Produce json
// @Accept json
// @Param request body models.CooperativeSetPayInfoReq true "设置支付信息模型"
// @Success 200 {object} app.Response
// @Router /api/v1/cooperative/set_pay_info [post]
func CooperativeSetPayInfo(c *gin.Context) {
	var req = new(models.CooperativeSetPayInfoReq)
	if err := c.ShouldBindJSON(&req); err != nil {
		logger.Errorf("ShouldBindJSON err:", logger.Field("err", err))
		app.Error(c, http.StatusBadRequest, err, "参数错误:"+err.Error())
		return
	}

	err := tools.Validate(req) //必填参数校验
	if err != nil {
		app.Error(c, http.StatusBadRequest, err, err.Error())
		return
	}

	sysUser, err := models.GetSysUserByCtx(c)
	if err != nil {
		logger.Error("sys user err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, "操作失败:"+err.Error())
		return
	}

	if req.CooperativeBusinessId == 0 { // 如果入参为空，则默认使用当前用户所属的合作商id
		if sysUser.CooperativeBusinessId == 0 {
			logger.Error("sysUser.CooperativeBusinessId is 0")
			app.Error(c, http.StatusInternalServerError, errors.New("合作商id为空"), "保存失败:合作商id为空")
			return
		}
		req.CooperativeBusinessId = sysUser.CooperativeBusinessId
	}

	err = models.SetPayInfo(req)
	if err != nil {
		logger.Error("CreateErpOrder err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}

	app.OK(c, nil, "")
}

// CooperativeGetPayInfo 获取支付信息
// @Summary 获取支付信息
// @Tags 合作商, v1.2.0
// @Produce json
// @Accept json
// @Success 200 {object} models.CooperativePayInfo
// @Router /api/v1/cooperative/get_pay_info [post]
func CooperativeGetPayInfo(c *gin.Context) {
	//var req = new(models.CooperativeGetPayInfoReq)
	//if err := c.ShouldBindJSON(&req); err != nil {
	//	logger.Errorf("ShouldBindJSON err:", logger.Field("err", err))
	//	app.Error(c, http.StatusBadRequest, err, "参数错误:"+err.Error())
	//	return
	//}
	//
	//err := tools.Validate(req) //必填参数校验
	//if err != nil {
	//	app.Error(c, http.StatusBadRequest, err, err.Error())
	//	return
	//}

	payInfo, err := models.GetPayInfo()
	if err != nil {
		logger.Error("CreateErpOrder err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}

	app.OK(c, payInfo, "")
}

// CooperativeGetDefaultInfo 获取合作商默认用户名和密码
// @Summary 获取合作商默认用户名和密码
// @Tags 合作商, v1.2.0
// @Produce json
// @Accept json
// @Success 200 {object} models.DefaultUserNameAndPasswordResp
// @Router /api/v1/cooperative/get_default_info [post]
func CooperativeGetDefaultInfo(c *gin.Context) {
	userInfo, err := models.GetDefaultUserNameAndPassword()
	if err != nil {
		logger.Error("GetDefaultUserNameAndPassword err:", logger.Field("err", err))
		app.Error(c, http.StatusInternalServerError, err, err.Error())
		return
	}

	app.OK(c, userInfo, "")
}
