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

import cn.com.ctop.common.module.utils.ResultMapUtils;
import cn.com.ctop.common.module.utils.StatusCode;
import cn.com.ctop.performanceappraisal.entity.OptimizerConfig;
import cn.com.ctop.performanceappraisal.entity.Performance;
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.IPerformanceService;
import cn.com.ctop.performanceappraisal.vo.DesignerCostDetailVO;
import cn.com.ctop.performanceappraisal.vo.OptimizerCostDetailVO;
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.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;
    @Autowired
    private PerformanceOptimizerMapper optimizerMapper;
    @Autowired
    private IOptimizerConfigService optimizerConfigService;
    /**
     * 计算设计岗位绩效逻辑
     * 1：查询用户总消耗以及总视频数
     * 2：查询视频有效率排行榜
     * 3：根据视频有效率分配提点比例
     * 4：计算个人总绩效
     */
    @Override
    public List<DesignerCostDetailVO> getTotalCostDetailByRoleId(String roleId) {
        return null;
    }

    @Override
    public List<OptimizerCostDetailVO> getOptimizerTotalCostDetailGroupByUserId(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) + "";
        return performanceMapper.getOptimizerTotalCostDetailGroupByUserId(startDate, endDate, year, quarter, userId, startIndex, pageSize);
    }

    /**
     * 计算优化师岗位绩效逻辑
     * 1：查询所有优化师总消耗数据
     * 2：查询媒体季度任务完成情况
     * 3：计算单个优化师提成总额
     */
    public List<OptimizerCostDetailVO> getOptimizerPerformance() {
        //1：查询所有优化师总消耗数据
        List<OptimizerCostDetailVO> detailVOS = getOptimizerTotalCostDetailGroupByUserId(null, 1, 10);
        //查询优化师系统设置数据
        OptimizerConfig config = optimizerConfigService.getEnabledConfigByMediaType("2");
        //2: 查询媒体季度任务完成情况
        OptimizerCostDetailVO totalCostVo = getOptimizerTotalCost();
        //3：计算单个优化师提成总额
        List<OptimizerCostDetailVO> getDetailVos = new ArrayList<>();
        if (null != detailVOS && detailVOS.size() > 0) {
            for (OptimizerCostDetailVO vo : detailVOS) {
                vo.setTotalRoyalty(getTotalRoyalty(config, vo, totalCostVo));
                PerformanceOptimizer optimizer = new PerformanceOptimizer(vo);
                optimizerMapper.insert(optimizer);
            }
        }
        return getDetailVos;
    }

    @Override
    public OptimizerCostDetailVO getOptimizerTotalCost() {
        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) + "";
        return performanceMapper.getOptimizerTotalCost(startDate, endDate, year, quarter);
    }

    @Override
    public Map<String, Object> getUserOptimizerProjectList(Integer pageNo, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        LoginUser sysUser = new LoginUser();
//        sysUser.setId("fcb3fbf6192640adaadb2a7df9c02dae");
        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 = performanceMapper.getUserOptimizerTotalCostGroupByProjectId(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(Long projectId, Integer pageNo, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
//        LoginUser sysUser = new LoginUser();
//        sysUser.setId("fcb3fbf6192640adaadb2a7df9c02dae");
        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 = performanceMapper.getUserOptimizerTotalCostGroupByAccountId(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();
//        LoginUser sysUser = new LoginUser();
//        sysUser.setId("fcb3fbf6192640adaadb2a7df9c02dae");
//        sysUser.setOrgCode("A01A07A01");
        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 = performanceMapper.getMemberPerformanceByOrgCode(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;
    }

    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);
    }

}
