package cn.com.ctop.performanceappraisal.service.impl;

import cn.com.ctop.common.module.utils.CtopAdConstant;
import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.performanceaccount.entity.PerformanceAccount;
import cn.com.ctop.performanceaccount.mapper.PerformanceAccountMapper;
import cn.com.ctop.performanceappraisal.entity.OptimizerConfig;
import cn.com.ctop.performanceappraisal.entity.PerformanceConfig;
import cn.com.ctop.performanceappraisal.entity.PerformanceOptimizer;
import cn.com.ctop.performanceappraisal.mapper.PerformanceMapper;
import cn.com.ctop.performanceappraisal.mapper.PerformanceOptimizerMapper;
import cn.com.ctop.performanceappraisal.service.IOptimizerConfigService;
import cn.com.ctop.performanceappraisal.service.IPerformanceConfigService;
import cn.com.ctop.performanceappraisal.service.IPerformanceOptimizerService;
import cn.com.ctop.performanceappraisal.service.IPerformanceService;
import cn.com.ctop.performanceappraisal.vo.OptimizerCostDetailVO;
import cn.com.ctop.performanceappraisal.vo.UserPerformanceDetailVO;
import cn.com.ctop.userefficientvideomap.entity.TransferorAccountDTO;
import cn.com.ctop.userefficientvideomap.entity.UserDto2;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 优化师绩效信息
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-12-13
 */
@Service
@Slf4j
public class PerformanceOptimizerServiceImpl extends ServiceImpl<PerformanceOptimizerMapper, PerformanceOptimizer> implements IPerformanceOptimizerService {
    @Autowired
    IPerformanceService performanceService;
    @Autowired
    private IOptimizerConfigService optimizerConfigService;
    @Autowired
    private UserEfficientVideoMapMapper userEfficientVideoMapMapper;
    @Autowired
    private PerformanceMapper performanceMapper;
    @Autowired
    private PerformanceOptimizerMapper performanceOptimizerMapper;
    @Autowired
    private PerformanceAccountMapper performanceAccountMapper;


    public void YunyingPerformance(Integer year, Integer quarter, String startDate, String endDate) {
        //Map<String,String> map = DateUtils.quarterStartEndDate(year, quarter);


    }


    //快手运营季度绩效计算
    public Map<String, Object> kuaishouYunyingQuarterPerformance(Integer year, Integer quarter, String startDate, String endDate) {
        Map<String, Object> result = new HashMap<>();
        //获取快手所有运营的数据
        //List<UserDto2> userList = userEfficientVideoMapMapper.getAllKuaishouYunyingDepartUserInfo();
        Integer mediaType = 2;
        //华北
        //查询当前媒体配置信息
        OptimizerConfig config = optimizerConfigService.getEnabledConfigByMediaType(mediaType + "", CtopAdConstant.CTOP_ORGCODE_NORTH_CHINA_PREFIX);
        if (null == config) {
            ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_OPTINIZER_CONFIG_IS_NULL.getCode());
            return result;
        }

        ///////////////方法2
        //1。获取所有快手账户
        //2。循环每个账户，然后查找每个账户下在本季度是否有转户的情况存在；

        //创建map，Map<String人,Map<String账户,时间段List<Map<String开始时间,String结束时间>>>>
        Map<String, Map<String, List<Map<String, String>>>> userAccountMap = new HashMap<>();

        //获取所有快手的账户
        List<String> accountList = userEfficientVideoMapMapper.getAccountListByMediaId(mediaType);
        //循环所有账户
        for (String account : accountList) {
            String userId = userEfficientVideoMapMapper.getAccountUserId(account);
            //判断本季度内是否有转户情况存在
            List<TransferorAccountDTO> transferorAccountDTOList = userEfficientVideoMapMapper.accountTransforerListByUserId(account, startDate, endDate);

            //如果此账户没有转户情况发生，则存入userAccountMap当中
            if (transferorAccountDTOList.size() == 0) {
                if (userAccountMap.get(userId) == null) {
                    Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                    List<Map<String, String>> dateList = new ArrayList<>();
                    Map<String, String> dateMap = new HashMap<>();

                    dateMap.put("startDate", startDate);
                    dateMap.put("endDate", endDate);
                    dateList.add(dateMap);
                    accountMap.put(account, dateList);
                    userAccountMap.put(userId, accountMap);
                } else {
                    Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(userId);
                    //如果此账户本季度没有转户行为，直接创建账户即可，不用再做判断
                    Map<String, String> dateMap = new HashMap<>();
                    dateMap.put("startDate", startDate);
                    dateMap.put("endDate", endDate);
                    if (accountMap.get(account) == null) {
                        List<Map<String, String>> dateList = new ArrayList<>();
                        dateList.add(dateMap);
                        accountMap.put(account, dateList);
                    } else {
                        List<Map<String, String>> dateList = accountMap.get(account);
                        dateList.add(dateMap);
                    }
                }
            } else {//如果此账户有转户情况
                //循环所有转户信息
                for (int j = 0; j < transferorAccountDTOList.size(); j++) {
                    if (j == 0) {
                        Map<String, String> dateMap = new HashMap<>();
                        dateMap.put("startDate", startDate);
                        dateMap.put("endDate", transferorAccountDTOList.get(j).getTransferorDate());
                        String transferorUserId = transferorAccountDTOList.get(j).getTransferor();
                        //判断：如果userAccountMap中没有assigneeUserId，则直接创建；
                        if (userAccountMap.get(transferorUserId) == null) {
                            Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                            List<Map<String, String>> dateList = new ArrayList<>();
                            dateList.add(dateMap);
                            accountMap.put(account, dateList);
                            userAccountMap.put(transferorUserId, accountMap);
                        } else {//如果已经有了这个userId，则需要判断是否有此账户
                            if (userAccountMap.get(transferorUserId).get(account) == null) {
                                Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(transferorUserId);
                                List<Map<String, String>> dateList = new ArrayList<>();
                                dateList.add(dateMap);
                                accountMap.put(account, dateList);
                            } else {
                                List<Map<String, String>> dateList = userAccountMap.get(transferorUserId).get(account);
                                dateList.add(dateMap);
                            }
                        }

                        if (j == transferorAccountDTOList.size() - 1) {
                            Map<String, String> dateMap2 = new HashMap<>();
                            dateMap2.put("startDate", transferorAccountDTOList.get(j).getAssigneeDate());
                            dateMap2.put("endDate", endDate);
                            String assigneeUserId = transferorAccountDTOList.get(j).getAssignee();
                            //判断：如果userAccountMap中没有assigneeUserId，则直接创建；
                            if (userAccountMap.get(assigneeUserId) == null) {
                                Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                                List<Map<String, String>> dateList = new ArrayList<>();
                                dateList.add(dateMap2);
                                accountMap.put(account, dateList);
                                userAccountMap.put(assigneeUserId, accountMap);
                            } else {//如果已经有了这个userId，则需要判断是否有此账户
                                if (userAccountMap.get(assigneeUserId).get(account) == null) {
                                    Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(assigneeUserId);
                                    List<Map<String, String>> dateList = new ArrayList<>();
                                    dateList.add(dateMap2);
                                    accountMap.put(account, dateList);
                                } else {
                                    List<Map<String, String>> dateList = userAccountMap.get(assigneeUserId).get(account);
                                    dateList.add(dateMap2);
                                }
                            }
                        }
                    } else {
                        Map<String, String> dateMap = new HashMap<>();
                        dateMap.put("startDate", transferorAccountDTOList.get(j).getAssigneeDate());
                        if (j == (transferorAccountDTOList.size() - 1)) {
                            dateMap.put("endDate", endDate);
                        } else {
                            dateMap.put("endDate", transferorAccountDTOList.get(j + 1).getTransferorDate());
                        }

                        String assigneeUserId = transferorAccountDTOList.get(j).getAssignee();
                        //判断：如果userAccountMap中没有assigneeUserId，则直接创建；
                        if (userAccountMap.get(assigneeUserId) == null) {
                            Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                            List<Map<String, String>> dateList = new ArrayList<>();
                            dateList.add(dateMap);
                            accountMap.put(account, dateList);
                            userAccountMap.put(assigneeUserId, accountMap);
                        } else {//如果已经有了这个userId，则需要判断是否有此账户

                            if (userAccountMap.get(assigneeUserId).get(account) == null) {
                                Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(assigneeUserId);
                                List<Map<String, String>> dateList = new ArrayList<>();
                                dateList.add(dateMap);
                                accountMap.put(account, dateList);
                            } else {
                                List<Map<String, String>> dateList = userAccountMap.get(assigneeUserId).get(account);
                                dateList.add(dateMap);
                            }

                        }

                    }

                } //转户列表循环结束
            } //else判断

        }//账户循环结束

        for (Map.Entry<String, Map<String, List<Map<String, String>>>> entry : userAccountMap.entrySet()) {
            String userAccountKey = entry.getKey();
            Map<String, List<Map<String, String>>> userAccountValue = entry.getValue();
            BigDecimal totalCharge = BigDecimal.ZERO;
            BigDecimal totalPerformance = BigDecimal.ZERO;

            for (Map.Entry<String, List<Map<String, String>>> entryAccount : userAccountValue.entrySet()) {
                String acountKey = entryAccount.getKey();
                List<Map<String, String>> accountValue = entryAccount.getValue();

                for (Map<String, String> dateMap : accountValue) {
                    //当前消耗
                    BigDecimal charge = userEfficientVideoMapMapper.getAccountSumCharge(acountKey, dateMap.get("startDate"), dateMap.get("endDate")) == null ? BigDecimal.ZERO : userEfficientVideoMapMapper.getAccountSumCharge(acountKey, dateMap.get("startDate"), dateMap.get("endDate"));
                    //此人总消耗
                    totalCharge = totalCharge.add(charge);

                    PerformanceAccount performanceAccount = new PerformanceAccount();
                    performanceAccount.setAccountId(Long.parseLong(acountKey));
                    performanceAccount.setCost(charge);
                    performanceAccount.setYear(year);
                    performanceAccount.setQuarter(quarter);
                    performanceAccount.setMediaType(mediaType);
                    performanceAccount.setUserId(userAccountKey);
                    performanceAccount.setStartDate(dateMap.get("startDate"));
                    performanceAccount.setEndDate(dateMap.get("endDate"));
                    performanceAccountMapper.insert(performanceAccount);
                }
            }

            //运营绩效数据入库
            PerformanceOptimizer performance = new PerformanceOptimizer();
            performance.setAppType(mediaType);
            performance.setQuarter(quarter + "");
            performance.setYear(year + "");
            performance.setRealname(userEfficientVideoMapMapper.getrealnameByUserId(userAccountKey));
            performance.setUserId(userAccountKey);
            performance.setTotalCost(totalCharge);

            //个人季度任务
            BigDecimal personalTask = config.getPersonalTask();
            //判断个人任务是否完成 ，如果完成则给到千分之5，如果未完成，则给到千分之3的绩效
            String roleCode = userEfficientVideoMapMapper.getRoleCodeByUserId(userAccountKey);
            if (!roleCode.equals("operationAssistant")) {
                if (totalCharge.compareTo(personalTask) > 0) {
                    totalPerformance = totalCharge.multiply(config.getMediaTaskFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
                } else {
                    totalPerformance = totalCharge.multiply(config.getMediaTaskNoFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
                }
            }
            performance.setTotalRoyalty(totalPerformance);
            performanceOptimizerMapper.insert(performance);
        }
        return result;
    }

    //头条运营季度绩效计算
    public void toutiaoYunyingQuarterPerformance(Integer year, Integer quarter, String startDate, String endDate) {
        //方法
        //1。获取所有头条账户
        //2。循环每个账户，然后查找每个账户下在本季度是否有转户的情况存在；
        Integer mediaType = 1;
        //创建map，Map<String人,Map<String账户,时间段List<Map<String开始时间,String结束时间>>>>
        Map<String, Map<String, List<Map<String, String>>>> userAccountMap = new HashMap<>();
        OptimizerConfig config = optimizerConfigService.getEnabledConfigByMediaType(mediaType + "", CtopAdConstant.CTOP_ORGCODE_NORTH_CHINA_PREFIX);
        //获取所有头条的账户
        List<String> accountList = userEfficientVideoMapMapper.getAccountListByMediaId(mediaType);

        //循环所有账户
        for (String account : accountList) {
            String userId = userEfficientVideoMapMapper.getAccountUserId(account);
            //判断本季度内是否有转户情况存在
            List<TransferorAccountDTO> transferorAccountDTOList = userEfficientVideoMapMapper.accountTransforerListByUserId(account, startDate, endDate);

            //如果此账户没有转户情况发生，则存入userAccountMap当中
            if (transferorAccountDTOList.size() == 0) {
                if (userAccountMap.get(userId) == null) {
                    Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                    List<Map<String, String>> dateList = new ArrayList<>();
                    Map<String, String> dateMap = new HashMap<>();

                    dateMap.put("startDate", startDate);
                    dateMap.put("endDate", endDate);
                    dateList.add(dateMap);
                    accountMap.put(account, dateList);
                    userAccountMap.put(userId, accountMap);
                } else {
                    Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(userId);
                    //如果此账户本季度没有转户行为，直接创建账户即可，不用再做判断
                    Map<String, String> dateMap = new HashMap<>();
                    dateMap.put("startDate", startDate);
                    dateMap.put("endDate", endDate);
                    if (accountMap.get(account) == null) {
                        List<Map<String, String>> dateList = new ArrayList<>();
                        dateList.add(dateMap);
                        accountMap.put(account, dateList);
                    } else {
                        List<Map<String, String>> dateList = accountMap.get(account);
                        dateList.add(dateMap);
                    }
                }
            } else {//如果此账户有转户情况
                //循环所有转户信息
                for (int j = 0; j < transferorAccountDTOList.size(); j++) {
                    if (j == 0) {
                        Map<String, String> dateMap = new HashMap<>();
                        dateMap.put("startDate", startDate);
                        dateMap.put("endDate", transferorAccountDTOList.get(j).getTransferorDate());
                        String transferorUserId = transferorAccountDTOList.get(j).getTransferor();
                        //判断：如果userAccountMap中没有assigneeUserId，则直接创建；
                        if (userAccountMap.get(transferorUserId) == null) {
                            Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                            List<Map<String, String>> dateList = new ArrayList<>();
                            dateList.add(dateMap);
                            accountMap.put(account, dateList);
                            userAccountMap.put(transferorUserId, accountMap);
                        } else {//如果已经有了这个userId，则需要判断是否有此账户
                            if (userAccountMap.get(transferorUserId).get(account) == null) {
                                Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(transferorUserId);
                                List<Map<String, String>> dateList = new ArrayList<>();
                                dateList.add(dateMap);
                                accountMap.put(account, dateList);
                            } else {
                                List<Map<String, String>> dateList = userAccountMap.get(transferorUserId).get(account);
                                dateList.add(dateMap);
                            }
                        }

                        if (j == transferorAccountDTOList.size() - 1) {
                            Map<String, String> dateMap2 = new HashMap<>();
                            dateMap2.put("startDate", transferorAccountDTOList.get(j).getAssigneeDate());
                            dateMap2.put("endDate", endDate);
                            String assigneeUserId = transferorAccountDTOList.get(j).getAssignee();
                            //判断：如果userAccountMap中没有assigneeUserId，则直接创建；
                            if (userAccountMap.get(assigneeUserId) == null) {
                                Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                                List<Map<String, String>> dateList = new ArrayList<>();
                                dateList.add(dateMap2);
                                accountMap.put(account, dateList);
                                userAccountMap.put(assigneeUserId, accountMap);
                            } else {//如果已经有了这个userId，则需要判断是否有此账户
                                if (userAccountMap.get(assigneeUserId).get(account) == null) {
                                    Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(transferorUserId);
                                    List<Map<String, String>> dateList = new ArrayList<>();
                                    dateList.add(dateMap2);
                                    accountMap.put(account, dateList);
                                } else {
                                    List<Map<String, String>> dateList = userAccountMap.get(assigneeUserId).get(account);
                                    dateList.add(dateMap2);
                                }
                            }
                        }
                    } else {
                        Map<String, String> dateMap = new HashMap<>();
                        dateMap.put("startDate", transferorAccountDTOList.get(j).getAssigneeDate());
                        if (j == (transferorAccountDTOList.size() - 1)) {
                            dateMap.put("endDate", endDate);
                        } else {
                            dateMap.put("endDate", transferorAccountDTOList.get(j + 1).getTransferorDate());
                        }

                        String assigneeUserId = transferorAccountDTOList.get(j).getAssignee();
                        //判断：如果userAccountMap中没有assigneeUserId，则直接创建；
                        if (userAccountMap.get(assigneeUserId) == null) {
                            Map<String, List<Map<String, String>>> accountMap = new HashMap<>();
                            List<Map<String, String>> dateList = new ArrayList<>();
                            dateList.add(dateMap);
                            accountMap.put(account, dateList);
                            userAccountMap.put(assigneeUserId, accountMap);
                        } else {//如果已经有了这个userId，则需要判断是否有此账户

                            if (userAccountMap.get(assigneeUserId).get(account) == null) {
                                Map<String, List<Map<String, String>>> accountMap = userAccountMap.get(assigneeUserId);
                                List<Map<String, String>> dateList = new ArrayList<>();
                                dateList.add(dateMap);
                                accountMap.put(account, dateList);
                            } else {
                                List<Map<String, String>> dateList = userAccountMap.get(assigneeUserId).get(account);
                                dateList.add(dateMap);
                            }

                        }

                    }

                } //转户列表循环结束
            } //else判断

        }//账户循环结束


        for (Map.Entry<String, Map<String, List<Map<String, String>>>> entry : userAccountMap.entrySet()) {
            String userAccountKey = entry.getKey();
            Map<String, List<Map<String, String>>> userAccountValue = entry.getValue();
            BigDecimal totalCharge = BigDecimal.ZERO;
            BigDecimal totalPerformance = BigDecimal.ZERO;

            for (Map.Entry<String, List<Map<String, String>>> entryAccount : userAccountValue.entrySet()) {
                String acountKey = entryAccount.getKey();
                List<Map<String, String>> accountValue = entryAccount.getValue();

                for (Map<String, String> dateMap : accountValue) {
                    //当前消耗
                    BigDecimal charge = userEfficientVideoMapMapper.getToutiaoAccountSumCharge(acountKey, dateMap.get("startDate"), dateMap.get("endDate")) == null ? BigDecimal.ZERO : userEfficientVideoMapMapper.getToutiaoAccountSumCharge(acountKey, dateMap.get("startDate"), dateMap.get("endDate"));
                    //此人总消耗
                    totalCharge = totalCharge.add(charge);

                    PerformanceAccount performanceAccount = new PerformanceAccount();
                    performanceAccount.setAccountId(Long.parseLong(acountKey));
                    performanceAccount.setCost(charge);
                    performanceAccount.setYear(year);
                    performanceAccount.setQuarter(quarter);
                    performanceAccount.setMediaType(mediaType);
                    performanceAccount.setUserId(userAccountKey);
                    performanceAccount.setStartDate(dateMap.get("startDate"));
                    performanceAccount.setEndDate(dateMap.get("endDate"));
                    performanceAccountMapper.insert(performanceAccount);
                }
            }

            //运营绩效数据入库
            PerformanceOptimizer performance = new PerformanceOptimizer();
            performance.setAppType(mediaType);
            performance.setQuarter(quarter + "");
            performance.setYear(year + "");
            performance.setRealname(userEfficientVideoMapMapper.getrealnameByUserId(userAccountKey));
            performance.setUserId(userAccountKey);
            performance.setTotalCost(totalCharge);

            //个人季度任务
            BigDecimal personalTask = config.getPersonalTask();
            //判断个人任务是否完成 ，如果完成则给到千分之5，如果未完成，则给到千分之3的绩效
            String roleCode = userEfficientVideoMapMapper.getRoleCodeByUserId(userAccountKey);
            if (!roleCode.equals("operationAssistant")) {
                if (totalCharge.compareTo(personalTask) > 0) {
                    totalPerformance = totalCharge.multiply(config.getMediaTaskFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
                } else {
                    totalPerformance = totalCharge.multiply(config.getMediaTaskNoFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
                }
            }
            performance.setTotalRoyalty(totalPerformance);
            performanceOptimizerMapper.insert(performance);
        }

        return;
    }

    //快手运营leader绩效计算
    public void kuaishouYunyingLeaderQuarterPerformance(Integer year, Integer quarter) {
        Integer mediaType = 2;
        //获取快手组下所有运营组长信息列表
        List<UserDto2> yunyingLeaderList = userEfficientVideoMapMapper.getKuaishouYunyingLeaderUserInfo();
        for (UserDto2 userDto2 : yunyingLeaderList) {
            BigDecimal royalty = BigDecimal.ZERO;
            List<UserDto2> userList = userEfficientVideoMapMapper.getYunyingLeaderMember(userDto2.getDepId());

            for (UserDto2 user : userList) {
                //增加判断：如果项目成员中包含自己的话，不将自己的消耗计算在内
                if (user.getUserId().equals(userDto2.getUserId())) {
                    continue;
                }
                BigDecimal userRoality = userEfficientVideoMapMapper.getYunyingRoyalty(user.getUserId(), year, quarter);
                if (userRoality == null) {
                    userRoality = BigDecimal.ZERO;
                }
                royalty = royalty.add(userRoality);
            }
            //运营leader绩效数据入库
            PerformanceOptimizer performanceOptimizer = new PerformanceOptimizer();
            performanceOptimizer.setAppType(mediaType);
            performanceOptimizer.setQuarter(quarter + "");
            performanceOptimizer.setYear(year + "");
            performanceOptimizer.setRealname(userDto2.getRealname());
            performanceOptimizer.setTotalCost(royalty);
            performanceOptimizer.setTotalRoyalty(royalty.multiply(new BigDecimal("0.2")));
            performanceOptimizer.setUserId(userDto2.getUserId());
            performanceOptimizerMapper.insert(performanceOptimizer);
        }
    }

    //TODO 头条运营leader绩效计算
    public void toutiaoYunyingLeaderQuarterPerformance(Integer year, Integer quarter) {
        Integer mediaType = 1;
        //获取快手组下所有运营组长信息列表
        List<UserDto2> yunyingLeaderList = userEfficientVideoMapMapper.getToutiaoYunyingLeaderUserInfo();
        for (UserDto2 userDto2 : yunyingLeaderList) {
            BigDecimal royalty = BigDecimal.ZERO;
            List<UserDto2> userList = userEfficientVideoMapMapper.getYunyingLeaderMember(userDto2.getDepId());

            for (UserDto2 user : userList) {
                //增加判断：如果项目成员中包含自己的话，不将自己的消耗计算在内
                if (user.getUserId().equals(userDto2.getUserId())) {
                    continue;
                }
                BigDecimal userRoality = userEfficientVideoMapMapper.getYunyingRoyalty(user.getUserId(), year, quarter);
                if (userRoality == null) {
                    userRoality = BigDecimal.ZERO;
                }
                royalty = royalty.add(userRoality);
            }
            //运营leader绩效数据入库
            PerformanceOptimizer performanceOptimizer = new PerformanceOptimizer();
            performanceOptimizer.setAppType(mediaType);
            performanceOptimizer.setQuarter(quarter + "");
            performanceOptimizer.setYear(year + "");
            performanceOptimizer.setRealname(userDto2.getRealname());
            performanceOptimizer.setTotalCost(royalty);
            performanceOptimizer.setTotalRoyalty(royalty.multiply(new BigDecimal("0.2")));
            performanceOptimizer.setUserId(userDto2.getUserId());
            performanceOptimizerMapper.insert(performanceOptimizer);
        }

    }


    private List<OptimizerCostDetailVO> getOptimizerTotalCostDetailGroupByUserId(String mediaType, String userId, Integer year, Integer quarter, String startDate, String endDate) {
        if (null != mediaType && mediaType.equals(CtopAdConstant.PLATFORM_TYPE_KUAISHOU)) {
            //快手
            return performanceMapper.getKuaishouOptimizerTotalCostDetailGroupByUserId(startDate, endDate, year+"", quarter+"", userId, null, null);
        } else {
            //头条
            return performanceMapper.getBytedanceOptimizerTotalCostDetailGroupByUserId(startDate, endDate, year+"", quarter+"", userId, null, null);
        }
    }



    @Override
    public Map<String, Object> getPerformanceDetail(String mediaType, Integer pageNo, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        Integer startIndex = (pageNo - 1) * pageSize;
        //查询当前登录人信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String orgCode = sysUser.getOrgCode();
        if (orgCode.startsWith(CtopAdConstant.CTOP_ORGCODE_NORTH_CHINA_PREFIX)) {
            //华北
            //查询当前媒体配置信息
            OptimizerConfig config = optimizerConfigService.getEnabledConfigByMediaType(mediaType, CtopAdConstant.CTOP_ORGCODE_NORTH_CHINA_PREFIX);
            if (null == config) {
                ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_OPTINIZER_CONFIG_IS_NULL.getCode());
                return result;
            }
            //:查询当前用户截止到目前当前季度的消耗统计数据
            List<OptimizerCostDetailVO> vos = performanceService.getOptimizerTotalCostDetailGroupByUserId(mediaType, sysUser.getId(), startIndex, pageSize);
            if (null == vos || vos.size() <= 0) {
                ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_OPTINIZER_PERSONNAL_DATA_IS_NULL.getCode());
                return result;
            }
            //2: 查询媒体季度任务完成情况
            UserPerformanceDetailVO performanceDetailVO = getPerformanceDetailVO(mediaType, vos.get(0), config);
            result.put("userDetail", performanceDetailVO);
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
            return result;
        } else if (orgCode.startsWith(CtopAdConstant.CTOP_ORGCODE_EAST_CHINA_PREFIX)) {
            //华东
            //查询当前媒体配置信息
            OptimizerConfig kuaishouConfig = optimizerConfigService.getEnabledConfigByMediaType(CtopAdConstant.PLATFORM_TYPE_KUAISHOU, CtopAdConstant.CTOP_ORGCODE_EAST_CHINA_PREFIX);
            OptimizerConfig bytedanceConfig = optimizerConfigService.getEnabledConfigByMediaType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE, CtopAdConstant.CTOP_ORGCODE_EAST_CHINA_PREFIX);
            if (null == kuaishouConfig || null == bytedanceConfig) {
                ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_OPTINIZER_CONFIG_IS_NULL.getCode());
                return result;
            }
            //:查询当前用户截止到目前当前季度的消耗统计数据
            List<OptimizerCostDetailVO> kuaishouVos = performanceService.getOptimizerTotalCostDetailGroupByUserId(CtopAdConstant.PLATFORM_TYPE_KUAISHOU, sysUser.getId(), startIndex, pageSize);
            List<OptimizerCostDetailVO> bytedanceVos = performanceService.getOptimizerTotalCostDetailGroupByUserId(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE, sysUser.getId(), startIndex, pageSize);
            boolean hasNoCost = (null == kuaishouVos || kuaishouVos.size() <= 0) && (null == bytedanceVos || bytedanceVos.size() <= 0);
            if (hasNoCost) {
                ResultMapUtils.setResultMap(result, StatusCode.OPTINIZER_PERSONNAL_DATA_IS_NULL.getCode());
                return result;
            }
            if (null == kuaishouVos || kuaishouVos.size() <= 0) {
                //快手消耗为0
                //2: 查询头条媒体季度任务完成情况
                UserPerformanceDetailVO performanceDetailVO = getPerformanceDetailVO(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE, bytedanceVos.get(0), bytedanceConfig);
                result.put("userDetail", performanceDetailVO);
                ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
                return result;
            }
            if (null == bytedanceVos || bytedanceVos.size() <= 0) {
                //头条消耗为0
                //2: 查询快手媒体季度任务完成情况
                UserPerformanceDetailVO performanceDetailVO = getPerformanceDetailVO(CtopAdConstant.PLATFORM_TYPE_KUAISHOU, kuaishouVos.get(0), kuaishouConfig);
                result.put("userDetail", performanceDetailVO);
                ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
                return result;
            }
            //快手+头条
            UserPerformanceDetailVO performanceDetailVO = getMultiPerformanceDetailVO(kuaishouVos.get(0), kuaishouConfig, bytedanceVos.get(0), bytedanceConfig);
            result.put("userDetail", performanceDetailVO);
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
            return result;
        } else {
            ResultMapUtils.setResultMap(result, StatusCode.CTOP_HAS_NO_PERFORMANCE_STATISTIC_LOGIC);
            return result;
        }
    }

    private UserPerformanceDetailVO getMultiPerformanceDetailVO(OptimizerCostDetailVO kuaishouQuarterCostVO, OptimizerConfig kuaishouConfig, OptimizerCostDetailVO bytedanceQuarterCostVO, OptimizerConfig bytedanceConfig) {
        //1：获取个人各渠道消耗
        OptimizerCostDetailVO kuaishouTotalCostVo = performanceService.getOptimizerTotalCost(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
        OptimizerCostDetailVO bytedanceTotalCostVo = performanceService.getOptimizerTotalCost(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);

        UserPerformanceDetailVO performanceDetailVO = new UserPerformanceDetailVO();
        performanceDetailVO.setRealName(kuaishouTotalCostVo.getRealName());
        //个人消耗
        performanceDetailVO.setKuaishouPersonalCost(kuaishouTotalCostVo.getTotalCost());
        performanceDetailVO.setBytedancePersonalCost(bytedanceTotalCostVo.getTotalCost());
        performanceDetailVO.setTotalPersonalCost(kuaishouTotalCostVo.getTotalCost().add(bytedanceTotalCostVo.getTotalCost()).setScale(2, RoundingMode.HALF_UP));
        //媒体消耗
        performanceDetailVO.setKuaishouMediaCost(kuaishouQuarterCostVO.getTotalCost());
        performanceDetailVO.setBytedanceMediaCost(bytedanceQuarterCostVO.getTotalCost());
        performanceDetailVO.setTotalMediaCost(bytedanceQuarterCostVO.getTotalCost().add(kuaishouQuarterCostVO.getTotalCost()).setScale(2, RoundingMode.HALF_UP));

        //媒体任务
        performanceDetailVO.setKuaishouMediaTask(kuaishouConfig.getMediaTask());
        performanceDetailVO.setBytedanceMediaTask(bytedanceConfig.getMediaTask());
        performanceDetailVO.setTotalMediaCost(kuaishouConfig.getMediaTask().add(bytedanceConfig.getMediaTask()).setScale(2, RoundingMode.HALF_UP));

        //个人任务
        performanceDetailVO.setTotalPersonalTask(kuaishouConfig.getTotalPersonalTask());
        performanceDetailVO.setKuaishouPersonalTask(kuaishouConfig.getPersonalTask());
        performanceDetailVO.setBytedancePersonalTask(bytedanceConfig.getPersonalTask());

        performanceDetailVO.setYear(kuaishouQuarterCostVO.getYear());
        performanceDetailVO.setQuarter(kuaishouQuarterCostVO.getQuarter());

        //快手提成
        performanceDetailVO.setKuaishouRoyalty(getRoyalty(kuaishouConfig,
                performanceDetailVO.getTotalPersonalCost(), performanceDetailVO.getTotalPersonalTask(),
                performanceDetailVO.getKuaishouMediaCost(), performanceDetailVO.getKuaishouMediaTask(),
                performanceDetailVO.getKuaishouPersonalCost()));
        //头条提成
        performanceDetailVO.setBytedanceRoyalty(getRoyalty(bytedanceConfig,
                performanceDetailVO.getTotalPersonalCost(), performanceDetailVO.getTotalPersonalTask(),
                performanceDetailVO.getBytedanceMediaCost(), performanceDetailVO.getBytedanceMediaTask(),
                performanceDetailVO.getBytedancePersonalCost()));

        //快手提成点
        performanceDetailVO.setKuaishouRoyaltyRatio(getRoyaltyRatio(kuaishouConfig, performanceDetailVO.getTotalPersonalCost(), performanceDetailVO.getTotalPersonalTask(), performanceDetailVO.getKuaishouMediaCost(), performanceDetailVO.getKuaishouMediaTask()));
        //头条提成点
        performanceDetailVO.setBytedanceRoyaltyRatio(getRoyaltyRatio(bytedanceConfig, performanceDetailVO.getTotalPersonalCost(), performanceDetailVO.getTotalPersonalTask(), performanceDetailVO.getBytedanceMediaCost(), performanceDetailVO.getBytedanceMediaTask()));
        //总提成
        performanceDetailVO.setTotalRoyalty(performanceDetailVO.getBytedanceRoyalty().add(performanceDetailVO.getKuaishouRoyalty()).setScale(2, RoundingMode.HALF_UP));

        return performanceDetailVO;
    }

    private BigDecimal getRoyalty(OptimizerConfig bytedanceConfig, BigDecimal totalPersonalCost, BigDecimal totalPersonalTask, BigDecimal bytedanceMediaCost, BigDecimal bytedanceMediaTask, BigDecimal bytedancePersonalCost) {
        BigDecimal royalty = BigDecimal.ZERO;

        //个人任务未完成
        if (totalPersonalCost.compareTo(totalPersonalTask) < 0) {
            return royalty;
        }
        //快手媒体任务未完成
        if (bytedanceMediaCost.compareTo(bytedanceMediaTask) < 0) {
            return bytedancePersonalCost.multiply(bytedanceConfig.getMediaTaskNoFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
        }

        PerformanceConfig performanceConfig = performanceConfigService.getNowConfig();
        if (null != performanceConfig && performanceConfig.getMediaTaskRaise() == 1) {
            //同意提高提成点
            return bytedancePersonalCost.multiply(bytedanceConfig.getMediaTaskFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
        } else {
            return bytedancePersonalCost.multiply(bytedanceConfig.getMediaTaskFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
        }
    }

    private BigDecimal getRoyaltyRatio(OptimizerConfig bytedanceConfig, BigDecimal totalPersonalCost, BigDecimal totalPersonalTask, BigDecimal mediaCost, BigDecimal mediaTask) {
        BigDecimal royalty = BigDecimal.ZERO;

        //个人任务未完成
        if (totalPersonalCost.compareTo(totalPersonalTask) < 0) {
            return royalty;
        }
        //快手媒体任务未完成
        if (mediaCost.compareTo(mediaTask) < 0) {
            return bytedanceConfig.getMediaTaskNoFinishRate().setScale(2, RoundingMode.HALF_UP);
        }

        PerformanceConfig performanceConfig = performanceConfigService.getNowConfig();
        if (null != performanceConfig && performanceConfig.getMediaTaskRaise() == 1) {
            //同意提高提成点
            return bytedanceConfig.getMediaTaskFinishRate().setScale(2, RoundingMode.HALF_UP);
        } else {
            return bytedanceConfig.getMediaTaskNoFinishRate().setScale(2, RoundingMode.HALF_UP);
        }
    }

    private UserPerformanceDetailVO getPerformanceDetailVO(String appType, OptimizerCostDetailVO kuaishouCostVo, OptimizerConfig kuaishouConfig) {
        OptimizerCostDetailVO totalCostVo = performanceService.getOptimizerTotalCost(appType);
        UserPerformanceDetailVO performanceDetailVO = new UserPerformanceDetailVO();
        //计算绩效
        kuaishouCostVo.setTotalRoyalty(getTotalRoyalty(kuaishouConfig, kuaishouCostVo, totalCostVo));
        performanceDetailVO.setRealName(kuaishouCostVo.getRealName());
        performanceDetailVO.setTotalPersonalCost(kuaishouCostVo.getTotalCost());
        performanceDetailVO.setTotalRoyalty(kuaishouCostVo.getTotalRoyalty());
        performanceDetailVO.setTotalMediaTask(kuaishouConfig.getMediaTask());
        performanceDetailVO.setTotalPersonalTask(kuaishouConfig.getPersonalTask());

        performanceDetailVO.setYear(kuaishouCostVo.getYear());
        performanceDetailVO.setQuarter(kuaishouCostVo.getQuarter());
        performanceDetailVO.setRoyaltyRatio(getRate(kuaishouConfig, kuaishouCostVo, totalCostVo).toString() + "‰");
        return performanceDetailVO;
    }

    @Override
    //TODO --先优先华北的逻辑
    public Map<String, Object> getRankingList(String mediaType, Integer pageNo, Integer pageSize, String orgCode) {
        Map<String, Object> result = new HashMap<>();
        Integer startIndex = (pageNo - 1) * pageSize;
        List<OptimizerCostDetailVO> vos = performanceService.getOptimizerTotalCostDetailGroupByUserId(mediaType, null, startIndex, pageSize);
        if (null == vos || vos.size() <= 0) {
            ResultMapUtils.setResultMap(result, StatusCode.KUAISHOU_CRAWLER_APP_ELEMENT_IS_NULL.getCode());
            return result;
        }
        //查询优化师系统设置数据
        OptimizerConfig config = optimizerConfigService.getEnabledConfigByMediaType(mediaType, orgCode);
        //2: 查询媒体季度任务完成情况
        OptimizerCostDetailVO totalCostVo = performanceService.getOptimizerTotalCost(mediaType);
        //3：计算单个优化师提成总额
        List<OptimizerCostDetailVO> getDetailVos = new ArrayList<>();
        if (null != vos && vos.size() > 0) {
            for (OptimizerCostDetailVO vo : vos) {
                vo.setTotalRoyalty(getTotalRoyalty(config, vo, totalCostVo));
                getDetailVos.add(vo);
            }
        }
        result.put("data", getDetailVos);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
        return result;
    }

    @Override
    //TODO --优先华北
    public Map<String, Object> getManagerPerformanceDetail(String mediaType, String orgCode) {
        Map<String, Object> result = new HashMap<>();
        //获取经理相关信息
        //查询优化师系统设置数据
        OptimizerConfig config = optimizerConfigService.getEnabledConfigByMediaType(mediaType, orgCode);
        //2: 查询媒体季度任务完成情况
        OptimizerCostDetailVO totalCostVo = performanceService.getOptimizerTotalCost(mediaType);
        result.put("totalCost", totalCostVo.getTotalCost().toString());
        if (totalCostVo.getTotalCost().compareTo(config.getMediaTask()) < 0) {
            //当前消耗季度任务未完成
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
            result.put("totalRoyalty", totalCostVo.getTotalRoyalty().toString());
            return result;
        }
        //3：查询经理手下所有优化师的总提成
        result = performanceService.getMemberPerformanceByUserId(config, totalCostVo);
        return result;
    }

    @Autowired
    private IPerformanceConfigService performanceConfigService;
    private BigDecimal getTotalRoyalty(OptimizerConfig config, OptimizerCostDetailVO vo, OptimizerCostDetailVO quarterCost) {
        BigDecimal royalty = BigDecimal.ZERO;
        //个人总消耗
        BigDecimal totalCost = vo.getTotalCost();
        //个人季度任务
        BigDecimal personalTask = config.getPersonalTask();
        //媒体季度任务
        //BigDecimal mediaTask = config.getMediaTask();
        //个人任务未完成
        //if (totalCost.compareTo(personalTask) < 0) {
        //    return royalty;
        //}
        //季度任务不在普通运营的业务范围内
        //if (quarterCost.getTotalCost().compareTo(mediaTask) < 0) {
        //    return totalCost.multiply(config.getMediaTaskNoFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
        //}
        PerformanceConfig performanceConfig = performanceConfigService.getNowConfig();
        //判断个人任务是否完成 ，如果完成则给到千分之5，如果未完成，则给到千分之3的绩效
        if (null != performanceConfig && performanceConfig.getMediaTaskRaise() == 1) {
            return totalCost.multiply(config.getMediaTaskFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
        } else {
            return totalCost.multiply(config.getMediaTaskNoFinishRate()).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
        }
    }

    private BigDecimal getRate(OptimizerConfig config, OptimizerCostDetailVO vo, OptimizerCostDetailVO quarterCost) {
        BigDecimal royalty = BigDecimal.ZERO;
        //个人总消耗
        BigDecimal totalCost = vo.getTotalCost();
        //个人季度任务
        BigDecimal personalTask = config.getPersonalTask();
        //媒体季度任务
        BigDecimal mediaTask = config.getMediaTask();
        //个人任务未完成
        if (totalCost.compareTo(personalTask) < 0) {
            return royalty;
        }
        //季度任务未完成
        if (quarterCost.getTotalCost().compareTo(mediaTask) < 0) {
            return config.getMediaTaskNoFinishRate().setScale(2, RoundingMode.HALF_UP);
        }

        PerformanceConfig performanceConfig = performanceConfigService.getNowConfig();
        if (null != performanceConfig && performanceConfig.getMediaTaskRaise() == 1) {
            return config.getMediaTaskFinishRate().setScale(2, RoundingMode.HALF_UP);
        } else {
            return config.getMediaTaskNoFinishRate().setScale(2, RoundingMode.HALF_UP);
        }

    }
}
