package com.rj.scheduler;

import com.rj.config.AppConfig;
import com.rj.config.HxrAdminProperties;
import com.rj.service.HxrAdminOrderSelectService;
import com.rj.service.ILbOrderRowService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

import java.time.Clock;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * hxrd 后台订单列表定时拉取：每 50 分钟触发一次，仅工作日（周一至周五）且在每天 18:10～23:59:59（应用时区）内真正执行。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class LBAdminPullScheduler {

    private static final long FIFTY_MINUTES_MS = 30L * 60L * 1000L;
    private static final long UnPay_MINUTES_MS = 20L * 60L * 1000L;

    private static final DateTimeFormatter BUY_TIME_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final AppConfig appConfig;
    private final HxrAdminProperties hxrAdminProperties;
    private final HxrAdminOrderSelectService hxrAdminOrderSelectService;
    private final ILbOrderRowService lbOrderRowService;
    private final Clock clock;

    @Scheduled(
            fixedRate = FIFTY_MINUTES_MS,
            initialDelayString = "${hxr.admin.pull-initial-delay-ms:0}")
    public void pullAdminOrders() {
        try {
            if (!appConfig.getScheduler().isStart()) {
                log.debug("全局调度未启用，跳过 未寄卖 订单拉取");
                return;
            }
            if (!hxrAdminProperties.isEnabled()) {
                log.debug("hxr.admin.enabled=false，跳过订单拉取");
                return;
            }
            ZoneId zone = ZoneId.of(appConfig.getTimezone());
            ZonedDateTime nowZdt = ZonedDateTime.now(clock.withZone(zone));
            DayOfWeek dow = nowZdt.getDayOfWeek();
            if (dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY) {
                log.debug("当前为周末 {}，跳过 未寄卖 订单拉取", dow);
                return;
            }
            LocalTime now = nowZdt.toLocalTime();
            LocalTime windowStart = LocalTime.of(18, 10);
            LocalTime windowEnd = LocalTime.of(23, 59, 59);
            if (now.isBefore(windowStart) || now.isAfter(windowEnd)) {
                log.debug("当前时刻 {} 不在窗口 {}～{}，跳过 未寄卖 订单拉取", now, windowStart, windowEnd);
                return;
            }

            log.info("开始执行 未寄卖 订单拉取（工作日 18:10～23:59:59 窗口内）");
            hxrAdminOrderSelectService.fetchAndLogEachOrder();
        } catch (Exception e) {
            log.error("未寄卖 admin 订单拉取失败", e);
        }
    }

    private static final int HXR_ORDER_STATUS_UNPAID = 0;
    private static final int HXR_ORDER_STATUS_PAID = 1;

    /**
     * 未支付/已支付订单同步：工作日每天 11:00～15:00（应用时区），仅在窗口内真正执行。
     */
//    @Scheduled(
//            fixedRate = UnPay_MINUTES_MS,
//            initialDelayString = "${hxr.admin.pull-initial-delay-ms:0}")
    public void pullOrdersForUnPay() {
        try {
            if (!appConfig.getScheduler().isStart()) {
                log.debug("全局调度未启用，跳过 未支付 订单拉取");
                return;
            }
            if (!hxrAdminProperties.isEnabled()) {
                log.debug("hxr.admin.enabled=false，跳过订单拉取");
                return;
            }
            ZoneId zone = ZoneId.of(appConfig.getTimezone());
            ZonedDateTime nowZdt = ZonedDateTime.now(clock.withZone(zone));
            DayOfWeek dow = nowZdt.getDayOfWeek();
            if (dow == DayOfWeek.SATURDAY || dow == DayOfWeek.SUNDAY) {
                log.debug("当前为周末 {}，跳过 未支付 订单拉取", dow);
                return;
            }
            LocalTime now = nowZdt.toLocalTime();
            LocalTime windowStart = LocalTime.of(11, 0);
            LocalTime windowEnd = LocalTime.of(15, 0);
            if (now.isBefore(windowStart) || now.isAfter(windowEnd)) {
                log.debug("当前时刻 {} 不在窗口 {}～{}，跳过 未支付 订单拉取", now, windowStart, windowEnd);
                return;
            }

            String tenantId = hxrAdminProperties.getSyncTenantId();
            if (tenantId == null || tenantId.isBlank()) {
                log.warn("hxr.admin.sync-tenant-id 未配置，跳过订单状态同步");
                return;
            }

            LocalDate today = nowZdt.toLocalDate();
            String buyTimeStart = today.atStartOfDay().format(BUY_TIME_FMT);
            String buyTimeEnd = today.atTime(23, 59, 59).format(BUY_TIME_FMT);
            String tid = tenantId.trim();

            syncOrdersByHxrStatus(tid, buyTimeStart, buyTimeEnd, HXR_ORDER_STATUS_UNPAID, "未支付");
            syncOrdersByHxrStatus(tid, buyTimeStart, buyTimeEnd, HXR_ORDER_STATUS_PAID, "已支付");
        } catch (Exception e) {
            log.error("订单状态同步失败", e);
        }
    }

    private void syncOrdersByHxrStatus(
            String tenantId, String buyTimeStart, String buyTimeEnd, int hxrOrderStatus, String label) {
        log.info(
                "开始执行 {} 订单同步 status={} tenantId={} buyTime={}～{}",
                label,
                hxrOrderStatus,
                tenantId,
                buyTimeStart,
                buyTimeEnd);
        Map<String, Object> syncResult =
                lbOrderRowService.syncFromHxrAdmin(buyTimeStart, buyTimeEnd, tenantId, null, hxrOrderStatus);
        if (Boolean.TRUE.equals(syncResult.get("success"))) {
            log.info(
                    "{}订单同步完成 synced={} remoteCount={}",
                    label,
                    syncResult.get("synced"),
                    syncResult.get("remoteCount"));
        } else {
            log.warn("{}订单同步失败: {}", label, syncResult.get("message"));
        }
    }


}
