package com.ruoyi.brewery.controller;

import com.ruoyi.bar.domain.WyActivityJoinBatch;
import com.ruoyi.bar.domain.WyBar;
import com.ruoyi.bar.domain.WyBarIcon;
import com.ruoyi.bar.domain.WyBeerQrcodeScanLog;
import com.ruoyi.bar.service.IWyActivityJoinBatchService;
import com.ruoyi.bar.service.IWyBarService;
import com.ruoyi.bar.service.IWyBeerQrcodeScanLogService;
import com.ruoyi.brewery.domain.BarVerifyDataVO;
import com.ruoyi.brewery.domain.BeerVerifyDataVO;
import com.ruoyi.brewery.domain.WyActivityReward;
import com.ruoyi.brewery.domain.WyBeer;
import com.ruoyi.brewery.service.IWyActivityRewardService;
import com.ruoyi.brewery.service.IWyBeerReviewService;
import com.ruoyi.brewery.service.IWyBeerService;
import com.ruoyi.common.constant.RewardStatusConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "品牌方统计相关接口")
@RestController
@RequestMapping("/brewery/data")
public class BreweryDataController extends BaseController {

    @Resource
    private IWyBeerQrcodeScanLogService wyBeerQrcodeScanLogService;
    @Resource
    private IWyActivityRewardService wyActivityRewardService;
    @Resource
    private IWyBeerReviewService wyBeerReviewService;
    @Resource
    private IWyActivityJoinBatchService wyActivityJoinBatchService;
    @Resource
    private IWyBarService barService;
    @Resource
    private IWyBeerService beerService;
    /**
     * 近期数据统计
     */
    @ApiOperation("近期数据统计")
    @PreAuthorize("@bss.hasPermi('brewery:data:recent')")
    @GetMapping("/recent")
    public AjaxResult recent() {
        Long breweryId = SecurityUtils.getBreweryId();
        //近七天扫码数据
        final HashMap<String, Object> stringObjectHashMap = wyBeerQrcodeScanLogService.selectQrcodeScanCountByDays(breweryId, 7);
        final WyActivityReward wyActivityReward = new WyActivityReward();
        wyActivityReward.setBreweryId(breweryId);
        wyActivityReward.setRewardStatus(RewardStatusConstants.Waiting);
        final Integer waitingRewardCount = wyActivityRewardService.selectWyActivityRewardCount(wyActivityReward);
        final Integer sevenDaysReviewCount = wyBeerReviewService.selectBeerReviewCountByDays(breweryId, 7);//近七天新增酒评
        final WyActivityJoinBatch wyActivityJoinBatch = new WyActivityJoinBatch();
        wyActivityJoinBatch.setJoinStatus(1);
        wyActivityJoinBatch.setBreweryId(breweryId);
        final List<WyActivityJoinBatch> wyActivityJoinBatches = wyActivityJoinBatchService.selectWyActivityJoinBatchList(wyActivityJoinBatch);
        final Map<Long, List<WyActivityJoinBatch>> collect = wyActivityJoinBatches.stream().collect(Collectors.groupingBy(WyActivityJoinBatch::getBatchId));
        //
        HashMap<String, Object> map = new HashMap<>();
        map.put("sevenDaysScanCount", stringObjectHashMap.get("scanCount")); //近七天累积核销酒款数
        map.put("sevenDaysBarCount", stringObjectHashMap.get("barCount")); //近七天累积核销门店数
        map.put("waitingRewardCount", waitingRewardCount); //待兑付订单数
        map.put("processingBarCount", collect.size()); //累积中的门店数
        map.put("sevenDaysReviewCount", sevenDaysReviewCount); //7天内新增酒评
        return AjaxResult.success(map);
    }

    /**
     * 月度核销数据
     */
    @ApiOperation("月度核销数据")
    @PreAuthorize("@bss.hasPermi('brewery:data:monthlyVerify')")
    @GetMapping("/monthlyVerify")
    public AjaxResult monthlyVerify(@RequestParam(value = "year", required = false) Integer year,
                                    @RequestParam(value = "month", required = false) Integer month) {
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        if (year == null) {
            year = currentDate.getYear();
        }
        if (month == null) {
            month = currentDate.getMonthValue();
        }
        Long breweryId = SecurityUtils.getBreweryId();
        WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
        wyBeerQrcodeScanLog.setBreweryId(breweryId);
        wyBeerQrcodeScanLog.setScanStatus(1);
        final HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        // 创建 YearMonth 对象
        YearMonth yearMonth = YearMonth.of(year, month);
        objectObjectHashMap.put("beginTime", yearMonth.atDay(1).toString());
        objectObjectHashMap.put("endTime", yearMonth.atEndOfMonth().toString());
        wyBeerQrcodeScanLog.setParams(objectObjectHashMap);

        final List<WyBeerQrcodeScanLog> wyBeerQrcodeScanLogs = wyBeerQrcodeScanLogService.selectWyBeerQrcodeScanLogList(wyBeerQrcodeScanLog);

        // 获取本月天数
        Calendar tempCal = Calendar.getInstance();
        tempCal.set(Calendar.YEAR, year);
        tempCal.set(Calendar.MONTH, month - 1);
        int daysInMonth = tempCal.getActualMaximum(Calendar.DAY_OF_MONTH);

        // 初始化每天的订单数量为 0
        Map<Integer, Integer> dailyOrderCount = new HashMap<>();
        for (int day = 1; day <= daysInMonth; day++) {
            dailyOrderCount.put(day, 0);
        }

        // 统计每天的订单数量
        for (WyBeerQrcodeScanLog log : wyBeerQrcodeScanLogs) {
            Date orderDate = log.getCreateTime();
            final Calendar instance = Calendar.getInstance();
            instance.setTime(orderDate);
            if (instance.get(Calendar.YEAR) == year && instance.get(Calendar.MONTH) == (month - 1)) {
                int day = instance.get(Calendar.DAY_OF_MONTH);
                dailyOrderCount.put(day, dailyOrderCount.get(day) + 1);
            }
        }

        return AjaxResult.success(dailyOrderCount);
    }

    /**
     * 近期核销店铺列表
     */
    @ApiOperation("近期核销店铺列表")
    @PreAuthorize("@bss.hasPermi('brewery:data:recentVerifyBars')")
    @GetMapping("/recentVerifyBars")
    public AjaxResult recentVerifyBars(@RequestParam(value = "lastDays", required = false, defaultValue = "7") Integer lastDays) {
        if (lastDays > 30) {
            throw new IllegalArgumentException("查询时间不能超过 不能超过 30 天");
        }
        Long breweryId = SecurityUtils.getBreweryId();
        WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
        wyBeerQrcodeScanLog.setBreweryId(breweryId);
        wyBeerQrcodeScanLog.setScanStatus(1);
        final HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        final String LastDay = DateUtils.getTime();
        final String firstDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.addDays(DateUtils.getNowDate(), -lastDays));
        objectObjectHashMap.put("beginTime", firstDay);
        objectObjectHashMap.put("endTime", LastDay);
        wyBeerQrcodeScanLog.setParams(objectObjectHashMap);
        final List<WyBeerQrcodeScanLog> wyBeerQrcodeScanLogs = wyBeerQrcodeScanLogService.selectWyBeerQrcodeScanLogList(wyBeerQrcodeScanLog);
        final Map<Long, Long> bars = wyBeerQrcodeScanLogs.stream().collect(Collectors.groupingBy(WyBeerQrcodeScanLog::getBarId, Collectors.counting()));
        // 将统计结果转换为包含 Map.Entry 的列表
        List<Map.Entry<Long, Long>> sortedList = new ArrayList<>(bars.entrySet());
        // 对列表按订单数量降序排序
        sortedList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
        List<BarVerifyDataVO> barVerifyDataVOList = new ArrayList<>();
        sortedList.forEach(entry -> {
            final WyBar wyBar = barService.selectWyBarById(entry.getKey());
            final BarVerifyDataVO barVerifyDataVO = new BarVerifyDataVO();
            barVerifyDataVO.setBarId(entry.getKey());
            barVerifyDataVO.setBarCode(wyBar.getBarName());
            barVerifyDataVO.setBarCity(wyBar.getCity());
            barVerifyDataVO.setVerifyCount(entry.getValue());
            barVerifyDataVOList.add(barVerifyDataVO);
        });
        return AjaxResult.success(barVerifyDataVOList);
    }

    /**
     * 近期热门酒款
     */
    @ApiOperation("近期热门酒款")
    @PreAuthorize("@bss.hasPermi('brewery:data:recentPopularBeer')")
    @GetMapping("/recentPopularBeer")
    public AjaxResult recentPopularBeer(@RequestParam(value = "lastDays", required = false, defaultValue = "30") Integer lastDays) {
        if (lastDays > 30) {
            throw new IllegalArgumentException("查询时间不能超过 不能超过 30 天");
        }
        Long breweryId = SecurityUtils.getBreweryId();
        WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
        wyBeerQrcodeScanLog.setBreweryId(breweryId);
        wyBeerQrcodeScanLog.setScanStatus(1);
        final HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        final String LastDay = DateUtils.getTime();
        final String firstDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.addDays(DateUtils.getNowDate(), -lastDays));
        objectObjectHashMap.put("beginTime", firstDay);
        objectObjectHashMap.put("endTime", LastDay);
        wyBeerQrcodeScanLog.setParams(objectObjectHashMap);
        final List<WyBeerQrcodeScanLog> wyBeerQrcodeScanLogs = wyBeerQrcodeScanLogService.selectWyBeerQrcodeScanLogList(wyBeerQrcodeScanLog);
        final Map<Long, Long> beers = wyBeerQrcodeScanLogs.stream().collect(Collectors.groupingBy(WyBeerQrcodeScanLog::getBeerId, Collectors.counting()));
        // 将统计结果转换为包含 Map.Entry 的列表
        List<Map.Entry<Long, Long>> sortedList = new ArrayList<>(beers.entrySet());
        // 对列表按订单数量降序排序
        sortedList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));

        List<BeerVerifyDataVO> beerVerifyDataVOList = new ArrayList<>();
        sortedList.forEach(entry -> {
            final WyBeer beer = beerService.selectWyBeerById(entry.getKey());
            final BeerVerifyDataVO beerVerifyData = new BeerVerifyDataVO();
            beerVerifyData.setBeerId(entry.getKey());
            beerVerifyData.setBeerName(beer.getBeerName());
            beerVerifyData.setBeerCover(beer.getCover());
            beerVerifyData.setVerifyCount(entry.getValue());
            beerVerifyDataVOList.add(beerVerifyData);
        });
        return AjaxResult.success(beerVerifyDataVOList);
    }

    /**
     * 近期热门核销城市
     */
    @ApiOperation("近期热门核销城市")
    @PreAuthorize("@bss.hasPermi('brewery:data:recentPopularCity')")
    @GetMapping("/recentPopularCity")
    public AjaxResult recentPopularCity(@RequestParam(value = "lastDays", required = false, defaultValue = "30") Integer lastDays) {
        if (lastDays > 30) {
            throw new IllegalArgumentException("查询时间不能超过 不能超过 30 天");
        }
        Long breweryId = SecurityUtils.getBreweryId();
        WyBeerQrcodeScanLog wyBeerQrcodeScanLog = new WyBeerQrcodeScanLog();
        wyBeerQrcodeScanLog.setBreweryId(breweryId);
        wyBeerQrcodeScanLog.setScanStatus(1);
        final HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        final String LastDay = DateUtils.getTime();
        final String firstDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.addDays(DateUtils.getNowDate(), -lastDays));
        objectObjectHashMap.put("beginTime", firstDay);
        objectObjectHashMap.put("endTime", LastDay);
        wyBeerQrcodeScanLog.setParams(objectObjectHashMap);
        final List<WyBeerQrcodeScanLog> wyBeerQrcodeScanLogs = wyBeerQrcodeScanLogService.selectWyBeerQrcodeScanLogList(wyBeerQrcodeScanLog);
        final Map<Long, Long> bars = wyBeerQrcodeScanLogs.stream().collect(Collectors.groupingBy(WyBeerQrcodeScanLog::getBarId, Collectors.counting()));
        // 将统计结果转换为包含 Map.Entry 的列表
        List<Map.Entry<Long, Long>> sortedList = new ArrayList<>(bars.entrySet());
        // 对列表按订单数量降序排序
        sortedList.sort((entry1, entry2) -> entry2.getValue().compareTo(entry1.getValue()));
        List<BarVerifyDataVO> barVerifyDataVOList = new ArrayList<>();
        sortedList.forEach(entry -> {
            final WyBar wyBar = barService.selectWyBarById(entry.getKey());
            if (wyBar != null) {
                final BarVerifyDataVO barVerifyDataVO = new BarVerifyDataVO();
                barVerifyDataVO.setBarId(entry.getKey());
                if (wyBar.getCity() != null){
                    barVerifyDataVO.setBarCity(wyBar.getCity());
                }else{
                    barVerifyDataVO.setBarCity("其他");
                }
                barVerifyDataVO.setVerifyCount(entry.getValue());
                barVerifyDataVOList.add(barVerifyDataVO);
            }
        });
        final Map<String, Long> cityCountMap = barVerifyDataVOList.stream().collect(
                Collectors.groupingBy(BarVerifyDataVO::getBarCity,
                        Collectors.summingLong(BarVerifyDataVO::getVerifyCount))
        );
        return AjaxResult.success(cityCountMap);
    }
}
