package com.rj.service.impl;

import com.rj.entity.AudioManagementStatistics;
import com.rj.entity.SalesManagement;
import com.rj.mapper.AudioManagementStatisticsMapper;
import com.rj.service.IAudioManagementStatisticsService;
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.math.BigDecimal;
import java.math.RoundingMode;
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 AudioManagementStatisticsServiceImpl extends ServiceImpl<AudioManagementStatisticsMapper, AudioManagementStatistics> implements IAudioManagementStatisticsService {

    @Autowired
    private ISalesManagementService salesManagementService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int generateStatisticsByDate(LocalDate date) {
        // 先删除该日期的统计数据（如果存在）
        baseMapper.deleteByStatisticsDate(date);
        
        // 查询该日期的门店录音统计数据
        List<Map<String, Object>> dealershipStatsList = baseMapper.getDealershipStatisticsByDate(date);
        
        // 查询该日期的销售人员录音统计数据
        List<Map<String, Object>> salesStatsList = baseMapper.getSalesStatisticsByDate(date);
        
        int count = 0;
        
        // 处理门店统计数据
        for (Map<String, Object> stat : dealershipStatsList) {
            AudioManagementStatistics statistics = new AudioManagementStatistics();
            
            // 设置门店信息
            Object dealershipIdObj = stat.get("dealership_id");
            if (dealershipIdObj != null) {
                try {
                    statistics.setDealershipId(Long.valueOf(dealershipIdObj.toString()));
                } catch (NumberFormatException e) {
                    // 如果dealership_id是UUID格式，使用hashCode作为ID
                    statistics.setDealershipId((long) dealershipIdObj.toString().hashCode());
                }
            } else {
                statistics.setDealershipId(0L);
            }
            
            Object dealershipNameObj = stat.get("dealership_name");
            statistics.setDealershipName(dealershipNameObj != null ? dealershipNameObj.toString() : "未知门店");
            
            // 设置门店录音统计数据
            Object totalDurationObj = stat.get("total_duration_minutes");
            if (totalDurationObj != null) {
                statistics.setDealershipTotalDuration(Long.valueOf(totalDurationObj.toString()));
            } else {
                statistics.setDealershipTotalDuration(0L);
            }
            
            Object recordingCountObj = stat.get("recording_count");
            if (recordingCountObj != null) {
                statistics.setDealershipRecordingCount(Integer.valueOf(recordingCountObj.toString()));
            } else {
                statistics.setDealershipRecordingCount(0);
            }
            
            // 计算门店平均时长
            if (statistics.getDealershipRecordingCount() > 0 && statistics.getDealershipTotalDuration() > 0) {
                BigDecimal avgDuration = BigDecimal.valueOf(statistics.getDealershipTotalDuration())
                        .divide(BigDecimal.valueOf(statistics.getDealershipRecordingCount()), 2, RoundingMode.HALF_UP);
                statistics.setDealershipAvgDuration(avgDuration);
            } else {
                statistics.setDealershipAvgDuration(BigDecimal.ZERO);
            }
            
            // 查找该门店对应的销售人员统计数据
            String dealershipId = dealershipIdObj != null ? dealershipIdObj.toString() : "";
            Map<String, Object> salesStat = findSalesStatByDealership(salesStatsList, dealershipId);
            
            if (salesStat != null) {
                // 设置销售人员信息
                Object salesIdObj = salesStat.get("sales_id");
                statistics.setSalesId(salesIdObj != null ? salesIdObj.toString() : "");
                
                // 设置销售人员录音统计数据
                Object salesTotalDurationObj = salesStat.get("total_duration_minutes");
                if (salesTotalDurationObj != null) {
                    statistics.setSalesTotalDuration(Long.valueOf(salesTotalDurationObj.toString()));
                } else {
                    statistics.setSalesTotalDuration(0L);
                }
                
                Object salesRecordingCountObj = salesStat.get("recording_count");
                if (salesRecordingCountObj != null) {
                    statistics.setSalesRecordingCount(Integer.valueOf(salesRecordingCountObj.toString()));
                } else {
                    statistics.setSalesRecordingCount(0);
                }
                
                // 计算销售人员平均时长
                if (statistics.getSalesRecordingCount() > 0 && statistics.getSalesTotalDuration() > 0) {
                    BigDecimal salesAvgDuration = BigDecimal.valueOf(statistics.getSalesTotalDuration())
                            .divide(BigDecimal.valueOf(statistics.getSalesRecordingCount()), 2, RoundingMode.HALF_UP);
                    statistics.setSalesAvgDuration(salesAvgDuration);
                } else {
                    statistics.setSalesAvgDuration(BigDecimal.ZERO);
                }
            } else {
                // 如果没有找到对应的销售人员数据，设置为空
                statistics.setSalesId("");
                statistics.setSalesTotalDuration(0L);
                statistics.setSalesRecordingCount(0);
                statistics.setSalesAvgDuration(BigDecimal.ZERO);
            }
            
            // 设置统计日期和时间
            statistics.setStatisticsDate(date);
            statistics.setCreatedAt(LocalDateTime.now());
            statistics.setUpdatedAt(LocalDateTime.now());
            
            // 保存统计记录
            save(statistics);
            count++;
        }
        
        return count;
    }

    /**
     * 根据门店ID查找对应的销售人员统计数据
     * @param salesStatsList 销售人员统计列表
     * @param dealershipId 门店ID
     * @return 销售人员统计数据
     */
    private Map<String, Object> findSalesStatByDealership(List<Map<String, Object>> salesStatsList, String dealershipId) {
        // 这里需要根据业务逻辑来确定门店和销售人员的对应关系
        // 由于原始数据中可能没有直接的关联关系，这里返回第一个销售人员数据作为示例
        // 实际使用时需要根据具体的业务逻辑来调整
        if (!salesStatsList.isEmpty()) {
            return salesStatsList.get(0);
        }
        return null;
    }

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

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

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

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

    @Override
    public List<AudioManagementStatistics> getStatisticsBySales(String salesId, String salesPhone, LocalDate startDate, LocalDate endDate) {
        LambdaQueryWrapper<AudioManagementStatistics> 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(AudioManagementStatistics::getSalesId, finalSalesId)
                   .between(AudioManagementStatistics::getStatisticsDate, startDate, endDate)
                   .orderByAsc(AudioManagementStatistics::getStatisticsDate);
        List<AudioManagementStatistics> statisticsList = list(queryWrapper);
        
        // 在数据库层面聚合查询总录音时长和平均录音时长
        Map<String, Object> aggregateResult = baseMapper.getSalesAggregateStatistics(finalSalesId, startDate, endDate);
        
        // 如果查询到聚合结果，将汇总统计信息设置到每条记录上
        if (aggregateResult != null && !aggregateResult.isEmpty() && !statisticsList.isEmpty()) {
            // 提取聚合结果
            Long totalDuration = null;
            Integer totalCount = null;
            BigDecimal avgDuration = null;
            
            // 获取总录音时长
            Object totalDurationObj = aggregateResult.get("total_duration");
            if (totalDurationObj != null) {
                totalDuration = Long.valueOf(totalDurationObj.toString());
            }
            
            // 获取总录音数量
            Object totalCountObj = aggregateResult.get("total_count");
            if (totalCountObj != null) {
                totalCount = Integer.valueOf(totalCountObj.toString());
            }
            
            // 获取平均录音时长
            Object avgDurationObj = aggregateResult.get("avg_duration");
            if (avgDurationObj != null) {
                avgDuration = new BigDecimal(avgDurationObj.toString());
            }
            
            // 将聚合统计结果设置到每条记录上
            for (AudioManagementStatistics stat : statisticsList) {
                // 设置总录音时长（汇总）
                if (totalDuration != null) {
                    stat.setSalesTotalDurationStatistic(totalDuration);
                }
                
                // 设置总录音数量（汇总）
                if (totalCount != null) {
                    stat.setSalesRecordingCountStatistic(totalCount);
                }
                
                // 设置平均录音时长（汇总）
                if (avgDuration != null) {
                    stat.setSalesAvgDuration(avgDuration);
                } else {
                    stat.setSalesAvgDuration(BigDecimal.ZERO);
                }
            }
        }
        
        return statisticsList;
    }
}
