package org.jeecg.modules.performance.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 com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.performance.entity.OptimizerConfig;
import org.jeecg.modules.performance.entity.Performance;
import org.jeecg.modules.performance.mapper.PerformanceMapper;
import org.jeecg.modules.performance.service.IPerformanceService;
import org.jeecg.modules.performance.vo.DesignerCostDetailVO;
import org.jeecg.modules.performance.vo.OptimizerCostDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

/**
 *
 * @author jeecg-boot
 * @version V1.0
 * @date 2019-12-10
 */
@Service
public class PerformanceServiceImpl extends ServiceImpl<PerformanceMapper, Performance> implements IPerformanceService {
    @Autowired
    private PerformanceMapper performanceMapper;
    /**
     * 计算设计岗位绩效逻辑
     * 1：查询用户总消耗以及总视频数
     * 2：查询视频有效率排行榜
     * 3：根据视频有效率分配提点比例
     * 4：计算个人总绩效
     */
    @Override
    public List<DesignerCostDetailVO> getTotalCostDetailByRoleId(String roleId) {
        return null;
    }

    @Override
    public List<OptimizerCostDetailVO> getOptimizerTotalCostDetailGroupByUserId(String mediaType, String userId, Integer startIndex, Integer pageSize) {
        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) + "";
        if (null != mediaType && mediaType.equals(CtopAdConstant.PLATFORM_TYPE_KUAISHOU)) {
            //快手
            return performanceMapper.getKuaishouOptimizerTotalCostDetailGroupByUserId(startDate, endDate, year, quarter, userId, startIndex, pageSize);
        } else {
            //头条
            return performanceMapper.getBytedanceOptimizerTotalCostDetailGroupByUserId(startDate, endDate, year, quarter, userId, startIndex, pageSize);
        }
    }

    @Override
    public OptimizerCostDetailVO getOptimizerTotalCost(String mediaType) {
        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) + "";
        if (null != mediaType && mediaType.equals(CtopAdConstant.PLATFORM_TYPE_KUAISHOU)) {
            //快手
            return performanceMapper.getKuaishouOptimizerTotalCost(startDate, endDate, year, quarter);
        } else {
            //头条
            return performanceMapper.getBytedanceOptimizerTotalCost(startDate, endDate, year, quarter);
        }
    }

    @Override
    public Map<String, Object> getUserOptimizerProjectList(Integer pageNo, Integer pageSize, String appType) {
        Map<String, Object> result = new HashMap<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer startIndex = (pageNo - 1) * pageSize;
        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) + "";
        List<OptimizerCostDetailVO> detailVOS = null;
        if (null != appType && appType.equals(CtopAdConstant.PLATFORM_TYPE_KUAISHOU)) {
            detailVOS = performanceMapper.getKuaishouUserOptimizerTotalCostGroupByProjectId(startDate, endDate, year, quarter, sysUser.getId(), startIndex, pageSize, null);
        } else {
            detailVOS = performanceMapper.getBytedanceUserOptimizerTotalCostGroupByProjectId(startDate, endDate, year, quarter, sysUser.getId(), startIndex, pageSize, null);
        }
        result.put("data", detailVOS);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
        return result;
    }

    @Override
    public Map<String, Object> getUserOptimizerAccountList(String appType, Long projectId, Integer pageNo, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer startIndex = (pageNo - 1) * pageSize;
        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) + "";
        List<OptimizerCostDetailVO> detailVOS = null;
        if (null != appType && appType.equals(CtopAdConstant.PLATFORM_TYPE_KUAISHOU)) {
            detailVOS = performanceMapper.getKuaishouUserOptimizerTotalCostGroupByAccountId(startDate, endDate, year, quarter, sysUser.getId(), startIndex, pageSize, projectId, null);
        } else {
            detailVOS = performanceMapper.getBytedanceUserOptimizerTotalCostGroupByAccountId(startDate, endDate, year, quarter, sysUser.getId(), startIndex, pageSize, projectId, null);
        }
        result.put("data", detailVOS);
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
        return result;
    }

    @Override
    public Map<String, Object> getMemberPerformanceByUserId(OptimizerConfig config, OptimizerCostDetailVO totalCostVo) {
        Map<String, Object> result = new HashMap<>();
        //查询此机构下其他运营专员跑量数据
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        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) + "";
        //查询用户相关机构编号
        List<OptimizerCostDetailVO> detailVOS = null;
        if (null != config.getAppType() && config.getAppType() + "" == CtopAdConstant.PLATFORM_TYPE_KUAISHOU) {
            performanceMapper.getKuaishouMemberPerformanceByOrgCode(startDate, endDate, year, quarter, sysUser.getOrgCode());
        } else {
            performanceMapper.getBytedanceMemberPerformanceByOrgCode(startDate, endDate, year, quarter, sysUser.getOrgCode());
        }

        List<OptimizerCostDetailVO> getDetails = new ArrayList<>();
        BigDecimal memberTotaRoyalty = BigDecimal.ZERO;
        BigDecimal memberTotaCost = BigDecimal.ZERO;
        result.put("mediaTotalCost", totalCostVo.getTotalCost());
        result.put("mediaTask", config.getMediaTask());
        for (OptimizerCostDetailVO vo : detailVOS) {
            BigDecimal royalty = getTotalRoyalty(config, vo, totalCostVo);
            vo.setTotalRoyalty(royalty);
            memberTotaRoyalty = memberTotaRoyalty.add(royalty);
            memberTotaCost = memberTotaCost.add(vo.getTotalCost());
            getDetails.add(vo);
        }
        result.put("memberDetails", getDetails);
        result.put("memberTotalCost", memberTotaCost.setScale(2, RoundingMode.HALF_UP).toString());
        if (totalCostVo.getTotalCost().compareTo(config.getMediaTask()) < 0) {
            result.put("totalRoyalty", "0");
            ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
            return result;
        }
        result.put("totalRoyalty", memberTotaRoyalty.multiply(new BigDecimal("0.2")).setScale(2, RoundingMode.HALF_UP).toString());
        ResultMapUtils.setResultMap(result, StatusCode.COMMON_SUCCESS.getCode());
        return result;
    }

    @Override
    public BigDecimal getBytedanceSeasonTotalCost(String startDate, String endDate) {
        BigDecimal cost = performanceMapper.getBytedanceSeasonTotalCost(startDate, endDate);
        if (null == cost) {
            return BigDecimal.ZERO;
        } else {
            return cost;
        }
    }

    @Override
    public BigDecimal getKuaishouSeasonTotalCost(String startDate, String endDate) {
        BigDecimal cost = performanceMapper.getKuaishouSeasonTotalCost(startDate, endDate);
        if (null == cost) {
            return BigDecimal.ZERO;
        } else {
            return cost;
        }
    }

    @Override
    public BigDecimal getKuaishouSalesSeasonTotalCostByParams(String startDate, String endDate, String salesId, String advertiserId, Long accountId) {
        BigDecimal cost = performanceMapper.getKuaishouSalesSeasonTotalCostByParams(startDate, endDate, salesId, advertiserId, accountId);
        if (null == cost) {
            return BigDecimal.ZERO;
        } else {
            return cost;
        }
    }

    @Override
    public BigDecimal getBytedanceSalesSeasonTotalCostByParams(String startDate, String endDate, String salesId, String advertiserId, Long accountId) {
        BigDecimal cost = performanceMapper.getBytedanceSalesSeasonTotalCostByParams(startDate, endDate, salesId, advertiserId, accountId);
        if (null == cost) {
            return BigDecimal.ZERO;
        } else {
            return cost;
        }
    }

    @Override
    public BigDecimal getSalesSeasonTotalCostByParams(String startDate, String endDate, String saledId, String advertiserId, Long accountId, String mediaType) {
        BigDecimal cost;
        if (null != mediaType && mediaType.equals(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE)) {
            cost = performanceMapper.getBytedanceSalesSeasonTotalCostByParams(startDate, endDate, saledId, advertiserId, accountId);
        } else {
            cost = performanceMapper.getKuaishouSalesSeasonTotalCostByParams(startDate, endDate, saledId, advertiserId, accountId);
        }
        if (null == cost) {
            return BigDecimal.ZERO;
        } else {
            return cost;
        }
    }

    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();
        //媒体任务未完成提点
        BigDecimal mediaTaskNoFinishRate = config.getMediaTaskNoFinishRate();
        //媒体任务未完成提点
        BigDecimal mediaTaskFinishRate = config.getMediaTaskFinishRate();
        //个人任务未完成
        if (totalCost.compareTo(personalTask) < 0) {
            return royalty;
        }
        //季度任务未完成
        if (totalCost.compareTo(mediaTask) < 0) {
            return totalCost.multiply(mediaTaskNoFinishRate).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
        }

        return totalCost.multiply(mediaTaskFinishRate).divide(new BigDecimal("1000")).setScale(2, RoundingMode.HALF_UP);
    }

}
