package card_redeem_order

import (
	"context"
	"fmt"
	v1 "kami/api/card_info_walmart/v1"
	"kami/internal/consts"
	"kami/internal/dao"
	"kami/internal/model"
	"kami/internal/model/do"
	"kami/internal/model/entity"
	"kami/internal/service"
	"kami/utility/config"
	"kami/utility/utils"

	"github.com/duke-git/lancet/v2/slice"
	"github.com/gogf/gf/v2/container/gset"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/text/gstr"
)

// AddOne 添加一条充值记录
func (h *sCardRedeemOrder) AddOne(ctx context.Context, input *model.RedeemCardSubmitInput) (orderNo string, err error) {
	orderNo = utils.GenerateRandomUUID()
	_, err = dao.V1CardRedeemOrderInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		InsertAndGetId(do.V1CardRedeemOrderInfo{
			OrderNo:     orderNo,
			CardNo:      input.CardNo,
			GiftCardPwd: input.GiftCardPwd,
			NotifyUrl:   input.NotifyUrl,
			MerchantId:  input.MerchantId,
			Attach:      input.Attach,
			Status:      consts.RedeemOrderPending,
			OrderAmount: input.Amount,
			Category:    input.Category,
		})
	_ = h.AddHistory(ctx, &model.RedeemCardOrderAddHistory{
		Amount:          input.Amount,
		OrderNo:         orderNo,
		Remark:          "新增订单",
		OperationStatus: consts.RedeemOrderOperationAdd,
	}, nil)
	return orderNo, err
}

func (h *sCardRedeemOrder) GetOrderOneByOrderNo(ctx context.Context, orderNo string, tx gdb.TX) (data *entity.V1CardRedeemOrderInfo, err error) {
	data = &entity.V1CardRedeemOrderInfo{}
	m := dao.V1CardRedeemOrderInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1CardRedeemOrderInfo.Columns().OrderNo, orderNo).
		Scan(&data)
	err = utils.HandleNoRowsError(err)
	return
}

// List 获取充值列表
func (h *sCardRedeemOrder) List(ctx context.Context, input *model.RedeemCardListInput) (total int, data []*model.RedeemCardOrderOutput, err error) {
	glog.Info(ctx, "input", input)

	data = make([]*model.RedeemCardOrderOutput, 0)

	m := dao.V1CardRedeemOrderInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if input.UserId != "" {
		m = m.Where(dao.V1CardRedeemOrderInfo.Columns().CreatedUserId, input.UserId)
	}
	if input.GiftCardPwd != "" {
		m = m.WhereLike(dao.V1CardRedeemOrderInfo.Columns().GiftCardPwd, utils.OrmLike(gstr.TrimAll(input.GiftCardPwd)))
	}
	if input.MerchantId != "" {
		m = m.WhereLike(dao.V1CardRedeemOrderInfo.Columns().MerchantId, utils.OrmLike(gstr.TrimAll(input.MerchantId)))
	}
	if input.Attach != "" {
		m = m.WhereLike(dao.V1CardRedeemOrderInfo.Columns().Attach, utils.OrmLike(gstr.TrimAll(input.Attach)))
	}
	if len(input.DateRange) == 2 {
		m = m.WhereBetween(fmt.Sprintf("DATE(`%s`)", dao.V1CardRedeemOrderInfo.Columns().CreatedAt), input.DateRange[0].StartOfDay(), input.DateRange[1].EndOfDay())
	}

	if input.AccountCk != "" || input.AccountNickName != "" || input.GroupId != 0 {
		accountIds := gset.NewStrSet()
		if input.AccountNickName != "" {
			if accountList, _ := service.CardRedeemAccount().Query(ctx, &model.RedeemAccountQueryInput{
				NickName: input.AccountNickName,
				Ck:       input.AccountCk,
				GroupId:  input.GroupId,
			}, nil); len(accountList) > 0 {
				slice.ForEach(accountList, func(_ int, item *entity.V1CardRedeemAccountInfo) {
					accountIds.Add(item.Id)
				})
			}
		}
		m = m.WhereIn(dao.V1CardRedeemOrderInfo.Columns().AccountId, accountIds.Slice())
	}

	if input.Category != "" {
		m = m.Where(dao.V1CardRedeemOrderInfo.Columns().Category, input.Category)
	}

	if input.Current != 0 && input.PageSize != 0 {
		m = m.Page(input.Current, input.PageSize)
	}

	list := make([]*entity.V1CardRedeemOrderInfo, 0)
	err = m.OrderDesc(dao.V1CardRedeemOrderInfo.Columns().CreatedAt).
		ScanAndCount(&list, &total, false)
	if err != nil {
		return
	}

	// 获取用户信息
	userList, err := service.SysUser().GetUsers(ctx, slice.Map(list, func(index int, item *entity.V1CardRedeemOrderInfo) string {
		return item.CreatedUserId
	}))
	if err != nil {
		return
	}

	slice.ForEach(list, func(index int, item *entity.V1CardRedeemOrderInfo) {
		user, ok := slice.FindBy(userList, func(index int, item2 *model.SysUserSimpleOutput) bool {
			return item2.Id == item.CreatedUserId
		})
		if !ok {
			user = &model.SysUserSimpleOutput{}
		}
		data = append(data, &model.RedeemCardOrderOutput{
			ListOutput: &v1.ListOutput{
				V1CardRedeemOrderInfo: item,
				UserInfo: struct {
					Id       string `json:"id" description:"用户ID"`
					Username string `json:"username" description:"用户名"`
				}{
					Id:       user.Id,
					Username: user.UserName,
				},
			},
		})
	})
	return
}

// IsCardPassRepeated 当前卡号是否重复
func (h *sCardRedeemOrder) IsCardPassRepeated(ctx context.Context, cardNo, CardPass string, tx gdb.TX) (isRepeated bool) {
	m := dao.V1CardRedeemOrderInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	count, _ := m.Where(dao.V1CardRedeemOrderInfo.Columns().CardNo, cardNo).
		Where(dao.V1CardRedeemOrderInfo.Columns().GiftCardPwd, CardPass).Count(1)
	return count > 1
}

func (h *sCardRedeemOrder) GetOneByMerchantId(ctx context.Context, merchantId string, tx gdb.TX) (entity *entity.V1CardRedeemOrderInfo, err error) {
	m := dao.V1CardRedeemOrderInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1CardRedeemOrderInfo.Columns().Attach, merchantId).Scan(&entity)
	return
}

// GetRandomOneById 随机获取一个失败订单
func (h *sCardRedeemOrder) GetRandomOneById(ctx context.Context, accountId string, status consts.RedeemOrderStatus, category consts.CardRedeemAccountCategory, tx gdb.TX) (entity *entity.V1CardRedeemOrderInfo, err error) {
	m := dao.V1CardRedeemOrderInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if tx != nil {
		m = m.TX(tx)
	}
	err = m.Where(dao.V1CardRedeemOrderInfo.Columns().AccountId, accountId).
		Where(dao.V1CardRedeemOrderInfo.Columns().OrderStatus, status).
		Where(dao.V1CardRedeemOrderInfo.Columns().Category, category).OrderRandom().Limit(1).Scan(&entity)
	return
}

//随机获取一个
