package com.storlead.sales.service.impl;

import com.storlead.framework.common.result.Result;
import com.storlead.sales.pojo.entity.report.DashboardSketchEntity;
import com.storlead.sales.pojo.vo.report.BroadcastCompanyVO;
import com.storlead.sales.pojo.vo.report.BroadcastDataVO;
import com.storlead.sales.pojo.vo.report.BroadcastPersonVO;
import com.storlead.sales.service.BroadcastDataService;
import com.storlead.sales.service.BroadcastMessageService;
import com.storlead.sales.mapper.BroadcastDataMapper;
import com.storlead.sales.service.DashboardSketchService;
import com.storlead.user.pojo.entity.CompanyEntity;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.service.ICompanyService;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IUserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.stream.Collectors;

@Log4j2
@Service
public class BroadcastDataServiceImpl implements BroadcastDataService {


    @Resource
    private BroadcastDataMapper broadcastDataMapper;
    @Resource
    private BroadcastMessageService assembleService;
    @Resource
    private ICompanyService companyService;
    @Resource
    private DashboardSketchService dashboardSketchService;
    @Resource
    private IUserService userService;
    @Resource
    private IDepartService departService;


    @Override
    public Result<?> sendChairData(Integer sketchType) {
        DateRange range = buildRange(sketchType);
        if (range == null) {
            return Result.error("无效的周期类型");
        }

        BroadcastCompanyVO companyVO = new BroadcastCompanyVO();

        // 查询各模块数据（sketchType=1表示按分公司统计）
        String startDateStr = formatDate(range.getStart());
        String endDateStr = formatDate(range.getEnd());
        List<BroadcastDataVO> customerList = broadcastDataMapper.customerList(startDateStr, endDateStr);
        List<BroadcastDataVO> businessList = broadcastDataMapper.busssniessList(startDateStr, endDateStr);
        List<BroadcastDataVO> orderList = broadcastDataMapper.orderList(startDateStr, endDateStr);
        List<BroadcastDataVO> orderAmountList = broadcastDataMapper.orderAmountList(startDateStr, endDateStr);
        List<BroadcastDataVO> leadList = broadcastDataMapper.leadList(startDateStr, endDateStr);
        List<BroadcastDataVO> followList = broadcastDataMapper.followList(startDateStr, endDateStr);
        List<BroadcastDataVO> mailList = broadcastDataMapper.mailList(startDateStr, endDateStr);

        // 设置明细数据
        companyVO.setBroadcastCustomerDates(customerList);
        companyVO.setBroadcastBusinessDates(businessList);
        companyVO.setBroadcastOrderDates(orderList);
        companyVO.setBroadcastOrderAmountDates(orderAmountList);
        companyVO.setBroadcastLeadDates(leadList);
        companyVO.setBroadcastFollowDates(followList);
        companyVO.setBroadcastMailDates(mailList);

        // 计算并设置总额
        companyVO.setTotalCustomerNum(calculateTotal(customerList));
        companyVO.setTotalBusinessNum(calculateTotal(businessList));
        companyVO.setTotalOrderNum(calculateTotal(orderList));
        companyVO.setTotalOrderAmount(calculateTotal(orderAmountList));
        companyVO.setTotalLeadNum(calculateTotal(leadList).intValue());
        companyVO.setTotalFollowNum(calculateTotal(followList).intValue());
        companyVO.setTotalMailNum(calculateTotal(mailList).intValue());

        // 设置记录产生时间和范围时间
        companyVO.setRecordTime(formatRecordTime(LocalDate.now()));
        companyVO.setRecordRangeTime(formatRecordRangeTime(range.getStart(), range.getEnd()));
        Set<Long> receivers = new HashSet<>();
        CompanyEntity company = companyService.getById(1);
        receivers.add(company.getManagerId());

        // 发送消息
        assembleService.sendCompanyDataReportMessages(sketchType, "CHAIR_DATA", receivers, companyVO);

        // 保存到dashboard_sketch表
        try {
            DashboardSketchEntity sketch = new DashboardSketchEntity();
            sketch.setOrganizationId(1L);
            sketch.setOrganizationName(company.getName());
            sketch.setSketchType(sketchType);
            sketch.setOrganizationType(40);
            LocalDate start = range.getStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            sketch.setYear(start.getYear());
            if (sketchType != 50) {
                sketch.setMonth(start.getMonthValue());
            }
            // cycle判断
            Integer cycle = computeCycle(start, sketchType);
            sketch.setCycle(cycle);
            sketch.setOrderAmount(companyVO.getTotalOrderAmount());
            sketch.setCustomerNewNum(companyVO.getTotalCustomerNum() == null ? 0 : companyVO.getTotalCustomerNum().intValue());
            sketch.setBusinessNewNum(companyVO.getTotalBusinessNum() == null ? 0 : companyVO.getTotalBusinessNum().intValue());
            sketch.setOrderNewNum(companyVO.getTotalOrderNum() == null ? 0 : companyVO.getTotalOrderNum().intValue());
            Map<String,Object> sketchMap = new HashMap<>();
            sketch.setLeadNewNum(companyVO.getTotalLeadNum());
            sketch.setFollowNewNum(companyVO.getTotalFollowNum());
            sketch.setMailNewNum(companyVO.getTotalMailNum());
            sketchMap.put("orderAmountTotal", companyVO.getTotalOrderAmount());
            sketchMap.put("orderAmountRecords", companyVO.getBroadcastOrderAmountDates());
            sketchMap.put("orderNumTotal", companyVO.getTotalOrderNum());
            sketchMap.put("orderNumRecords", companyVO.getBroadcastOrderDates());
            sketchMap.put("businessTotal", companyVO.getTotalBusinessNum());
            sketchMap.put("businessRecords", companyVO.getBroadcastBusinessDates());
            sketchMap.put("customerTotal", companyVO.getTotalCustomerNum());
            sketchMap.put("customerRecords", companyVO.getBroadcastCustomerDates());
            sketchMap.put("leadTotal", companyVO.getTotalLeadNum());
            sketchMap.put("leadRecords", companyVO.getBroadcastLeadDates());
            sketchMap.put("followTotal", companyVO.getTotalFollowNum());
            sketchMap.put("followRecords", companyVO.getBroadcastFollowDates());
            sketchMap.put("mailTotal", companyVO.getTotalMailNum());
            sketchMap.put("mailRecords", companyVO.getBroadcastMailDates());
            // 组织元数据
            sketchMap.put("organizationName", company.getName());
            sketchMap.put("sketchType", sketchType);
            sketchMap.put("year", start.getYear());
            if (sketchType != 50) {
                sketchMap.put("month", start.getMonthValue());
            }
            sketchMap.put("cycle", cycle);
            sketch.setSketchDataJson(com.alibaba.fastjson.JSON.toJSONString(sketchMap));
            dashboardSketchService.assembleData(sketch);
        } catch (Exception e) {
            log.error("保存dashboard数据失败", e);
        }

        return Result.result(companyVO);
    }

    @Override
    public Result<?> sendCeoData(Integer sketchType) {
        DateRange range = buildRange(sketchType);
        if (range == null) {
            return Result.error("无效的周期类型");
        }

        List<SubCompanyEntity> subCompanies = broadcastDataMapper.subCompanyList();
        if (subCompanies == null || subCompanies.isEmpty()) {
            return Result.result(true);
        }

        List<BroadcastCompanyVO> resultList = new ArrayList<>();
        for (SubCompanyEntity subCompany : subCompanies) {
            BroadcastCompanyVO companyVO = buildSubCompanyStatistics(subCompany.getId(), range);
            if (subCompany != null) {
                companyVO.setCompanyName(subCompany.getName());
            }
            resultList.add(companyVO);

            // 只有当分公司有实际数据时才推送消息和保存数据
            if (hasSubCompanyData(companyVO)) {
                Set<Long> receivers = new HashSet<>();
                if (subCompany != null && subCompany.getLeaderId() != null) {
                    receivers.add(subCompany.getLeaderId());
                }
                assembleService.sendBranchDataReportMessages(sketchType, "BRANCH_DATA", receivers, companyVO);
                // 保存dashboard数据（分公司）
                try {
                    DashboardSketchEntity sketch = new DashboardSketchEntity();
                    sketch.setOrganizationId(subCompany.getId());
                    sketch.setOrganizationName(subCompany.getName());
                    sketch.setSketchType(sketchType);
                    sketch.setOrganizationType(30);
                    LocalDate start = range.getStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    sketch.setYear(start.getYear());
                    if (sketchType != 50) {
                        sketch.setMonth(start.getMonthValue());
                    }
                    sketch.setCycle(computeCycle(start, sketchType));
                    sketch.setOrderAmount(companyVO.getTotalOrderAmount());
                    sketch.setCustomerNewNum(companyVO.getTotalCustomerNum() == null ? 0 : companyVO.getTotalCustomerNum().intValue());
                    sketch.setBusinessNewNum(companyVO.getTotalBusinessNum() == null ? 0 : companyVO.getTotalBusinessNum().intValue());
                    sketch.setOrderNewNum(companyVO.getTotalOrderNum() == null ? 0 : companyVO.getTotalOrderNum().intValue());
                    sketch.setLeadNewNum(companyVO.getTotalLeadNum());
                    sketch.setFollowNewNum(companyVO.getTotalFollowNum());
                    sketch.setMailNewNum(companyVO.getTotalMailNum());
                    Map<String,Object> sketchMap = new HashMap<>();
                    sketchMap.put("orderAmountTotal", companyVO.getTotalOrderAmount());
                    sketchMap.put("orderAmountRecords", companyVO.getBroadcastOrderAmountDates());
                    sketchMap.put("orderNumTotal", companyVO.getTotalOrderNum());
                    sketchMap.put("orderNumRecords", companyVO.getBroadcastOrderDates());
                    sketchMap.put("businessTotal", companyVO.getTotalBusinessNum());
                    sketchMap.put("businessRecords", companyVO.getBroadcastBusinessDates());
                    sketchMap.put("customerTotal", companyVO.getTotalCustomerNum());
                    sketchMap.put("customerRecords", companyVO.getBroadcastCustomerDates());
                    // 补充线索/跟进/邮件总数（分公司层级）及明细记录
                    sketchMap.put("leadTotal", companyVO.getTotalLeadNum());
                    sketchMap.put("leadRecords", companyVO.getBroadcastLeadDates());
                    sketchMap.put("followTotal", companyVO.getTotalFollowNum());
                    sketchMap.put("followRecords", companyVO.getBroadcastFollowDates());
                    sketchMap.put("mailTotal", companyVO.getTotalMailNum());
                    sketchMap.put("mailRecords", companyVO.getBroadcastMailDates());
                    // 组织元数据
                    sketchMap.put("organizationName", companyVO.getCompanyName());
                    sketchMap.put("sketchType", sketchType);
                    sketchMap.put("year", start.getYear());
                    if (sketchType != 50) {
                        sketchMap.put("month", start.getMonthValue());
                    }
                    sketchMap.put("cycle", computeCycle(start, sketchType));
                    sketch.setSketchDataJson(com.alibaba.fastjson.JSON.toJSONString(sketchMap));
                    dashboardSketchService.assembleData(sketch);
                } catch (Exception e) {
                    log.error("保存分公司dashboard失败", e);
                }
            }
        }

        return Result.result(resultList);
    }

    @Override
    public Result<?> sendDeptData(Integer sketchType) {
        DateRange range = buildRange(sketchType);
        if (range == null) {
            return Result.error("无效的周期类型");
        }

        // 获取周期内有任何新增数据的用户集合
        Set<Long> activeUserIds = fetchPersonUserIds(range);
        if (activeUserIds.isEmpty()) {
            return Result.result(createEmptyPersonVO(range));
        }

        // 按照用户的实际部门ID对有数据的用户进行分组
        Map<Long, List<Long>> deptActiveUserMap = new HashMap<>();
        for (Long userId : activeUserIds) {
            try {
                // 查询用户的部门信息
                com.storlead.user.pojo.entity.UserEntity user = userService.getById(userId);
                if (user != null && user.getDeptId() != null) {
                    deptActiveUserMap.computeIfAbsent(user.getDeptId(), k -> new ArrayList<>()).add(userId);
                }
            } catch (Exception e) {
                log.warn("查询用户部门信息失败: userId={}", userId, e);
            }
        }

        if (deptActiveUserMap.isEmpty()) {
            return Result.result(createEmptyPersonVO(range));
        }

        // 准备分公司名称映射
        List<SubCompanyEntity> subCompanies = broadcastDataMapper.subCompanyList();
        Map<Long, String> subCompanyNameMap = Collections.emptyMap();
        if (subCompanies != null) {
            subCompanyNameMap = subCompanies.stream()
                    .filter(Objects::nonNull)
                    .collect(Collectors.toMap(SubCompanyEntity::getId, SubCompanyEntity::getName, (a,b)->a));
        }

        // 为每个有活跃用户的部门生成报表
        for (Map.Entry<Long, List<Long>> entry : deptActiveUserMap.entrySet()) {
            Long deptId = entry.getKey();

            // 获取该部门的所有成员（包括没有活跃数据的成员）
            List<Long> allDeptMemberIds = broadcastDataMapper.deptMemberIdsByDeptId(deptId);
            if (allDeptMemberIds == null || allDeptMemberIds.isEmpty()) {
                continue;
            }

            // 统计该部门所有成员的数据总和及详细记录
            BroadcastPersonVO detailVO = buildPersonStatisticsWithRecords(allDeptMemberIds, range);

            // 获取部门信息
            com.storlead.user.pojo.entity.DeptEntity dept = departService.getById(deptId);
            if (dept != null) {
                detailVO.setDeptName(dept.getName());
                if (dept.getSubCompanyId() != null && subCompanyNameMap.containsKey(dept.getSubCompanyId())) {
                    detailVO.setCompanyName(subCompanyNameMap.get(dept.getSubCompanyId()));
                }
            }

            // 获取部门领导ID（从dept表中的manager_id字段）
            Set<Long> receivers = new HashSet<>();
            if (dept != null && dept.getManagerId() != null) {
                receivers.add(dept.getManagerId());
                assembleService.sendDeptDataReportMessages(sketchType, "DEPT_DATA", receivers, detailVO);
            }

            // 保存dashboard数据（部门）
            try {
                DashboardSketchEntity sketch = new DashboardSketchEntity();
                if (dept != null) {
                    sketch.setOrganizationId(dept.getId());
                    sketch.setOrganizationName(dept.getName());
                } else {
                    sketch.setOrganizationId(deptId);
                    sketch.setOrganizationName("未知部门");
                }
                sketch.setSketchType(sketchType);
                sketch.setOrganizationType(20);
                LocalDate start = range.getStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                sketch.setYear(start.getYear());
                if (sketchType != 50) {
                    sketch.setMonth(start.getMonthValue());
                }
                sketch.setCycle(computeCycle(start, sketchType));
                // 七个模块映射
                sketch.setOrderAmount(detailVO.getTotalOrderAmount());
                sketch.setCustomerNewNum(detailVO.getTotalCustomerNum() == null ? 0 : detailVO.getTotalCustomerNum().intValue());
                sketch.setBusinessNewNum(detailVO.getTotalBusinessNum() == null ? 0 : detailVO.getTotalBusinessNum().intValue());
                sketch.setOrderNewNum(detailVO.getTotalOrderNum() == null ? 0 : detailVO.getTotalOrderNum().intValue());
                sketch.setLeadNewNum(detailVO.getTotalClueNum() == null ? 0 : detailVO.getTotalClueNum().intValue());
                sketch.setFollowNewNum(detailVO.getTotalFollowNum() == null ? 0 : detailVO.getTotalFollowNum().intValue());
                sketch.setMailNewNum(detailVO.getTotalEmailNum() == null ? 0 : detailVO.getTotalEmailNum().intValue());
                Map<String,Object> sketchMap = new HashMap<>();
                sketchMap.put("orderAmountTotal", detailVO.getTotalOrderAmount());
                sketchMap.put("orderAmountRecords", detailVO.getBroadcastOrderAmountDates());
                sketchMap.put("orderNumTotal", detailVO.getTotalOrderNum());
                sketchMap.put("orderNumRecords", detailVO.getBroadcastOrderDates());
                sketchMap.put("businessTotal", detailVO.getTotalBusinessNum());
                sketchMap.put("businessRecords", detailVO.getBroadcastBusinessDates());
                sketchMap.put("customerTotal", detailVO.getTotalCustomerNum());
                sketchMap.put("customerRecords", detailVO.getBroadcastCustomerDates());
                sketchMap.put("leadTotal", detailVO.getTotalClueNum());
                sketchMap.put("leadRecords", detailVO.getBroadcastLeadDates());
                sketchMap.put("followTotal", detailVO.getTotalFollowNum());
                sketchMap.put("followRecords", detailVO.getBroadcastFollowDates());
                sketchMap.put("mailTotal", detailVO.getTotalEmailNum());
                sketchMap.put("mailRecords", detailVO.getBroadcastMailDates());
                // 组织元数据
                sketchMap.put("organizationName", dept != null ? dept.getName() : "未知部门");
                sketchMap.put("sketchType", sketchType);
                sketchMap.put("year", start.getYear());
                if (sketchType != 50) {
                    sketchMap.put("month", start.getMonthValue());
                }
                sketchMap.put("cycle", computeCycle(start, sketchType));
                sketch.setSketchDataJson(com.alibaba.fastjson.JSON.toJSONString(sketchMap));
                dashboardSketchService.assembleData(sketch);
            } catch (Exception e) {
                log.error("保存部门dashboard失败", e);
            }
        }

        return Result.result(true);
    }

    @Override
    public Result<?> sendPersonData(Integer sketchType) {
        DateRange range = buildRange(sketchType);
        if (range == null) {
            return Result.error("无效的周期类型");
        }

        // 取周期内新增客户的归属人集合
        Set<Long> userIds = fetchPersonUserIds(range);

        if (userIds.isEmpty()) {
            return Result.result(true);
        }

        for (Long userId : userIds) {
            BroadcastPersonVO detailVO = buildPersonStatistics(Collections.singletonList(userId), range);
            assembleService.sendPersonalDataReportMessages(sketchType, "PERSON_DATA", Collections.singleton(userId), detailVO);
            // 保存dashboard数据（个人） — 只存7个模块总额及简化 JSON，同时存 userId 与 userName
            try {
                DashboardSketchEntity sketch = new DashboardSketchEntity();
                sketch.setOrganizationId(userId);
                // 查用户姓名
                com.storlead.user.pojo.entity.UserEntity user = userService.getById(userId);
                String realName = (user != null ? user.getRealName() : "");
                sketch.setOrganizationName(realName);
                sketch.setSketchType(sketchType);
                sketch.setOrganizationType(10);
                LocalDate start = range.getStart().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                sketch.setYear(start.getYear());
                if (sketchType != 50) {
                    sketch.setMonth(start.getMonthValue());
                }
                sketch.setCycle(computeCycle(start, sketchType));
                sketch.setOrderAmount(detailVO.getTotalOrderAmount());
                sketch.setCustomerNewNum(detailVO.getTotalCustomerNum() == null ? 0 : detailVO.getTotalCustomerNum().intValue());
                sketch.setBusinessNewNum(detailVO.getTotalBusinessNum() == null ? 0 : detailVO.getTotalBusinessNum().intValue());
                sketch.setOrderNewNum(detailVO.getTotalOrderNum() == null ? 0 : detailVO.getTotalOrderNum().intValue());
                sketch.setLeadNewNum(detailVO.getTotalClueNum() == null ? 0 : detailVO.getTotalClueNum().intValue());
                sketch.setFollowNewNum(detailVO.getTotalFollowNum() == null ? 0 : detailVO.getTotalFollowNum().intValue());
                sketch.setMailNewNum(detailVO.getTotalEmailNum() == null ? 0 : detailVO.getTotalEmailNum().intValue());
                Map<String,Object> sketchMap = new HashMap<>();
                sketchMap.put("orderAmountTotal", detailVO.getTotalOrderAmount());
                sketchMap.put("orderNumTotal", detailVO.getTotalOrderNum());
                sketchMap.put("businessTotal", detailVO.getTotalBusinessNum());
                sketchMap.put("customerTotal", detailVO.getTotalCustomerNum());
                sketchMap.put("leadTotal", detailVO.getTotalClueNum());
                sketchMap.put("followTotal", detailVO.getTotalFollowNum());
                sketchMap.put("mailTotal", detailVO.getTotalEmailNum());
                // 组织元数据
                sketchMap.put("organizationName", realName);
                sketchMap.put("sketchType", sketchType);
                sketchMap.put("year", start.getYear());
                if (sketchType != 50) {
                    sketchMap.put("month", start.getMonthValue());
                }
                sketchMap.put("cycle", computeCycle(start, sketchType));
                sketch.setSketchDataJson(com.alibaba.fastjson.JSON.toJSONString(sketchMap));
                dashboardSketchService.assembleData(sketch);
            } catch (Exception e) {
                log.error("保存个人dashboard失败", e);
            }
        }

        return Result.result(true);
    }

    private BroadcastPersonVO createEmptyPersonVO(DateRange range) {
        BroadcastPersonVO vo = new BroadcastPersonVO();
        vo.setRecordTime(formatRecordTime(LocalDate.now()));
        vo.setRecordRangeTime(formatRecordRangeTime(range.getStart(), range.getEnd()));
        vo.setTotalCustomerNum(BigDecimal.ZERO);
        vo.setTotalClueNum(BigDecimal.ZERO);
        vo.setTotalBusinessNum(BigDecimal.ZERO);
        vo.setTotalOrderNum(BigDecimal.ZERO);
        vo.setTotalOrderAmount(BigDecimal.ZERO);
        vo.setTotalFollowNum(BigDecimal.ZERO);
        vo.setTotalEmailNum(BigDecimal.ZERO);
        return vo;
    }

    private BroadcastCompanyVO buildSubCompanyStatistics(Long subCompanyId, DateRange range) {
        String startDateStr = formatDate(range.getStart());
        String endDateStr = formatDate(range.getEnd());

        List<BroadcastDataVO> customerList = broadcastDataMapper.customerListBySubCompany(subCompanyId, startDateStr, endDateStr);
        List<BroadcastDataVO> businessList = broadcastDataMapper.businessListBySubCompany(subCompanyId, startDateStr, endDateStr);
        List<BroadcastDataVO> orderList = broadcastDataMapper.orderListBySubCompany(subCompanyId, startDateStr, endDateStr);
        List<BroadcastDataVO> orderAmountList = broadcastDataMapper.orderAmountListBySubCompany(subCompanyId, startDateStr, endDateStr);
        List<BroadcastDataVO> leadList = broadcastDataMapper.leadListBySubCompany(subCompanyId, startDateStr, endDateStr);
        List<BroadcastDataVO> followList = broadcastDataMapper.followListBySubCompany(subCompanyId, startDateStr, endDateStr);
        List<BroadcastDataVO> mailList = broadcastDataMapper.mailListBySubCompany(subCompanyId, startDateStr, endDateStr);

        BroadcastCompanyVO companyVO = new BroadcastCompanyVO();
        companyVO.setBroadcastCustomerDates(customerList);
        companyVO.setBroadcastBusinessDates(businessList);
        companyVO.setBroadcastOrderDates(orderList);
        companyVO.setBroadcastOrderAmountDates(orderAmountList);

        companyVO.setTotalCustomerNum(calculateTotal(customerList));
        companyVO.setTotalBusinessNum(calculateTotal(businessList));
        companyVO.setTotalOrderNum(calculateTotal(orderList));
        companyVO.setTotalOrderAmount(calculateTotal(orderAmountList));
        // 分公司级：线索/跟进/邮件总数
        Long leadCnt = broadcastDataMapper.leadCountBySubCompany(subCompanyId, startDateStr, endDateStr);
        Long followCnt = broadcastDataMapper.followCountBySubCompany(subCompanyId, startDateStr, endDateStr);
        Long mailCnt = broadcastDataMapper.mailCountBySubCompany(subCompanyId, startDateStr, endDateStr);
        companyVO.setTotalLeadNum(leadCnt == null ? 0 : leadCnt.intValue());
        companyVO.setTotalFollowNum(followCnt == null ? 0 : followCnt.intValue());
        companyVO.setTotalMailNum(mailCnt == null ? 0 : mailCnt.intValue());
        companyVO.setBroadcastLeadDates(leadList);
        companyVO.setBroadcastFollowDates(followList);
        companyVO.setBroadcastMailDates(mailList);

        companyVO.setRecordTime(formatRecordTime(LocalDate.now()));
        companyVO.setRecordRangeTime(formatRecordRangeTime(range.getStart(), range.getEnd()));
        return companyVO;
    }

    /**
     * 检查分公司是否有实际数据（非空数据）
     * @param companyVO 分公司数据VO
     * @return true-有数据，false-无数据
     */
    private boolean hasSubCompanyData(BroadcastCompanyVO companyVO) {
        if (companyVO == null) {
            return false;
        }

        // 检查各种数据总数
        boolean hasCustomerData = companyVO.getTotalCustomerNum() != null && companyVO.getTotalCustomerNum().compareTo(BigDecimal.ZERO) > 0;
        boolean hasBusinessData = companyVO.getTotalBusinessNum() != null && companyVO.getTotalBusinessNum().compareTo(BigDecimal.ZERO) > 0;
        boolean hasOrderData = companyVO.getTotalOrderNum() != null && companyVO.getTotalOrderNum().compareTo(BigDecimal.ZERO) > 0;
        boolean hasOrderAmountData = companyVO.getTotalOrderAmount() != null && companyVO.getTotalOrderAmount().compareTo(BigDecimal.ZERO) > 0;
        boolean hasLeadData = companyVO.getTotalLeadNum() != null && companyVO.getTotalLeadNum() > 0;
        boolean hasFollowData = companyVO.getTotalFollowNum() != null && companyVO.getTotalFollowNum() > 0;
        boolean hasMailData = companyVO.getTotalMailNum() != null && companyVO.getTotalMailNum() > 0;

        return hasCustomerData || hasBusinessData || hasOrderData || hasOrderAmountData ||
               hasLeadData || hasFollowData || hasMailData;
    }

    private BroadcastPersonVO buildPersonStatistics(List<Long> targetUserIds, DateRange range) {
        BroadcastPersonVO vo = createEmptyPersonVO(range);
        if (targetUserIds == null || targetUserIds.isEmpty()) {
            return vo;
        }
        String startDateStr = formatDate(range.getStart());
        String endDateStr = formatDate(range.getEnd());
        vo.setTotalCustomerNum(toDecimal(broadcastDataMapper.personCustomerCount(targetUserIds, startDateStr, endDateStr, 10)));
        vo.setTotalClueNum(toDecimal(broadcastDataMapper.personCustomerCount(targetUserIds, startDateStr, endDateStr, 11)));
        vo.setTotalBusinessNum(toDecimal(broadcastDataMapper.personBusinessCount(targetUserIds, startDateStr, endDateStr)));
        vo.setTotalOrderNum(toDecimal(broadcastDataMapper.personOrderCount(targetUserIds, startDateStr, endDateStr)));
        vo.setTotalOrderAmount(safe(broadcastDataMapper.personOrderAmount(targetUserIds, startDateStr, endDateStr)));
        vo.setTotalFollowNum(toDecimal(broadcastDataMapper.personFollowCount(targetUserIds, startDateStr, endDateStr)));
        vo.setTotalEmailNum(toDecimal(broadcastDataMapper.personEmailCount(targetUserIds, startDateStr, endDateStr)));
        return vo;
    }

    private BroadcastPersonVO buildPersonStatisticsWithRecords(List<Long> targetUserIds, DateRange range) {
        BroadcastPersonVO vo = buildPersonStatistics(targetUserIds, range);
        if (targetUserIds == null || targetUserIds.isEmpty()) {
            return vo;
        }
        String startDateStr = formatDate(range.getStart());
        String endDateStr = formatDate(range.getEnd());

        // 获取各部门成员的详细记录数据
        vo.setBroadcastCustomerDates(broadcastDataMapper.customerListByDeptMembers(targetUserIds, startDateStr, endDateStr));
        vo.setBroadcastBusinessDates(broadcastDataMapper.businessListByDeptMembers(targetUserIds, startDateStr, endDateStr));
        vo.setBroadcastOrderDates(broadcastDataMapper.orderListByDeptMembers(targetUserIds, startDateStr, endDateStr));
        vo.setBroadcastOrderAmountDates(broadcastDataMapper.orderAmountListByDeptMembers(targetUserIds, startDateStr, endDateStr));
        vo.setBroadcastLeadDates(broadcastDataMapper.leadListByDeptMembers(targetUserIds, startDateStr, endDateStr));
        vo.setBroadcastFollowDates(broadcastDataMapper.followListByDeptMembers(targetUserIds, startDateStr, endDateStr));
        vo.setBroadcastMailDates(broadcastDataMapper.mailListByDeptMembers(targetUserIds, startDateStr, endDateStr));

        return vo;
    }

    private BigDecimal safe(BigDecimal value) {
        return value == null ? BigDecimal.ZERO : value;
    }

    private DateRange buildRange(Integer type) {
        LocalDate today = LocalDate.now();
        LocalDate start = null;
        LocalDate end = null;
        switch (type) {
            case 10: // 上周：上周一-上周日
                LocalDate thisWeekMon = today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                start = thisWeekMon.minusWeeks(1);
                end = thisWeekMon.minusDays(1);
                break;
            case 20: // 上月：上月1日-上月末
                LocalDate firstDayPrevMonth = today.withDayOfMonth(1).minusMonths(1);
                start = firstDayPrevMonth;
                end = firstDayPrevMonth.plusMonths(1).minusDays(1);
                break;
            case 30: // 上季度
                int currentQuarter = (today.getMonthValue() - 1) / 3 + 1;
                int prevQuarter = currentQuarter == 1 ? 4 : currentQuarter - 1;
                int year = currentQuarter == 1 ? today.getYear() - 1 : today.getYear();
                int startMonth = (prevQuarter - 1) * 3 + 1;
                start = LocalDate.of(year, startMonth, 1);
                end = start.plusMonths(3).minusDays(1);
                break;
            case 40: // 半年，固定取「最近已结束的半年」
                if (today.getMonthValue() <= Month.JUNE.getValue()) {
                    // 当前处于上半年，取上一年的下半年（7-12月）
                    start = LocalDate.of(today.minusYears(1).getYear(), Month.JULY, 1);
                    end = LocalDate.of(today.minusYears(1).getYear(), Month.DECEMBER, 31);
                } else {
                    // 当前处于下半年，取当年的上半年（1-6月）
                    start = LocalDate.of(today.getYear(), Month.JANUARY, 1);
                    end = LocalDate.of(today.getYear(), Month.JUNE, 30);
                }
                break;
            case 50: // 去年
                start = LocalDate.of(today.minusYears(1).getYear(), Month.JANUARY, 1);
                end = LocalDate.of(today.minusYears(1).getYear(), Month.DECEMBER, 31);
                break;
            default:
                break;
        }
        if (start == null || end == null) {
            return null;
        }
        LocalDateTime startDateTime = start.atStartOfDay();
        LocalDateTime endDateTime = end.plusDays(1).atStartOfDay().minusSeconds(1);
        return new DateRange(toDate(startDateTime), toDate(endDateTime));
    }

    /**
     * 计算周期内的 cycle 值（周->当月第几周，季度->当年第几季度，半年->1/2）
     */
    private Integer computeCycle(LocalDate startDate, Integer sketchType) {
        if (startDate == null || sketchType == null) {
            return null;
        }
        switch (sketchType) {
            case 10: { // 周 - 当月第几周
                WeekFields wf = WeekFields.of(Locale.getDefault());
                return startDate.get(wf.weekOfMonth());
            }
            case 30: { // 季度 - 当年第几季度
                int q = (startDate.getMonthValue() - 1) / 3 + 1;
                return q;
            }
            case 40: { // 半年 - 1 上半年(1-6) 2 下半年(7-12)
                int m = startDate.getMonthValue();
                return m <= 6 ? 1 : 2;
            }
            default:
        return null;
        }
    }
    private Date toDate(LocalDateTime ldt) {
        return Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());
    }

    /**
     * 格式化日期为字符串（yyyy-MM-dd HH:mm:ss）
     * @param date 日期对象
     * @return 格式化后的日期字符串
     */
    private String formatDate(Date date) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date);
    }

    /**
     * 格式化记录产生时间（格式：yyyy年MM月dd日）
     * @param date 日期
     * @return 格式化后的时间字符串
     */
    private String formatRecordTime(LocalDate date) {
        if (date == null) {
            return null;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
        return date.format(formatter);
    }

    /**
     * 格式化记录范围时间（格式：yyyyMMdd-yyyyMMdd）
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @return 格式化后的范围时间字符串
     */
    private String formatRecordRangeTime(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            return null;
        }
        LocalDate start = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        LocalDate end = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        return start.format(formatter) + "-" + end.format(formatter);
    }

    /**
     * 计算列表数据的总和
     * @param dataList 数据列表
     * @return 总和
     */
    private BigDecimal calculateTotal(List<BroadcastDataVO> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return BigDecimal.ZERO;
        }
        return dataList.stream()
                .map(vo -> vo.getTotalNum() != null ? vo.getTotalNum() : BigDecimal.ZERO)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 获取周期内新增客户归属人集合
     */
    private Set<Long> fetchPersonUserIds(DateRange range) {
        String startDateStr = formatDate(range.getStart());
        String endDateStr = formatDate(range.getEnd());
        List<Long> ids = broadcastDataMapper.personUserIds(startDateStr, endDateStr);
        if (ids == null) {
            return Set.of();
        }
        return ids.stream().filter(Objects::nonNull).collect(Collectors.toSet());
    }

    private BigDecimal toDecimal(Long val) {
        if (val == null) {
            return BigDecimal.ZERO;
        }
        return BigDecimal.valueOf(val);
    }

    private static class DateRange {
        private final Date start;
        private final Date end;

        DateRange(Date start, Date end) {
            this.start = start;
            this.end = end;
        }

        public Date getStart() {
            return start;
        }

        public Date getEnd() {
            return end;
        }
    }
}
