package dao

import (
	"demo/configs"
	"demo/data/dao/manage"
	"demo/data/domain"
	"demo/data/domain/vo"
	"fmt"
	"strings"
	"time"
)

// SelectSkuBySkuId 根据id查询sku
func SelectSkuBySkuId(skuId int) (domain.GoodsSku, error) {
	var sku domain.GoodsSku
	_, err := configs.Engine.Table("goods_sku").Where("id = ?", skuId).Get(&sku)
	if err != nil {
		return sku, err
	}
	return sku, nil
}

// GetSkuBelong 查询sku所属topic，goods，type
func GetSkuBelong(skuId, couponUserId int64, tp float64) (bool, string, error) {
	//时间内可用
	availableTime := false
	//范围内可用
	availableField := false
	//金额条件可用
	availableMatch := false

	var couponUser domain.GoodsCouponUser
	_, err := configs.Engine.Table("goods_coupon_user").Where("id = ?", couponUserId).Get(&couponUser)
	if err != nil {
		return false, "", err
	}
	coupon, err := manage.GetGoodsCouponById(couponUser.CouponId)
	if err != nil {
		return false, "", err
	}
	//判断是否过期
	//领取后开始计时
	if coupon.Validity == "ClaimTiming" {
		if couponUser.CollectionTime.UnixMilli()+coupon.ValidityPeriod.UnixMilli() < time.Now().UnixMilli() {
			return false, "优惠券已过期", nil
		}
		//固定时间段内可用
	} else if coupon.Validity == "FixedTime" {
		if coupon.ValidityPeriod.UnixMilli() < time.Now().UnixMilli() {
			return false, "优惠券不在可使用时间段内", nil
		}
	} else {
		availableTime = true
	}
	if !availableTime {
		return availableTime, "", nil
	}

	sku, err := manage.GetGoodsSkuById(skuId)
	if err != nil {
		return false, "", err
	}
	//goods
	if coupon.ConditionByGoods != "" {
		split := strings.Split(coupon.ConditionByGoods, ",")
		for i := range split {
			if fmt.Sprint(skuId) == split[i] {
				availableField = true
				break
			}
		}
	}
	m := make(map[string]interface{})
	_, err = configs.Engine.Select("goods_type.id as tid, goods.id as gid").Table("goods_type").
		Join("INNER ", "goods", "goods_type.id = goods.type_id").
		Join("INNER ", "goods_sku", "goods.id = goods_sku.goods_id").
		Where("goods_sku.id = ?", sku.GoodsId).Get(&m)
	if err != nil {
		return false, "type 查询错误", err
	}
	//type
	if !availableField && coupon.ConditionByType != "" && m["tid"] != "" {
		split := strings.Split(coupon.ConditionByType, ",")
		for i := range split {
			if fmt.Sprint(m["tid"]) == split[i] {
				availableField = true
				break
			}
		}
	}
	//topic
	var topic domain.ShopTopic
	_, err = configs.Engine.Table("shop_topic").Where("find_in_set(?,type_ids)", m["tid"]).Get(&topic)
	if err != nil {
		return false, "topic 查询错误", err
	}
	if !availableField && topic.Id != 0 {
		availableField = true
	}

	if tp > coupon.CashBackPoint {
		availableMatch = true
	}
	if !availableTime || !availableField || !availableMatch {
		return false, "不满足条件", nil
	}
	return availableTime && availableField && availableMatch, "", nil
}

// CreateOrder 创建订单
func CreateOrder(order *domain.GoodsOrder) (*domain.GoodsOrder, error) {

	var couponUser domain.GoodsCouponUser
	_, err := configs.Engine.Table("goods_coupon_user").Where("id = ?", order.CouponUserId).Get(&couponUser)
	if err != nil {
		return order, err
	}
	coupon, err := manage.GetGoodsCouponById(couponUser.CouponId)
	if err != nil {
		return order, err
	}
	order.TotalPrice = order.TotalPrice - coupon.CashBackPrice
	//优惠券使用
	configs.Engine.ID(order.CouponUserId).Cols("state").Update(map[string]any{"state": 2})
	//创建订单
	id, err := configs.Engine.Table("goods_order").Insert(&order)
	fmt.Println("is id? ", id)
	if err != nil {
		return order, err
	}
	fmt.Println("order is ", order)
	return order, err
}

// OrderPaySuccess 订单支付成功
func OrderPaySuccess(orderId int64, userId int64) error {
	//查询订单
	order, err := manage.GetGoodsOrderById(orderId)
	if err != nil {
		return err
	}
	update, err := configs.Engine.Table("goods_order").Where("id = ?", orderId).Update(map[string]any{"state": 1})
	if err != nil {
		fmt.Println(update, err)
	}

	//获取价格
	var price = order.TotalPrice
	//给推荐人分成
	user, err := manage.GetUserById(userId)
	if user.InviterBy != 0 {
		wallet := domain.UserWallet{UserId: user.InviterBy}
		list, err := manage.GetUserWalletList(wallet, 0, 1)
		if err != nil {
			return err
		}
		userWallet, ok := list.List[0].(domain.UserWallet)
		if ok {
			//userWallet.Balance = userWallet.Balance + (price * 0.1)
			userWallet.PromotionAmount = userWallet.PromotionAmount + (price * 0.1)
			configs.Engine.Table("user_wallet").ID(userWallet.Id).Cols("balance").
				Update(map[string]any{"promotion_amount": userWallet.PromotionAmount})
		}
	}
	return nil
}

// GetOrderByUserId 获取订单集合
func GetOrderByUserId(userId int64) ([]domain.GoodsOrder, error) {
	order := domain.GoodsOrder{}
	rows, err := configs.Engine.Table("goods_order").Where("create_by = ?", userId).Desc("create_time").Rows(&order)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var orders []domain.GoodsOrder
	for rows.Next() {
		var order domain.GoodsOrder
		err := rows.Scan(&order)
		if err != nil {
			return nil, err
		}
		orders = append(orders, order)
	}
	return orders, nil
}

// GetUserWalletByUserId 获取用户的钱包信息
func GetUserWalletByUserId(userId int64) (domain.UserWallet, error) {
	var wallet domain.UserWallet
	_, err := configs.Engine.Where("user_id = ?", userId).Get(&wallet)
	if err != nil {
		return wallet, err
	}
	return wallet, nil

}

// GetUserCouponByUserId  获取用户的优惠券信息
func GetUserCouponByUserId(userId int64) ([]domain.CouponUserJDM, error) {

	var couponUserJDMs []domain.CouponUserJDM
	err := configs.Engine.Table("goods_coupon_user").
		Join("INNER", "goods_coupon", "goods_coupon_user.coupon_id = goods_coupon.id").
		Where("goods_coupon_user.user_id = ?", userId).
		Find(&couponUserJDMs)
	if err != nil {
		return couponUserJDMs, err
	}

	return couponUserJDMs, nil
}

// GetListGoodsOrder 获取用户的订单信息
func GetListGoodsOrder(state string, userId int64, pageNum, pageSize int) (vo.BaseListVo, error) {
	var goodsOrder domain.GoodsOrder
	Session := configs.Engine.Table("goods_order")
	if state != "" {
		Session.Where("state = ?", state)
	}
	rows, err := Session.Where("create_by = ?", userId).Limit(pageSize, (pageNum-1)*pageSize).Desc("id").Rows(&goodsOrder)
	var vo vo.BaseListVo
	if err != nil {
		return vo, err
	}
	vo.PageNum = pageNum
	vo.PageSize = pageSize
	vo.List = make([]any, 0)
	for rows.Next() {
		var u domain.GoodsOrder
		rows.Scan(&u)
		vo.List = append(vo.List, u)
	}
	CountSess := configs.Engine.Table("goods_order")
	if state != "" {
		CountSess.Where("state = ?", state)
	}
	//查询数量
	count, err := CountSess.Where("create_by = ?", userId).Count(&goodsOrder)
	vo.Total = int(count)
	return vo, nil
}

// 领取优惠券
//func pickUpTheCoupon(couponId int, userId int) (bool, error) {
//	gcu := domain.GoodsCouponUser{
//		UserId:         userId,
//		CouponId:       couponId,
//		CollectionTime: time.Now(),
//		State:          "1",
//	}
//	//判断优惠券数量是否充足
//	coupon, err := manage.GetByIdGoodsCoupon(couponId)
//	if err != nil {
//		return false, err
//	}
//	//判断条件
//	if coupon.Count > 0 {
//		if coupon.Count == 1 {
//			//优惠券数量为1时，直接领取
//			_, err := manage.PostGoodsCouponUser(&gcu)
//			if err != nil {
//				return false, err
//			}
//			manage.PutGoodsCoupon(map[string]any{"count": coupon.Count - 1}, couponId)
//			return true, nil
//		} else {
//			//优惠券数量大于1时，判断是否满足领取条件
//			if coupon.Condition == 1 {
//				//满足领取条件
//				_, err := manage.PostGoodsCouponUser(&gcu)
//				if err != nil {
//				}
//			}
//		}
//
//	}
//
//}
