package com.ruixuan.isc.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruixuan.common.utils.Check;
import com.ruixuan.common.utils.DateUtils;
import com.ruixuan.isc.entity.KuaishouRuleSettlementData;
import com.ruixuan.isc.entity.KuaishouSettlementRules;
import com.ruixuan.isc.mapper.KuaishouRuleSettlementDataMapper;
import com.ruixuan.isc.service.IKuaishouRuleSettlementDataService;
import com.ruixuan.isc.service.IKuaishouSettlementRulesService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2023-05-16
 */
@Service
@Slf4j
public class KuaishouRuleSettlementDataServiceImpl implements IKuaishouRuleSettlementDataService {
    @Autowired
    private KuaishouRuleSettlementDataMapper kuaishouRuleSettlementDataMapper;
    @Autowired
    private IKuaishouSettlementRulesService settlementRulesService;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public KuaishouRuleSettlementData selectKuaishouRuleSettlementDataById(Long id) {
        return kuaishouRuleSettlementDataMapper.selectKuaishouRuleSettlementDataById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param kuaishouRuleSettlementData 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<KuaishouRuleSettlementData> selectKuaishouRuleSettlementDataList(KuaishouRuleSettlementData kuaishouRuleSettlementData) {
        return kuaishouRuleSettlementDataMapper.selectKuaishouRuleSettlementDataList(kuaishouRuleSettlementData);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param kuaishouRuleSettlementData 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertKuaishouRuleSettlementData(KuaishouRuleSettlementData kuaishouRuleSettlementData) {
        kuaishouRuleSettlementData.setCreateTime(DateUtils.getNowDate());
        return kuaishouRuleSettlementDataMapper.insertKuaishouRuleSettlementData(kuaishouRuleSettlementData);
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param kuaishouRuleSettlementData 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateKuaishouRuleSettlementData(KuaishouRuleSettlementData kuaishouRuleSettlementData) {
        kuaishouRuleSettlementData.setUpdateTime(DateUtils.getNowDate());
        return kuaishouRuleSettlementDataMapper.updateKuaishouRuleSettlementData(kuaishouRuleSettlementData);
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouRuleSettlementDataByIds(Long[] ids) {
        return kuaishouRuleSettlementDataMapper.deleteKuaishouRuleSettlementDataByIds(ids);
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */
    @Override
    public int deleteKuaishouRuleSettlementDataById(Long id) {
        return kuaishouRuleSettlementDataMapper.deleteKuaishouRuleSettlementDataById(id);
    }

    @Override
    public void data(Long statDate, JSONArray dataArr) {
        if (!Check.isNull(dataArr)) {
            List<KuaishouRuleSettlementData> adds = new ArrayList<>();
            for (int i = 0; i < dataArr.size(); i++) {
                JSONObject dataJson = dataArr.getJSONObject(i);
                KuaishouRuleSettlementData settlementData = new KuaishouRuleSettlementData();
                Long relateId = dataJson.getLong("relateId");
                Long ruleId = dataJson.getLong("ruleId");
                String itemIds = dataJson.getString("itemIds");
                Long promoterId = dataJson.getLong("promoterId");
                String promoterName = dataJson.getString("promoterName");
                Long itemCreateId = dataJson.getLong("itemCreateId");
                String itemCreateName = dataJson.getString("itemCreateName");
                Long promoterCreateId = dataJson.getLong("promoterCreateId");
                String promoterCreateName = dataJson.getString("promoterCreateName");
                Long orderNum = dataJson.getLong("orderNum");
                Long validOrderNum = dataJson.getLong("validOrderNum");
                if (validOrderNum == 0 || Check.isNull(validOrderNum)) {
                    continue;
                }
                Long yesterdayOrderNum = dataJson.getLong("yesterdayOrderNum");
                Long yesterdayValidOrderNum = dataJson.getLong("yesterdayValidOrderNum");
                Integer rule_type = dataJson.getInteger("rule_type");
                JSONObject ruleData = new JSONObject();
                if (rule_type == 1) {
                    ruleData = getRuleData(relateId, promoterId, ruleId,  validOrderNum);

                } else if (rule_type == 2) {
                    ruleData = getOrderRuleData(relateId, promoterId, ruleId, validOrderNum);
                }
                settlementData.setRuleId(ruleId);
                settlementData.setRuleName(ruleData.getString("ruleName"));
                settlementData.setSonRuleId(ruleData.getLong("sonRuleId"));
                settlementData.setRelateId(relateId);
                settlementData.setItemIds(itemIds);
                settlementData.setPromoterId(promoterId);
                settlementData.setPromoterName(promoterName);
                settlementData.setItemCreateId(itemCreateId);
                settlementData.setItemCreateName(itemCreateName);
                settlementData.setPromoterCreateId(promoterCreateId);
                settlementData.setPromoterCreateName(promoterCreateName);
                settlementData.setOrderNum(orderNum);
                settlementData.setValidOrderNum(validOrderNum);
                settlementData.setYesterdayOrderNum(yesterdayOrderNum);
                settlementData.setYesterdayValidOrderNum(yesterdayValidOrderNum);
                settlementData.setStatDate(statDate);
                settlementData.setAnchorAmount(ruleData.getBigDecimal("anchorAmount"));
                settlementData.setReferenceAmount(ruleData.getBigDecimal("referenceAmount"));
                settlementData.setSettlementStatus(ruleData.getInteger("settlementStatus"));
                settlementData.setLastSettlementOrderNum(ruleData.getLong("lastSettlementOrderNum"));
                settlementData.setRuleType(rule_type);
                adds.add(settlementData);
            }
            if (!Check.isNull(adds)) {
                kuaishouRuleSettlementDataMapper.replaceDatas(adds);
                log.info("结算信息入库完成，时间：{},数据量：{}", statDate, adds.size());
            }

        }
    }


    @Override
    public void promoterData(Long statDate, JSONArray dataArr) {
        if (!Check.isNull(dataArr)) {
            List<KuaishouRuleSettlementData> adds = new ArrayList<>();
            for (int i = 0; i < dataArr.size(); i++) {
                JSONObject dataJson = dataArr.getJSONObject(i);
                KuaishouRuleSettlementData settlementData = new KuaishouRuleSettlementData();
                Long relateId = dataJson.getLong("relateId");
                Long ruleId = dataJson.getLong("ruleId");
                Long promoterId = dataJson.getLong("promoterId");
                String promoterName = dataJson.getString("promoterName");
                Long orderNum = dataJson.getLong("orderNum");
                Long validOrderNum = dataJson.getLong("validOrderNum");
                if (validOrderNum == 0 || Check.isNull(validOrderNum)) {
                    continue;
                }
                Long yesterdayOrderNum = dataJson.getLong("yesterdayOrderNum");
                Long yesterdayValidOrderNum = dataJson.getLong("yesterdayValidOrderNum");
                Integer rule_type = dataJson.getInteger("rule_type");
                JSONObject ruleData = new JSONObject();
                if (rule_type == 3) {
                    ruleData = getPromoterRuleData(relateId, promoterId, ruleId,  validOrderNum);

                } else  {
                    continue;
                }
                settlementData.setRuleId(ruleId);
                settlementData.setRuleName(ruleData.getString("ruleName"));
                settlementData.setSonRuleId(ruleData.getLong("sonRuleId"));
                settlementData.setPromoterId(promoterId);
                settlementData.setPromoterName(promoterName);
                settlementData.setOrderNum(orderNum);
                settlementData.setValidOrderNum(validOrderNum);
                settlementData.setYesterdayOrderNum(yesterdayOrderNum);
                settlementData.setYesterdayValidOrderNum(yesterdayValidOrderNum);
                settlementData.setStatDate(statDate);
                settlementData.setAnchorAmount(ruleData.getBigDecimal("anchorAmount"));
                settlementData.setReferenceAmount(ruleData.getBigDecimal("referenceAmount"));
                settlementData.setSettlementStatus(ruleData.getInteger("settlementStatus"));
                settlementData.setLastSettlementOrderNum(ruleData.getLong("lastSettlementOrderNum"));
                settlementData.setRuleType(rule_type);
                adds.add(settlementData);
            }
            if (!Check.isNull(adds)) {
                kuaishouRuleSettlementDataMapper.replaceDatas(adds);
                log.info("结算信息入库完成，时间：{},数据量：{}", statDate, adds.size());
            }

        }
    }




    // 按区间结算
    @Override
    public JSONObject getRuleData(Long relateId, Long promoterId, Long ruleId, Long validOrderNum) {
        JSONObject returnJson = new JSONObject();
        BigDecimal anchorAmount = new BigDecimal(0); // 达人激励
        BigDecimal referenceAmount = new BigDecimal(0); // 推荐人激励
        KuaishouSettlementRules kuaishouSettlementRules = settlementRulesService.selectKuaishouSettlementRulesById(ruleId);
        returnJson.put("ruleId", ruleId);
        returnJson.put("ruleName", kuaishouSettlementRules.getRuleName());
        List<JSONObject> ruleList = kuaishouRuleSettlementDataMapper.getRuleList(ruleId);
        JSONObject lastRule = kuaishouRuleSettlementDataMapper.lastRule(relateId, promoterId, ruleId); //上次结算命中的规则
        Long lastValidOrderNum = 0L;
        if (!Check.isNull(lastRule)) {
            lastValidOrderNum += lastRule.getLong("validOrderNum");
        }

        JSONObject ruleJson = new JSONObject();
        if (validOrderNum <= lastValidOrderNum) { // 有效订单数据小于等于昨天 不做结算
            returnJson.put("ruleId", ruleId);
            returnJson.put("sonRuleId", 0);
            returnJson.put("ruleName", "未命中结算规则");
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 1);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;
        } else if (validOrderNum < 10000) { // 单量 小于等于1w 在第一个结算周期内
            for (int i = 0; i < ruleList.size(); i++) {
                JSONObject rule = ruleList.get(i);
                Long startItemCount = rule.getLong("startItemCount");
                Long endItemCount = rule.getLong("endItemCount");
                if (validOrderNum >= startItemCount && validOrderNum <= endItemCount) {
                    ruleJson = rule;
                    break;
                }
            }
            if (Check.isNull(ruleJson) || ruleJson.size() == 0) {
                returnJson.put("sonRuleId", 0);
                returnJson.put("anchorAmount", anchorAmount);
                returnJson.put("referenceAmount", referenceAmount);
                returnJson.put("settlementStatus", 1);
                returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                return returnJson;
            }
            Integer lastSortCount = null;
            if (Check.isNull(lastRule)) {
                lastSortCount = 0;
            }
            if (!Check.isNull(lastRule)) {
                Integer sortCount = lastRule.getInteger("sortCount"); // 上次结算命中的规则序号
                if (Check.isNull(sortCount)) {
                    lastSortCount = 0;
                } else {
                    lastSortCount = sortCount;
                }
            }
            Integer currentSortCount = ruleJson.getInteger("sortCount"); // 当前结算命中的规则序号
            if (currentSortCount <= lastSortCount) {
                returnJson.put("sonRuleId", 0);
                returnJson.put("anchorAmount", anchorAmount);
                returnJson.put("referenceAmount", referenceAmount);
                returnJson.put("settlementStatus", 1);
                returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                return returnJson;
            } else {
                JSONObject totalAmount = kuaishouRuleSettlementDataMapper.getTotalAmount(ruleId, lastSortCount, currentSortCount);
                returnJson.put("sonRuleId", ruleJson.getLong("id"));
                returnJson.put("anchorAmount", totalAmount.getBigDecimal("anchorAmount"));
                returnJson.put("referenceAmount", totalAmount.getBigDecimal("referenceAmount"));
                returnJson.put("settlementStatus", 2);
                returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                return returnJson;
            }
        } else if (validOrderNum >= 10000) {
            System.err.println(validOrderNum);
            Integer incentivizedCount = (int) Math.floor(validOrderNum / 10000); // 需要 1w单结算次数
            Integer lastIncentivizedCount = kuaishouRuleSettlementDataMapper.selectIncentiveLog(relateId, promoterId); // 一万单已结算次数
            if (Check.isNull(lastIncentivizedCount)) {
                lastIncentivizedCount = 0;
            }
            if (incentivizedCount > lastIncentivizedCount) {
                BigDecimal count = new BigDecimal(incentivizedCount - lastIncentivizedCount);
                BigDecimal promoterRide = new BigDecimal(700); // 达人破万奖励金额
                BigDecimal referenceRide = new BigDecimal(100); // 推荐人破万奖励金额
                BigDecimal promoterIncentiveAmount = count.multiply(promoterRide); // 达人破万单奖励
                BigDecimal referenceIncentiveAmount = count.multiply(referenceRide); // 推荐人破万单奖励
                anchorAmount = anchorAmount.add(promoterIncentiveAmount);
                referenceAmount = referenceAmount.add(referenceIncentiveAmount);
                kuaishouRuleSettlementDataMapper.replaceIncentiveLog(relateId, promoterId, ruleId, incentivizedCount, lastIncentivizedCount);
            }
            if (Check.isNull(lastRule)) { //查询到上次命中的结算规则 则代表为新结算用户
                JSONObject getTotalByCountAndRuleId = kuaishouRuleSettlementDataMapper.getTotalByCountAndRuleId(incentivizedCount, ruleId);
                if (!Check.isNull(getTotalByCountAndRuleId)) {
                    anchorAmount = anchorAmount.add(getTotalByCountAndRuleId.getBigDecimal("anchorAmount"));
                    referenceAmount = referenceAmount.add(getTotalByCountAndRuleId.getBigDecimal("referenceAmount"));
                }
                BigDecimal decValidOrderNum = new BigDecimal(validOrderNum);
                Long residueNum = decValidOrderNum.subtract(new BigDecimal(incentivizedCount).multiply(new BigDecimal(10000))).longValue(); // 新用户 剩余不到1w单的结算
                for (int i = 0; i < ruleList.size(); i++) {
                    JSONObject rule = ruleList.get(i);
                    Long startItemCount = rule.getLong("startItemCount");
                    Long endItemCount = rule.getLong("endItemCount");
                    if (residueNum >= startItemCount && residueNum <= endItemCount) {
                        ruleJson = rule;
                        break;
                    }
                }
                if (Check.isNull(ruleJson) || ruleJson.size() == 0) { // 剩余单量未命中结算规则 直接跳出此次结算计算
                    returnJson.put("sonRuleId", 0);
                    returnJson.put("anchorAmount", anchorAmount);
                    returnJson.put("referenceAmount", referenceAmount);
                    returnJson.put("settlementStatus", 2);
                    returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                    return returnJson;
                }
                Integer currentSortCount = ruleJson.getInteger("sortCount"); // 当前结算命中的规则序号
                JSONObject totalAmount = kuaishouRuleSettlementDataMapper.getTotalAmount(ruleId, 0, currentSortCount); // 新的规则 序号从0开始
                returnJson.put("sonRuleId", ruleJson.getLong("id"));
                anchorAmount = anchorAmount.add(totalAmount.getBigDecimal("anchorAmount"));
                referenceAmount = referenceAmount.add(totalAmount.getBigDecimal("referenceAmount"));
                returnJson.put("anchorAmount", anchorAmount);
                returnJson.put("referenceAmount", referenceAmount);
                returnJson.put("settlementStatus", 2);
                returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                return returnJson;
            } else { // 非新结算达人
                if (validOrderNum <= lastValidOrderNum) { // 当前结算有效订单 小于等于上次结算有效订单数 则不参与接下来的结算
                    returnJson.put("sonRuleId", 0);
                    returnJson.put("anchorAmount", 0);
                    returnJson.put("referenceAmount", 0);
                    returnJson.put("settlementStatus", 1);
                    returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                    return returnJson;
                }
                Integer lastSortCount = lastRule.getInteger("sortCount"); // 上次结算命中的规则序号
                Integer ruleMaxCount = kuaishouRuleSettlementDataMapper.getMaxRuleCountByRuleId(ruleId); // 当前规则下最大的序号
                Long complement = null;
                if (lastValidOrderNum > 10000) {
                    String lastValidOrderNumStr = String.valueOf(lastValidOrderNum);
                    String substring = lastValidOrderNumStr.substring(lastValidOrderNumStr.length() - 4);
                    Long aLong = Long.valueOf(substring);
                    Long curComplement = 10000 - aLong;
                    if (validOrderNum - lastValidOrderNum <= curComplement) { // 当前单量不够补齐10000单
                        Long ruleOrder = aLong + (validOrderNum - lastValidOrderNum); //  当前单数补齐上一次结算的最终单数
                        for (int i = 0; i < ruleList.size(); i++) {
                            JSONObject rule = ruleList.get(i);
                            Long startItemCount = rule.getLong("startItemCount");
                            Long endItemCount = rule.getLong("endItemCount");
                            if (ruleOrder >= startItemCount && ruleOrder <= endItemCount) {
                                ruleJson = rule;
                                break;
                            }
                        }
                        if (Check.isNull(ruleJson) || ruleJson.size() == 0) { // 剩余单量未命中结算规则 直接跳出此次结算计算
                            returnJson.put("sonRuleId", 0);
                            returnJson.put("anchorAmount", anchorAmount);
                            returnJson.put("referenceAmount", referenceAmount);
                            returnJson.put("settlementStatus", 2);
                            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                            return returnJson;
                        } else {
                            Integer currentSortCount = ruleJson.getInteger("sortCount"); // 当前结算命中的规则序号
                            JSONObject amount = kuaishouRuleSettlementDataMapper.getTotalAmount(ruleId, lastSortCount, currentSortCount); // 新的规则 序号从0开始
                            returnJson.put("sonRuleId", ruleJson.getLong("id"));
                            anchorAmount = anchorAmount.add(amount.getBigDecimal("anchorAmount"));
                            referenceAmount = referenceAmount.add(amount.getBigDecimal("referenceAmount"));
                            returnJson.put("anchorAmount", anchorAmount);
                            returnJson.put("referenceAmount", referenceAmount);
                            returnJson.put("settlementStatus", 2);
                            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                            return returnJson;
                        }
                    } else {
                        complement = 10000 - aLong;
                    }

                } else {
                    Long asLong = 10000 - lastValidOrderNum; // 补齐1000单需要的单数
                    if (validOrderNum - lastValidOrderNum <= asLong) {  // 当前单量不够补齐10000单
                        Long ruleOrder = lastValidOrderNum + (validOrderNum - lastValidOrderNum); //  当前单数补齐上一次结算的最终单数
                        for (int i = 0; i < ruleList.size(); i++) {
                            JSONObject rule = ruleList.get(i);
                            Long startItemCount = rule.getLong("startItemCount");
                            Long endItemCount = rule.getLong("endItemCount");
                            if (ruleOrder >= startItemCount && ruleOrder <= endItemCount) {
                                ruleJson = rule;
                                break;
                            }
                        }
                        if (Check.isNull(ruleJson) || ruleJson.size() == 0) { // 剩余单量未命中结算规则 直接跳出此次结算计算
                            returnJson.put("sonRuleId", 0);
                            returnJson.put("anchorAmount", anchorAmount);
                            returnJson.put("referenceAmount", referenceAmount);
                            returnJson.put("settlementStatus", 2);
                            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                            return returnJson;
                        } else {
                            Integer currentSortCount = ruleJson.getInteger("sortCount"); // 当前结算命中的规则序号
                            JSONObject amount = kuaishouRuleSettlementDataMapper.getTotalAmount(ruleId, lastSortCount, currentSortCount); // 新的规则 序号从0开始
                            returnJson.put("sonRuleId", ruleJson.getLong("id"));
                            anchorAmount = anchorAmount.add(amount.getBigDecimal("anchorAmount"));
                            referenceAmount = referenceAmount.add(amount.getBigDecimal("referenceAmount"));
                            returnJson.put("anchorAmount", anchorAmount);
                            returnJson.put("referenceAmount", referenceAmount);
                            returnJson.put("settlementStatus", 2);
                            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                            return returnJson;
                        }

                    } else {
                        complement = 10000 - lastValidOrderNum;
                    }
                }
                // 查询 上次结算补齐10000需要激励的金额
                JSONObject totalAmount = kuaishouRuleSettlementDataMapper.getTotalAmount(ruleId, lastSortCount, ruleMaxCount);
                anchorAmount = anchorAmount.add(totalAmount.getBigDecimal("anchorAmount"));
                referenceAmount = referenceAmount.add(totalAmount.getBigDecimal("referenceAmount"));
                Long newValidOrderNum = validOrderNum - complement - lastValidOrderNum;
                if (newValidOrderNum > 10000) { // 如果剩余单量大于一万单 计算完成1w周期内的结算金额
                    Integer newSettlementCount = (int) Math.floor(newValidOrderNum / 10000); // 补齐上次结算10000单后需要结算的完整次数
                    JSONObject totalByCountAndRuleId = kuaishouRuleSettlementDataMapper.getTotalByCountAndRuleId(newSettlementCount, ruleId);
                    anchorAmount = anchorAmount.add(totalByCountAndRuleId.getBigDecimal("anchorAmount"));
                    referenceAmount = referenceAmount.add(totalByCountAndRuleId.getBigDecimal("referenceAmount"));
                    newValidOrderNum = newValidOrderNum - (newSettlementCount * 10000);
                }
                for (int i = 0; i < ruleList.size(); i++) {
                    JSONObject rule = ruleList.get(i);
                    Long startItemCount = rule.getLong("startItemCount");
                    Long endItemCount = rule.getLong("endItemCount");
                    if (newValidOrderNum >= startItemCount && newValidOrderNum <= endItemCount) {
                        ruleJson = rule;
                        break;
                    }
                }
                if (Check.isNull(ruleJson) || ruleJson.size() == 0) { // 剩余单量未命中结算规则 直接跳出此次结算计算
                    returnJson.put("sonRuleId", 0);
                    returnJson.put("anchorAmount", anchorAmount);
                    returnJson.put("referenceAmount", referenceAmount);
                    returnJson.put("settlementStatus", 2);
                    returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                    return returnJson;
                }
                Integer currentSortCount = ruleJson.getInteger("sortCount"); // 当前结算命中的规则序号
                JSONObject amount = kuaishouRuleSettlementDataMapper.getTotalAmount(ruleId, 0, currentSortCount); // 新的规则 序号从0开始
                returnJson.put("sonRuleId", ruleJson.getLong("id"));
                anchorAmount = anchorAmount.add(amount.getBigDecimal("anchorAmount"));
                referenceAmount = referenceAmount.add(amount.getBigDecimal("referenceAmount"));
                returnJson.put("anchorAmount", anchorAmount);
                returnJson.put("referenceAmount", referenceAmount);
                returnJson.put("settlementStatus", 2);
                returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
                return returnJson;
            }
        }
        return returnJson;
    }


    // 按单量结算
    @Override
    public JSONObject getOrderRuleData(Long relateId, Long promoterId, Long ruleId, Long validOrderNum) {
        JSONObject returnJson = new JSONObject();
        BigDecimal anchorAmount = new BigDecimal(0); // 达人激励
        BigDecimal referenceAmount = new BigDecimal(0); // 推荐人激励
        KuaishouSettlementRules kuaishouSettlementRules = settlementRulesService.selectKuaishouSettlementRulesById(ruleId);
        returnJson.put("ruleId", ruleId);
        JSONObject lastRule = kuaishouRuleSettlementDataMapper.lastRule(relateId, promoterId, ruleId); //上次结算命中的规则
        Long lastValidOrderNum = 0L;
        if (!Check.isNull(lastRule)) {
            lastValidOrderNum += lastRule.getLong("validOrderNum");
        }
        JSONObject ruleJson = kuaishouRuleSettlementDataMapper.getRuleJson(ruleId);
        if (Check.isNull(ruleJson)) {
            returnJson.put("sonRuleId", 0);
            returnJson.put("ruleName", "未命中结算规则");
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 1);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;
        }
        Integer itemCount = ruleJson.getInteger("startItemCount"); // 规则单数
        BigDecimal ruleAnchorAmount = ruleJson.getBigDecimal("anchorAmount"); // 规则达人激励金额
        if(Check.isNull(ruleAnchorAmount)){
            ruleAnchorAmount = new BigDecimal(0);
        }
        BigDecimal ruleReferenceAmount = ruleJson.getBigDecimal("referenceAmount"); // 规则达人激励金额
        if(Check.isNull(ruleReferenceAmount)){
            ruleReferenceAmount = new BigDecimal(0);
        }

        if (validOrderNum < itemCount) {
            returnJson.put("sonRuleId", 0);
            returnJson.put("ruleName", "未命中结算规则");
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 1);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;
        }


        Integer incentivizedCount = (int) Math.floor(validOrderNum / itemCount); // 需要结算的次数
        Integer lastIncentivizedCount = kuaishouRuleSettlementDataMapper.selectIncentiveLog(relateId, promoterId); // 已结算次数
        if (Check.isNull(lastIncentivizedCount)) {
            lastIncentivizedCount = 0;
        }
        if (incentivizedCount > lastIncentivizedCount) {
            BigDecimal count = new BigDecimal(incentivizedCount - lastIncentivizedCount);
            BigDecimal promoterIncentiveAmount = count.multiply(ruleAnchorAmount); // 达人奖励
            BigDecimal referenceIncentiveAmount = count.multiply(ruleReferenceAmount); // 推荐人奖励
            anchorAmount = anchorAmount.add(promoterIncentiveAmount);
            referenceAmount = referenceAmount.add(referenceIncentiveAmount);
            kuaishouRuleSettlementDataMapper.replaceIncentiveLog(relateId, promoterId, ruleId, incentivizedCount, lastIncentivizedCount);
            returnJson.put("sonRuleId", ruleJson.getLong("id"));
            returnJson.put("ruleName", kuaishouSettlementRules.getRuleName());
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 2);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;

        } else {
            returnJson.put("sonRuleId", 0);
            returnJson.put("ruleName", "未命中结算规则");
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 1);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;
        }
    }


    // 按达人结算

    @Override
    public JSONObject getPromoterRuleData(Long relateId, Long promoterId, Long ruleId, Long validOrderNum) {
        JSONObject returnJson = new JSONObject();
        BigDecimal anchorAmount = new BigDecimal(0); // 达人激励
        BigDecimal referenceAmount = new BigDecimal(0); // 推荐人激励
        KuaishouSettlementRules kuaishouSettlementRules = settlementRulesService.selectKuaishouSettlementRulesById(ruleId);
        returnJson.put("ruleId", ruleId);
        JSONObject lastRule = kuaishouRuleSettlementDataMapper.lastRule(null, promoterId, ruleId); //上次结算命中的规则
        Long lastValidOrderNum = 0L;
        if (!Check.isNull(lastRule)) {
            lastValidOrderNum += lastRule.getLong("validOrderNum");
        }
        JSONObject ruleJson = kuaishouRuleSettlementDataMapper.getRuleJson(ruleId);
        if (Check.isNull(ruleJson)) {
            returnJson.put("sonRuleId", 0);
            returnJson.put("ruleName", "未命中结算规则");
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 1);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;
        }
        Integer itemCount = ruleJson.getInteger("startItemCount"); // 规则单数
        BigDecimal ruleAnchorAmount = ruleJson.getBigDecimal("anchorAmount"); // 规则达人激励金额
        if(Check.isNull(ruleAnchorAmount)){
            ruleAnchorAmount = new BigDecimal(0);
        }
        BigDecimal ruleReferenceAmount = ruleJson.getBigDecimal("referenceAmount"); // 规则达人激励金额
        if(Check.isNull(ruleReferenceAmount)){
            ruleReferenceAmount = new BigDecimal(0);
        }

        if (validOrderNum < itemCount) {
            returnJson.put("sonRuleId", 0);
            returnJson.put("ruleName", "未命中结算规则");
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 1);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;
        }


        Integer incentivizedCount = (int) Math.floor(validOrderNum / itemCount); // 需要结算的次数
        Integer lastIncentivizedCount = kuaishouRuleSettlementDataMapper.selectPromoterIncentiveLog(promoterId); // 已结算次数
        if (Check.isNull(lastIncentivizedCount)) {
            lastIncentivizedCount = 0;
        }
        if (incentivizedCount > lastIncentivizedCount) {
            BigDecimal count = new BigDecimal(incentivizedCount - lastIncentivizedCount);
            BigDecimal promoterIncentiveAmount = count.multiply(ruleAnchorAmount); // 达人奖励
            BigDecimal referenceIncentiveAmount = count.multiply(ruleReferenceAmount); // 推荐人奖励
            anchorAmount = anchorAmount.add(promoterIncentiveAmount);
            referenceAmount = referenceAmount.add(referenceIncentiveAmount);
            kuaishouRuleSettlementDataMapper.replacePromoterIncentiveLog( promoterId, ruleId, incentivizedCount, lastIncentivizedCount);
            returnJson.put("sonRuleId", ruleJson.getLong("id"));
            returnJson.put("ruleName", kuaishouSettlementRules.getRuleName());
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 2);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;

        } else {
            returnJson.put("sonRuleId", 0);
            returnJson.put("ruleName", "未命中结算规则");
            returnJson.put("anchorAmount", anchorAmount);
            returnJson.put("referenceAmount", referenceAmount);
            returnJson.put("settlementStatus", 1);
            returnJson.put("lastSettlementOrderNum", lastValidOrderNum);
            return returnJson;
        }
    }


    @Override
    public List<JSONObject> getSettlementDate(Long statDate, Long promoterId, String promoterName) {
        return kuaishouRuleSettlementDataMapper.getSettlementDate(statDate, promoterId, promoterName);
    }

    @Override
    public void updatePromoterStatus(Long statDate, Long promoterId, Integer status) {
        kuaishouRuleSettlementDataMapper.updatePromoterStatus(statDate, promoterId, status);
    }

    @Override
    public List<JSONObject> getPromoterSettlementDetail(Long date, Long promoterId, Integer settlementStatus) {
        return kuaishouRuleSettlementDataMapper.getPromoterSettlementDetail(date, promoterId, settlementStatus);
    }

    @Override
    public JSONObject getData() {
        return kuaishouRuleSettlementDataMapper.getData();
    }


}

