package shop.alien.job.store;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import shop.alien.entity.store.*;
import shop.alien.mapper.*;
import shop.alien.util.common.constant.DiscountCouponEnum;
import shop.alien.util.type.LifeNoticeUtil;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 优惠券定时任务
 *
 * @author ssk
 * @version 1.0
 * @date 2025/8/6 14:19
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LifeCouponJob {

    private static final int HOURS_72_DAYS = 3;
    private static final int HOURS_24_DAYS = 1;
    private static final String RECEIVE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
    private final LifeDiscountCouponUserMapper lifeDiscountCouponUserMapper;
    private final LifeDiscountCouponMapper lifeDiscountCouponMapper;
    private final LifeUserMapper lifeUserMapper;
    private final LifeNoticeMapper lifeNoticeMapper;

    private final LifeNoticeUtil lifeNoticeUtil;
    private final StoreInfoMapper storeInfoMapper;

    /**
     * 优惠券即将到期提醒：查询 life_discount_coupon_user 表，若距离到期时间为 72 小时（3 天）或 24 小时（1 天），则给用户发送站内通知。
     */
    @XxlJob("couponExpiringNoticeJob")
    public void couponExpiringNotice() {
        LocalDate now = LocalDate.now();
        LocalDate expireIn3Days = now.plusDays(HOURS_72_DAYS);
        LocalDate expireIn1Day = now.plusDays(HOURS_24_DAYS);

        // 查询 72h(3天) 和 24h(1天) 后到期的、待使用的用户优惠券（仅优惠券，不含代金券）
        LambdaQueryWrapper<LifeDiscountCouponUser> wrapper = new LambdaQueryWrapper<LifeDiscountCouponUser>()
                .eq(LifeDiscountCouponUser::getStatus, Integer.parseInt(DiscountCouponEnum.WAITING_USED.getValue()))
                .isNotNull(LifeDiscountCouponUser::getCouponId)
                .in(LifeDiscountCouponUser::getExpirationTime, expireIn1Day, expireIn3Days);

        List<LifeDiscountCouponUser> userCoupons = lifeDiscountCouponUserMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(userCoupons)) {
            log.info("优惠券到期提醒: 无符合条件（72h/24h 内到期）的用户优惠券");
            return;
        }

        SimpleDateFormat receiveSdf = new SimpleDateFormat(RECEIVE_TIME_PATTERN);
        DateTimeFormatter expirationFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        int sendCount = 0;
        for (LifeDiscountCouponUser userCoupon : userCoupons) {
            try {
                LifeDiscountCoupon coupon = lifeDiscountCouponMapper.selectByIdIncludeDeleted(userCoupon.getCouponId());
                if (coupon == null) {
                    log.warn("优惠券不存在, couponId={}", userCoupon.getCouponId());
                    continue;
                }

                LifeUser user = lifeUserMapper.selectById(userCoupon.getUserId());
                if (user == null || !StringUtils.hasText(user.getUserPhone())) {
                    log.warn("用户不存在或手机号为空, userId={}", userCoupon.getUserId());
                    continue;
                }

                String storeName = "未知店铺";
                if (StringUtils.hasText(coupon.getStoreId())) {
                    try {
                        StoreInfo store = storeInfoMapper.selectById(Integer.parseInt(coupon.getStoreId().trim()));
                        if (store != null && StringUtils.hasText(store.getStoreName())) {
                            storeName = store.getStoreName();
                        }
                    } catch (NumberFormatException e) {
                        log.debug("优惠券 storeId 非数字, couponId={}, storeId={}", coupon.getId(), coupon.getStoreId());
                    }
                }

                String receiveTimeStr = userCoupon.getReceiveTime() != null
                        ? receiveSdf.format(userCoupon.getReceiveTime())
                        : "";

                String expirationTimeStr = userCoupon.getExpirationTime() != null
                        ? userCoupon.getExpirationTime().format(expirationFormatter) + " 23:59:59"
                        : "";

                String amountDesc = coupon.getNominalValue() != null && coupon.getNominalValue().compareTo(BigDecimal.ZERO) > 0
                        ? coupon.getNominalValue().intValue() + "元"
                        : "优惠";
                String couponName = StringUtils.hasText(coupon.getName()) ? coupon.getName() : "优惠券";

                String context = String.format(
                        "您在%s领取的%s店铺的%s优惠券(%s)；在%s到期，可在我的券包中查看，快去使用吧",
                        receiveTimeStr,
                        storeName,
                        amountDesc,
                        couponName,
                        expirationTimeStr
                );

                LifeNotice notice = new LifeNotice();
                notice.setSenderId("system");
                notice.setReceiverId("user_" + user.getUserPhone());
                notice.setContext(context);
                notice.setTitle("优惠券即将到期");
                notice.setIsRead(0);
                notice.setNoticeType(2);
                lifeNoticeUtil.fillUserTypeAndRefId(notice);
                lifeNoticeMapper.insert(notice);
                sendCount++;
            } catch (Exception e) {
                log.error("优惠券到期提醒发送失败, userCouponId={}, userId={}", userCoupon.getId(), userCoupon.getUserId(), e);
            }
        }

        log.info("优惠券到期提醒: 共处理 {} 条, 成功发送 {} 条通知", userCoupons.size(), sendCount);
    }
}
