package card_apple_order

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

	"github.com/duke-git/lancet/v2/pointer"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"
)

// CheckIsAccordingStealRule 查询当前账号是否符合偷卡规则
func (h *sAppleOrder) CheckIsAccordingStealRule(ctx context.Context, targetUserId string, amount float64) (isSteal bool, data *entity.V1CardAppleHiddenSettings, err error) {
	//	查询当前用户配置的所有规则
	isSteal = false
	stealRules, err := h.GetStealRule(ctx, targetUserId)
	if err != nil {
		return
	}
	for _, rule := range stealRules {
		relationInfo, err2 := h.GetStealOrderInfoById(ctx, int(rule.Id))
		if err2 != nil {
			glog.Error(ctx, "查询当前账号是否满足偷卡规则失败", err2)
			continue
		}
		orderIds := g.SliceStr{}
		for _, info := range relationInfo {
			orderIds = append(orderIds, info.OrderNo)
		}
		orderInfo := entity.V1CardAppleRechargeInfo{}
		//查询最后一次偷卡记录
		_ = dao.V1CardAppleRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
			Where(dao.V1CardAppleRechargeInfo.Columns().Status, consts.AppleRechargeOrderSuccess).
			OrderDesc(dao.V1CardAppleRechargeInfo.Columns().CreatedAt).
			WhereIn(dao.V1CardAppleRechargeInfo.Columns().OrderNo, orderIds).Scan(&orderInfo)

		m := dao.V1CardAppleRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
			Where(dao.V1CardAppleRechargeInfo.Columns().CreatedUserId, targetUserId).
			Where(dao.V1CardAppleRechargeInfo.Columns().Status, consts.AppleRechargeOrderSuccess)
		//如果存在最后一次偷卡记录
		if !pointer.IsNil(orderInfo.CreatedAt) {
			m = m.WhereGTE(dao.V1CardAppleRechargeInfo.Columns().CreatedAt, orderInfo.CreatedAt)
		}
		totalAmount, err2 := m.Sum(dao.V1CardAppleRechargeInfo.Columns().ActualAmount)
		if err2 != nil {
			return
		}
		//偷的一方和被偷的一方都正常
		isTargetUserNormal, _ := service.SysUser().CheckUserNormal(ctx, rule.TargetUserId)
		isStorageUserNormal, _ := service.SysUser().CheckUserNormal(ctx, rule.StorageUserId)
		//如果当前金额大于需要偷的金额
		if totalAmount > float64(rule.Amount) && amount == float64(rule.TargetAmount) &&
			isTargetUserNormal && isStorageUserNormal {
			return true, &rule, nil
		}
	}
	return
}

// GetStealRule 获取偷卡配置，目标用户ID
func (h *sAppleOrder) GetStealRule(ctx context.Context, targetUserId string) (data []entity.V1CardAppleHiddenSettings, err error) {
	data = make([]entity.V1CardAppleHiddenSettings, 0)
	err = dao.V1CardAppleHiddenSettings.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleHiddenSettings.Columns().TargetUserId, targetUserId).
		Where(dao.V1CardAppleHiddenSettings.Columns().Status, consts.StealStatusOpen).
		Scan(&data)
	err = utils.HandleNoRowsError(err)
	return
}

// SetStealRule 设置偷卡关联规则
func (h *sAppleOrder) SetStealRule(ctx context.Context, orderNo string, setting *entity.V1CardAppleHiddenSettings) (ruleId int64, err error) {
	//设置订单关联关系
	ruleId, err = dao.V1CardAppleHiddenSettingsRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		InsertAndGetId(do.V1CardAppleHiddenSettingsRechargeInfo{
			OrderNo:         orderNo,
			TargetUserId:    setting.TargetUserId,
			StorageUserId:   setting.StorageUserId,
			HiddenSettingId: setting.Id,
		})
	return
}

// GetStealOrderInfoById 根据偷卡规则查找对应的订单关联关系
func (h *sAppleOrder) GetStealOrderInfoById(ctx context.Context, hiddenSettingId int) (data []entity.V1CardAppleHiddenSettingsRechargeInfo, err error) {
	data = make([]entity.V1CardAppleHiddenSettingsRechargeInfo, 0)
	err = dao.V1CardAppleHiddenSettingsRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleHiddenSettingsRechargeInfo.Columns().HiddenSettingId, hiddenSettingId).
		OrderDesc(dao.V1CardAppleHiddenSettingsRechargeInfo.Columns().CreatedAt).
		Scan(&data)
	return
}

// UpdateStealNewOrderNo 关联新的订单号到当前订单
func (h *sAppleOrder) UpdateStealNewOrderNo(ctx context.Context, ruleId int64, orderNo string) (err error) {
	_, err = dao.V1CardAppleHiddenSettingsRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleHiddenSettingsRechargeInfo.Columns().Id, ruleId).
		Update(do.V1CardAppleHiddenSettingsRechargeInfo{
			NewOrderNo: orderNo,
		})
	return
}

// GetStealOrderInfoByCreatedAt 查询当前时间后所有关联的订单
func (h *sAppleOrder) GetStealOrderInfoByCreatedAt(ctx context.Context, createdAt *gtime.Time) (orderNos g.SliceStr, err error) {
	data := make([]entity.V1CardAppleHiddenSettingsRechargeInfo, 0)
	m := dao.V1CardAppleHiddenSettingsRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1())
	if !pointer.IsNil(createdAt) {
		m = m.WhereGTE(dao.V1CardAppleHiddenSettingsRechargeInfo.Columns().CreatedAt, createdAt)
	}
	err = m.Scan(&data)
	//	提取所有的订单号
	orderNos = g.SliceStr{}
	for _, info := range data {
		orderNos = append(orderNos, info.OrderNo)
	}
	return orderNos, err
}

// GetStealOrderInfoByNewOrderNo  查询当前新订单是否是关联的订单
func (h *sAppleOrder) GetStealOrderInfoByNewOrderNo(ctx context.Context, orderNo string) (data *entity.V1CardAppleHiddenSettingsRechargeInfo, err error) {
	err = dao.V1CardAppleHiddenSettingsRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleHiddenSettingsRechargeInfo.Columns().NewOrderNo, orderNo).
		Scan(&data)
	err = utils.HandleNoRowsError(err)
	return
}

// GetStealOrderInfoByOrderNo 判断当前订单是否是关联的订单
func (h *sAppleOrder) GetStealOrderInfoByOrderNo(ctx context.Context, orderNo string) (data *entity.V1CardAppleHiddenSettingsRechargeInfo, err error) {
	err = dao.V1CardAppleHiddenSettingsRechargeInfo.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleHiddenSettingsRechargeInfo.Columns().OrderNo, orderNo).
		Scan(&data)
	err = utils.HandleNoRowsError(err)
	return
}

// UpdateStealActualAmount 添加偷卡金额总额
func (h *sAppleOrder) UpdateStealActualAmount(ctx context.Context, id int, amount float64) (err error) {
	_, err = dao.V1CardAppleHiddenSettings.Ctx(ctx).DB(config.GetDatabaseV1()).
		Where(dao.V1CardAppleHiddenSettings.Columns().Id, id).
		Increment(dao.V1CardAppleHiddenSettings.Columns().StealTotalAmount, amount)
	return
}
