package com.ycwl.basic.pricing.service.impl;

import com.ycwl.basic.pricing.dto.CouponClaimRequest;
import com.ycwl.basic.pricing.entity.PriceCouponClaimRecord;
import com.ycwl.basic.pricing.entity.PriceCouponConfig;
import com.ycwl.basic.pricing.enums.ProductType;
import com.ycwl.basic.pricing.mapper.PriceCouponClaimRecordMapper;
import com.ycwl.basic.pricing.mapper.PriceCouponConfigMapper;
import com.ycwl.basic.pricing.service.IAutoCouponService;
import com.ycwl.basic.pricing.service.ICouponService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 自动发券服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AutoCouponServiceImpl implements IAutoCouponService {

    private final PriceCouponConfigMapper couponConfigMapper;
    private final PriceCouponClaimRecordMapper couponClaimRecordMapper;
    private final ICouponService couponService;

    @Override
    public boolean autoGrantCoupon(Long memberId, Long faceId, Long scenicId, ProductType productType) {
        try {
            // 1. 校验参数
            if (memberId == null || scenicId == null || productType == null) {
                log.warn("自动发券参数不完整: memberId={}, faceId={}, scenicId={}, productType={}",
                        memberId, faceId, scenicId, productType);
                return false;
            }

            // 2. 查找该景区、该商品类型的所有首次打印优惠券配置
            List<Long> couponIds = findFirstCouponIds(scenicId, productType);
            if (couponIds == null || couponIds.isEmpty()) {
                log.debug("景区未配置首次打印优惠券: scenicId={}, productType={}", scenicId, productType);
                return false;
            }

            log.info("找到{}张首次优惠券待发放: scenicId={}, productType={}, couponIds={}",
                    couponIds.size(), scenicId, productType, couponIds);

            // 3. 遍历所有优惠券，逐一检查并发放
            int successCount = 0;
            int skipCount = 0;
            int failCount = 0;

            for (Long couponId : couponIds) {
                try {
                    // 检查用户是否已领取过该券（领券即消耗首次资格）
                    List<PriceCouponClaimRecord> existingRecords = couponClaimRecordMapper.selectUserCouponRecords(
                            memberId,
                            couponId
                    );

                    if (existingRecords != null && !existingRecords.isEmpty()) {
                        // 只要有记录（无论状态），都算已领取过
                        PriceCouponClaimRecord existingRecord = existingRecords.get(0);
                        log.debug("用户已领取过优惠券，跳过: memberId={}, couponId={}, claimTime={}",
                                memberId, couponId, existingRecord.getClaimTime());
                        skipCount++;
                        continue;
                    }

                    // 自动发券
                    CouponClaimRequest request = new CouponClaimRequest(
                            memberId,
                            couponId,
                            scenicId.toString(),
                            "AUTO_GRANT"  // 标记为自动发券来源
                    );

                    couponService.claimCoupon(request);
                    successCount++;

                    log.info("成功自动发放首次优惠券: memberId={}, faceId={}, scenicId={}, productType={}, couponId={}",
                            memberId, faceId, scenicId, productType, couponId);

                } catch (Exception e) {
                    failCount++;
                    log.error("单张优惠券发放失败，继续处理其他券: memberId={}, couponId={}, error={}",
                            memberId, couponId, e.getMessage());
                }
            }

            log.info("自动发券完成: memberId={}, 成功{}张, 跳过{}张, 失败{}张",
                    memberId, successCount, skipCount, failCount);

            // 只要有一张成功就返回true
            return successCount > 0;

        } catch (Exception e) {
            log.error("自动发券失败: memberId={}, faceId={}, scenicId={}, productType={}",
                    memberId, faceId, scenicId, productType, e);
            return false;
        }
    }

    /**
     * 查找指定景区、指定商品类型的所有首次打印优惠券ID
     * 规则：优惠券名称包含 "首次" 且 适用商品类型包含目标类型
     *
     * @param scenicId 景区ID
     * @param productType 商品类型
     * @return 优惠券ID列表，未找到返回空列表
     */
    private List<Long> findFirstCouponIds(Long scenicId, ProductType productType) {
        List<Long> couponIds = new java.util.ArrayList<>();
        try {
            // 查询该景区的有效优惠券
            List<PriceCouponConfig> coupons = couponConfigMapper.selectValidCouponsByScenicId(
                    scenicId.toString()
            );

            for (PriceCouponConfig coupon : coupons) {
                // 检查优惠券名称是否包含"首次"关键字
                if (coupon.getCouponName() != null && (coupon.getCouponName().contains("首次"))) {

                    // 检查适用商品类型
                    String applicableProducts = coupon.getApplicableProducts();
                    if (applicableProducts != null &&
                            applicableProducts.contains(productType.getCode())) {
                        couponIds.add(coupon.getId());
                        log.debug("找到匹配的首次优惠券: couponId={}, couponName={}, scenicId={}, productType={}",
                                coupon.getId(), coupon.getCouponName(), scenicId, productType);
                    }
                }
            }

            if (couponIds.isEmpty()) {
                log.debug("未找到匹配的首次打印优惠券: scenicId={}, productType={}", scenicId, productType);
            }

            return couponIds;

        } catch (Exception e) {
            log.error("查找首次打印优惠券失败: scenicId={}, productType={}", scenicId, productType, e);
            return couponIds;
        }
    }
}
