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

import cn.com.ctop.performanceappraisal.entity.OptimizerConfig;
import cn.com.ctop.performanceappraisal.entity.Performance;
import cn.com.ctop.performanceappraisal.mapper.PerformanceMapper;
import cn.com.ctop.performanceappraisal.service.IOptimizerConfigService;
import cn.com.ctop.performanceappraisal.vo.OptimizerCostDetailVO;
import cn.com.ctop.planeprojectcost.entity.PlaneProjectCost;
import cn.com.ctop.planeprojectcost.mapper.PlaneProjectCostMapper;
import cn.com.ctop.userefficientvideomap.entity.*;
import cn.com.ctop.userefficientvideomap.mapper.UserEfficientVideoMapMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.system.entity.EffiRateComparator;
import org.jeecg.modules.system.entity.UserDto;
import org.jeecg.modules.system.mapper.SysRoleMapper;
import org.jeecg.modules.system.service.IPerformanceService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * 设计师季度绩效表
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-12-10
 */
@Slf4j
@Service
public class PerformanceServiceImpl2 extends ServiceImpl<PerformanceMapper, Performance> implements IPerformanceService2 {

    @Autowired
    private PerformanceMapper performanceMapper;
    @Autowired
    private UserEfficientVideoMapMapper userEfficientVideoMapMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private IOptimizerConfigService optimizerConfigService;
    @Autowired
    private PlaneProjectCostMapper planeProjectCostMapper;

    //获取季度有效视频和角色对应关系的定时任务
    //每天定时任务：角色对应本季度有效视频计算--需要工具类有效视频计算工具类
    public void efficientVideoTask(String calcDateStr) {
        //本周五-下一个周四 为一周的计算起止时间
        //
        //例如：20191220-20191226这周
        //总视频数：这一周时间内发布的所有视频的总数；
        //有效视频数：20191129-20191205这一周发布的所有视频，在20191206-20191219这两周内成为有效视频的数量；

        //1.有效视频应分平台，不同平台的人使用自己平台的计算（极少会有相同素材在两个平台上的交叉，这种情况下人工处理）
        //2.设置周五为一个星期的第一天，则下一周的周四为一周的最后一天
        //3.使用当前时间计算出周五的时间，然后根据此时间找出本周计算有效视频的时间，进行计算
        //
        Date calcDate = null;
        try {
            calcDate = DateUtils.parseDate(calcDateStr, "yyyy-MM-dd");
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //传入时间，获取对应的年份
        Date friday = DateUtils.getFriday(new Date());
        String effiCalcStart = DateUtils.formatDate(DateUtils.addDay(friday, -14)); //计算有效视频开始的时间
        String effiCalcEnd = DateUtils.formatDate(DateUtils.addDay(friday, -1)); //计算有效视频结束的时间

        String effiStart = DateUtils.formatDate(DateUtils.addDay(friday, -21)); //有效视频发布开始时间
        String effiEnd = DateUtils.formatDate(DateUtils.addDay(friday, -15)); //有效视频发布结束时间

        //以周为维度计算
        //获取当前时间所在周所在年份以及季度（如果季度末最后一周的天数>=4则这周属于此季度，否则属于下一个季度）
        Map<String, Integer> yearQuarterMap = DateUtils.getYearQuarter(calcDate);
        int thisYear = yearQuarterMap.get("year"); //获取当天所在周所在的年份
        int thisMonth = yearQuarterMap.get("month"); //获取当天所在周所在的月份
        int thisQuarter = yearQuarterMap.get("quarter"); //获取当天所在周坐在的季度

        //获取时间段内所有<快手>的有效视频
        List<EffiVideoDTO> EffiVideoDTOList = userEfficientVideoMapMapper.getUserVideoMap(effiStart, effiEnd, effiCalcStart, effiCalcEnd);

        for (EffiVideoDTO effiVideoDTO : EffiVideoDTOList) {
            //判断此视频是否已经在关系表中存在，如果已经存在则说明此视频已经存在,跳过即可
            //有效视频的逻辑是无论是快手还是头条
            int signatureCount = userEfficientVideoMapMapper.getEffiVideoCountBySignature(effiVideoDTO.getSignature(), new Integer(1));//1快手 2头条
            if (signatureCount != 0) {
                continue;
            }

            UserEfficientVideoMap shot = new UserEfficientVideoMap();
            UserEfficientVideoMap plane = new UserEfficientVideoMap();
            UserEfficientVideoMap plan = new UserEfficientVideoMap();
            UserEfficientVideoMap clip = new UserEfficientVideoMap();

            //拍摄
            shot.setUserId(effiVideoDTO.getShotId());
            shot.setEfficientVideoSignature(effiVideoDTO.getSignature());
            shot.setQuarter(thisQuarter);
            shot.setAppType(1); //1快手 2头条
            shot.setYear(thisYear);
            shot.setMonth(thisMonth);
            shot.setCalcDate(calcDate);
            shot.setRoleId("7bff9afed625aeeabca6bffe3c189183");
            userEfficientVideoMapMapper.insert(shot);

            //平面
            plane.setUserId(effiVideoDTO.getPlaneId());
            plane.setEfficientVideoSignature(effiVideoDTO.getSignature());
            plane.setQuarter(thisQuarter);
            plane.setAppType(1); //1快手 2头条
            plane.setYear(thisYear);
            plane.setMonth(thisMonth);
            plane.setCalcDate(calcDate);
            plane.setRoleId("8dc30cb9810bde89bdc3fa8a85b830b0");
            userEfficientVideoMapMapper.insert(plane);

            //策划
            plan.setUserId(effiVideoDTO.getPlanId());
            plan.setEfficientVideoSignature(effiVideoDTO.getSignature());
            plan.setQuarter(thisQuarter);
            plan.setAppType(1); //1快手 2头条
            plan.setYear(thisYear);
            plan.setMonth(thisMonth);
            plan.setCalcDate(calcDate);
            plan.setRoleId("0214283aa16f943efbb149ea4bb18f18");
            userEfficientVideoMapMapper.insert(plan);

            //剪辑
            clip.setUserId(effiVideoDTO.getClipId());
            clip.setEfficientVideoSignature(effiVideoDTO.getSignature());
            clip.setQuarter(thisQuarter);
            clip.setAppType(1); //1快手 2头条
            clip.setYear(thisYear);
            clip.setMonth(thisMonth);
            clip.setCalcDate(calcDate);
            clip.setRoleId("f38d8d70cf7ec50d5357a749e4dbf8ee");
            userEfficientVideoMapMapper.insert(clip);
        }
    }

    /**
     * 分平台：快手、抖音
     * <p>
     * 编导、剪辑、拍摄：
     * 1.根据角色（编导、剪辑、拍摄）查询出相对应角色所有的人
     * 2.根据查询出来的所属角色的人，从定时任务跑出来的视频人对应的表中查询出来每个人对应的季度视频总数和季度有效视频数量
     * 3.循环所有人并计算出相对应的视频有效率，并排序
     * 4.根据有效率和对应的绩效梯度进行绩效计算，前百分之30，给予千分之5的提点绩效；中间百分之50%，给予千分之3的提点绩效
     * 即角色人的本季度绩效=本季度视频总消耗*提点*角色提成点（需要考虑到小数点问题和绩效节点上下有效率相同的问题）
     * <p>
     * 平面设计：
     * 1.根据角色查询出相对应的平面设计所有的人
     * 2.循环所有人并计算出相对应的素材总消耗
     * 3.判断媒体总任务是否完成，如果完成则按照千分之5来进行提点绩效；如果未完成，则给予千分之3的提点绩效
     * <p>
     * 设计师leader：
     * 1.如果媒体总任务未达成，则没有绩效；如果已达成，则按照千分之5给予提点绩效
     * 2.查询出所有设计部门的代码，并找出每部门的leader，和部门下所有人员
     * 3.根据编导（或剪辑、拍摄）算出素材的总消耗
     * 4.根据部门当中是否有平面设计师来判断提成绩效。有平面，按照15%计算；没有按照20%计算
     */
    //季度绩效任务（在有效视频绑定人定时任务之后跑）：设计师绩效计算-----包括快手和头条的计算逻辑

    public void designerPerformanceTask(int year, int quarter) {
        kuaishouDesigner(year, quarter);//快手
        toutiaoDesigner();//头条
    }

    //快手设计师、设计师leader和平面设计师逻辑
    private void kuaishouDesigner(int thisYear, int thisQuarter) {
        Map<String, String> quarterStartEndDateMap = DateUtils.quarterStartEndDate(thisYear, thisQuarter);
        String startTime = quarterStartEndDateMap.get("startDate");
        String endTime = quarterStartEndDateMap.get("endDate");

        //编导
        planPerformance(thisYear, thisQuarter, startTime, endTime);
        //拍摄
        shotPerformance(thisYear, thisQuarter, startTime, endTime);
        //剪辑
        clipPerformance(thisYear, thisQuarter, startTime, endTime);
        //平面设计
        planePerformance(thisYear, thisQuarter, startTime, endTime);
        //设计师leader
        designLeaderPerformance(thisYear, thisQuarter, startTime, endTime);
    }

    //头条设计师逻辑
    private void toutiaoDesigner() {
        //TODO 头条目前还没有开发基础部件，等待开发完
    }

    //根据userId查询出所属的所有项目
    private List<ProjectDTO> getProjects(String userId) {
        List<ProjectDTO> projectDTOList = userEfficientVideoMapMapper.getProjectsByUserId(userId);
        return projectDTOList;
    }

    //根据projectId判断此项目是否存在plane平面设计师
    private boolean planeExistsInProject(Long projectId) {
        int planeCount = userEfficientVideoMapMapper.getPlaneCountByProjectId(projectId);
        if (planeCount == 0) {
            return true;
        }
        return false;
    }

    //根据角色id判断所在team是否存在平面设计师
    private boolean planeExistsInTeam(String userId) {
        int planeCount = userEfficientVideoMapMapper.getPlaneCountByUserId(userId);
        if (planeCount == 0) {
            return true;
        }
        return true;
    }

    //判断媒体季度任务是否完成（设计师不需要判断季度媒体任务）
    private boolean mediaMission() {
        //查询优化师系统设置数据
        OptimizerConfig config = optimizerConfigService.getEnabledConfigByMediaType(String.valueOf(2));

        //2: 查询媒体季度任务完成情况
        OptimizerCostDetailVO totalCostVo = getOptimizerTotalCost();
        //result.put("totalCost", totalCostVo.getTotalCost().toString());
        if (totalCostVo.getTotalCost().compareTo(config.getMediaTask()) < 0) {
            //当前消耗季度任务未完成
            return false;
        }
        return true;
    }

    public OptimizerCostDetailVO getOptimizerTotalCost() {
        Date date = new Date();
        Date getDate = DateUtils.addDay(date, -1);
        String startDate = DateUtils.getQuarterStartDate(getDate);
        String endDate = DateUtils.getQuarterEndDate(getDate);
        String endNowDate = DateUtils.formatDate(getDate);
        String year = DateUtils.getYear(getDate) + "";
        String quarter = DateUtils.getQuarter(getDate) + "";
        return performanceMapper.getOptimizerTotalCost(startDate, endNowDate, year, quarter);
    }

    //1
    //季度到前一天为止个人的有效数量、素材总数、素材有效率、总跑量
    //{"effiVideoCount有效数":70,"videoCount素材总数":200,"effiRate":40,"cost":2019;performance绩效":20000}
    public Map<String, Object> getPerformanceInfo() {
        Map<String, Object> performanceInfoMap = new HashMap<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //LoginUser sysUser = new LoginUser();
        //sysUser.setId("9712328fddd1443faf566ddb87693658");

        //获取前一天的时间
        Date date = new Date();
        Date getDate = DateUtils.addDay(date, -1);
        String startDate = DateUtils.getQuarterStartDate(getDate);
        String endDate = DateUtils.getQuarterEndDate(getDate);
        String endNowDate = DateUtils.formatDate(getDate);

        String roleCode = sysRoleMapper.getRoleCodeByUserId(sysUser.getId());

        log.info(roleCode + ":" + sysUser.getRealname() + "getPerformanceInfo接口开始");

        Map<String, String> lastDateMap = getLastDateInfo();
        //获取本人的视频总有效数量
        int effiVideoCount = userEfficientVideoMapMapper.getEffiVideoCountByUserId(Integer.parseInt(lastDateMap.get("year")), Integer.parseInt(lastDateMap.get("quarter")), sysUser.getId());
        //获取本人的视频总数
        int videoCount = userEfficientVideoMapMapper.getQuarterMaterialCountByUserId(roleCode, startDate, endNowDate, sysUser.getId());
        //获取本人目前的视频有效率
        BigDecimal videoEffiRate = BigDecimal.ZERO;
        if (effiVideoCount != 0 && videoCount != 0) {
            videoEffiRate = new BigDecimal(String.valueOf(effiVideoCount)).divide(new BigDecimal(String.valueOf(videoCount))).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
        }
        //获取本人的总跑量
        BigDecimal cost = BigDecimal.ZERO;

        if (roleCode.equals("plan")) {
            cost = userEfficientVideoMapMapper.getTotalCostByPlanId(sysUser.getId(), startDate, endDate);
        } else if (roleCode.equals("shot")) {
            cost = userEfficientVideoMapMapper.getTotalCostByShotId(sysUser.getId(), startDate, endDate);
        } else if (roleCode.equals("clip")) {
            cost = userEfficientVideoMapMapper.getTotalCostByClipId(sysUser.getId(), startDate, endDate);
        }

        performanceInfoMap.put("effiVideoCount", effiVideoCount);
        performanceInfoMap.put("videoCount", videoCount);
        performanceInfoMap.put("effiRate", videoEffiRate);
        performanceInfoMap.put("cost", cost);

        log.info(roleCode + ":" + sysUser.getRealname() + "getPerformanceInfo接口开始");
        return performanceInfoMap;
    }

    //2
    //有效率排行榜
    //{"list":[{"name":"pipi","effiRate":50},{"name":"pipixia","effiRate":40},{"name":"pipiqiu","effiRate":30}],"performance":performance}
    public Map<String, Object> effiRateRank(Integer size) {
        Map<String, Object> resultMap = new HashMap<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //LoginUser sysUser = new LoginUser();
        //sysUser.setId("9712328fddd1443faf566ddb87693658");

        //获取前一天的时间
        Date date = new Date();
        Date getDate = DateUtils.addDay(date, -1);
        String startDate = DateUtils.getQuarterStartDate(getDate);
        String endDate = DateUtils.getQuarterEndDate(getDate);
        String endNowDate = DateUtils.formatDate(getDate);
        Map<String, String> lastDateMap = getLastDateInfo();
        String roleCode = sysRoleMapper.getRoleCodeByUserId(sysUser.getId());

        log.info(roleCode + ":" + sysUser.getRealname() + "有效率排行榜接口开始");

        List<UserDto> userRoleList = new ArrayList<>();
        BigDecimal rate = BigDecimal.ZERO; //提成比例
        if (roleCode.equals("plan")) {
            userRoleList = sysRoleMapper.getUserByRoleCode("plan"); //编导
            rate = new BigDecimal("0.4");
        } else if (roleCode.equals("shot")) {
            userRoleList = sysRoleMapper.getUserByRoleCode("shot"); //拍摄
            rate = new BigDecimal("0.1");
        } else if (roleCode.equals("clip")) {
            userRoleList = sysRoleMapper.getUserByRoleCode("clip"); //剪辑
            rate = new BigDecimal("0.3");
        }

        if (userRoleList != null) {
            for (UserDto userDto : userRoleList) {
                //有效视频数量
                int effiVideoCount = userEfficientVideoMapMapper.getEffiVideoCountByUserId(Integer.parseInt(lastDateMap.get("year")), Integer.parseInt(lastDateMap.get("quarter")), userDto.getUserId());
                //总视频数量
                int videoCount = userEfficientVideoMapMapper.getQuarterMaterialCountByUserId(roleCode, startDate, endNowDate, userDto.getUserId());
                //视频有效率
                BigDecimal effiRate = BigDecimal.ZERO;
                if (effiVideoCount != 0 && videoCount != 0) {
                    effiRate = new BigDecimal(String.valueOf(effiVideoCount)).divide(new BigDecimal(String.valueOf(videoCount))).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_UP);
                }
                userDto.setEffiRate(effiRate);
            }
            Collections.sort(userRoleList, new EffiRateComparator());

            //获取剪辑人数并按照提点比例计算每个梯度的人数
            int userRoleLength = userRoleList.size();
            //获取前30%和中间50%的人数（视频有效率四舍五入）
            int userTopSize = new BigDecimal(String.valueOf(userRoleLength)).multiply(new BigDecimal("0.3")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            int userMiddleSize = new BigDecimal(String.valueOf(userRoleLength)).multiply(new BigDecimal("0.5")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
            log.info(roleCode + "的总人数为：" + userRoleLength + ";前30%人数为：" + userTopSize + "；中间50%的人数为：" + userMiddleSize);

            int index = 0;
            for (int i = 0; i <= userRoleLength; i++) {
                index = index + 1;
                if (userRoleList.get(i).getUserId().equals(sysUser.getId())) {
                    log.info("当前登陆人userId:" + sysUser.getId() + ";姓名:" + sysUser.getRealname() + ";排名:" + index);
                    break;
                }
            }

            //总消耗--获取这个人素材总消耗
            //总绩效=总消耗*提点比例（5‰）*提成比例（剪辑30%）
            BigDecimal performance = BigDecimal.ZERO; //绩效
            BigDecimal totalCost = BigDecimal.ZERO;  //总消耗
            if (roleCode.equals("plan")) {
                totalCost = userEfficientVideoMapMapper.getTotalCostByPlanId(sysUser.getId(), startDate, endNowDate);
                if (index <= userTopSize) {
                    performance = totalCost.multiply(new BigDecimal("0.005")).multiply(new BigDecimal("0.4"));
                } else if (index > userTopSize && index <= (userTopSize + userMiddleSize)) {
                    performance = totalCost.multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.4"));
                } else {
                    performance = BigDecimal.ZERO;
                }
            } else if (roleCode.equals("shot")) {
                totalCost = userEfficientVideoMapMapper.getTotalCostByShotId(sysUser.getId(), startDate, endNowDate);
                if (index <= userTopSize) {
                    performance = totalCost.multiply(new BigDecimal("0.005")).multiply(new BigDecimal("0.1"));
                } else if (index > userTopSize && index <= (userTopSize + userMiddleSize)) {
                    performance = totalCost.multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.1"));
                } else {
                    performance = BigDecimal.ZERO;
                }
            } else {
                totalCost = userEfficientVideoMapMapper.getTotalCostByClipId(sysUser.getId(), startDate, endNowDate);
                if (index <= userTopSize) {
                    performance = totalCost.multiply(new BigDecimal("0.005")).multiply(new BigDecimal("0.3"));
                } else if (index > userTopSize && index <= (userTopSize + userMiddleSize)) {
                    performance = totalCost.multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.3"));
                } else {
                    performance = BigDecimal.ZERO;
                }
            }

            //去掉list中前30的数据
            if (size != null) {
                userRoleList.subList(size, userRoleList.size()).clear();
            }

            resultMap.put("userRoleList", userRoleList);
            resultMap.put("performance", performance);
        } else {
            resultMap.put("userRoleList", null);
            resultMap.put("performance", 0);
        }

        log.info(roleCode + ":" + sysUser.getRealname() + "有效率排行榜接口结束");
        return resultMap;
    }

    //3
    //素材、素材跑量、封面点击数、封面曝光数、行为数
    //{"videoUrl":"http://dadfadfadf.mp4","videoCost":34.56,"pageClickCount":1200,"pageExposureCount":3939,"behaviorCount":5000}
    public List<DesignMaterialInfo> materialInfoList() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //LoginUser sysUser = new LoginUser();
        //sysUser.setId("9712328fddd1443faf566ddb87693658");
        String roleCode = sysRoleMapper.getRoleCodeByUserId(sysUser.getId());

        log.info(roleCode + ":" + sysUser.getRealname() + "materialInfoList接口开始");

        Date date = new Date();
        Date getDate = DateUtils.addDay(date, -1);
        String startDate = DateUtils.getQuarterStartDate(getDate);
        String endDate = DateUtils.getQuarterEndDate(getDate);
        String endNowDate = DateUtils.formatDate(getDate);

        List<DesignMaterialInfo> materialInfoList = userEfficientVideoMapMapper.designMaterialInfoList(roleCode, sysUser.getId(), startDate, endNowDate);

        log.info(roleCode + ":" + sysUser.getRealname() + "materialInfoList接口结束");
        return materialInfoList;
    }

    //4
    //点击+符号 投放账户、投放账户、跑量
    //{"videoAccount":"aabbcc","servingAccount":"ttyyhh","cost":34234.43}
    public List<DesignMaterialInfo> materialAccountInfo(String materialInfoId) {
        log.info("materialAccountInfo接口开始");
        Date date = new Date();
        Date getDate = DateUtils.addDay(date, -1);
        String startDate = DateUtils.getQuarterStartDate(getDate);
        String endDate = DateUtils.getQuarterEndDate(getDate);
        String endNowDate = DateUtils.formatDate(getDate);

        List<DesignMaterialInfo> materialInfoList = userEfficientVideoMapMapper.getMaterialAccountInfoByMaterialId(materialInfoId, startDate, endNowDate);
        log.info("materialAccountInfo接口结束");
        return materialInfoList;
    }

    //获取前一天的年、季度信息
    private Map<String, String> getLastDateInfo() {
        Map<String, String> timeMap = new HashMap<String, String>();
        Date date = new Date();
        Date getDate = DateUtils.addDay(date, -1);
        String startDate = DateUtils.getQuarterStartDate(getDate);
        String endDate = DateUtils.getQuarterEndDate(getDate);
        String year = DateUtils.getYear(getDate) + "";
        String quarter = DateUtils.getQuarter(getDate) + "";

        timeMap.put("startDate", startDate);
        timeMap.put("endDate", endDate);
        timeMap.put("year", year);
        timeMap.put("quarter", quarter);
        return timeMap;
    }

    //编导季度绩效计算
    private void planPerformance(int thisYear, int thisQuarter, String startTime, String endTime) {
        //1.根据角色（编导）查询出相对应角色所有的人
        List<UserDto> planList = sysRoleMapper.getUserByRoleCode("plan"); //编导
        //循环编导列表计算视频有效率并排序
        for (UserDto userDto : planList) {
            //有效视频数量
            int effiVideoCount = userEfficientVideoMapMapper.getEffiVideoCountByUserId(thisYear, thisQuarter, userDto.getUserId());
            //总视频数量
            int videoCount = userEfficientVideoMapMapper.getQuarterMaterialCountByUserId("plan", startTime, endTime, userDto.getUserId());
            //视频有效率
            BigDecimal effiRate = new BigDecimal(String.valueOf(effiVideoCount)).divide(new BigDecimal(String.valueOf(videoCount)));
            userDto.setEffiRate(effiRate);
        }
        Collections.sort(planList, new EffiRateComparator());

        //获取编导人数并按照提点比例计算每个梯度的人数
        int planLength = planList.size();
        //获取前30%和中间50%的人数（视频有效率四舍五入）
        int top30 = new BigDecimal(String.valueOf(planLength)).multiply(new BigDecimal("0.3")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        int middle50 = new BigDecimal(String.valueOf(planLength)).multiply(new BigDecimal("0.5")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();

        //循环前30%有绩效的人数并计算其绩效，并入库
        for (int i = 0; i <= top30 - 1; i++) {
            //总消耗--获取这个人所在项目的总消耗
            BigDecimal totalCost = userEfficientVideoMapMapper.getProjectTotalCostByUserId(planList.get(i).getUserId(), startTime, endTime);
            //总绩效=总消耗*提点比例（5‰）*提成比例（编导40%）
            BigDecimal totalPerformance = totalCost.multiply(new BigDecimal("0.005")).multiply(new BigDecimal("0.4"));

            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(planList.get(i).getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.005"));
            performance.setTotalCost(totalCost);
            performance.setTotalPerformance(totalPerformance);
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setVideoEfficiency(planList.get(i).getEffiRate().setScale(4, BigDecimal.ROUND_HALF_UP));
            performance.setUserId(planList.get(i).getUserId());
            performanceMapper.insert(performance);
        }

        //去掉list中前30的数据
        planList.subList(0, top30 - 1).clear();

        //循环中间50%有绩效的人，计算绩效并入库
        for (int i = 0; i <= middle50 - 1; i++) {
            //总消耗--获取这个人所在项目的总消耗
            BigDecimal totalCost = userEfficientVideoMapMapper.getProjectTotalCostByUserId(planList.get(i).getUserId(), startTime, endTime);
            //总绩效=总消耗*提点比例（3‰）*提成比例（编导40%）
            BigDecimal totalPerformance = totalCost.multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.4"));

            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(planList.get(i).getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.003"));
            performance.setTotalCost(totalCost);
            performance.setTotalPerformance(totalPerformance);
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setVideoEfficiency(planList.get(i).getEffiRate().setScale(4, BigDecimal.ROUND_HALF_UP));
            performance.setUserId(planList.get(i).getUserId());
            performanceMapper.insert(performance);
        }
        /////////////////////////////////////////编导end
    }

    private void shotPerformance(int thisYear, int thisQuarter, String startTime, String endTime) {
        //根据角色（拍摄）查询出相对应角色所有的人
        List<UserDto> shotList = sysRoleMapper.getUserByRoleCode("shot"); //拍摄
        for (UserDto userDto : shotList) {
            //有效视频数量
            int effiVideoCount = userEfficientVideoMapMapper.getEffiVideoCountByUserId(thisYear, thisQuarter, userDto.getUserId());
            //总视频数量
            int videoCount = userEfficientVideoMapMapper.getQuarterMaterialCountByUserId("shot", startTime, endTime, userDto.getUserId());
            //视频有效率
            BigDecimal effiRate = new BigDecimal(String.valueOf(effiVideoCount)).divide(new BigDecimal(String.valueOf(videoCount)));
            userDto.setEffiRate(effiRate);
        }
        Collections.sort(shotList, new EffiRateComparator());

        //获取编导人数并按照提点比例计算每个梯度的人数
        int shotLength = shotList.size();
        //获取前30%和中间50%的人数（视频有效率四舍五入）
        int shotTop30 = new BigDecimal(String.valueOf(shotLength)).multiply(new BigDecimal("0.3")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        int shotMiddle50 = new BigDecimal(String.valueOf(shotLength)).multiply(new BigDecimal("0.5")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();

        //循环前30%有绩效的人数并计算其绩效，并入库
        for (int i = 0; i <= shotTop30 - 1; i++) {
            //总消耗--获取这个人所在项目的总消耗
            BigDecimal totalCost = userEfficientVideoMapMapper.getProjectTotalCostByUserId(shotList.get(i).getUserId(), startTime, endTime);
            //总绩效=总消耗*提点比例（5‰）*提成比例（拍摄10%）
            BigDecimal totalPerformance = totalCost.multiply(new BigDecimal("0.005")).multiply(new BigDecimal("0.1"));

            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(shotList.get(i).getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.005"));
            performance.setTotalCost(totalCost);
            performance.setTotalPerformance(totalPerformance);
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setVideoEfficiency(shotList.get(i).getEffiRate().setScale(4, BigDecimal.ROUND_HALF_UP));
            performance.setUserId(shotList.get(i).getUserId());
            performanceMapper.insert(performance);
        }

        //去掉list中前30的数据
        shotList.subList(0, shotTop30 - 1).clear();

        //循环中间50%有绩效的人，计算绩效并入库
        for (int i = 0; i <= shotMiddle50 - 1; i++) {
            //总消耗--获取这个人所在项目的总消耗
            BigDecimal totalCost = userEfficientVideoMapMapper.getProjectTotalCostByUserId(shotList.get(i).getUserId(), startTime, endTime);
            //总绩效=总消耗*提点比例（3‰）*提成比例（拍摄10%）
            BigDecimal totalPerformance = totalCost.multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.1"));

            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(shotList.get(i).getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.003"));
            performance.setTotalCost(totalCost);
            performance.setTotalPerformance(totalPerformance);
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setVideoEfficiency(shotList.get(i).getEffiRate().setScale(4, BigDecimal.ROUND_HALF_UP));
            performance.setUserId(shotList.get(i).getUserId());
            performanceMapper.insert(performance);
        }
    }

    //剪辑
    private void clipPerformance(int thisYear, int thisQuarter, String startTime, String endTime) {
        ///根据角色（剪辑）查询出相对应角色所有的人
        List<UserDto> clipList = sysRoleMapper.getUserByRoleCode("clip"); //剪辑
        for (UserDto userDto : clipList) {
            //有效视频数量
            int effiVideoCount = userEfficientVideoMapMapper.getEffiVideoCountByUserId(thisYear, thisQuarter, userDto.getUserId());
            //总视频数量
            int videoCount = userEfficientVideoMapMapper.getQuarterMaterialCountByUserId("clip", startTime, endTime, userDto.getUserId());
            //视频有效率
            BigDecimal effiRate = new BigDecimal(String.valueOf(effiVideoCount)).divide(new BigDecimal(String.valueOf(videoCount)));
            userDto.setEffiRate(effiRate);
        }
        Collections.sort(clipList, new EffiRateComparator());

        //获取剪辑人数并按照提点比例计算每个梯度的人数
        int clipLength = clipList.size();
        //获取前30%和中间50%的人数（视频有效率四舍五入）
        int clipTop30 = new BigDecimal(String.valueOf(clipLength)).multiply(new BigDecimal("0.3")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
        int clipMiddle50 = new BigDecimal(String.valueOf(clipLength)).multiply(new BigDecimal("0.5")).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();

        //循环前30%有绩效的人数并计算其绩效，并入库
        for (int i = 0; i <= clipTop30 - 1; i++) {
            //总消耗--获取这个人所在项目的总消耗
            BigDecimal totalCost = userEfficientVideoMapMapper.getProjectTotalCostByUserId(clipList.get(i).getUserId(), startTime, endTime);
            //总绩效=总消耗*提点比例（5‰）*提成比例（剪辑30%）
            BigDecimal totalPerformance = totalCost.multiply(new BigDecimal("0.005")).multiply(new BigDecimal("0.3"));

            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(clipList.get(i).getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.005"));
            performance.setTotalCost(totalCost);
            performance.setTotalPerformance(totalPerformance);
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setVideoEfficiency(clipList.get(i).getEffiRate().setScale(4, BigDecimal.ROUND_HALF_UP));
            performance.setUserId(clipList.get(i).getUserId());
            performanceMapper.insert(performance);
        }

        //去掉list中前30的数据
        clipList.subList(0, clipTop30 - 1).clear();

        //循环中间50%有绩效的人，计算绩效并入库
        for (int i = 0; i <= clipMiddle50 - 1; i++) {
            //总消耗--获取这个人所在项目的总消耗
            BigDecimal totalCost = userEfficientVideoMapMapper.getProjectTotalCostByUserId(clipList.get(i).getUserId(), startTime, endTime);
            //总绩效=总消耗*提点比例（3‰）*提成比例（剪辑30%）
            BigDecimal totalPerformance = totalCost.multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.3"));

            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(clipList.get(i).getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.003"));
            performance.setTotalCost(totalCost);
            performance.setTotalPerformance(totalPerformance);
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setVideoEfficiency(clipList.get(i).getEffiRate().setScale(4, BigDecimal.ROUND_HALF_UP));
            performance.setUserId(clipList.get(i).getUserId());
            performanceMapper.insert(performance);
        }
    }

    //目前先按照同一个项目最后时间的所有平面设计师平分消耗绩效来计算
    public void planePerformance(int thisYear, int thisQuarter, String startTime, String endTime) {
        //搜索所有项目，循环并计算时间段内的项目总消耗，并查询其中有没有平面设计师
        //如果有并且不止一个就平分；创建一个list，将设计师的userDto加入进来，然后可以在不同的项目中累加（需要增加一张表格，然后记录其中的每一个项目消耗）
        Map<String, UserDto2> planeMap = new HashMap<>();

        //获取所有project根据媒体类型获取快手下的项目类型 1-头条 2-快手
        List<ProjectDTO> projectDTOS = userEfficientVideoMapMapper.getProjects("2");

        //循环project
        for (ProjectDTO projectDTO : projectDTOS) {
            BigDecimal quarterCost = userEfficientVideoMapMapper.getProjectQuarterCostById(startTime, endTime, projectDTO.getProjectId());
            List<UserDto2> planeList = userEfficientVideoMapMapper.getPlaneByProjectId(projectDTO.getProjectId());
            //此项目当中平面数量
            int size = planeList.size();
            BigDecimal averageQuarterCost = quarterCost.divide(new BigDecimal(String.valueOf(size)));

            //循环项目下所有平面设计
            for (UserDto2 plane : planeList) {
                //将金额和项目插入数据库当中（需要新建表）
                plane.setEffiRate(averageQuarterCost);
                //插入数据
                PlaneProjectCost planeProjectCost = new PlaneProjectCost();
                planeProjectCost.setAppType(1); //1-kuaishou 2-douyin
                planeProjectCost.setProjectId(projectDTO.getProjectId());
                planeProjectCost.setYear(thisYear);
                planeProjectCost.setQuarter(thisQuarter);
                planeProjectCost.setProjectTotalCost(quarterCost);
                planeProjectCost.setProjectCost(averageQuarterCost);
                planeProjectCost.setUserId(plane.getUserId());

                if (null == planeMap.get(plane.getUserId())) {
                    plane.setEffiRate(averageQuarterCost);
                    planeMap.put("plane.getUserId()", plane);
                } else {
                    //将增加的金额增加到
                    planeMap.get(plane.getUserId()).setEffiRate(planeMap.get(plane.getUserId()).getEffiRate().add(plane.getEffiRate()));
                }
                planeProjectCostMapper.insert(planeProjectCost);
            }
        }

        //循环planeMap插入数据
        for (String key : planeMap.keySet()) {
            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(planeMap.get(key).getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.2"));
            performance.setTotalCost(planeMap.get(key).getEffiRate());
            performance.setTotalPerformance(planeMap.get(key).getEffiRate().multiply(new BigDecimal("0.2")));
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setUserId(planeMap.get(key).getUserId());
            performanceMapper.insert(performance);
        }
    }

    //设计师leader绩效计算
    private void designLeaderPerformance(int thisYear, int thisQuarter, String startTime, String endTime) {
        //找出设计部所有部门，循环这些部门，查出这个部门当中的设计师leader；
        //如果有设计师leader的话找出其下面的剪辑，循环查询数据库当中的总消耗，相加*平台占比*20%

        //直接查询出来各种媒体类型的设计组长，然后根据
        List<UserDto2> designLeaderList = userEfficientVideoMapMapper.getKuaishouDesignLeaderList();

        //循环list然后根据查出leader组下的剪辑userId
        for(UserDto2 userDto:designLeaderList){
            List<String> clipList = userEfficientVideoMapMapper.getClip(userDto.getDepId());
            BigDecimal totalCost = BigDecimal.ZERO; //剪辑总消耗

            for(String clipUserId:clipList){
                BigDecimal clipCost = userEfficientVideoMapMapper.getClipQuarterCost(1,thisYear,thisQuarter,clipUserId);  //媒体类型 1-快手 2抖音
                totalCost = totalCost.add(clipCost);
            }

            //总绩效=剪辑消耗总合 * 平台比例 * 20%
            BigDecimal totalPerformance = totalCost.multiply(new BigDecimal("0.003")).multiply(new BigDecimal("0.2"));

            Performance performance = new Performance();
            performance.setAppType(1); //1快手 2抖音
            performance.setRoleId(userDto.getRoleId());
            performance.setQuarter(thisQuarter);
            performance.setYear(thisYear);
            performance.setCommissionRate(new BigDecimal("0.003"));
            performance.setTotalCost(totalCost);
            performance.setTotalPerformance(totalPerformance);
            performance.setStartTime(startTime);
            performance.setEndTime(endTime);
            performance.setRoleCommissionRate(new BigDecimal("20"));
            performance.setUserId(userDto.getUserId());
            performanceMapper.insert(performance);
        }
    }
}
