package com.ruoyi.job;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyl.manager.oms.domain.Order;
import com.cyl.manager.oms.mapper.OrderMapper;
import com.cyl.manager.ums.domain.Member;
import com.cyl.manager.ums.mapper.MemberMapper;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.domain.AppletConfig;
import com.ruoyi.model.service.IAppUsersService;
import com.ruoyi.model.service.IAppletConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.List;

/**
 * 合伙人等级检查定时任务
 * 每月检查合伙人是否达到保段要求，未达标则降级
 * 
 * @author system
 */
@Component
@Slf4j
public class PartnerLevelCheckJob {

    @Autowired
    private IAppUsersService appUsersService;
    
    @Autowired
    private IAppletConfigService appletConfigService;
    
    @Autowired
    private MemberMapper memberMapper;
    
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 每月1号凌晨3点执行合伙人等级检查
     * 检查上个月的数据是否达到保段要求
     */
    @Async
    @Scheduled(cron = "0 0 3 1 * ?")
    public void checkPartnerLevel() {
        log.info("定时任务[合伙人等级检查]开始执行");
        
        try {
            // 获取所有合伙人用户（userHh = 1 且 userHhRole > 0）
            List<AppUsers> partners = appUsersService.list(
                Wrappers.<AppUsers>lambdaQuery()
                    .eq(AppUsers::getUserHh, 1)
                    .gt(AppUsers::getUserHhRole, 0)
            );
            
            if (partners.isEmpty()) {
                log.info("当前没有合伙人用户需要检查");
                return;
            }
            
            // 获取上个月的时间范围
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime lastMonthStart = now.minusMonths(1)
                .with(TemporalAdjusters.firstDayOfMonth())
                .withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime lastMonthEnd = now.minusMonths(1)
                .with(TemporalAdjusters.lastDayOfMonth())
                .withHour(23).withMinute(59).withSecond(59);
            
            int totalChecked = 0;
            int totalDowngraded = 0;
            
            for (AppUsers partner : partners) {
                totalChecked++;
                
                // 获取当前等级的保段要求
                AppletConfig currentLevelConfig = appletConfigService.getOne(
                    Wrappers.<AppletConfig>lambdaQuery()
                        .eq(AppletConfig::getParamClass, "pet_payment_hh")
                        .eq(AppletConfig::getParamValueNum, partner.getUserHhRole())
                );
                
                if (currentLevelConfig == null) {
                    log.warn("合伙人用户ID: {} 的等级配置不存在，跳过检查", partner.getUserId());
                    continue;
                }
                
                // 获取保段要求
                Integer keepUserNum = currentLevelConfig.getKeepUserNum(); // 保段注册人数
                Integer keepOrderUserNum = currentLevelConfig.getKeepOrderUserNum(); // 保段下单人数
                
                if (keepUserNum == null || keepOrderUserNum == null) {
                    log.warn("合伙人用户ID: {} 的等级保段要求未配置，跳过检查", partner.getUserId());
                    continue;
                }
                
                // 获取用户邀请码
                String invitationCode = appUsersService.getUserCode(partner.getUserId());
                
                // 统计上个月通过邀请码注册的用户数
                Integer monthRegisterUsers = memberMapper.selectCount(
                    Wrappers.<Member>lambdaQuery()
                        .eq(Member::getInviteCode, invitationCode)
                        .ge(Member::getCreateTime, lastMonthStart)
                        .le(Member::getCreateTime, lastMonthEnd)
                );
                
                // 获取通过邀请码注册的所有用户ID列表
                List<Member> invitedMembers = memberMapper.selectList(
                    Wrappers.<Member>lambdaQuery()
                        .select(Member::getId)
                        .eq(Member::getInviteCode, invitationCode)
                );
                
                List<Long> memberIds = new ArrayList<>();
                for (Member member : invitedMembers) {
                    memberIds.add(member.getId());
                }
                
                // 统计上个月下单用户数（排除待支付和已关闭订单）
                Integer monthOrderUsers = 0;
                if (!memberIds.isEmpty()) {
                    List<Order> monthOrderList = orderMapper.selectList(
                        Wrappers.<Order>lambdaQuery()
                            .select(Order::getMemberId)
                            .in(Order::getMemberId, memberIds)
                            .notIn(Order::getStatus, 0, 4) // 排除待支付和已关闭订单
                            .ge(Order::getCreateTime, lastMonthStart)
                            .le(Order::getCreateTime, lastMonthEnd)
                            .groupBy(Order::getMemberId)
                    );
                    monthOrderUsers = monthOrderList.size();
                }
                
                // 检查是否达到保段要求
                boolean meetRequirement = monthRegisterUsers >= keepUserNum && monthOrderUsers >= keepOrderUserNum;
                
                log.info("合伙人用户ID: {}, 当前等级: {}, 上月注册用户: {}/{}, 上月下单用户: {}/{}, 是否达标: {}", 
                    partner.getUserId(), partner.getUserHhRole(), 
                    monthRegisterUsers, keepUserNum, 
                    monthOrderUsers, keepOrderUserNum, 
                    meetRequirement);
                
                // 如果未达到保段要求，则降级
                if (!meetRequirement && partner.getUserHhRole() > 0) {
                    int newLevel = partner.getUserHhRole() - 1;
                    
                    // 更新用户等级
                    boolean updateResult = appUsersService.lambdaUpdate()
                        .eq(AppUsers::getUserId, partner.getUserId())
                        .set(AppUsers::getUserHhRole, newLevel)
                        .update();
                    
                    if (updateResult) {
                        totalDowngraded++;
                        log.info("合伙人用户ID: {} 因未达保段要求，等级从 {} 降至 {}", 
                            partner.getUserId(), partner.getUserHhRole(), newLevel);
                    } else {
                        log.error("合伙人用户ID: {} 等级降级失败", partner.getUserId());
                    }
                } else if (!meetRequirement && partner.getUserHhRole() == 0) {
                    log.info("合伙人用户ID: {} 已是最低等级(0级)，无法继续降级", partner.getUserId());
                }
            }
            
            log.info("定时任务[合伙人等级检查]执行完成，共检查 {} 个合伙人，降级 {} 个", totalChecked, totalDowngraded);
            
        } catch (Exception e) {
            log.error("定时任务[合伙人等级检查]执行异常", e);
        }
    }
}