package com.ruoyi.model.service.impl;

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.cyl.manager.ums.pojo.query.MemberQuery;
import com.cyl.manager.ums.pojo.vo.MemberDataStatisticsVO;
import com.cyl.manager.ums.pojo.vo.MemberExtendVo;
import com.cyl.manager.ums.service.MemberService;
import com.ruoyi.applet.utils.conf.AppletUtil;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.model.domain.AppUsers;
import com.ruoyi.model.domain.AppletAmountLog;
import com.ruoyi.model.domain.AppletConfig;
import com.ruoyi.model.service.IAApiAppletHhrWorkOutService;
import com.ruoyi.model.service.IAppUsersService;
import com.ruoyi.model.service.IAppletAmountLogService;
import com.ruoyi.model.service.IAppletConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AApiAppletHhrWorkOutServiceImpl implements IAApiAppletHhrWorkOutService {

    @Resource
    private IAppUsersService appUsersService;
    @Resource
    private TokenService tokenService;
    @Resource
    private IAppletConfigService appletConfigService;

    @Resource
    private MemberService memberService;
    
    @Resource
    private MemberMapper memberMapper;
    
    @Resource
    private OrderMapper orderMapper;
    
    @Resource
    private IAppletAmountLogService appletAmountLogService;

    //合伙人工作台 - 绑定用户基础信息
    @Override
    public AjaxResult HhrInfo(Long appUserId){
//      AppUsers localAppletUser = AppletUtil.getLocalAppletUser();
        AppUsers localAppletUser = new AppUsers();
        localAppletUser.setUserId(appUserId);
        AppUsers appUsers = appUsersService.selectAppUsersByUserId(localAppletUser.getUserId());

        Map<String,Object> map = new HashMap<>();
        map.put("info",appUsers); //用户信息

        // 计算合伙人入住时间
        String partnerTime = "0分钟";
        if (appUsers.getCreateTime() != null) {
            LocalDateTime createTime = appUsers.getCreateTime();
            LocalDateTime now = LocalDateTime.now();
            long days = ChronoUnit.DAYS.between(createTime, now);
            
            if (days > 0) {
                partnerTime = days + "天";
            } else {
                long hours = ChronoUnit.HOURS.between(createTime, now);
                if (hours > 0) {
                    partnerTime = hours + "小时";
                } else {
                    long minutes = ChronoUnit.MINUTES.between(createTime, now);
                    if (minutes > 0) {
                        partnerTime = minutes + "分钟";
                    } else {
                        long seconds = ChronoUnit.SECONDS.between(createTime, now);
                        if (seconds > 0) {
                            partnerTime = seconds + "秒";
                        } else {
                            partnerTime = "刚刚加入";
                        }
                    }
                }
            }
        }
        map.put("partner_day", partnerTime); //合伙人加入时间

        AppletConfig petPaymentHh = appletConfigService.selectAppletConfigByClassAndNum("pet_payment_hh", appUsers.getUserHhRole());

        if (petPaymentHh != null){
            map.put("partner_new_num",petPaymentHh.getParamValueText()); //合伙人当前合伙人比例
            map.put("partner_new_image",petPaymentHh.getParamValueImage()); //合伙人当前合伙人比例
            map.put("partner_level", petPaymentHh.getParamValue()); //合伙人等级
        }else {
//            map.put("partner_new_num", 0); //合伙人当前合伙人比例
        }

        AppletConfig partner_upgrade_num = appletConfigService.selectAppletConfigByClassAndNum("pet_payment_hh", appUsers.getUserHhRole()+1);

        if (partner_upgrade_num != null){
            map.put("partner_upgrade_num", partner_upgrade_num.getParamValueText()); //合伙人晋级之后的合伙人比例
        }else {
//            map.put("partner_upgrade_num", -1); //合伙人晋级之后的合伙人比例
        }

        map.put("user_code", appUsersService.getUserCode(appUserId)); //邀请码
        map.put("level_list", appletConfigService.lambdaQuery().eq(AppletConfig::getParamClass, "pet_payment_hh").list()); //等级列表
        map.put("user_code_bj","https://image.hhlm1688.com/img/work/log/indexInfo/11.png"); //邀请码背景图
        map.put("user_code_fx","https://image.hhlm1688.com/img/work/log/indexInfo/11.png"); //分享海报背景图
        map.put("user_code_url","https://image.hhlm1688.com/img/work/log/indexInfo/11.png"); //分销链接背景图



        map.put("upgrade_register_num","5"); //距离下一个等级需要注册多少人
        map.put("upgrade_order_num","20"); //距离下一个等级需要下单人数
        map.put("upgrade_image","https://image.hhlm1688.com/img/work/log/indexInfo/11.png"); //背景图
        map.put("upgrade_details","合伙人权益说明：富文本"); //合伙人权益说明：富文本



        map.put("user_details","*累计报酬:当该用户订单完成时，才会纳入报酬计算：这是一个富文本"); //我的用户说明
        map.put("level_details","累积数据:即注册至今的累计数据:这是一个富文本"); //我的等级说明
        map.put("withdrawal_details","提现说明:这是一个富文本提现说明:这是一个富文本提现说明:这是一个富文本提现说明:这是一个富文本"); //提现说明



        // 获取用户邀请码
        String invitationCode = appUsersService.getUserCode(appUserId);

//        List<Long> memberIds = memberMapper.selectList(Wrappers.<Member>lambdaQuery()
//                        .select(Member::getId)
//                        .eq(Member::getInviteCode, invitationCode))
//                .stream().map(n -> n.getId())
//                .collect(Collectors.toList());
        
        // 获取当月开始和结束时间
        LocalDateTime monthStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime monthEnd = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
        
        // 统计当月注册用户（通过邀请码注册的用户）
        Integer monthRegisterUsers = memberMapper.selectCount(
            Wrappers.<Member>lambdaQuery()
                .eq(Member::getInviteCode, invitationCode)
                .ge(Member::getCreateTime, monthStart)
                .le(Member::getCreateTime, monthEnd)
        );
        
        // 统计累积注册用户
        Integer totalRegisterUsers = memberMapper.selectCount(
            Wrappers.<Member>lambdaQuery()
                .eq(Member::getInviteCode, invitationCode)
        );
        
        // 获取通过邀请码注册的所有用户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;
        BigDecimal monthOrderMoney = BigDecimal.ZERO;
        if (!memberIds.isEmpty()) {
            // 获取当月下单的唯一用户ID列表
            List<Order> monthOrderList = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getMemberId)
                    .in(Order::getMemberId, memberIds)
                    .notIn(Order::getStatus, 0, 4) // 排除待支付和已关闭订单
                    .ge(Order::getCreateTime, monthStart)
                    .le(Order::getCreateTime, monthEnd)
                    .groupBy(Order::getMemberId)
            );
            monthOrderUsers = monthOrderList.size();
            
            // 统计当月订单金额
            List<Order> monthOrders = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getPayAmount)
                    .in(Order::getMemberId, memberIds)
                    .notIn(Order::getStatus, 0, 4) // 排除待支付和已关闭订单
                    .ge(Order::getCreateTime, monthStart)
                    .le(Order::getCreateTime, monthEnd)
            );
            
            for (Order order : monthOrders) {
                if (order.getPayAmount() != null) {
                    monthOrderMoney = monthOrderMoney.add(order.getPayAmount());
                }
            }
        }
        
        // 统计累积下单用户
        Integer totalOrderUsers = 0;
        BigDecimal totalOrderMoney = BigDecimal.ZERO;
        if (!memberIds.isEmpty()) {
            // 获取累积下单的唯一用户ID列表
            List<Order> totalOrderList = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getMemberId)
                    .in(Order::getMemberId, memberIds)
                    .notIn(Order::getStatus, 0, 4) // 排除待支付和已关闭订单
                    .groupBy(Order::getMemberId)
            );
            totalOrderUsers = totalOrderList.size();
            
            // 统计累积订单金额
            List<Order> totalOrders = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getPayAmount)
                    .in(Order::getMemberId, memberIds)
                    .notIn(Order::getStatus, 0, 4) // 排除待支付和已关闭订单
            );
            
            for (Order order : totalOrders) {
                if (order.getPayAmount() != null) {
                    totalOrderMoney = totalOrderMoney.add(order.getPayAmount());
                }
            }
        }
        
        // 统计当月有效用户（已完成订单的用户）
        Integer monthValidUsers = 0;
        BigDecimal monthValidMoney = BigDecimal.ZERO;
        if (!memberIds.isEmpty()) {
            // 获取当月有效订单的唯一用户ID列表
            List<Order> monthValidUserList = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getMemberId)
                    .in(Order::getMemberId, memberIds)
                    .eq(Order::getStatus, 3) // 已完成状态
                    .ge(Order::getCreateTime, monthStart)
                    .le(Order::getCreateTime, monthEnd)
                    .groupBy(Order::getMemberId)
            );
            monthValidUsers = monthValidUserList.size();
            
            // 统计当月有效订单金额
            List<Order> monthValidOrders = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getPayAmount)
                    .in(Order::getMemberId, memberIds)
                    .eq(Order::getStatus, 3)
                    .ge(Order::getCreateTime, monthStart)
                    .le(Order::getCreateTime, monthEnd)
            );
            
            for (Order order : monthValidOrders) {
                if (order.getPayAmount() != null) {
                    monthValidMoney = monthValidMoney.add(order.getPayAmount());
                }
            }
        }
        
        // 统计累积有效用户
        Integer totalValidUsers = 0;
        BigDecimal totalValidMoney = BigDecimal.ZERO;
        if (!memberIds.isEmpty()) {
            // 获取累积有效订单的唯一用户ID列表
            List<Order> totalValidUserList = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getMemberId)
                    .in(Order::getMemberId, memberIds)
                    .eq(Order::getStatus, 3)
                    .groupBy(Order::getMemberId)
            );
            totalValidUsers = totalValidUserList.size();
            
            // 统计累积有效订单金额
            List<Order> totalValidOrders = orderMapper.selectList(
                Wrappers.<Order>lambdaQuery()
                    .select(Order::getPayAmount)
                    .in(Order::getMemberId, memberIds)
                    .eq(Order::getStatus, 3)
            );
            
            for (Order order : totalValidOrders) {
                if (order.getPayAmount() != null) {
                    totalValidMoney = totalValidMoney.add(order.getPayAmount());
                }
            }
        }
        
        // 统计当月分成收入
        List<AppletAmountLog> monthIncomes = appletAmountLogService.list(
            Wrappers.<AppletAmountLog>lambdaQuery()
                .eq(AppletAmountLog::getUserId, appUserId)
                .eq(AppletAmountLog::getType, 0) // 收入
                .eq(AppletAmountLog::getMoneyType, 0) // 合伙人余额
                .ge(AppletAmountLog::getCreateTime, monthStart)
                .le(AppletAmountLog::getCreateTime, monthEnd)
        );
        
        BigDecimal monthIncome = monthIncomes.stream()
            .map(AppletAmountLog::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);
        
        // 统计累积分成收入
        List<AppletAmountLog> totalIncomes = appletAmountLogService.list(
            Wrappers.<AppletAmountLog>lambdaQuery()
                .eq(AppletAmountLog::getUserId, appUserId)
                .eq(AppletAmountLog::getType, 0) // 收入
                .eq(AppletAmountLog::getMoneyType, 0) // 合伙人余额
        );
        
        BigDecimal totalIncome = totalIncomes.stream()
            .map(AppletAmountLog::getAmount)
            .reduce(BigDecimal.ZERO, BigDecimal::add);

        map.put("register_users", monthRegisterUsers); //当月注册用户
        map.put("order_users", monthOrderUsers); //当月下单用户
        map.put("use_users", monthValidUsers); //当月有效用户

        map.put("order_users_money", monthOrderMoney); //本月订单金额
        map.put("use_users_money", monthValidMoney); //本月有效订单金额

        map.put("register_users_sum", totalRegisterUsers); //累积注册用户
        map.put("order_users_sum", totalOrderUsers); //累积下单用户
        map.put("use_users_sum", totalValidUsers); //累积有效用户

        map.put("order_users_sum_money", totalOrderMoney); //累积订单金额
        map.put("use_users_sum_money", totalValidMoney); //累积有效订单金额

        map.put("money", appUsers.getMoney()); //钱包金额
        map.put("new_money", monthIncome); //本月分成
        map.put("old_money", totalIncome); //累积分成



        return  AjaxResult.success(map);
    }



    //合伙人工作台 - 绑定二维码
    @Override
    public AjaxResult HhrCode(Long appUserId){
        AppUsers localAppletUser = new AppUsers();
        localAppletUser.setUserId(appUserId);
        AppUsers appUsers = appUsersService.selectAppUsersByUserId(localAppletUser.getUserId());

        Map<String,Object> map = new HashMap<>();
        map.put("code",appUsers.getInvitationCode());//邀请码





        List<AppletConfig> appletConfigs = appletConfigService.selectAppletConfigList(null);
        for (AppletConfig appletConfig : appletConfigs){
            if(appletConfig.getParamCode().equals("background_poster")){
                map.put("bj_url",appletConfig.getParamValueImage());//海报背景图
            }
            if(appletConfig.getParamCode().equals("share_qr_url")){
                map.put("url",appletConfig.getParamValueImage());//二维码地址
            }
        }


        map.put("title","欢迎来到宠物小程序二维码");//说明

        return AjaxResult.success(map);
    }


    //合伙人工作台 - 我的用户列表 0 未下单 1已下单
    @Override
    public AjaxResult HhrMyUserList(Long appUserId,Integer state, Pageable page){
        AppUsers localAppletUser = new AppUsers();
        localAppletUser.setUserId(appUserId);
        List<AppUsers> pageRes = appUsersService.selectAppUsersList(new AppUsers());
//        memberService.selectList()
//        PageImpl<AppUsers> appUsers = new PageImpl<>(pageRes, page, ((Page) pageRes).getTotal());
        return AjaxResult.success("查询分页成功",pageRes);
    }




    //合伙人工作台 - 根据用户标识查询用户下单详细信息
    @Override
    public AjaxResult HhrMyUserGetById(Long appUserId){
        Map<String,Object> map = new HashMap<>();
        map.put("createTime",new Date());//注册时间
        map.put("recently_pay_time",new Date());//最近下单时间
        map.put("accumulate_money","9999.99");//海报背景图
        map.put("reward_money","100");//累积报酬
        return  AjaxResult.success("用户下单详细信息成功",map);
    }

    //合伙人等级升级检查
    @Override
    public AjaxResult checkPartnerUpgrade(Long appUserId) {
        try {
            // 获取用户信息
            AppUsers appUsers = appUsersService.selectAppUsersByUserId(appUserId);
            if (appUsers == null) {
                return AjaxResult.error("用户不存在");
            }
            
            // 检查是否为合伙人
            if (appUsers.getUserHh() == null || appUsers.getUserHh() != 1) {
                return AjaxResult.error("用户不是合伙人");
            }
            
            Integer currentLevel = appUsers.getUserHhRole();
            if (currentLevel == null) {
                currentLevel = 0;
            }
            
            // 获取下一个等级的配置
            AppletConfig nextLevelConfig = appletConfigService.getOne(
                Wrappers.<AppletConfig>lambdaQuery()
                    .eq(AppletConfig::getParamClass, "pet_payment_hh")
                    .eq(AppletConfig::getParamValueNum, currentLevel + 1)
            );
            
            if (nextLevelConfig == null) {
                return AjaxResult.success("已是最高等级，无法继续升级");
            }
            
            // 获取升级要求
            Integer needRegisterNum = nextLevelConfig.getParamCondition(); // 需要注册人数
            Integer needOrderUserNum = nextLevelConfig.getNeedOrderUserNum(); // 需要下单人数
            
            if (needRegisterNum == null || needOrderUserNum == null) {
                return AjaxResult.error("下一等级升级条件未配置");
            }
            
            // 获取当前等级的保段要求
            AppletConfig currentLevelConfig = appletConfigService.getOne(
                Wrappers.<AppletConfig>lambdaQuery()
                    .eq(AppletConfig::getParamClass, "pet_payment_hh")
                    .eq(AppletConfig::getParamValueNum, currentLevel)
            );
            
            Integer keepUserNum = 0;
            Integer keepOrderUserNum = 0;
            if (currentLevelConfig != null) {
                keepUserNum = currentLevelConfig.getKeepUserNum() != null ? currentLevelConfig.getKeepUserNum() : 0;
                keepOrderUserNum = currentLevelConfig.getKeepOrderUserNum() != null ? currentLevelConfig.getKeepOrderUserNum() : 0;
            }
            
            // 获取用户邀请码
            String invitationCode = appUsersService.getUserCode(appUserId);
            
            // 获取当月时间范围
            LocalDateTime monthStart = LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()).withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime monthEnd = LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth()).withHour(23).withMinute(59).withSecond(59);
            
            // 统计累积注册用户
            Integer totalRegisterUsers = memberMapper.selectCount(
                Wrappers.<Member>lambdaQuery()
                    .eq(Member::getInviteCode, invitationCode)
            );
            
            // 统计当月注册用户
            Integer monthRegisterUsers = memberMapper.selectCount(
                Wrappers.<Member>lambdaQuery()
                    .eq(Member::getInviteCode, invitationCode)
                    .ge(Member::getCreateTime, monthStart)
                    .le(Member::getCreateTime, monthEnd)
            );
            
            // 获取通过邀请码注册的所有用户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 totalOrderUsers = 0;
            Integer monthOrderUsers = 0;
            
            if (!memberIds.isEmpty()) {
                // 累积下单用户
                List<Order> totalOrderList = orderMapper.selectList(
                    Wrappers.<Order>lambdaQuery()
                        .select(Order::getMemberId)
                        .in(Order::getMemberId, memberIds)
                        .notIn(Order::getStatus, 0, 4) // 排除待支付和已关闭订单
                        .groupBy(Order::getMemberId)
                );
                totalOrderUsers = totalOrderList.size();
                
                // 当月下单用户
                List<Order> monthOrderList = orderMapper.selectList(
                    Wrappers.<Order>lambdaQuery()
                        .select(Order::getMemberId)
                        .in(Order::getMemberId, memberIds)
                        .notIn(Order::getStatus, 0, 4) // 排除待支付和已关闭订单
                        .ge(Order::getCreateTime, monthStart)
                        .le(Order::getCreateTime, monthEnd)
                        .groupBy(Order::getMemberId)
                );
                monthOrderUsers = monthOrderList.size();
            }
            
            // 检查升级条件（累计注册或累计下单达成其中一个条件即可）
            boolean meetUpgradeCondition = totalRegisterUsers >= needRegisterNum || totalOrderUsers >= needOrderUserNum;
            
            // 检查当月保段条件
            boolean meetMonthlyCondition = monthRegisterUsers >= keepUserNum && monthOrderUsers >= keepOrderUserNum;
            
            Map<String, Object> result = new HashMap<>();
            result.put("currentLevel", currentLevel);
            result.put("nextLevel", currentLevel + 1);
            result.put("totalRegisterUsers", totalRegisterUsers);
            result.put("needRegisterNum", needRegisterNum);
            result.put("totalOrderUsers", totalOrderUsers);
            result.put("needOrderUserNum", needOrderUserNum);
            result.put("monthRegisterUsers", monthRegisterUsers);
            result.put("keepUserNum", keepUserNum);
            result.put("monthOrderUsers", monthOrderUsers);
            result.put("keepOrderUserNum", keepOrderUserNum);
            result.put("meetUpgradeCondition", meetUpgradeCondition);
            result.put("meetMonthlyCondition", meetMonthlyCondition);
            
            // 如果同时满足升级条件和当月保段条件，则进行升级
            if (meetUpgradeCondition && meetMonthlyCondition) {
                boolean upgradeResult = appUsersService.lambdaUpdate()
                    .eq(AppUsers::getUserId, appUserId)
                    .set(AppUsers::getUserHhRole, currentLevel + 1)
                    .update();
                
                if (upgradeResult) {
                    result.put("upgraded", true);
                    result.put("message", "恭喜！等级升级成功，从等级" + currentLevel + "升至等级" + (currentLevel + 1));
                    log.info("合伙人用户ID: {} 升级成功，从等级 {} 升至等级 {}", appUserId, currentLevel, currentLevel + 1);
                } else {
                    result.put("upgraded", false);
                    result.put("message", "升级失败，请稍后重试");
                    log.error("合伙人用户ID: {} 升级失败", appUserId);
                }
            } else {
                result.put("upgraded", false);
                if (!meetUpgradeCondition && !meetMonthlyCondition) {
                    result.put("message", "未达到升级条件且当月未达保段要求");
                } else if (!meetUpgradeCondition) {
                    result.put("message", "累积数据未达到升级条件");
                } else {
                    result.put("message", "当月数据未达到保段要求");
                }
            }

            log.info("checkPartnerUpgrade 合伙人等级升级检查结果: {}", result);
            return AjaxResult.success("检查完成", result);
            
        } catch (Exception e) {
            log.error("合伙人等级升级检查异常，用户ID: {}", appUserId, e);
            return AjaxResult.error("检查异常: " + e.getMessage());
        }
    }

}
