package com.jeesharp.business.modules.setting.application.support;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jeesharp.business.modules.coupon.entity.CouponTemplate;
import com.jeesharp.business.modules.coupon.enums.CouponDiscountTypeEnum;
import com.jeesharp.business.modules.coupon.enums.CouponTemplateStatusEnum;
import com.jeesharp.business.modules.coupon.enums.CouponTemplateTypeEnum;
import com.jeesharp.business.modules.coupon.service.CouponTemplateService;
import com.jeesharp.business.modules.setting.dto.OperationPopupExtConfigDTO;
import com.jeesharp.business.modules.setting.enums.OperationPopupDisplayModeEnum;
import com.jeesharp.business.modules.setting.vo.OperationPopupClientCouponItemVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 首页弹窗券包模式：按模板 ID 组装 C 端券列表。
 */
@Component
@RequiredArgsConstructor
public class OperationPopupCouponPackSupport {

    private final CouponTemplateService couponTemplateService;

    public OperationPopupExtConfigDTO parseExtConfig(String extConfigJson) {
        if (StrUtil.isBlank(extConfigJson)) {
            return new OperationPopupExtConfigDTO();
        }
        try {
            return JSONUtil.toBean(extConfigJson, OperationPopupExtConfigDTO.class);
        } catch (Exception ex) {
            return new OperationPopupExtConfigDTO();
        }
    }

    public String normalizeExtConfigJson(String extConfigJson) {
        OperationPopupExtConfigDTO dto = parseExtConfig(extConfigJson);
        if (dto.getMaxShow() == null || dto.getMaxShow() < 1) {
            dto.setMaxShow(2);
        }
        if (dto.getMaxShow() > 5) {
            dto.setMaxShow(5);
        }
        return JSONUtil.toJsonStr(dto);
    }

    public List<OperationPopupClientCouponItemVO> buildCouponItems(
            OperationPopupDisplayModeEnum mode,
            String extConfigJson,
            String defaultLinkPath) {
        if (mode != OperationPopupDisplayModeEnum.COUPON_PACK) {
            return Collections.emptyList();
        }
        OperationPopupExtConfigDTO ext = parseExtConfig(extConfigJson);
        List<String> templateIds = ext.getTemplateIds();
        if (templateIds == null || templateIds.isEmpty()) {
            return Collections.emptyList();
        }
        int maxShow = ext.getMaxShow() != null && ext.getMaxShow() > 0 ? ext.getMaxShow() : 2;
        List<OperationPopupClientCouponItemVO> out = new ArrayList<>();
        for (String templateId : templateIds) {
            if (out.size() >= maxShow) {
                break;
            }
            if (StrUtil.isBlank(templateId)) {
                continue;
            }
            CouponTemplate template = couponTemplateService.get(templateId.trim());
            if (template == null) {
                continue;
            }
            if (template.getStatus() != null
                    && !CouponTemplateStatusEnum.IN_PROGRESS.getValue().equals(template.getStatus())) {
                continue;
            }
            OperationPopupClientCouponItemVO item = new OperationPopupClientCouponItemVO();
            item.setId(template.getId());
            item.setFace(formatFace(template));
            item.setName(StrUtil.blankToDefault(template.getCouponName(), "优惠券"));
            item.setThreshold(formatThreshold(template));
            item.setExpireDays(resolveExpireDays(template));
            item.setLinkPath(resolveCouponLink(template, defaultLinkPath));
            out.add(item);
        }
        return out;
    }

    private static String resolveCouponLink(CouponTemplate template, String defaultLinkPath) {
        if (StrUtil.isNotBlank(defaultLinkPath)) {
            return defaultLinkPath;
        }
        return "/package-views/pages/coupon/index";
    }

    private static Integer resolveExpireDays(CouponTemplate template) {
        LocalDateTime end = null;
        if (template.getValidityType() != null && template.getValidityType() == 1) {
            end = template.getValidEndDate();
        } else if (template.getValidDays() != null && template.getValidDays() > 0) {
            return template.getValidDays();
        }
        if (end == null) {
            end = template.getGetEndDate();
        }
        if (end == null) {
            return null;
        }
        long days = ChronoUnit.DAYS.between(LocalDateTime.now(), end);
        return (int) Math.max(days, 0);
    }

    private static String formatThreshold(CouponTemplate template) {
        BigDecimal min = template.getMinConsumeAmount();
        if (min != null && min.compareTo(BigDecimal.ZERO) > 0) {
            return "满" + stripTrailingZero(min) + "元可用";
        }
        Integer type = template.getCouponType();
        if (type != null && CouponTemplateTypeEnum.NO_THRESHOLD.getValue().equals(type)) {
            return "无门槛";
        }
        return "详见券面说明";
    }

    private static String formatFace(CouponTemplate template) {
        Integer discountType = template.getDiscountType();
        BigDecimal value = template.getDiscountValue();
        if (value == null) {
            return "优惠";
        }
        if (discountType != null && CouponDiscountTypeEnum.RATE.getValue().equals(discountType)) {
            return stripTrailingZero(value) + "折";
        }
        return "¥" + stripTrailingZero(value);
    }

    private static String stripTrailingZero(BigDecimal value) {
        return value.setScale(2, RoundingMode.HALF_UP).stripTrailingZeros().toPlainString();
    }
}
