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. 查找该景区、该商品类型的首次打印优惠券配置
            Long couponId = findFirstCouponId(scenicId, productType);
            if (couponId == null) {
                log.debug("景区未配置首次打印优惠券: scenicId={}, productType={}", scenicId, productType);
                return false;
            }

            // 3. 检查用户是否已领取过该券（领券即消耗首次资格）
            PriceCouponClaimRecord existingRecord = couponClaimRecordMapper.selectUserCouponRecord(
                    memberId,
                    couponId
            );

            if (existingRecord != null) {
                log.debug("用户已领取过首次优惠券，不重复发券: memberId={}, couponId={}, claimTime={}",
                        memberId, couponId, existingRecord.getClaimTime());
                return false;
            }

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

            couponService.claimCoupon(request);

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

            return true;

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

    /**
     * 查找指定景区、指定商品类型的首次打印优惠券ID
     * 规则：优惠券名称包含 "首次" 且 适用商品类型包含目标类型
     *
     * @param scenicId 景区ID
     * @param productType 商品类型
     * @return 优惠券ID，未找到返回null
     */
    private Long findFirstCouponId(Long scenicId, ProductType productType) {
        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())) {
                        return coupon.getId();
                    }
                }
            }

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

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