package com.rj.service.impl;

import com.rj.entity.CustomerManagementStatistics;
import com.rj.entity.SalesManagement;
import com.rj.mapper.CustomerManagementStatisticsMapper;
import com.rj.service.ICustomerManagementStatisticsService;
import com.rj.service.ISalesManagementService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 客户统计表 服务实现类
 * </p>
 *
 * @author 李中华 ,spllzh
 * @since 2025-08-07
 */
@Service
public class CustomerManagementStatisticsServiceImpl extends ServiceImpl<CustomerManagementStatisticsMapper, CustomerManagementStatistics> implements ICustomerManagementStatisticsService {

    @Autowired
    private ISalesManagementService salesManagementService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int generateStatisticsByDate(LocalDate date) {
        // 先删除该日期的统计数据（如果存在）
        baseMapper.deleteByStatisticsDate(date);
        
        // 查询该日期的统计数据（按租户、经销商、项目、销售分组）
        List<Map<String, Object>> statsList = baseMapper.getStatisticsByDate(date);
        
        int count = 0;
        
        // 处理统计数据，每个组合生成一条记录
        for (Map<String, Object> stat : statsList) {
            CustomerManagementStatistics statistics = new CustomerManagementStatistics();
            
            // 设置租户ID
            Object tenantIdObj = stat.get("tenant_id");
            statistics.setTenantId(tenantIdObj != null ? tenantIdObj.toString() : "");
            
            // 设置经销商信息
            Object dealershipIdObj = stat.get("dealership_id");
            statistics.setDealershipId(dealershipIdObj != null ? dealershipIdObj.toString() : "");
            
            Object dealershipNameObj = stat.get("dealership_name");
            statistics.setDealershipName(dealershipNameObj != null ? dealershipNameObj.toString() : "未知经销商");
            
            // 设置销售信息
            Object salesIdObj = stat.get("sales_id");
            statistics.setSalesId(salesIdObj != null ? salesIdObj.toString() : "");
            
            // 设置经销商统计数量（该经销商当天的客户总数）
            Object countByDealershipObj = stat.get("count_by_dealership");
            if (countByDealershipObj != null) {
                statistics.setCountByDealership(Integer.valueOf(countByDealershipObj.toString()));
            } else {
                statistics.setCountByDealership(0);
            }
            
            // 设置销售统计数量（该销售当天的客户总数）
            Object countBySalesObj = stat.get("count_by_sales");
            if (countBySalesObj != null) {
                statistics.setCountBySales(Integer.valueOf(countBySalesObj.toString()));
            } else {
                statistics.setCountBySales(0);
            }
            
            // 设置项目统计数量（该项目当天的客户总数）
            Object countByProjectObj = stat.get("count_by_project");
            if (countByProjectObj != null) {
                statistics.setCountByProject(Integer.valueOf(countByProjectObj.toString()));
            } else {
                statistics.setCountByProject(0);
            }
            
            // 设置统计日期和时间
            statistics.setStatisticsDate(date);
            statistics.setCreatedAt(LocalDateTime.now());
            statistics.setUpdatedAt(LocalDateTime.now());
            
            // 保存统计记录
            save(statistics);
            count++;
        }
        
        return count;
    }

    @Override
    public int generateYesterdayStatistics() {
        LocalDate yesterday = LocalDate.now().minusDays(1);
        return generateStatisticsByDate(yesterday);
    }

    @Override
    public List<CustomerManagementStatistics> getStatisticsByDateRange(LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<CustomerManagementStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.between(CustomerManagementStatistics::getStatisticsDate, startDate, endDate)
                   .orderByAsc(CustomerManagementStatistics::getStatisticsDate)
                   .orderByAsc(CustomerManagementStatistics::getDealershipId);
        return list(queryWrapper);
    }

    @Override
    public List<CustomerManagementStatistics> getStatisticsByDealership(String dealershipId, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<CustomerManagementStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerManagementStatistics::getDealershipId, dealershipId)
                   .between(CustomerManagementStatistics::getStatisticsDate, startDate, endDate)
                   .orderByAsc(CustomerManagementStatistics::getStatisticsDate);
        return list(queryWrapper);
    }

    @Override
    public List<CustomerManagementStatistics> getStatisticsBySales(String salesId, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<CustomerManagementStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerManagementStatistics::getSalesId, salesId)
                   .between(CustomerManagementStatistics::getStatisticsDate, startDate, endDate)
                   .orderByAsc(CustomerManagementStatistics::getStatisticsDate);
        return list(queryWrapper);
    }

    @Override
    public List<CustomerManagementStatistics> getStatisticsBySales(String salesId, String salesPhone, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<CustomerManagementStatistics> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果提供了电话号码，先通过电话号码查询到salesId
        String finalSalesId = salesId;
        if ((finalSalesId == null || finalSalesId.trim().isEmpty()) && 
            salesPhone != null && !salesPhone.trim().isEmpty()) {
            // 通过电话号码查询销售人员
            LambdaQueryWrapper<SalesManagement> salesQueryWrapper = new LambdaQueryWrapper<>();
            salesQueryWrapper.eq(SalesManagement::getLoginAccount, salesPhone);
            List<SalesManagement> salesList = salesManagementService.list(salesQueryWrapper);
            
            if (salesList == null || salesList.isEmpty()) {
                // 如果没有找到对应的销售人员，返回空列表
                return List.of();
            }
            
            // 如果找到多个销售人员，使用第一个的ID
            // 或者可以根据业务需求处理多个销售人员的情况
            finalSalesId = salesList.get(0).getId();
        }
        
        // 如果最终没有salesId，返回空列表
        if (finalSalesId == null || finalSalesId.trim().isEmpty()) {
            return List.of();
        }
        
        // 根据salesId查询统计数据
        queryWrapper.eq(CustomerManagementStatistics::getSalesId, finalSalesId)
                   .between(CustomerManagementStatistics::getStatisticsDate, startDate, endDate)
                   .orderByAsc(CustomerManagementStatistics::getStatisticsDate);
        return list(queryWrapper);
    }
}

