package com.jiayue.ssi.service;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiayue.ssi.BaseTest;
import com.jiayue.ssi.entity.SysLogininfor;
import com.jiayue.ssi.util.DateUtils;
import com.jiayue.ssi.util.LocalCache;
import com.jiayue.ssi.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;


/**
 * TODO
 *
 * @author xsl
 * @version 3.0
 */
public class DataHandleServiceTest extends BaseTest {
    @Autowired
    SysLogininforService sysLogininforService;

    @Test
    public void test(){
        String startLoginTime = "2023-03-30";
        String endLoginTime = "2023-03-31";
        QueryWrapper<SysLogininfor> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(startLoginTime)) {
            wrapper.ge("login_time", DateUtils.getDayStartTime(DateUtil.parseDate(startLoginTime)));
        }
        if (StringUtils.isNotEmpty(endLoginTime)) {
            wrapper.le("login_time", DateUtils.getDayLastTime(DateUtil.parseDate(endLoginTime)));
        }
        List<SysLogininfor> sysLogininforList = sysLogininforService.list(wrapper);
        Map<String,List<SysLogininfor>> map = sysLogininforList.stream().collect(Collectors.groupingBy(item->DateUtil.format(item.getLoginTime(),"yyyy-MM-dd")));
        List<Map<String,String>> resultList = new ArrayList<>();
        map.forEach((key,value)->{
            List<SysLogininfor> list = value;
            Map<String,String> recordMap = new HashMap<>();
            recordMap.put("day",key);
            recordMap.put("count",list.size()+"");
            // 登录成功统计
            List<SysLogininfor> successList = list.stream().filter(sysLogininfor->"0".equals(sysLogininfor.getStatus())).collect(Collectors.toList());
            recordMap.put("success",successList.size()+"");
            // 登录失败统计
            List<SysLogininfor> failList = list.stream().filter(sysLogininfor->"1".equals(sysLogininfor.getStatus())).collect(Collectors.toList());
            recordMap.put("fail",failList.size()+"");
            // 登录ip个数统计
            int ips = list.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(s -> s.getIpaddr()))), ArrayList::new)).size();
            recordMap.put("ip",ips+"");
            resultList.add(recordMap);
        });

        System.out.println(resultList.toString());
    }
}
