package org.jeecg.modules.ctop.service.impl;

import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.ExportExcelUtils;
import cn.com.ctop.common.module.utils.HttpUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.constant.AccountReportConstants;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.JsonResourceUtil;
import org.jeecg.modules.ctop.mapper.MaterialReportOverViewMapper;
import org.jeecg.modules.ctop.service.IMaterialReportOverViewService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class MaterialReportOverViewServiceImpl implements IMaterialReportOverViewService {

    @Resource
    private MaterialReportOverViewMapper materialReportOverViewMapper;

    @Autowired
    private ISysRoleService roleService;

    @Override
    public Set<String> recursiveQuerySubordinate(String userId) {
        Set<String> result;
        //查询当前用户是否存在下级
        Set<String> subordinate = materialReportOverViewMapper.recursiveQuerySubordinateByLeader(userId);
        if (subordinate.isEmpty()) {
            subordinate.add(userId);
            return subordinate;
        } else {
            result = querySubordinate(subordinate, subordinate);
            result.add(userId);
        }
        return result;
    }

    @Override
    public Set<JSONObject> queryProjectBy(Set<String> userIds, int mediaId) {
        JSONArray mediaIds = new JSONArray();
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            mediaIds.add(1);
            mediaIds.add(3);
        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            mediaIds.add(2);
            mediaIds.add(4);
        }
        return materialReportOverViewMapper.queryProjectBy(userIds, mediaIds);
    }

    @Override
    public JSONArray queryProjectIdBy(Set<String> userIds, int mediaId) {
        JSONArray mediaIds = new JSONArray();
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            mediaIds.add(1);
            mediaIds.add(3);
        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            mediaIds.add(2);
            mediaIds.add(4);
        }
        return materialReportOverViewMapper.queryProjectIdBy(userIds, mediaIds);
    }

    @Override
    public Map<String, Object> getTotalModule(int mediaId, String startDate, String endDate, JSONArray projects) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowData = sdf.format(new Date());

        Map<String, Object> result = new HashMap<>();
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(mediaId);
        }
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            //总消耗
            BigDecimal cost = materialReportOverViewMapper.queryBytedanceCost(startDate, endDate, projects);
            //上阶段消耗
            BigDecimal lastCost = materialReportOverViewMapper.queryBytedanceCost(DateUtils.addDay(startDate, -DateUtils.dateDiff(startDate, endDate)-1), DateUtils.addDay(startDate, -1), projects);
            result.put("costTotal", cost);
            //同比 （本阶段截止昨天消耗-上一个阶段截止和昨天对应日期的消耗）/上一个阶段截止和昨天对应日期的消耗 X 100%
            result.put("yearOnYearCompare", countLink(cost,lastCost));
            //昨日消耗
            BigDecimal yesterdayCost = materialReportOverViewMapper.queryBytedanceCost(DateUtils.addDay(nowData, -1), DateUtils.addDay(nowData, -1), projects);
            //前天消耗
            BigDecimal beforeYesterdayCost = materialReportOverViewMapper.queryBytedanceCost(DateUtils.addDay(nowData, -2), DateUtils.addDay(nowData, -2), projects);
            result.put("yesterdayCost", yesterdayCost);
            //环比 （昨日消耗-前日消耗）/前日消耗 X 100%
            result.put("chainCompare", countLink(yesterdayCost,beforeYesterdayCost));

        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            //总消耗
            BigDecimal cost = materialReportOverViewMapper.queryKuaishouCost(startDate, endDate, projects);
            //上阶段
            BigDecimal lastCost = materialReportOverViewMapper.queryKuaishouCost(DateUtils.addDay(startDate, -DateUtils.dateDiff(startDate, endDate)-1), DateUtils.addDay(startDate, -1), projects);
            result.put("costTotal", cost);
            //同比 （本阶段截止昨天消耗-上一个阶段截止和昨天对应日期的消耗）/上一个阶段截止和昨天对应日期的消耗 X 100%
            result.put("yearOnYearCompare", countLink(cost,lastCost));
            //昨日消耗
            BigDecimal yesterdayCost = materialReportOverViewMapper.queryKuaishouCost(DateUtils.addDay(nowData, -1), DateUtils.addDay(nowData, -1), projects);
            //前天消耗
            BigDecimal beforeYesterdayCost = materialReportOverViewMapper.queryKuaishouCost(DateUtils.addDay(nowData, -2), DateUtils.addDay(nowData, -2), projects);
            result.put("yesterdayCost", yesterdayCost);
            //环比 （昨日消耗-前日消耗）/前日消耗 X 100%
            result.put("chainCompare", countLink(yesterdayCost,beforeYesterdayCost));
        }
        return result;
    }



    @Override
    public Map<String, Object> sumDataVideoNewEffective(int mediaId, String startDate, String endDate, JSONArray projects) {
        Map<String, Object> result = new HashMap<>();
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(mediaId);
        }
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
              //视频上新
            List<Map<String, String>> videoList = materialReportOverViewMapper.queryMaterialCountList(startDate+" 00:00:00", endDate+" 23:59:59", projects);
            //总数
            long videoTotal = videoList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            result.put("videoList",videoList);
            result.put("videoTotal",videoTotal);
            //素材使用率 = 有消耗的素材 / 总数 * 100%
            long videoCost = materialReportOverViewMapper.queryMaterialCostList(startDate+" 00:00:00", endDate+" 23:59:59", projects);
            result.put("useCompare", Check.isNull(videoCost) ? 0: new BigDecimal(videoCost).divide(new BigDecimal(videoTotal),4, RoundingMode.HALF_UP));
            //有效视频
            List<Map<String, String>> effectiveList = materialReportOverViewMapper.selectEffectiveMaterialVideoBytedance(startDate,endDate, projects);
            //总数
            long effectiveTotal = effectiveList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            result.put("effectiveList",effectiveList);
            result.put("effectiveTotal",effectiveTotal);
            //素材有效率 = 有效视频数量 / 视频总数 X 100%
            result.put("effectiveCompare",Check.isNull(videoCost) ? 0: new BigDecimal(effectiveTotal).divide(new BigDecimal(videoTotal),4, RoundingMode.HALF_UP));

        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {

            //视频上新
            List<Map<String, String>> videoList = materialReportOverViewMapper.queryMaterialCountListKs(startDate+" 00:00:00", endDate+" 23:59:59", projects);
            //总数
            long videoTotal = videoList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            result.put("videoList",videoList);
            result.put("videoTotal",videoTotal);
            //素材使用率 = 有消耗的素材 / 总数 * 100%
            long videoCost = materialReportOverViewMapper.queryMaterialCostListKs(startDate+" 00:00:00", endDate+" 23:59:59", projects);
            result.put("useCompare", Check.isNull(videoCost) ? 0: new BigDecimal(videoCost).divide(new BigDecimal(videoTotal),4, RoundingMode.HALF_UP));
            //有效视频
            List<Map<String, String>> effectiveList = materialReportOverViewMapper.selectEffectiveMaterialVideoKs(startDate,endDate, projects);
            //总数
            long effectiveTotal = effectiveList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            result.put("effectiveList",effectiveList);
            result.put("effectiveTotal",effectiveTotal);
            //素材有效率 = 有效视频数量 / 视频总数 X 100%
            result.put("effectiveCompare",Check.isNull(videoTotal) ? 0 : new BigDecimal(effectiveTotal).divide(new BigDecimal(videoTotal),4, RoundingMode.HALF_UP));

        }
        return result;
    }

    //爆款视频
    @Override
    public Map<String, Object> sumDataVideoHot(int mediaId, String startDate, String endDate, JSONArray projects) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowData = sdf.format(new Date());
        Map<String, Object> result = new HashMap<>();
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(mediaId);
        }
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            //爆款视频
            List<Map<String, String>> hotList = materialReportOverViewMapper.selectHotMaterialVideoBytedance(startDate,endDate, projects);
            //总数
            long hotTotal = hotList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            result.put("hotList",hotList);
            result.put("hotTotal",hotTotal);
            //上阶段
            List<Map<String, String>> lastHostList = materialReportOverViewMapper.selectHotMaterialVideoBytedance(DateUtils.addDay(startDate, -DateUtils.dateDiff(startDate, endDate)-1), DateUtils.addDay(startDate, -1), projects);
            long lastHotTotal = lastHostList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            //同比 （本阶段截止昨天的爆款视频数量-上一个阶段截止和昨天对应日期的爆款视频数量）/上一个阶段截止和昨天对应日期的爆款视频数量X 100%
            result.put("hotYearOnYearCompare", countLink(new BigDecimal(hotTotal),new BigDecimal(lastHotTotal)));
            //昨日消耗
            List<Map<String, String>> yesterdayHost = materialReportOverViewMapper.selectHotMaterialVideoBytedance(DateUtils.addDay(nowData, -1),DateUtils.addDay(nowData, -1), projects);
            //前天消耗
            List<Map<String, String>> beforeYesterdayHost = materialReportOverViewMapper.selectHotMaterialVideoBytedance(DateUtils.addDay(nowData, -2), DateUtils.addDay(nowData, -2), projects);
            long yesterday = yesterdayHost.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            long before = beforeYesterdayHost.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            //环比 （昨日-前日）/前日消耗 X 100%
            result.put("hostCompare", countLink(new BigDecimal(yesterday),new BigDecimal(before)));

        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            //爆款视频
            List<Map<String, String>> hotList = materialReportOverViewMapper.selectHotMaterialVideoKs(startDate,endDate, projects);
            //总数
            long hotTotal = hotList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            result.put("hotList",hotList);
            result.put("hotTotal",hotTotal);
            //上阶段
            List<Map<String, String>> lastHostList = materialReportOverViewMapper.selectHotMaterialVideoKs(DateUtils.addDay(startDate, -DateUtils.dateDiff(startDate, endDate)-1), DateUtils.addDay(startDate, -1), projects);
            long lastHotTotal = lastHostList.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            //同比 （本阶段截止昨天的爆款视频数量-上一个阶段截止和昨天对应日期的爆款视频数量）/上一个阶段截止和昨天对应日期的爆款视频数量X 100%
            result.put("hotYearOnYearCompare", countLink(new BigDecimal(hotTotal),new BigDecimal(lastHotTotal)));
            //昨日消耗
            List<Map<String, String>> yesterdayHost = materialReportOverViewMapper.selectHotMaterialVideoKs(DateUtils.addDay(nowData, -1),DateUtils.addDay(nowData, -1), projects);
            //前天消耗
            List<Map<String, String>> beforeYesterdayHost = materialReportOverViewMapper.selectHotMaterialVideoKs(DateUtils.addDay(nowData, -2), DateUtils.addDay(nowData, -2), projects);
            long yesterday = yesterdayHost.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            long before = beforeYesterdayHost.stream().collect(Collectors.summarizingInt(s->Integer.valueOf(String.valueOf(s.get("count"))))).getSum();
            //环比 （昨日-前日）/前日消耗 X 100%
            result.put("hostCompare", countLink(new BigDecimal(yesterday),new BigDecimal(before)));
        }
        return result;
    }







    @Override
    public List<JSONObject> getTotalChat(int mediaId, String startDate, String endDate, JSONArray projects) {
        List<JSONObject> result = new ArrayList<>();
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(mediaId);
        }
        try {
            if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
                if (DateUtils.isMoreSixMonth(startDate, endDate)) {
                    result = materialReportOverViewMapper.queryBytedanceChatGroupMonth(startDate, endDate, projects);
                } else {
                    result = materialReportOverViewMapper.queryBytedanceChat(startDate, endDate, projects);
                }
            } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
                if (DateUtils.isMoreSixMonth(startDate, endDate)) {
                    result = materialReportOverViewMapper.queryKuaishouChatGroupMonth(startDate, endDate, projects);
                } else {
                    result = materialReportOverViewMapper.queryKuaishouChat(startDate, endDate, projects);
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public JSONObject getTagProportion(int mediaId, String startDate, String endDate, int tagId) {
        return null;
    }

    @Override
    public List<JSONObject> getTopMaterialList(int mediaId, String startDate, String endDate, JSONArray projects, Integer channelType) {
        List<JSONObject> result = new ArrayList<>();
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(mediaId);
        }
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            result = materialReportOverViewMapper.queryBytedanceTopMaterial(startDate, endDate, projects);

        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            result = materialReportOverViewMapper.queryKuaishouTopMaterial(startDate, endDate, projects, channelType);
        }
        return result;
    }

    @Override
    public PageInfo<JSONObject> getTopMaterialList(int mediaId, String startDate, String endDate, JSONArray projects
            , String channelType, String md5, String target, String order, int pageNo, int pageSize) {
        PageInfo<JSONObject> result = new PageInfo<>();
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(mediaId);
        }
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.dicMapByVideo);
            PageHelper.startPage(pageNo, pageSize, false);
            List<JSONObject> list = materialReportOverViewMapper.queryBytedanceMaterialReport(filedAll, startDate, endDate, projects, md5, target, order);
            Long count = materialReportOverViewMapper.queryBytedanceMaterialReportCount(startDate, endDate, projects, md5);
            result.setTotal(count);
            result.setList(list);
        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.kuaishouVideoReportMap);
            PageHelper.startPage(pageNo, pageSize, false);
            List<JSONObject> list = materialReportOverViewMapper.queryKuaishouMaterialReport(filedAll, startDate, endDate, projects, channelType, md5, target, order);
            Long count = materialReportOverViewMapper.queryKuaishouMaterialReportCount(startDate, endDate, projects, channelType, md5);
            result.setTotal(count);
            result.setList(list);
        }
        return result;
    }

    @Override
    public void exportBytedanceExcel(JSONObject requestBody, HttpServletRequest request, HttpServletResponse response) {
        JSONArray projects= requestBody.getJSONArray("projects");
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(requestBody.getInteger("mediaId"));
        }
        JSONArray columns = requestBody.getJSONArray("columns");
        if (columns.isEmpty()) {
            //默认消耗必查
            columns.add("cost");
        }
        String filed = JsonResourceUtil.joinFiled(AccountReportConstants.dicMapByVideo, columns);
        List<String> titles = new ArrayList<>(JsonResourceUtil.joinTitle(AccountReportConstants.dicMapByVideo, columns));

        titles.add(0, "唯一标识");
        titles.add(1, "视频");
        titles.add(2, "视频名称");
        titles.add(3, "项目名称");
        columns.add(0, "signature");
        columns.add(1, "url");
        columns.add(2, "materialName");
        columns.add(3, "projectName");

        List<JSONObject> excelData = materialReportOverViewMapper.queryBytedanceMaterialReport(filed, requestBody.getString("startDate"), requestBody.getString("endDate"),
                projects, requestBody.getString("md5"),requestBody.getString("target")==null?"cost":requestBody.getString("target")
                , requestBody.getString("order")==null?"desc":requestBody.getString("order"));

        if (null != excelData && excelData.isEmpty()) {
            return;
        }
        List<List<Object>> excelList = new ArrayList<>();
        excelData.forEach(data -> {
            List<Object> temp = new ArrayList<>();
            columns.forEach(k -> {
                temp.add(data.get(k.toString()));
            });
            excelList.add(temp);
        });
        try {
            String[] headers = titles.toArray(new String[titles.size()]);
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            eeu.exportExcel(workbook, 0, "头条视频报表", headers, excelList);
            HttpUtils.setResponseHeader(response, "头条视频报表.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public void exportKuaishouExcel(JSONObject requestBody, HttpServletRequest request, HttpServletResponse response) {
        JSONArray projects= requestBody.getJSONArray("projects");
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(requestBody.getInteger("mediaId"));
        }
        JSONArray columns2 = new JSONArray();
        columns2.add(0, "signature");
        columns2.add(1, "url");
        columns2.add(2, "projectName");
        columns2.add(3, "materialName");
        JSONArray columns = requestBody.getJSONArray("columns");
        for (int i = 0; i < columns.size(); i++) {
            columns2.add(columns2.size(), columns.getString(i));
        }
        List<String> titles = getfileIds(AccountReportConstants.kuaishouVideoReportDict, columns2);
        String filedAll = JsonResourceUtil.joinAllFiled(AccountReportConstants.kuaishouVideoReportMap);
        List<JSONObject> excelData = materialReportOverViewMapper.queryKuaishouMaterialReport(filedAll, requestBody.getString("startDate"), requestBody.getString("endDate"),
                projects, requestBody.getString("channelType"),requestBody.getString("md5"), requestBody.getString("target")==null?"cost":requestBody.getString("target")
                , requestBody.getString("order")==null?"desc":requestBody.getString("order"));
        if (null != excelData && excelData.isEmpty()) {
            return;
        }
        List<List<Object>> excelList = new ArrayList<>();
        for (int i = 0; i < excelData.size(); i++) {
            List<Object> temp = new ArrayList<>();
            JSONObject jsonObject = excelData.get(i);
            for (int j = 0; j < columns2.size(); j++) {
                String key = columns2.getString(j);
                String value = jsonObject.getString(key);
                temp.add(value);
            }
            excelList.add(temp);
        }

        try {
            String[] strings = titles.toArray(new String[]{});
            OutputStream os = response.getOutputStream();
            ExportExcelUtils eeu = new ExportExcelUtils();
            XSSFWorkbook workbook = new XSSFWorkbook();
            eeu.exportExcel(workbook, 0, "快手素材报表", strings, excelList);
            HttpUtils.setResponseHeader(response, "快手素材.xlsx");
            workbook.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
    }

    @Override
    public List<JSONObject> getTopDesignList(Integer mediaId, String startDate, String endDate, JSONArray projects, String type) {
        List<JSONObject> result = new ArrayList<>();
        if (projects.isEmpty()) {
            projects = getProjectsByCurrentUser(mediaId);
        }
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            result = materialReportOverViewMapper.queryBytedanceTopDesign(startDate, endDate, projects, type);

        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            result = materialReportOverViewMapper.queryKuaishouTopDesign(startDate, endDate, projects, type);
        }
        return result;
    }

    @Override
    public JSONObject getMaterialDetailInfo(int mediaId, String md5) {
        JSONObject result = new JSONObject();
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            result = materialReportOverViewMapper.queryBytedanceVideoDetail(md5);
        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            result = materialReportOverViewMapper.queryKuaishouVideoDetail(md5);

        }
        return result;
    }

    @Override
    public Map<String, Object> materialDetailAnalyse(int mediaId, String md5) {
        Map<String, Object> result = new HashMap<>();
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            Long projectId = materialReportOverViewMapper.queryBytedanceProjectIdByMd5(md5);
            result.put("cost", materialReportOverViewMapper.queryBytedanceCostByMd5(md5, projectId));
            result.put("click", materialReportOverViewMapper.queryBytedanceClickByMd5(md5, projectId));
            result.put("materialShow", materialReportOverViewMapper.queryBytedanceMaterialShowByMd5(md5, projectId));
            result.put("play100Rate", materialReportOverViewMapper.queryBytedancePlay100RateByMd5(md5, projectId));
            result.put("likeMaterial", materialReportOverViewMapper.queryBytedanceLikeMaterialByMd5(md5, projectId));
            result.put("commentMaterial", materialReportOverViewMapper.queryBytedanceCommentMaterialByMd5(md5, projectId));
            result.put("shareMaterial", materialReportOverViewMapper.queryBytedanceShareMaterialByMd5(md5, projectId));
            result.put("follow", materialReportOverViewMapper.queryBytedanceFollowByMd5(md5, projectId));
        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            Long projectId = materialReportOverViewMapper.queryKuaishouProjectIdByMd5(md5);
            result.put("charge", materialReportOverViewMapper.queryKuaishouChargeByMd5(md5, projectId));
            result.put("photoShow", materialReportOverViewMapper.queryKuaishouPhotoShowByMd5(md5, projectId));
            result.put("photoClick", materialReportOverViewMapper.queryKuaishouPhotoClickByMd5(md5, projectId));
            result.put("aclick", materialReportOverViewMapper.queryKuaishouAClickByMd5(md5, projectId));
            result.put("bclick", materialReportOverViewMapper.queryKuaishouBClickByMd5(md5, projectId));
            result.put("activation", materialReportOverViewMapper.queryKuaishouActivationByMd5(md5, projectId));
            result.put("play3sRate", materialReportOverViewMapper.queryKuaishouPlay3sRateByMd5(md5, projectId));
        }
        return result;
    }

    @Override
    public List<JSONObject> getMaterialDetailChat(int mediaId, String md5) {
        List<JSONObject> result = new ArrayList<>();
        if (mediaId == CtopAdConstant.PLATFORM_TYPE_BYTEDANCE_INT) {
            result = materialReportOverViewMapper.queryBytedanceVideoChat(md5);
        } else if (mediaId == CtopAdConstant.PLATFORM_TYPE_KUAISHOU_INT) {
            result = materialReportOverViewMapper.queryKuaishouVideoChat(md5);
        }
        return result;
    }

    //递归查询
    private Set<String> querySubordinate(Set<String> leaderIds, Set<String> result) {
        if (leaderIds.isEmpty()) {
            return result;
        }
        Set<String> temp = materialReportOverViewMapper.recursiveQuerySubordinateByLeaders(leaderIds);
        result.addAll(temp);
        querySubordinate(temp, result);
        return result;
    }

    //当项目为空的时候，根据当前登录人查询可查看的所有项目集合
    private JSONArray getProjectsByCurrentUser(int mediaId) {
        String currentUser = ((LoginUser) SecurityUtils.getSubject().getPrincipal()).getId();
        //String currentUser = "e9ca23d68d884d4ebb19d07889727dae";
        //TODO 为了解决管理员等角色初始化查全部项目查询效率慢的问题判断角色，待优化
        String roleCode = roleService.getRoleCodeByUserId(currentUser);
        if (roleCode.equals("admin")) {
            return null;
        }
        return Check.isNull(queryProjectIdBy(recursiveQuerySubordinate(currentUser), mediaId)) ? null : queryProjectIdBy(recursiveQuerySubordinate(currentUser), mediaId);
    }
    private List<String> getfileIds(Map<String, Map<String, Object>> kuaishouVideoReportMap, JSONArray columns) {
        List<String> titles = new ArrayList<>();
        for (int i = 0; i < columns.size(); i++) {
            String string = columns.getString(i);
            Map<String, Object> stringObjectMap = kuaishouVideoReportMap.get(string);
            if (Check.isNull(stringObjectMap)) {
                titles.add("-");
                continue;
            }
            Object comment = stringObjectMap.get("comment");
            titles.add(String.valueOf(comment));

        }
        return titles;
    }

    //环比计算
    private  BigDecimal countLink(BigDecimal numA, BigDecimal numB) {
        BigDecimal link = new BigDecimal("0");
        if (Check.isNull(numA) || Check.isNull(numB)){
            return link;
        }
        if (numB.compareTo(BigDecimal.ZERO)!=0) {
            link = (numA.subtract(numB)).divide(numB, 4, RoundingMode.HALF_UP);
        }
        return link;
    }


    /**
     * 同比 (当前 - 上阶段 ） / 上阶段
     * @param current 当前阶段数值
     * @param last 上阶段数值
     * @return
     */
    private BigDecimal yearOnYearCompare(BigDecimal current,BigDecimal last){
        BigDecimal yearOnYear = new BigDecimal("0");
        if (last.compareTo(BigDecimal.ZERO)!=0) {
            // (当前 - 上阶段 ） / 上阶段
            yearOnYear = (current.subtract(last)).divide(last,20,BigDecimal.ROUND_HALF_UP);
        }
        return yearOnYear;
    }


}
