package svc

import (
	"applet/app/db"
	"applet/app/db/model"
	"applet/app/e"
	"applet/app/utils"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/copier"
	"time"
)

func CouponReceive(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	coupon := db.GetCouponById(MasterDb(c), arg["id"])
	if coupon == nil {
		e.OutErr(c, 400, e.NewErr(400, "优惠券不存在"))
		return
	}
	user := GetUser(c)
	count, _ := MasterDb(c).Where("uid=? and merchant_scheme_id=?", user.Info.Uid, arg["id"]).Count(&model.CommunityTeamCouponUser{})
	if count > 0 {
		e.OutErr(c, 400, e.NewErr(400, "您已领取过"))
		return
	}
	var data model.CommunityTeamCouponUser
	err := copier.Copy(&data, coupon)
	fmt.Println(err)
	data.MerchantSchemeId = int(data.Id)
	data.Id = 0
	data.IsUse = 1
	data.Uid = user.Info.Uid
	now := time.Now()
	data.CreateTime = time.Now()
	data.UpdateTime = time.Now()
	if coupon.ValidTimeType == 2 {
		data.ValidTimeStart = now
		data.ValidTimeEnd = time.Unix(now.Unix()+int64(coupon.ValidDayNum)*86400, 0)
	}
	MasterDb(c).Insert(&data)
	e.OutSuc(c, "success", nil)
	return
}
func Coupon(c *gin.Context) {
	var arg map[string]string
	if err := c.ShouldBindJSON(&arg); err != nil {
		e.OutErr(c, e.ERR_INVALID_ARGS, err)
		return
	}
	cate := db.GetCoupon(MasterDb(c), arg)
	list := make([]map[string]string, 0)
	if cate != nil {
		stateMap := []string{"", "立减", "满减", "折扣"}
		scheme, host := ImageBucket(c)
		for _, v := range *cate {
			tmp := map[string]string{
				"id":         utils.IntToStr(v.Id),
				"name":       v.Name,
				"info":       v.Info,
				"type":       stateMap[v.Kind],
				"num":        utils.IntToStr(v.Num),
				"valid_time": "",
				"img_url":    ImageFormatWithBucket(scheme, host, v.Img),
				"create_at":  v.CreatedTime.Format("2006-01-02 15:04:05"),
			}
			if v.ValidTimeType == 1 {
				tmp["valid_time"] = v.ValidTimeStart.Format("2006.01.02") + "-" + v.ValidTimeEnd.Format("2006.01.02")
			} else {
				tmp["valid_time"] = "领取后" + utils.IntToStr(v.ValidDayNum) + "天有效"
			}
			list = append(list, tmp)
		}
	}

	e.OutSuc(c, list, nil)
	return
}
