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

import cn.com.ctop.common.module.entity.Advertiser;
import cn.com.ctop.common.module.entity.SysUser;
import cn.com.ctop.common.module.entity.UserAllocation;
import cn.com.ctop.common.module.utils.CtopAdConstant;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.ctop.service.IAdvertiserService;
import org.jeecg.modules.ctop.service.IPerformanceSaleService;
import org.jeecg.modules.performance.entity.SalePerformanceDetail;
import org.jeecg.modules.performance.service.IPerformanceService;
import org.jeecg.modules.performance.service.ISalePerformanceDetailService;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class PerformanceSaleServiceImpl implements IPerformanceSaleService {

    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IPerformanceService performanceService;

    @Override
    public void loadSalsePerformance() {
        //1:获取销售列表
        List<SysUser> sales = sysUserService.getUserListByRoleId(CtopAdConstant.SYSTEM_SALE_CODE);
        if (null != sales && sales.size() > 0) {
            sales.forEach(sale -> {
                countPerformance(sale);
            });
        }
        //2:获取销售AM列表
        List<SysUser> saleAms = sysUserService.getUserListByRoleId(CtopAdConstant.SYSTEM_SALE_AM_CODE);
        if (null != saleAms && saleAms.size() > 0) {
            saleAms.forEach(saleAm -> {
                countPerformance(saleAm);
            });
        }
    }

    @Autowired
    private ISysUserRoleService userRoleService;
    @Autowired
    private ISalePerformanceDetailService salePerformanceDetailService;

    public void countPerformance(SysUser user) {
//        Date getDate = DateUtils.addDay(new Date(), -1)
        log.info("销售人员名称:{}", user.getRealname());
        Date getDate = DateUtils.addDay(new Date(), -18);
        String startDateStr = DateUtils.getQuarterStartDate(getDate);
        String endDateStr = DateUtils.getQuarterEndDate(getDate);
        //获取用户角色信息
        SysUserRole userRole = userRoleService.getUserRoleByUserId(user.getId());
        //1:获取快手季度总消耗 TODO 后续需要改成动态获取
        BigDecimal kuaishouFinishMediaTask = CtopAdConstant.KUAISHOU_MEDIA_TASK_COST;
        //2:获取快手个人季度总消耗
        BigDecimal kuaishouFinishPersonnalTask = performanceService.getKuaishouSalesSeasonTotalCostByParams(startDateStr, endDateStr, user.getId(), null, null);
        //1:获取头条季度总消耗 TODO 后续需要改成动态获取
        BigDecimal bytedanceFinishMediaTask = CtopAdConstant.BYTEDANCE_MEDIA_TASK_COST;
        //2:获取头条个人季度总消耗
        BigDecimal bytedanceFinishPersonnalTask = performanceService.getBytedanceSalesSeasonTotalCostByParams(startDateStr, endDateStr, user.getId(), null, null);
        //获取销售所属的广告主信息
        List<Advertiser> advertiserList = advertiserService.getBySaleId(user.getId());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startSeasonDate = null;
        Date endSeasonDate = null;
        try {
            startSeasonDate = dateFormat.parse(startDateStr);
            endSeasonDate = dateFormat.parse(endDateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (null != advertiserList && advertiserList.size() > 0) {
            for (Advertiser advertiser : advertiserList) {
                //1:根据广告主查询用户绑定信息
                List<UserAllocation> allocations = advertiserService.getAllocationsByAdvertiserId(advertiser.getId());
                if (null != allocations && allocations.size() > 0) {
                    Date finalStartSeasonDate = startSeasonDate;
                    Date finalEndSeasonDate = endSeasonDate;
                    allocations.forEach(allocation -> {
                        Date endOldDate = DateUtils.addDay(allocation.getCreateTime(), 90);
                        if (finalStartSeasonDate.after(endOldDate)) {
                            //季度开始时间大于新户结束时间(全部按照老户逻辑计算)
                            saveSalePerformanceDetail(allocation, advertiser, user, userRole, DateUtils.getYear(getDate), DateUtils.getQuarter(getDate),
                                    startDateStr, endDateStr, bytedanceFinishMediaTask, bytedanceFinishPersonnalTask, kuaishouFinishMediaTask,
                                    kuaishouFinishPersonnalTask, 0);
                        } else if (endOldDate.after(finalEndSeasonDate)) {
                            saveSalePerformanceDetail(allocation, advertiser, user, userRole, DateUtils.getYear(getDate), DateUtils.getQuarter(getDate),
                                    startDateStr, endDateStr, bytedanceFinishMediaTask, bytedanceFinishPersonnalTask, kuaishouFinishMediaTask,
                                    kuaishouFinishPersonnalTask, 1);
                        } else {
                            //新户结束时间处于本季度中间
                            String endduring1Date = DateUtils.formatDate(endOldDate);
                            saveSalePerformanceDetail(allocation, advertiser, user, userRole, DateUtils.getYear(getDate), DateUtils.getQuarter(getDate),
                                    startDateStr, endduring1Date, bytedanceFinishMediaTask, bytedanceFinishPersonnalTask, kuaishouFinishMediaTask,
                                    kuaishouFinishPersonnalTask, 1);
                            saveSalePerformanceDetail(allocation, advertiser, user, userRole, DateUtils.getYear(getDate), DateUtils.getQuarter(getDate),
                                    endduring1Date, endDateStr, bytedanceFinishMediaTask, bytedanceFinishPersonnalTask, kuaishouFinishMediaTask,
                                    kuaishouFinishPersonnalTask, 0);
                        }
                    });
                }
            }
        }
    }

    private void saveSalePerformanceDetail(UserAllocation allocation, Advertiser advertiser, SysUser user, SysUserRole userRole, int year, int quarter, String startDate, String endDate, BigDecimal bytedanceFinishMediaTask, BigDecimal bytedanceFinishPersonnalTask, BigDecimal kuaishouFinishMediaTask, BigDecimal kuaishouFinishPersonnalTask, Integer brandNew) {
        SalePerformanceDetail detail = new SalePerformanceDetail();
        detail.setAccountId(allocation.getAccountId());
        detail.setAdvertiserId(advertiser.getId());
        detail.setSaleId(user.getId());
        detail.setRoleId(userRole.getRoleId());
        detail.setYear(year);
        detail.setQuarter(quarter);
        detail.setStartDate(startDate);
        detail.setEndDate(endDate);
     //   detail.setExtensionSelf(advertiser.getAdvertiserType());
        detail.setBrandNew(brandNew);
        if (user.getOrgCode().startsWith(CtopAdConstant.HB_BYTEDANCE_SALE_ORG_CODE)) {
            detail.setMediaType(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
            BigDecimal totalCost = performanceService.getSalesSeasonTotalCostByParams(startDate, endDate, null, null, allocation.getAccountId(), CtopAdConstant.PLATFORM_TYPE_BYTEDANCE);
            if (null == totalCost) {
                totalCost = BigDecimal.ZERO;
            }
            detail.setTotalCost(totalCost);
            detail.setMediaTask(CtopAdConstant.BYTEDANCE_MEDIA_TASK_COST);
            detail.setDoMediaTask(bytedanceFinishMediaTask);
            detail.setPersonnalTask(CtopAdConstant.BYTEDANCE_PERSONAL_TASK_COST);
            detail.setDoPersonalTask(bytedanceFinishPersonnalTask);
            detail.setPercent(getPercentagePercent(detail));
            detail.setPercentage(detail.getTotalCost().multiply(detail.getPercent()).setScale(2, RoundingMode.HALF_UP));
            salePerformanceDetailService.save(detail);
        } else if (user.getOrgCode().startsWith(CtopAdConstant.HB_KUAISHOU_SALE_ORG_CODE)) {
            detail.setMediaType(CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
            BigDecimal totalCost = performanceService.getSalesSeasonTotalCostByParams(startDate, endDate, null, null, allocation.getAccountId(), CtopAdConstant.PLATFORM_TYPE_KUAISHOU);
            if (null == totalCost) {
                totalCost = BigDecimal.ZERO;
            }
            detail.setTotalCost(totalCost);
            detail.setMediaTask(CtopAdConstant.KUAISHOU_MEDIA_TASK_COST);
            detail.setDoMediaTask(kuaishouFinishMediaTask);
            detail.setPersonnalTask(CtopAdConstant.KUAISHOU_PERSONAL_TASK_COST);
            detail.setDoPersonalTask(kuaishouFinishPersonnalTask);
            //提成比例
            detail.setPercent(getPercentagePercent(detail));
            detail.setPercentage(detail.getTotalCost().multiply(detail.getPercent()).setScale(2, RoundingMode.HALF_UP));
            salePerformanceDetailService.save(detail);
        } else {
            return;
        }
    }

    private BigDecimal getPercentagePercent(SalePerformanceDetail detail) {
        BigDecimal percent = detail.getDoMediaTask().divide(detail.getMediaTask(), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100"));
        //AM非自拓客户
        if (detail.getRoleId().equals(CtopAdConstant.SYSTEM_SALE_AM_CODE) && detail.getExtensionSelf() != 1) {
            return new BigDecimal("0.0005");
        }
        if (detail.getMediaType().equals(CtopAdConstant.PLATFORM_TYPE_BYTEDANCE)) {
            //头条
            if (detail.getBrandNew() == 0) {
                return new BigDecimal("0.001");
            }
            if (percent.compareTo(new BigDecimal("100")) >= 0) {
                return new BigDecimal("0.003");
            } else if (percent.compareTo(new BigDecimal("80")) >= 0) {
                return new BigDecimal("0.0025");
            } else if (percent.compareTo(new BigDecimal("60")) >= 0) {
                return new BigDecimal("0.002");
            } else {
                return BigDecimal.ZERO;
            }
        } else {
            //快手
            if (detail.getBrandNew() == 1) {
                if (percent.compareTo(new BigDecimal("100")) >= 0) {
                    return new BigDecimal("0.005");
                } else if (percent.compareTo(new BigDecimal("80")) >= 0) {
                    return new BigDecimal("0.004");
                } else if (percent.compareTo(new BigDecimal("60")) >= 0) {
                    return new BigDecimal("0.003");
                } else {
                    return BigDecimal.ZERO;
                }
            }
            //自拓
            if (detail.getExtensionSelf() == 1) {
                return new BigDecimal("0.0015");
            } else {
                return new BigDecimal("0.001");
            }
        }
    }

    @Autowired
    private IAdvertiserService advertiserService;
}
