package models

import (
	"fmt"
	"github.com/codinl/go-logger"
	orm "go-admin/common/global"
	"time"
)

type UserCouponReq struct {
	Page        int       `json:"pageIndex"`
	PageSize    int       `json:"pageSize"`
	State       uint32    `json:"state"` // 1-未使用 2-已使用 3-已过期
	Uid         uint32    `json:"uid"`
	RedeemCode  string    `json:"redeem_code"`
	MemberLevel uint32    `json:"member_level"` // 会员等级 1-用户  2-会员
	StartTime   time.Time `json:"start_time"`   // 开始时间
	EndTime     time.Time `json:"end_time"`     // 结束时间
}

func (u *UserCouponReq) List() ([]UserCoupon, int64, error) {
	var userCoupons []UserCoupon

	if u.PageSize == 0 {
		u.PageSize = 10
	}
	qs := orm.Eloquent.Table("user_coupon")
	if u.Uid != 0 {
		qs = qs.Where("uid=?", u.Uid)
	}
	if u.State != 0 {
		qs = qs.Where("state=?", u.State)
	}
	if u.MemberLevel != 0 {
		qs = qs.Where("member_level=?", u.MemberLevel)
	}
	if !u.StartTime.IsZero() {
		fmt.Println("起始时间:", u.StartTime.Unix())
		qs = qs.Where("created_at > ?", u.StartTime)
	}
	if !u.EndTime.IsZero() {
		fmt.Println("时间:", u.StartTime.Unix())
		qs = qs.Where("created_at < ?", u.EndTime)
	}
	if u.RedeemCode != "" {
		qs = qs.Where("redeem_code=?", u.RedeemCode)
	}

	var count int64
	err := qs.Count(&count).Error
	if err != nil {
		logger.Error("err:", err)
		return userCoupons, 0, err
	}
	page := u.Page
	pageSize := u.PageSize
	page -= 1
	if page < 0 {
		page = 0
	}
	err = qs.Order("id DESC").Offset(page * pageSize).Limit(pageSize).Find(&userCoupons).Error
	if err != nil {
		logger.Error("err:", err)
		return userCoupons, 0, err
	}

	UserCouponListSetUserAndCoupon(userCoupons)

	return userCoupons, count, nil
}

func UserCouponListSetUserAndCoupon(list []UserCoupon) {
	uids := make([]uint32, 0, len(list))
	couponIds := make([]uint32, 0, len(list))
	for i, _ := range list {
		uids = append(uids, list[i].Uid)
		couponIds = append(couponIds, list[i].CouponId)
	}

	infoMap, err := GetUserInfoMap(uids)
	if err != nil {
		logger.Error("get user info map err:", err)
		return
	}

	couponMap, err := GetCouponMap(couponIds)
	if err != nil {
		logger.Error("get coupon map err:", err)
		return
	}

	for i, _ := range list {
		v, ok := infoMap[list[i].Uid]
		if ok {
			list[i].UserInfo = v
		}

		coupon, ok2 := couponMap[list[i].CouponId]
		if ok2 {
			list[i].Coupon = &coupon
		}
	}
}

func GetCouponMap(ids []uint32) (map[uint32]Coupon, error) {
	couponMap := make(map[uint32]Coupon, 0)
	if len(ids) == 0 {
		logger.Error("ids is nil")
		return couponMap, nil
	}
	var coupons []Coupon
	err := orm.Eloquent.Table("coupon").Where("id in (?)", ids).Find(&coupons).Error
	if err != nil {
		logger.Error("coupons err:", err)
		return couponMap, err
	}
	for i, _ := range coupons {
		couponMap[coupons[i].ID] = coupons[i]
	}

	return couponMap, nil
}
