package com.ylx.web.controller.massage;

import cn.hutool.core.collection.CollectionUtil;
import com.ylx.common.constant.MassageConstants;
import com.ylx.common.exception.ServiceException;
import com.ylx.common.utils.StringUtils;
import com.ylx.massage.domain.TJsDay;
import com.ylx.massage.domain.vo.HomeBlock;
import com.ylx.massage.domain.vo.HomeBlocks;
import com.ylx.massage.mapper.*;
import com.ylx.order.service.TOrderService;
import com.ylx.massage.utils.DateTimeUtils;
import com.ylx.massage.utils.WeChatUtil;
import com.ylx.system.service.ISysOperLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.compress.utils.Lists;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author jianlong
 * @date 2024-09-02 16:58
 */

@RestController
@RequestMapping("homeController")
@Slf4j
@Api(tags = {"首页"})
public class HomeController {


    @Resource
    private TOrderService orderService;

    @Resource
    private TConsumptionLogMapper consumptionLogMapper;

    @Resource
    private TWxUserMapper wxUserMapper;

    @Resource
    private ISysOperLogService operatorsLogService;

    @Resource
    private TJsMapper jsMapper;

    @Resource
    private TTxRecordMapper txRecordMapper;

    @Resource
    private TJsDayMapper jsDayMapper;

    @Resource
    private WeChatUtil weChatUtil;

    @GetMapping("block")
    @ApiOperation("首页数据块")
    public HomeBlocks block(String deptId) {
        try {
            if (StringUtils.isBlank(deptId)) {
                throw new ServiceException("部门Id不能为空");
            }

            //获取上个月时间
            Date update = DateTimeUtils.addMonths(new Date(), -1);

            //上个月第一天
            Date start = DateTimeUtils.getBeginDayOfMonth(update);
            //当月最后一天
            Date end = DateTimeUtils.getEndDayOfMonth(new Date());

            String currentMonth = DateTimeUtils.formatDate(new Date(), DateTimeUtils.DATE_NUMBER_YEAR_MONTH_FORMAT2);
            //营业额
            //订单量
//            List<HomeBlock> blockOrder = orderService.getBlock(start, end, deptId);
            List<HomeBlock> blockOrder = new ArrayList<>();

                    //提现
//        List<HomeBlock> blockAmount = consumptionLogMapper.getBlockGetAmount(start, end, deptId);
            List<HomeBlock> blockAmount = txRecordMapper.getBlockGetAmount(start, end, deptId);
            //用户总数
            List<HomeBlock> blockUser = wxUserMapper.getBlockGetUser(start, end, deptId);
            Integer sumUser = wxUserMapper.getBlockUser();
            //教练数量
            List<HomeBlock> blockJs = jsMapper.getBlockGetJs(start, end, deptId);
            Integer sumJs = jsMapper.getBlockJs(deptId);

            //块
            HomeBlocks homeBlocks = new HomeBlocks();
            if (blockOrder.size() > 1) {
                Optional<Integer> orderNumMax = blockOrder.stream().max(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getOrderNum()).orElse(MassageConstants.INTEGER_ZERO));
                homeBlocks.setOrderNum(orderNumMax.orElse(MassageConstants.INTEGER_ZERO));
                Optional<BigDecimal> turnover = blockOrder.stream().max(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getTurnover()).orElse(BigDecimal.ZERO));
                homeBlocks.setTurnover(turnover.orElse(BigDecimal.ZERO));
            } else {
                homeBlocks.setOrderNum(MassageConstants.INTEGER_ZERO);
                homeBlocks.setTurnover(BigDecimal.ZERO);
            }

            Optional<Integer> upOrderNum = blockOrder.stream().min(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getOrderNum()).orElse(MassageConstants.INTEGER_ZERO));
            homeBlocks.setUpOrderNum(upOrderNum.orElse(MassageConstants.INTEGER_ZERO));

            Optional<BigDecimal> upTurnover = blockOrder.stream().min(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getTurnover()).orElse(BigDecimal.ZERO));
            homeBlocks.setUpTurnover(upTurnover.orElse(BigDecimal.ZERO));


            if (blockAmount.size() > 1) {
                Optional<BigDecimal> getAmountMax = blockAmount.stream().max(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getGetAmount()).orElse(BigDecimal.ZERO));
                homeBlocks.setGetAmount(getAmountMax.orElse(BigDecimal.ZERO));
            } else {
                homeBlocks.setGetAmount(BigDecimal.ZERO);
            }
            Optional<BigDecimal> getupAmount = blockAmount.stream().min(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getGetAmount()).orElse(BigDecimal.ZERO));
            homeBlocks.setUpGetAmount(getupAmount.orElse(BigDecimal.ZERO));

            homeBlocks.setUserNum(sumUser);
            //获取当月新增用户数
            //Optional<Integer> userNumMax = blockUser.stream().max(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getUserNum()).orElse(MassageConstants.INTEGER_ZERO));
            List<HomeBlock> currentUser = blockUser.stream().filter(i -> i.getMonth().equals(currentMonth)).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(currentUser)) {
                homeBlocks.setUpUserNum(sumUser);
            } else {
                homeBlocks.setUpUserNum(sumUser - currentUser.get(0).getUserNum());
            }


            homeBlocks.setJsNum(sumJs);
            //获取当前月新增的教练数量
            List<HomeBlock> currentHomeBlock = blockJs.stream().filter(i -> i.getMonth().equals(currentMonth)).collect(Collectors.toList());

            if (CollectionUtil.isEmpty(currentHomeBlock)) {
                homeBlocks.setUpJsNum(sumJs);
            } else {
                homeBlocks.setUpJsNum(sumJs - currentHomeBlock.get(0).getJsNum());
            }
            //Optional<Integer> jsNumMax = blockJs.stream().max(Comparator.comparing(HomeBlock::getMonth)).map(i -> Optional.ofNullable(i.getJsNum()).orElse(MassageConstants.INTEGER_ZERO));
            //昨日关注量
            Date date = DateTimeUtils.addDays(new Date(), -1);
            homeBlocks.setFollowers(weChatUtil.getFollowers(DateTimeUtils.formatDate(date), DateTimeUtils.formatDate(date)));

            Integer pageViews = operatorsLogService.selectDate(DateTimeUtils.formatDate(date),DateTimeUtils.formatDate(new Date()));

            homeBlocks.setPageViews(pageViews);
            return homeBlocks;
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }


    @GetMapping("columnar")
    @ApiOperation("首页柱状图")
    public List<HashMap<String, Object>> columnar(String deptId) {
        if (StringUtils.isBlank(deptId)) {
            throw new ServiceException("部门Id不能为空");
        }
        //获取上个年时间
        Date update = DateTimeUtils.addYears(new Date(), -1);
        //上个月第一天
        Date start = DateTimeUtils.getBeginDayOfMonth(update);
        //当月最后一天
        Date end = DateTimeUtils.getEndDayOfMonth(new Date());
        //营业额
        //订单量
        List<HomeBlock> blockOrder = new ArrayList<>();
//        List<HomeBlock> blockOrder = orderService.getBlock(start, end, deptId);
        //提现
        List<HomeBlock> blockAmount = txRecordMapper.getBlockGetAmount(start, end, deptId);
        //用户总数
        List<HomeBlock> blockUser = wxUserMapper.getBlockGetUser(start, end, deptId);
        //教练数量
        List<HomeBlock> blockJs = jsMapper.getBlockGetJs(start, end, deptId);
        //图
        blockOrder.addAll(blockAmount);
        blockOrder.addAll(blockUser);
        blockOrder.addAll(blockJs);
        Map<String, List<HomeBlock>> blockMap = blockOrder.stream().collect(Collectors.groupingBy(HomeBlock::getMonth));

        ArrayList<HashMap<String, Object>> blockM = Lists.newArrayList();
        blockMap.forEach((k, v) -> {

            HashMap<String, Object> homeBlockMap = new HashMap<>();

            HomeBlock homeBlock = new HomeBlock();
            homeBlock.setMonth(k);
            homeBlockMap.put("横坐标", k);

            Integer userNum = v.stream().map(i -> Optional.ofNullable(i.getUserNum()).orElse(MassageConstants.INTEGER_ZERO)).reduce(0, Integer::sum);
            homeBlock.setUserNum(userNum);
            homeBlockMap.put("用户总数", userNum);


            Integer jsNum = v.stream().map(i -> Optional.ofNullable(i.getJsNum()).orElse(MassageConstants.INTEGER_ZERO)).reduce(0, Integer::sum);
            homeBlock.setJsNum(jsNum);
            homeBlockMap.put("教练总数", jsNum);

            Integer orderNum = v.stream().map(i -> Optional.ofNullable(i.getOrderNum()).orElse(MassageConstants.INTEGER_ZERO)).reduce(0, Integer::sum);
            homeBlock.setOrderNum(orderNum);
            homeBlockMap.put("订单数量", orderNum);

            BigDecimal turnover = v.stream().map(i -> Optional.ofNullable(i.getTurnover()).orElse(BigDecimal.ZERO)).reduce(BigDecimal.ZERO, BigDecimal::add);
            homeBlock.setTurnover(turnover);
            homeBlockMap.put("营业额", turnover);

            BigDecimal getAmount = v.stream().map(i -> Optional.ofNullable(i.getGetAmount()).orElse(BigDecimal.ZERO)).reduce(BigDecimal.ZERO, BigDecimal::add);
            homeBlock.setGetAmount(getAmount);
            homeBlockMap.put("提现金额", getAmount);

            blockM.add(homeBlockMap);
        });
        blockM.sort(Comparator.comparing(map -> map.get("横坐标").toString()));
        return blockM;
    }

    @GetMapping("ranking")
    @ApiOperation("首页排名")
    public List<TJsDay> ranking(String deptId, String start, String end) {
        if (StringUtils.isBlank(deptId)) {
            throw new ServiceException("部门Id不能为空");
        }
        return jsDayMapper.selectRanking(null, deptId, start, end);
    }




}
