package com.cyksj.service.giftcard.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cyksj.mapper.GiftCardOrderUseRecordMapper;
import com.cyksj.mapper.GiftCardUserRecordMapper;
import com.cyksj.model.entity.GiftCardOrderUseRecord;
import com.cyksj.model.entity.GiftCardUserRecord;
import com.cyksj.service.giftcard.GiftCardOrderUseRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/*
 *项目名: netflix
 *文件名: GiftCardOrderUseRecordServiceImpl
 *创建者: JavaZou
 *创建时间:2023/8/29 16:44
 */
@Service
@RequiredArgsConstructor
public class GiftCardOrderUseRecordServiceImpl extends ServiceImpl<GiftCardOrderUseRecordMapper, GiftCardOrderUseRecord> implements GiftCardOrderUseRecordService {
	private final GiftCardUserRecordMapper giftCardUserRecordMapper;

	@Override
	public void returnGiftCardCash(Long orderId) {
		List<GiftCardOrderUseRecord> useRecords = this.list(Wrappers.lambdaQuery(GiftCardOrderUseRecord.class)
				.eq(GiftCardOrderUseRecord::getOrderId, orderId));
		if (CollUtil.isNotEmpty(useRecords)) {
			useRecords.forEach(data -> {
				while (true) {
					Long gcId = data.getGcId();
					BigDecimal addCash = data.getCash();
					GiftCardUserRecord giftCardUserRecord = giftCardUserRecordMapper.selectById(gcId);
					BigDecimal remainCash = giftCardUserRecord.getRemainCash();
					Integer update = giftCardUserRecordMapper.updateGiftCardRemainCash(gcId, addCash, remainCash);
					if (update > 0) {
						break;
					}
				}
			});
		}
	}
}
