package cn.com.ctop.kuaishou.modules.report.service.impl;


import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.entity.SysRole;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.mapper.SysDepartMapper;
import cn.com.ctop.common.module.mapper.SysRoleMapper;
import cn.com.ctop.common.module.mapper.SysUserDepartMapper;
import cn.com.ctop.common.module.mapper.UserAllocationMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.kuaishou.modules.batch.mapper.KuaiShouCreativeMapper;
import cn.com.ctop.kuaishou.modules.batch.service.IKuaishouInterfaceService;
import cn.com.ctop.kuaishou.modules.report.entity.EtlKuaishouReportAccountHourly;
import cn.com.ctop.kuaishou.modules.report.enums.CheckParametersCostEnum;
import cn.com.ctop.kuaishou.modules.report.enums.CheckParametersEnum;
import cn.com.ctop.kuaishou.modules.report.mapper.EtlKuaishouReportAccountDailyMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.EtlKuaishouReportAccountHourlyMapper;
import cn.com.ctop.kuaishou.modules.report.mapper.KuaishouReportHourlyAccountMapper;
import cn.com.ctop.kuaishou.modules.report.service.IEtlKuaishouReportAccountHourlyService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.AccountReportConstants;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.JsonResourceUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 账户维度-每小时盯盘数据
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2021-03-04
 */
@Service
public class EtlKuaishouReportAccountHourlyServiceImpl extends ServiceImpl<EtlKuaishouReportAccountHourlyMapper, EtlKuaishouReportAccountHourly> implements IEtlKuaishouReportAccountHourlyService {

    @Autowired
    private KuaishouReportHourlyAccountMapper hourlyAccountMapper;
    @Autowired
    private KuaiShouCreativeMapper kuaiShouCreativeMapper;
    @Autowired
    private UserAllocationMapper allocationMapper;

    @Autowired
    private EtlKuaishouReportAccountHourlyMapper etlHourlyAccountMapper;

    @Autowired
    private IKuaishouInterfaceService iKuaishouInterfaceService;
    @Autowired
    private EtlKuaishouReportAccountDailyMapper etlDailyAccountMapper;
    @Autowired
    private ICtopOauthTokenService oauthTokenService;
    @Resource
    private SysDepartMapper departMapper;
    @Resource
    private SysUserDepartMapper sysUserDepartMapper;
    @Resource
    private SysRoleMapper roleMapper;

    @Override
    public void queryEveryhourlyDataForAccount() {
        List<EtlKuaishouReportAccountHourly> list = hourlyAccountMapper.queryEveryhourlyDataForAccount();
        if (!Check.isNull(list)) {
            etlHourlyAccountMapper.replaceBatch(list);
        }
        etlDailyAccountMapper.replaceBatch(list);
    }

    @Override
    public void updateYesterdayEtlHourlyData() {
        //昨天日期
        String lastStartDate = DateUtils.getLastDay(DateUtils.formatDate(new Date()), 1);
        List<EtlKuaishouReportAccountHourly> list = etlDailyAccountMapper.selectList(lastStartDate, lastStartDate);
        if (!Check.isNull(list)) {
            for (EtlKuaishouReportAccountHourly accountHourly : list) {
                accountHourly.setStatHour(23l);
            }
            etlHourlyAccountMapper.replaceBatch(list);
        }
    }

    @Override
    public Result<Object> getAggregateByHour(JSONObject request) throws ParseException {
        Long accountId = request.getLong("accountId");
        String startTime = request.getString("startTime");
        if (Check.isNull(accountId) || Check.isNull(startTime)) {
            return Result.error("请选择时间和账户");
        }
        String endTime = request.getString("endTime");
        EtlKuaishouReportAccountHourly today = null;
        EtlKuaishouReportAccountHourly yesterday = null;
        if (endTime.equals(startTime)) {
            today = etlHourlyAccountMapper.getOnedayAggregateByHour(startTime, accountId);
            String lastDay = DateUtils.getLastDay(startTime, 1);
            yesterday = etlHourlyAccountMapper.getOnedayAggregateByHour(lastDay, accountId);
        } else {
            today = etlDailyAccountMapper.getOnedayAggregatebyDaily(startTime, endTime, accountId);
            int days = DateUtils.dateDiff(startTime, endTime);
            String endTime2 = DateUtils.getLastDay(startTime, 1);
            String startTime2 = DateUtils.getLastDay(endTime2, days);
            yesterday = etlDailyAccountMapper.getOnedayAggregatebyDaily(startTime2, endTime2, accountId);
        }
        if (!Check.isNull(today) && !Check.isNull(yesterday)) {
            BigDecimal tcharge = today.getCharge();
            BigDecimal ycharge = yesterday.getCharge();
            if (ycharge.compareTo(BigDecimal.ZERO) != 0 && ycharge.compareTo(BigDecimal.ZERO) != 0) {
                BigDecimal grew = tcharge.subtract(ycharge).divide(ycharge, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)).setScale(2, RoundingMode.HALF_UP);
                today.setGrew(grew);
            }
        }
        JSONObject obj = new JSONObject();
        obj.put("today", today);
        obj.put("yesterday", yesterday);
        return Result.ok(obj);
    }

    @Override
    public Result<Object> getEtlReportList(JSONObject request) {
        Long accountId = request.getLong("accountId");
        String startTime = request.getString("startTime");
        String value = request.getString("value");
        if (Check.isNull(accountId) || Check.isNull(startTime) || Check.isNull(value)) {
            return Result.error("必填参数为空");
        }
        //type alone 是独立字段例如:charge,activation，more是复杂字段
        String type = "more";
        if (CheckParametersEnum.isInclude(value)) {
            type = "alone";
            value = CheckParametersEnum.getSqlName(value);
        }
        String endTime = request.getString("endTime");
        JSONObject obj = new JSONObject();
        List<JSONObject> todayList = null;
        List<JSONObject> yesterdayList = null;
        String updateTime = "";
        if (endTime.equals(startTime)) {
            updateTime = etlHourlyAccountMapper.getNewlyUpdateTime();
            if ("photo_share".equals(value)) {
                value = "share";
            }
            if ("photo_comment".equals(value)) {
                value = "comment";
            }
            if ("play_3s_count".equals(value)) {
                value = value = request.getString("value");
                type = "more";
            }
            todayList = etlHourlyAccountMapper.getOnedayEtlReportList(startTime, accountId, value, type);
            String lastDay = DateUtils.getLastDay(startTime, 1);
            yesterdayList = etlHourlyAccountMapper.getOnedayEtlReportList(lastDay, accountId, value, type);
            completionTime(todayList);
            completionTime(yesterdayList);
        } else {
            if (value.equals("play_3s_ratio")) {
                value = request.getString("value");
                type = "more";
            }
            updateTime = etlDailyAccountMapper.getNewlyUpdateTime();
            todayList = etlDailyAccountMapper.getOnedayEtlReportList(startTime, endTime, accountId, value, type);
            int days = DateUtils.dateDiff(startTime, endTime);
            String endTime2 = DateUtils.getLastDay(startTime, 1);
            String startTime2 = DateUtils.getLastDay(endTime2, days);
            yesterdayList = etlDailyAccountMapper.getOnedayEtlReportList(startTime2, endTime2, accountId, value, type);
            int todayNum = Check.isNull(todayList) ? 0 : todayList.size();
            int yesterdayNum = Check.isNull(yesterdayList) ? 0 : yesterdayList.size();
            days += 1;
            List<String> dayList = null;
            if (days > todayNum) {
                dayList = DateUtils.getDays(startTime, endTime);
                completionDate(todayList, dayList);
            }
            if (days > yesterdayNum) {
                dayList = DateUtils.getDays(startTime2, endTime2);
                completionDate(yesterdayList, dayList);
            }
            statDateListSort(todayList);
            statDateListSort(yesterdayList);
        }
        obj.put("today", todayList);
        obj.put("yesterday", yesterdayList);
        obj.put("updateTime", updateTime);
        return Result.ok(obj);
    }

    /**
     * 补全日期
     */
    private void completionDate(List<JSONObject> dataList, List<String> dayList) {
        List<String> newDayList = new ArrayList<>();
        for (JSONObject data : dataList) {
            newDayList.add(data.getString("statDate"));
        }
        for (String day : dayList) {
            if (!newDayList.contains(day)) {
                JSONObject obj = new JSONObject();
                obj.put("statDate", day);
                obj.put("value", 0);
                dataList.add(obj);
            }
        }
    }

    /**
     * 补全时辰
     */
    private void completionTime(List<JSONObject> dataList) {
        List<Integer> newDayList = new ArrayList<>();
        for (JSONObject data : dataList) {
            newDayList.add(data.getInteger("statHour"));
        }
        List<Integer> dayList = new ArrayList<>();
        for (int i = 0; i < 23; i++) {
            dayList.add(i);
        }
        for (Integer hour : dayList) {
            if (!newDayList.contains(hour)) {
                JSONObject obj = new JSONObject();
                obj.put("statHour", hour);
                obj.put("value", 0);
                dataList.add(obj);
            }
        }
        statHourListSort(dataList);
    }

    private static void statDateListSort(List<JSONObject> list) {
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date dt1 = format.parse(o1.getString("statDate"));
                    Date dt2 = format.parse(o2.getString("statDate"));
                    return dt1.compareTo(dt2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    private static void statHourListSort(List<JSONObject> list) {
        Collections.sort(list, new Comparator<JSONObject>() {
            @Override
            public int compare(JSONObject o1, JSONObject o2) {
                try {
                    Integer dt1 = o1.getInteger("statHour");
                    Integer dt2 = o2.getInteger("statHour");
                    return dt1.compareTo(dt2);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return 0;
            }
        });
    }

    @Override
    public Result<Object> getMaxChargeAccountIdByUser(String userId) {
        JSONObject obj = etlDailyAccountMapper.getMaxChargeAccountId(userId);
        if (Check.isNull(obj)) {
            obj = etlDailyAccountMapper.getMaxChargeAccountId(null);
        }
        return Result.ok(obj.getLong("accountId"));
    }

    @Override
    public Result<Object> getMaxChargeAccountId(Long accountId) {
        JSONObject obj = new JSONObject();
        UserAllocation userAllocation = allocationMapper.getUserAllocation(accountId);
        if (!Check.isNull(userAllocation)) {
            obj.put("accountName", userAllocation.getAuthName());
            obj.put("status", userAllocation.getAccountStatus());
            obj.put("statusStr", userAllocation.getAccountStatus() == 0 ? "投放中" : "无效");
        }
        Integer counts = kuaiShouCreativeMapper.getRejectedCountsforAccountId(accountId);
        obj.put("rejectedCounts", counts);
        obj.put("accountId", accountId);
        CtopOauthToken oauthToken = oauthTokenService.getTokenByAccountId(accountId);
        if (Check.isNull(oauthToken)) {
            Result result = new Result();
            result.setResult(obj);
            result.setSuccess(false);
            result.setCode(500);
            result.setMessage("未获取到账户信息");
            return result;
        }
        obj.put("totalBalance", getBalance(oauthToken));
        return Result.ok(obj);
    }

    private BigDecimal getBalance(CtopOauthToken oauthToken) {
        JSONObject fundJson = iKuaishouInterfaceService.fundGet(oauthToken);
        if (!Check.isNull(fundJson)) {
            return fundJson.getBigDecimal("balance"); // 余额
        }
        return new BigDecimal(0);
    }

    /**
     * 运营盯盘，---------个人绩效
     */
    @Override
    public Result<Object> queryPersonalAchievements(String userId) {
        Map<String, Object> paramsMap = new HashMap<>();
        //本周一
        String monday = DateUtils.getdateFromWeek(1);
        //当天日期
        String today = DateUtils.formatDate(new Date());
        //上周一日期
        String lastStartDate = DateUtils.getLastDay(monday, 7);
        //上周当天日期
        String lastEndDate = DateUtils.getLastDay(today, 7);
        paramsMap.put("lastStartDate", lastStartDate);
        paramsMap.put("lastEndDate", lastEndDate);
        paramsMap.put("startDate", monday);
        paramsMap.put("today", today);
        paramsMap.put("userId", userId);
        JSONObject data = hourlyAccountMapper.queryPersonalAchievements(paramsMap);
        if (!Check.isNull(data)) {
            Integer totle = 0;
            Integer rank = 0;
            paramsMap.put("mStartDate", DateUtils.dateformat(DateUtils.initDateByMonth(), DateUtils.WEB_FORMAT));
            JSONObject user = etlDailyAccountMapper.getMonthlyRank(paramsMap);
            if (!Check.isNull(user)) {
                totle = user.getInteger("totle");
                rank = user.getInteger("id");
                data.put("monthCharge", user.getBigDecimal("charge"));
            }
            data.put("total", totle);
            data.put("rank", rank);
        }
        return Result.ok(data);
    }

    @Override
    public Result<Object> checkRole(String userId) {
        SysRole role = roleMapper.queryRoleByUserId(userId);
        if (Check.isNull(role)) {
            return Result.error("员工未划分角色");
        }
        boolean flag = false;
        String roleCode = role.getRoleCode();
        //TODO 后续去除 roleName相关的逻辑
        String roleName = role.getRoleName();
        if (roleName.contains("总监") || roleName.contains("经理") || roleName.contains("管理员")
                || "genera_manager_of_operations".equals(roleCode)
                || "kuaishou_operations_director".equals(roleCode)
                || "kuaishou_operations_manager".equals(roleCode)) {
            flag = true;
        }
        return Result.ok(flag);
    }

    @Override
    public Result<Object> accountPageList(JSONObject request) throws Exception {
        Integer pageNo = request.getInteger("pageNo");
        Integer pageSize = request.getInteger("pageSize");
        if (Check.isNull(pageNo)) {
            pageNo = 1;
        }
        if (Check.isNull(pageSize)) {
            pageSize = 10;
        }
        String startTime = request.getString("startTime");
        String endTime = request.getString("endTime");
        String userId = request.getString("userId");
        if (Check.isNull(startTime) && Check.isNull(userId)) {
            return Result.error("请选择时间和用户");
        }
        //参数处理
        configParameter(request);
        List<JSONObject> list = null;
        int total = 0;
        //单日数据
        if (endTime.equals(startTime)) {
            if (startTime.equals(DateUtils.formatDate(new Date()))) {
                request.put("hours", DateUtils.getNowHour());
            } else {
                request.put("hours", 24);
            }
            total = etlHourlyAccountMapper.accountPageListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlHourlyAccountMapper.accountPageList(request);
        } else {
            //多日数据
            total = etlDailyAccountMapper.accountPageListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlDailyAccountMapper.accountPageList(request);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        if (!Check.isNull(pageInfo)) {
            pageInfo.setTotal(total);
        }
        return Result.ok(pageInfo);
    }

    /**
     * 配置参数
     */
    private void configParameter(JSONObject request) throws Exception {
        Map<String, Map<String, Object>> parameter = AccountReportConstants.dicMapKs;
        parameter.remove("play3sRate");
        String filedAll = JsonResourceUtil.joinAllFiled(parameter);
        if (Check.isNull(filedAll)) {
            throw new Exception("初始化查询字段,结果为空");
        }
        request.put("filed", filedAll);
        String sortCode = request.getString("sortCode");
        if (Check.isNull(sortCode)) {
            request.put("sortCode", "sum(charge)");
        } else {
            request.put("sortCode", CheckParametersCostEnum.getFormula(sortCode));
        }
        if (Check.isNull(request.getString("sortType"))) {
            request.put("sortType", "DESC");
        }
    }


    @Override
    public Result<Object> queryNewlyData(JSONObject request) {
        String userId = request.getString("userId");
        String startTime = request.getString("startTime");
        String endTime = request.getString("endTime");
        String parameterCode = request.getString("parameterCode");
        if (Check.isNull(userId) || Check.isNull(startTime) || Check.isNull(endTime) || Check.isNull(parameterCode)) {
            return Result.error("缺失参数");
        }
        request.put("userIds", getUserIdList(userId));
        List<JSONObject> data = null;
        JSONObject result = new JSONObject();
        //单日数据
        String updateTime = "";
        if (startTime.equals(endTime)) {
            data = etlHourlyAccountMapper.queryEveryHourlyCharge(request);
            updateTime = etlHourlyAccountMapper.getNewlyUpdateTime();
        } else {
            updateTime = etlDailyAccountMapper.getNewlyUpdateTime();
            if (parameterCode.equals("campaign") || parameterCode.equals("unit")) {
                data = etlDailyAccountMapper.queryEveryDayCount(request);
            } else {
                data = etlDailyAccountMapper.queryEveryDayCharge(request);
            }
        }
        result.put("data", data);
        result.put("updateTime", updateTime);
        return Result.ok(result);
    }

    /**
     * 通过经理或者总监userId，获取其部门的员工Id
     */
    private List<String> getUserIdList(String userId) {
        SysRole role = roleMapper.queryRoleByUserId(userId);
        String roleCode = role.getRoleCode();
        List<String> ids = new ArrayList<>();
        List<JSONObject> departIds = new ArrayList<>();
        //管理员和运营总经理 可以查看所有快手的运营信息
        if ("genera_manager_of_operations".equals(roleCode) || "admin".equals(roleCode)) {
            JSONObject obj = new JSONObject();
            //快手运营部 峰级部门 ID
            obj.put("id", "024b0dc0840045afb048022a8c61253f");
            departIds.add(obj);
        } else {
            departIds = departMapper.getDepartmentIds(userId);
        }
        if (!Check.isNull(departIds)) {
            ids.add(departIds.get(0).getString("id"));
            checkDepart(departIds, ids);
        }
        List<String> userIds = null;
        if (!Check.isNull(ids)) {
            userIds = sysUserDepartMapper.getUserIds(ids);
        }
        if (Check.isNull(userIds)) {
            userIds = new ArrayList<>();
            userIds.add(userId);
        }
        return userIds;
    }

    @Override
    public Result<Object> operatingStaffDataList(JSONObject request) {
        String userId = request.getString("userId");
        String startTime = request.getString("startTime");
        String endTime = request.getString("endTime");
        if (Check.isNull(userId)||Check.isNull(startTime)||Check.isNull(endTime)) {
            return Result.error("缺少账户入参");
        }
        String sortCode = request.getString("sortCode");
        if (Check.isNull(sortCode)) {
            request.put("sortCode", "SUM(t1.charge)");
        } else {
            if ("charge".equals(sortCode)) {
                request.put("sortCode", "SUM(t1.charge)");
            }
        }
        if (Check.isNull(request.getString("sortType"))) {
            request.put("sortType", "DESC");
        }
        Integer pageNo = request.getInteger("pageNo");
        Integer pageSize = request.getInteger("pageSize");
        if (Check.isNull(pageNo)) {
            pageNo = 1;
        }
        if (Check.isNull(pageSize)) {
            pageSize = 10;
        }
        //本周一
        String weekStartTime = DateUtils.getdateFromWeek(1);
        //当天日期
        String today = DateUtils.formatDate(new Date());
        //上周一日期
        String lweekStartTime = DateUtils.getLastDay(weekStartTime, 7);
        //上周当天日期
        String lweekEndTime = DateUtils.getLastDay(today, 7);
        //昨天
        String yesterday = DateUtils.getLastDay(today, 1);
        request.put("today", today);
        request.put("weekStartTime", weekStartTime);
        request.put("lweekEndTime", lweekEndTime);
        request.put("lweekStartTime", lweekStartTime);
        request.put("yesterday", yesterday);
        //获取人群集
        request.put("userIds", getUserIdList(userId));
        List<JSONObject> list = null;
        int total = 0;
        //单日数据
        if (endTime.equals(startTime)) {
            if(!today.equals(startTime)){
                request.put("yesterday", startTime);
            }
            total = etlHourlyAccountMapper.operatingStaffDataListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlHourlyAccountMapper.operatingStaffDataList(request);
        }else {
            total = etlDailyAccountMapper.operatingStaffDataListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlDailyAccountMapper.operatingStaffDataList(request);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        if (!Check.isNull(pageInfo)) {
            pageInfo.setTotal(total);
        }
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> projectList(JSONObject request) throws Exception {
        Integer pageNo = request.getInteger("pageNo");
        Integer pageSize = request.getInteger("pageSize");
        if (Check.isNull(pageNo)) {
            pageNo = 1;
        }
        if (Check.isNull(pageSize)) {
            pageSize = 10;
        }
        String startTime = request.getString("startTime");
        String endTime = request.getString("endTime");
        String userId = request.getString("userId");
        if (Check.isNull(startTime) && Check.isNull(userId)) {
            return Result.error("请选择时间和用户");
        }
        //参数处理
        configParameter(request);
        //获取人群集
        request.put("userIds", getUserIdList(userId));
        List<JSONObject> list = null;
        int total = 0;
        //单日数据
        if (endTime.equals(startTime)) {
            if (startTime.equals(DateUtils.formatDate(new Date()))) {
                request.put("hours", DateUtils.getNowHour());
            } else {
                request.put("hours", 24);
            }
            total = etlHourlyAccountMapper.projectPageListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlHourlyAccountMapper.projectPageList(request);
        } else {
            //多日数据
            total = etlDailyAccountMapper.projectPageListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlDailyAccountMapper.projectPageList(request);
        }

        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        if (!Check.isNull(pageInfo)) {
            pageInfo.setTotal(total);
        }
        return Result.ok(pageInfo);
    }

    @Override
    public Result<Object> leaderAccountPageList(JSONObject request) throws Exception {
        Integer pageNo = request.getInteger("pageNo");
        Integer pageSize = request.getInteger("pageSize");
        if (Check.isNull(pageNo)) {
            pageNo = 1;
        }
        if (Check.isNull(pageSize)) {
            pageSize = 10;
        }
        String startTime = request.getString("startTime");
        String endTime = request.getString("endTime");
        String userId = request.getString("userId");
        if (Check.isNull(startTime) && Check.isNull(userId)) {
            return Result.error("请选择时间和用户");
        }
        //参数处理
        configParameter(request);
        List<JSONObject> list = null;
        int total = 0;
        if (Check.isNull(request.getLong("projectId"))) {
            //获取人群集
            request.put("userIds", getUserIdList(userId));
        }
        //单日数据
        if (endTime.equals(startTime)) {
            if (startTime.equals(DateUtils.formatDate(new Date()))) {
                request.put("hours", DateUtils.getNowHour());
            } else {
                request.put("hours", 24);
            }
            total = etlHourlyAccountMapper.leaderAccountPageListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlHourlyAccountMapper.leaderAccountPageList(request);
        } else {
            //多日数据
            total = etlDailyAccountMapper.leaderAccountPageListTotal(request);
            PageHelper.startPage(pageNo, pageSize, false);
            list = etlDailyAccountMapper.leaderAccountPageList(request);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        if (!Check.isNull(pageInfo)) {
            pageInfo.setTotal(total);
        }
        return Result.ok(pageInfo);
    }

    /**
     * 递归查询出所有部门
     */
    private void checkDepart(List<JSONObject> departIds, List<String> ids) {
        for (JSONObject depart : departIds) {
            ids.add(depart.getString("id"));
        }
        departIds = departMapper.checkLowestLevelDepartment(departIds);
        if (!Check.isNull(departIds)) {
            checkDepart(departIds, ids);
        }
    }
}
