package com.fs.company.controller.company;

import com.fs.common.core.domain.R;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.ServletUtils;
import com.fs.company.domain.Company;
import com.fs.company.service.ICompanyService;
import com.fs.config.cloud.CloudHostProper;
import com.fs.framework.security.LoginUser;
import com.fs.framework.service.TokenService;
import com.fs.statis.StatisticsRedisConstant;
import com.fs.statis.dto.*;
import com.fs.statis.service.IStatisticsService;
import com.fs.statis.service.impl.StatisticsCompanyServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.fs.statis.StatisticsRedisConstant.*;

/**
 * 首页-统计
 */
@RestController
@RequestMapping("/index/statistics")
public class IndexStatisticsController {
    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private IStatisticsService statisticsService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    CloudHostProper cloudHostProper;
    @Autowired
    private StatisticsCompanyServiceImpl statisticsCompanyService;

    /**
     * 分析概览
     */
    @PostMapping("/analysisPreview")
    public R analysisPreview(@RequestBody AnalysisPreviewQueryDTO param){
        AnalysisPreviewDTO analysisPreviewDTO = null;
        Integer type = param.getType();
        Integer userType = param.getUserType();

        if(type == null) {
            type = 0;
        }

        if(userType == null) {
            userType = 0;
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        param.setCompanyId(loginUser.getCompany().getCompanyId());
        if (param.getType().equals(5)){// 指定日期直接查，不走缓存
            return R.ok().put("data",statisticsCompanyService.analysisPreview(param));
        }else {
            analysisPreviewDTO = redisCache.getCacheObject(String.format("%s:%d:%d:%d",DATA_OVERVIEW_DEALER_ANALYSISPREVIEW,type,userType,param.getCompanyId()));
        }

        return R.ok().put("data",analysisPreviewDTO);
    }


    /**
     * 消费余额
     */
    @GetMapping("/rechargeComsumption")
    public R rechargeComsumption(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        ConsumptionBalanceDataDTO consumptionBalanceDataDTO = redisCache.getCacheObject(String.format("%s:%d",StatisticsRedisConstant.DATA_OVERVIEW_DEALER_BALANCE,companyId));
        return R.ok().put("data", consumptionBalanceDataDTO);
    }

    /**
     * 获取统计流量
     * @return
     */
    @GetMapping("/trafficLog")
    public R getTrafficLog(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        TrafficLogDTO trafficLogDTO = redisCache.getCacheObject(String.format("%s:%d",DATA_OVERVIEW_TRAFFIC_LOG,companyId));
        return R.ok().put("data",trafficLogDTO);
    }

    /**
     * 观看趋势
     */
    @PostMapping("/watchEndPlayTrend")
    public R watchEndPlayTrend(@RequestBody AnalysisPreviewQueryDTO param){
        Integer type = param.getType();
        Integer userType = param.getUserType();

        if(type == null) {
            type = 0;
        }
        if(userType == null){
            userType = 0;
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());

        if("四川致医".equals(cloudHostProper.getCompanyName())){
            Long companyId1 = loginUser.getCompany().getCompanyId();
            Company company = loginUser.getCompany();
            param.setCompanyId(companyId1);
            List<WatchEndPlayTrendDTO> watchEndPlayTrendDTOS;

            // 参考watchCourseTopTen方法的处理逻辑
            if ((param.getCompanyId() == null && param.getDeptId() == null) || (param.getCompanyId() == null && param.getDeptId() == 1)){
                String key = String.format("%s:%d:%d", DATA_OVERVIEW_DEALER_CHARTS, type,userType);
                watchEndPlayTrendDTOS = redisCache.getCacheObject(key);
            }else if(param.getCompanyId() != null){
                String key = String.format("%s:%d:%d:%d", DATA_OVERVIEW_DEALER_CHARTS, type,userType,param.getCompanyId());
                watchEndPlayTrendDTOS = redisCache.getCacheObject(key);
            }else{
                Long[] companyIds = companyService.selectCompanyList(company).stream().map(Company::getCompanyId).toArray(Long[]::new);
                List<WatchEndPlayTrendDTO> tempDTOS = new ArrayList<>();
                for(Long companyId : companyIds){
                    String key = String.format("%s:%d:%d:%d", DATA_OVERVIEW_DEALER_CHARTS, type,userType,companyId);
                    List<WatchEndPlayTrendDTO> companyData = redisCache.getCacheObject(key);
                    if (companyData != null) {
                        tempDTOS.addAll(companyData);
                    }
                }
                // 根据startDate 和 x 分组,合并watchUserCount和completedUserCount 限制最多返回10条记录
                watchEndPlayTrendDTOS = tempDTOS.stream()
                        .collect(Collectors.groupingBy(
                                dto -> dto.getStartDate() + ":" + dto.getX(),  // 根据startDate和x分组
                                Collectors.reducing(new WatchEndPlayTrendDTO(), (dto1, dto2) -> {
                                    // 合并watchUserCount和completedUserCount
                                    WatchEndPlayTrendDTO result = new WatchEndPlayTrendDTO();
                                    // 复制分组标识字段
                                    if (dto2 != null && dto2.getStartDate() != null) {
                                        result.setStartDate(dto2.getStartDate());
                                    } else if (dto1 != null) {
                                        result.setStartDate(dto1.getStartDate());
                                    }

                                    if (dto2 != null && dto2.getX() != null) {
                                        result.setX(dto2.getX());
                                    } else if (dto1 != null) {
                                        result.setX(dto1.getX());
                                    }

                                    // 合并数值字段
                                    result.setWatchUserCount(
                                            (dto1 == null || dto1.getWatchUserCount() == null ? 0 : dto1.getWatchUserCount()) +
                                                    (dto2 == null || dto2.getWatchUserCount() == null ? 0 : dto2.getWatchUserCount())
                                    );

                                    result.setCompletedUserCount(
                                            (dto1 == null || dto1.getCompletedUserCount() == null ? 0 : dto1.getCompletedUserCount()) +
                                                    (dto2 == null || dto2.getCompletedUserCount() == null ? 0 : dto2.getCompletedUserCount())
                                    );

                                    return result;
                                })
                        ))
                        .values()
                        .stream()
                        .filter(Objects::nonNull)  // 过滤掉null值
                        .limit(10)
                        .sorted(Comparator.comparing(WatchEndPlayTrendDTO::getX))
                        .collect(Collectors.toList());
            }

            if(watchEndPlayTrendDTOS == null){
                watchEndPlayTrendDTOS = new ArrayList<>();
            }

            return R.ok().put("data", watchEndPlayTrendDTOS);
        }else{
            Long companyId = loginUser.getCompany().getCompanyId();
            param.setCompanyId(companyId);
            if (param.getType().equals(5)){
                return R.ok().put("data", statisticsCompanyService.watchEndPlayTrend(param));
            }
            String key = String.format("%s:%d:%d:%d", DATA_OVERVIEW_DEALER_CHARTS, type,userType,param.getCompanyId());
            List<DeaMemberTopTenDTO> deaMemberTopTenDTOS = redisCache.getCacheObject(key);
            return R.ok().put("data", deaMemberTopTenDTOS);
        }
    }

    /**
     * 经销商会员观看
     */
    @PostMapping("/deaMemberTopTen")
    public R deaMemberTopTen(@RequestBody AnalysisPreviewQueryDTO param){
        Integer type = param.getType();
        Integer statisticalType = param.getStatisticalType();
        Integer userType = param.getUserType();

        if(type == null) {
            type = 0;
        }
        if(userType == null){
            userType = 0;
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        param.setCompanyId(companyId);
        if (param.getType().equals(5)){
            return R.ok().put("data", statisticsService.deaMemberTopTen(param));
        }
        List<DeaMemberTopTenDTO> deaMemberTopTenDTOS = redisCache.getCacheObject(String.format("%s:%d:%d:%d:%d", CHARTS_MEMBER_TOP_TEN_WATCH, type, statisticalType,userType,param.getCompanyId()));
        if(deaMemberTopTenDTOS == null){
            deaMemberTopTenDTOS = new ArrayList<>();
        }
        return R.ok().put("data", deaMemberTopTenDTOS);
    }

    /**
     * 奖励金额top10
     */
    @PostMapping("/rewardMoneyTopTen")
    public R rewardMoneyTopTen(@RequestBody AnalysisPreviewQueryDTO param){
        Integer type = param.getType();
        Integer dataType = param.getDataType();
        Integer userType = param.getUserType();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        param.setCompanyId(companyId);
        if (param.getType().equals(5)){
            R.ok().put("data", statisticsCompanyService.rewardMoneyTopTen(param));
        }
        List<RewardMoneyTopTenDTO> rewardMoneyTopTenDTOS = redisCache.getCacheObject( String.format("%s:%d:%d:%d:%d", CHARTS_REWARD_MONEY_TOP_TEN, type,dataType,userType,param.getCompanyId()));
        return R.ok().put("data", rewardMoneyTopTenDTOS);
    }

    /**
     * 答题红包金额趋势图
     */
    @PostMapping("/rewardMoneyTrend")
    public R rewardMoneyTrend(@RequestBody AnalysisPreviewQueryDTO param){
        Integer type = param.getType();
        Integer userType = param.getUserType();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        param.setCompanyId(companyId);
        if (param.getType().equals(5)){
            return R.ok().put("data", statisticsCompanyService.rewardMoneyTrendDTO(param));
        }
        List<RewardMoneyTrendDTO> rewardMoneyTrendDTOS = redisCache.getCacheObject( String.format("%s:%d:%d:%d", CHARTS_REWARD_MONEY_TREND, type,userType,param.getCompanyId()));
        return R.ok().put("data", rewardMoneyTrendDTOS);
    }

    /**
     * 课程观看top10
     */
    @PostMapping("/watchCourseTopTen")
    public R watchCourseTopTen(@RequestBody AnalysisPreviewQueryDTO param){
        Integer type = param.getType();
        String sort = param.getSort();
        Integer statisticalType = param.getStatisticalType();
        Integer userType = param.getUserType();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        param.setCompanyId(companyId);

        if (param.getType().equals(5)){
            return R.ok().put("data",statisticsService.watchCourseTopTen(param));
        }
        List<CourseStatsDTO> courseStatsDTOS = redisCache.getCacheObject(String.format("%s:%d:%d:%d:%s:%d", CHARTS_WATCH_TOP_TEN, type,statisticalType,userType,sort,param.getCompanyId()));
        return R.ok().put("data", courseStatsDTOS);
    }

    /**
     * 数据概览
     */
    @GetMapping("/dealerAggregated")
    public R dealerAggregated(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        DealerAggregatedDTO dealerAggregatedDTO = redisCache.getCacheObject(String.format("%s:%d",StatisticsRedisConstant.DATA_OVERVIEW_DEALER_AGGREGATED,companyId));

        return R.ok().put("data",dealerAggregatedDTO);
    }

    /**
     * 短信余额
     */
    @GetMapping("/smsBalance")
    public R smsBalance(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        Long smsBalance = redisCache.getCacheObject(String.format("%s:%d",StatisticsRedisConstant.DATA_OVERVIEW_DEALER_SMS_BALANCE,companyId));

        return R.ok().put("data", smsBalance);
    }


    /**
     * 授权信息
     */
    @GetMapping("/authorizationInfo")
    public R authorizationInfo(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        AuthorizationInfoDTO authorizationInfoDTO = redisCache.getCacheObject(String.format("%s:%d",StatisticsRedisConstant.DATA_OVERVIEW_DEALER_AUTHORIZATION_INFO,companyId));

        return R.ok().put("data", authorizationInfoDTO);
    }


    /**
     * 当月订单数统计
     * @return
     */
    @GetMapping("/thisMonthOrderCount")
    public R thisMonthOrderCount(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        R result = redisCache.getCacheObject(String.format("%s:%d",StatisticsRedisConstant.THIS_MONTH_ORDER_COUNT,companyId));
        return result;
    }

    /**
     * 当月收益统计
     * @return
     */
    @GetMapping("/thisMonthRecvCount")
    public R thisMonthRecvCount(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();

        R result = redisCache.getCacheObject(String.format("%s:%d",StatisticsRedisConstant.THIS_MONTH_RECV_COUNT,companyId));
        return result;
    }

    /**
     * @Description: 看课统计按公司
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2025/10/27 16:29
     */
    @PostMapping("/getWatchCourseStatisticsData")
    public R getWatchCourseStatisticsData(@RequestBody AnalysisPreviewQueryDTO param){
        // 获取公司ID
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long companyId = loginUser.getCompany().getCompanyId();
        if(param.getCompanyId()==null){
            param.setCompanyId(companyId);
        }
        // 从缓存获取看客统计数据
        List<WatchCourseStatisticsResultDTO> data=statisticsService.getWatchCourseStatisticsData(param);

        return R.ok().put("data", data);
    }
}
