package cn.iocoder.yudao.module.crm.service.salesperformancesettlement;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.SocialTypeEnum;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.template.WxMpMsgTemplateUtils;
import cn.iocoder.yudao.framework.common.template.dto.PerformanceResultConfirmationReminderDTO;
import cn.iocoder.yudao.framework.common.template.vo.SubscribeMessageReqDTO;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.framework.common.util.number.BigDecimalUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.bpm.api.oa.BpmOAContractApi;
import cn.iocoder.yudao.module.bpm.api.oa.BpmOAReceiptApi;
import cn.iocoder.yudao.module.bpm.api.oa.BpmOASalesPerformanceApi;
import cn.iocoder.yudao.module.bpm.api.oa.vo.receipt.ReceiptSettlementDTO;
import cn.iocoder.yudao.module.bpm.api.oa.vo.receipt.ReceiptSettlementVO;
import cn.iocoder.yudao.module.bpm.api.oa.vo.salesperformance.SalesPerformanceDTO;
import cn.iocoder.yudao.module.crm.controller.admin.salesperformancesettlement.vo.SalesPerformanceSettlementPageReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.salesperformancesettlement.vo.SalesPerformanceSettlementSaveReqVO;
import cn.iocoder.yudao.module.crm.controller.admin.userlivetree.vo.UserLiveTreeListVO;
import cn.iocoder.yudao.module.crm.dal.dataobject.salesperformanceassessment.SalesPerformanceAssessmentDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.salesperformancesettlement.SalesPerformanceSettlementDO;
import cn.iocoder.yudao.module.crm.dal.dataobject.salesperformanceweight.SalesPerformanceWeightDO;
import cn.iocoder.yudao.module.crm.dal.mysql.salesperformancesettlement.SalesPerformanceSettlementMapper;
import cn.iocoder.yudao.module.crm.service.crmcontract.CrmContractService;
import cn.iocoder.yudao.module.crm.service.salesperformanceassessment.SalesPerformanceAssessmentService;
import cn.iocoder.yudao.module.crm.service.salesperformanceweight.SalesPerformanceWeightService;
import cn.iocoder.yudao.module.crm.service.userlivetree.UserLiveTreeService;
import cn.iocoder.yudao.module.hrm.api.crmcontract.dto.CrmContractProductSettlementDTO;
import cn.iocoder.yudao.module.system.api.auth.AdminOauthUserOtherInfoApi;
import cn.iocoder.yudao.module.system.api.auth.dto.AdminOauthUserOtherInfoApiDTO;
import cn.iocoder.yudao.module.system.api.auth.vo.AdminOauthUserOtherInfoApiVO;
import cn.iocoder.yudao.module.system.api.permission.RoleApi;
import cn.iocoder.yudao.module.system.api.subscribe.SubscribeMessageSendApi;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.ognl.Ognl;
import org.apache.ibatis.ognl.OgnlException;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.module.hrm.enums.ErrorCodeConstants.NOT_EDITABLE_UNTIL_SALES_TARGET_HAS_BEEN_APPLIED;

/**
 * 销售业绩结算记录 Service 实现类
 *
 * @author 艾楷
 */
@Service
@Validated
@Slf4j
public class SalesPerformanceSettlementServiceImpl extends ServiceImpl<SalesPerformanceSettlementMapper, SalesPerformanceSettlementDO> implements SalesPerformanceSettlementService {

    @Resource
    private SalesPerformanceSettlementMapper salesPerformanceSettlementMapper;
    @Resource
    private UserLiveTreeService userLiveTreeService;
    @Resource
    private CrmContractService crmContractService;
    @Resource
    private BpmOAReceiptApi receiptApi;
    @Resource
    private SalesPerformanceWeightService salesPerformanceWeightService;
    @Resource
    private BpmOASalesPerformanceApi salesPerformanceApi;
    @Resource
    private SalesPerformanceAssessmentService salesPerformanceAssessmentService;
    @Resource
    private AdminOauthUserOtherInfoApi adminOauthUserOtherInfoApi;
    @Resource
    private SubscribeMessageSendApi subscribeMessageSendApi;
    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private BpmOAContractApi bpmOAContractApi;
    @Resource
    private RoleApi roleApi;

    //百分比
    private static final BigDecimal PERCENTAGE = new BigDecimal("0.01");
    //十分比率
    private static final BigDecimal TEN_PERCENT = new BigDecimal("10");

    @Override
    public void createSalesPerformanceSettlement(LocalDateTime now, Long userId) {
        // 插入
        SalesPerformanceSettlementDO salesPerformanceSettlementDO = new SalesPerformanceSettlementDO();
        salesPerformanceSettlementDO.setUserId(userId);
        salesPerformanceSettlementDO.setYear(String.valueOf(now.getYear()));
        // 月份补0
        salesPerformanceSettlementDO.setMonth(String.format("%02d", now.getMonthValue()));
        salesPerformanceSettlementMapper.insert(salesPerformanceSettlementDO);
    }

    @Override
    public void updateSalesPerformanceSettlement(SalesPerformanceSettlementSaveReqVO updateReqVO) {
        SalesPerformanceSettlementDO salesPerformanceSettlementDO = salesPerformanceSettlementMapper.selectById(updateReqVO.getId());
        // 更新
        SalesPerformanceSettlementDO updateObj = BeanUtils.toBean(updateReqVO, SalesPerformanceSettlementDO.class);
        // 如果更新的是 /实际回款额 /实际销售额 /评分 重新计算 对应的比例以及总分和核发比例
        boolean changeFlag = false;
        //获取当月目标审核通过的
        SalesPerformanceDTO salesPerformanceDTO = null;
        //获取权重
        SalesPerformanceWeightDO salesPerformanceWeight = salesPerformanceWeightService.getSalesPerformanceWeight();
        if (salesPerformanceSettlementDO.getSalesPerformanceId() != null) {
            salesPerformanceDTO = salesPerformanceApi.getBySalesPerformanceId(salesPerformanceSettlementDO.getSalesPerformanceId()).getCheckedData();
        }
        if (!BigDecimalUtil.isEqualTo(updateObj.getActualPayment(), salesPerformanceSettlementDO.getActualPayment())) {
            if (salesPerformanceDTO == null) {
                // 未申请销售目标前不可编辑
                throw exception(NOT_EDITABLE_UNTIL_SALES_TARGET_HAS_BEEN_APPLIED);
            }
            BigDecimal saleScore = (salesPerformanceDTO.getSaleTarget() == null || salesPerformanceDTO.getSaleTarget() == 0) ? BigDecimal.ZERO :
                    (BigDecimal.valueOf(updateObj.getActualSale()).divide(BigDecimal.valueOf(salesPerformanceDTO.getSaleTarget()), 2, RoundingMode.HALF_UP));
            saleScore = (saleScore.compareTo(BigDecimal.ONE) >= 0) ? salesPerformanceWeight.getSaleWeight() :
                    salesPerformanceWeight.getSaleWeight().multiply(saleScore);
            // 销售任务最终得分
            updateObj.setSaleTask(saleScore);
            changeFlag = true;
        }
        if (updateObj.getActualSale() != null && updateObj.getActualSale().equals(salesPerformanceSettlementDO.getActualSale())) {
            if (salesPerformanceDTO == null) {
                // 未申请销售目标前不可编辑
                throw exception(NOT_EDITABLE_UNTIL_SALES_TARGET_HAS_BEEN_APPLIED);
            }
            BigDecimal paymentScore = BigDecimalUtil.isEqZero(salesPerformanceDTO.getPaymentTarget()) ? BigDecimal.ZERO :
                    (updateObj.getActualPayment().divide(salesPerformanceDTO.getPaymentTarget(), 2, RoundingMode.HALF_UP));
            paymentScore = (paymentScore.compareTo(BigDecimal.ONE) >= 0) ? salesPerformanceWeight.getPaymentWeight() :
                    salesPerformanceWeight.getPaymentWeight().multiply(paymentScore);
            // 回款任务最终得分
            updateObj.setPaymentTask(paymentScore);
            changeFlag = true;
        }
        if (!BigDecimalUtil.isEqualTo(updateObj.getScore(), salesPerformanceSettlementDO.getScore())) {
            BigDecimal score = new BigDecimal(String.valueOf(updateObj.getScore()))
                    .divide(TEN_PERCENT, 2, RoundingMode.HALF_UP);
            score = (score.compareTo(BigDecimal.ONE) >= 0) ? salesPerformanceWeight.getScoreWeight() :
                    salesPerformanceWeight.getScoreWeight().multiply(score);
            // 回款任务最终得分
            updateObj.setScoreTask(score);
            changeFlag = true;
            // --
            updateObj.setScoreStatus(1);
            if (salesPerformanceSettlementDO.getSettlementStatus() == 1) {
                updateObj.setSettlementStatus(2);
            }
        }
        if (changeFlag) {
            // 重新计算 -
            updateObj.setTotalScore(BigDecimalUtil.adds(updateObj.getSaleTask(), updateObj.getPaymentTask(), updateObj.getScoreTask()));
            // -- 根据总分再计算核发比例
            List<SalesPerformanceAssessmentDO> salesPerformanceAssessmentDOS = salesPerformanceAssessmentService.list(new LambdaQueryWrapper<SalesPerformanceAssessmentDO>()
                    .orderByDesc(SalesPerformanceAssessmentDO::getProportion));
            for (SalesPerformanceAssessmentDO salesPerformanceAssessmentDO : salesPerformanceAssessmentDOS) {
                if (calculation(salesPerformanceAssessmentDO.getCalculationExpression(), updateObj.getTotalScore())) {
                    updateObj.setProportionOfIssuance(salesPerformanceAssessmentDO.getProportion());
                    break;
                }
            }
        }
        salesPerformanceSettlementMapper.updateById(updateObj);
    }

    @Override
    public void deleteSalesPerformanceSettlement(Long id) {
        // 删除
        salesPerformanceSettlementMapper.deleteById(id);
    }

    @Override
    public SalesPerformanceSettlementDO getSalesPerformanceSettlement(Long id) {
        return salesPerformanceSettlementMapper.getSalesPerformanceSettlement(id);
    }

    @Override
    public PageResult<SalesPerformanceSettlementDO> getSalesPerformanceSettlementPage(SalesPerformanceSettlementPageReqVO pageReqVO) {
        Long userId = SecurityFrameworkUtils.getLoginUserId();
        // -- 这里要做什么？ 要筛选出可见范围 - 但是crm用户不和system 用户 结构一体 - 所以 需要从代码中来区分 - 我们设定一个角色 可以看全部内容 - 完了后 其他的用户只能看自己以及下级的信息 通过pid 和 id来判断
        // 那么怎么获取到这个用户有没有包含这个角色呢？
        boolean calculator = roleApi.validCalculator(userId).getCheckedData();
        if (!calculator) {
            List<Long> userIds = userLiveTreeService.getItemIdsByUserId(userId);
            userIds.add(userId);
            pageReqVO.setUserIds(userIds);
        }
        IPage<SalesPerformanceSettlementDO> pageResult = salesPerformanceSettlementMapper.getSalesPerformanceSettlementPage(pageReqVO, MyBatisUtils.buildPage(pageReqVO));
        return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
    }

    @Override
    public void settlement() {
        LocalDateTime now = LocalDateTime.now().minusMonths(1L);
        String year = String.valueOf(now.getYear());
        String month = String.format("%02d", now.getMonthValue());
        // 获取CRM用户一下
        List<UserLiveTreeListVO> userLiveList = userLiveTreeService.getUserLiveList();
        // 计算当前月所有销售的 销售额 - 销售台数
        // -- 合同产品数量 （后续可能需要根据不同的产品来定目标 - 所以这里 我们预判下 - 将合同对应的projectId也查询出来 好方便后续做产品区分）
        List<CrmContractProductSettlementDTO> contractProductSettlementDTOList = crmContractService.getContractProductSettlement();

        contractProductSettlementDTOList = CollUtil.isEmpty(contractProductSettlementDTOList) ? Collections.emptyList() : contractProductSettlementDTOList;
        //根据用户id分组 并且合并数量
        Map<Long, Integer> productMap = contractProductSettlementDTOList.stream().collect(Collectors.groupingBy(CrmContractProductSettlementDTO::getUserId,
                Collectors.summingInt(CrmContractProductSettlementDTO::getNums)));
        //根据用户id分组 并且合并渠道商转介数量
        Map<Long, Integer> channelMap = contractProductSettlementDTOList.stream().collect(Collectors.groupingBy(CrmContractProductSettlementDTO::getUserId,
                Collectors.summingInt(CrmContractProductSettlementDTO::getChannelNums)));

        // -- 回款申请 / - 回了多少就是多少咯 - 这个没啥业务判断当前月回了多少款即可
        LocalDateTime beginTime = LocalDateTimeUtils.beginOfMonth(now);
        LocalDateTime endTime = LocalDateTimeUtils.endOfMonth(now);
        LocalDateTime[] times = {beginTime, endTime};
        ReceiptSettlementVO receiptSettlementVO = new ReceiptSettlementVO();
        receiptSettlementVO.setCreateTime(times);
        List<ReceiptSettlementDTO> receiptSettlementList = receiptApi.getReceiptSettlement(receiptSettlementVO).getCheckedData();
        receiptSettlementList = CollUtil.isEmpty(receiptSettlementList) ? Collections.emptyList() : receiptSettlementList;
        Map<Long, ReceiptSettlementDTO> receiptSettlementMap = convertMap(receiptSettlementList, ReceiptSettlementDTO::getUserId);

        List<SalesPerformanceSettlementDO> salesPerformanceSettlementDOS = salesPerformanceSettlementMapper.selectList(new LambdaQueryWrapperX<SalesPerformanceSettlementDO>()
                .eq(SalesPerformanceSettlementDO::getYear, year)
                .eq(SalesPerformanceSettlementDO::getMonth, month));
        Map<Long, SalesPerformanceSettlementDO> map = salesPerformanceSettlementDOS.stream().collect(Collectors.toMap(SalesPerformanceSettlementDO::getUserId, Function.identity()));

        List<SalesPerformanceSettlementDO> list = new ArrayList<>();
        //获取当月目标审核通过的
        List<SalesPerformanceDTO> salesPerformanceDTOS = salesPerformanceApi.getReceiptSettlement(year, month).getCheckedData();
        Map<Long, SalesPerformanceDTO> salesPerformanceMap = salesPerformanceDTOS.stream().collect(Collectors.toMap(SalesPerformanceDTO::getUserId, Function.identity()));

        //获取权重
        SalesPerformanceWeightDO salesPerformanceWeight = salesPerformanceWeightService.getSalesPerformanceWeight();
        //获取绩效考核设置
        for (UserLiveTreeListVO vo : userLiveList) {
            SalesPerformanceSettlementDO salesPerformanceSettlementDO = map.get(vo.getUserId());
            ReceiptSettlementDTO receiptSettlementDTO = receiptSettlementMap.get(vo.getUserId());
            if (salesPerformanceSettlementDO == null) {
                salesPerformanceSettlementDO = new SalesPerformanceSettlementDO();
            }
            salesPerformanceSettlementDO.setUserId(vo.getUserId());
            salesPerformanceSettlementDO.setYear(String.valueOf(now.getYear()));
            salesPerformanceSettlementDO.setMonth(String.format("%02d", now.getMonthValue()));
            salesPerformanceSettlementDO.setActualSale(productMap.getOrDefault(vo.getUserId(), 0));
            salesPerformanceSettlementDO.setChannelSale(channelMap.getOrDefault(vo.getUserId(), 0));
            salesPerformanceSettlementDO.setActualPayment(receiptSettlementDTO != null ? receiptSettlementDTO.getMoney() : BigDecimal.ZERO);
            salesPerformanceSettlementDO.setChannelPayment(receiptSettlementDTO != null ? receiptSettlementDTO.getChannelAmount() : BigDecimal.ZERO);
            SalesPerformanceDTO salesPerformanceDTO = salesPerformanceMap.get(vo.getUserId());
            if (salesPerformanceDTO == null) {
                continue;
            }
            // 计算得分
            if (salesPerformanceWeight != null) {
                // -- 如果实际/目标>0则拿到全额的权重
                // ----------- 销售任务得分计算 -----------
                BigDecimal saleScore = (salesPerformanceDTO.getSaleTarget() == null || salesPerformanceDTO.getSaleTarget() == 0) ? BigDecimal.ZERO :
                        (BigDecimal.valueOf(salesPerformanceSettlementDO.getActualSale())
                                .divide(BigDecimal.valueOf(salesPerformanceDTO.getSaleTarget()), 2, RoundingMode.HALF_UP));
                saleScore = (saleScore.compareTo(BigDecimal.ONE) >= 0) ? salesPerformanceWeight.getSaleWeight() :
                        salesPerformanceWeight.getSaleWeight().multiply(saleScore);
                // 销售任务最终得分
                salesPerformanceSettlementDO.setSaleTask(saleScore);

                // ----------- 回款任务得分计算 -----------
                BigDecimal paymentScore = BigDecimalUtil.isEqZero(salesPerformanceDTO.getPaymentTarget()) ? BigDecimal.ZERO :
                        (salesPerformanceSettlementDO.getActualPayment()
                                .divide(salesPerformanceDTO.getPaymentTarget(), 2, RoundingMode.HALF_UP));
                paymentScore = (paymentScore.compareTo(BigDecimal.ONE) >= 0) ? salesPerformanceWeight.getPaymentWeight() :
                        salesPerformanceWeight.getPaymentWeight().multiply(paymentScore);
                // 回款任务最终得分
                salesPerformanceSettlementDO.setPaymentTask(paymentScore);

                // ----------- 评分任务得分计算 10分制 -----------
                BigDecimal score = BigDecimal.ZERO;
                if (salesPerformanceSettlementDO.getScore() != null) {
                    score = new BigDecimal(String.valueOf(salesPerformanceSettlementDO.getScore()))
                            .divide(TEN_PERCENT, 2, RoundingMode.HALF_UP);
                    score = (score.compareTo(BigDecimal.ONE) >= 0) ? salesPerformanceWeight.getScoreWeight() :
                            salesPerformanceWeight.getScoreWeight().multiply(score);
                    // 回款任务最终得分
                    salesPerformanceSettlementDO.setScoreTask(score);
                }
                salesPerformanceSettlementDO.setTotalScore(saleScore.add(paymentScore).add(score));
                // -- 根据总分再计算核发比例
                List<SalesPerformanceAssessmentDO> salesPerformanceAssessmentDOS = salesPerformanceAssessmentService.list(new LambdaQueryWrapper<SalesPerformanceAssessmentDO>()
                        .orderByDesc(SalesPerformanceAssessmentDO::getProportion));
                for (SalesPerformanceAssessmentDO salesPerformanceAssessmentDO : salesPerformanceAssessmentDOS) {
                    if (this.calculation(salesPerformanceAssessmentDO.getCalculationExpression(), salesPerformanceSettlementDO.getTotalScore())) {
                        salesPerformanceSettlementDO.setProportionOfIssuance(salesPerformanceAssessmentDO.getProportion());
                        break;
                    }
                }
                salesPerformanceSettlementDO.setCanConfirmFlag(1);
                salesPerformanceSettlementDO.setSettlementStatus(salesPerformanceSettlementDO.getScoreStatus() == 1 ? 2 : 1);
            }
            list.add(salesPerformanceSettlementDO);
        }
        if (CollUtil.isNotEmpty(list)) {
            salesPerformanceSettlementMapper.insertOrUpdateBatch(list);
        }

        List<Long> userIds = new ArrayList<>(salesPerformanceMap.keySet());
        //获取用户列表
        List<AdminUserRespDTO> adminUserRespDTOList = adminUserApi.getUserList(userIds).getCheckedData();
        Map<Long, AdminUserRespDTO> userMap = adminUserRespDTOList.stream().collect(Collectors.toMap(AdminUserRespDTO::getId, Function.identity()));
        List<AdminOauthUserOtherInfoApiVO> adminOauthUserOtherInfoApiVOS = adminOauthUserOtherInfoApi.getOpenIdByCondition(
                new AdminOauthUserOtherInfoApiDTO().setUserIds(userIds)
                        .setSocialType(SocialTypeEnum.WECHAT_MP.getType())).getCheckedData();
        log.info("用户列表:{}", userIds);
        log.info("用户三方账号列表:{}", adminOauthUserOtherInfoApiVOS);
        // - 结算完毕 - 通知所有填写申请到crm用户确认
        for (AdminOauthUserOtherInfoApiVO adminOauthUserOtherInfoApiVO : adminOauthUserOtherInfoApiVOS) {
            SubscribeMessageReqDTO dto = new WxMpMsgTemplateUtils().convertPerformanceResultConfirmationReminder(new PerformanceResultConfirmationReminderDTO()
                    .setOpenId(adminOauthUserOtherInfoApiVO.getOpenId())
                    .setUserName(userMap.get(adminOauthUserOtherInfoApiVO.getUserId()).getNickname())
                    .setTime(year + "年" + month + "月")
                    .setMiniProgramState("formal")
                    .setPage("pages/components/pages/performanceSet/detail" + "?id=" + map.get(adminOauthUserOtherInfoApiVO.getUserId()).getId()));
            subscribeMessageSendApi.sendMpMsg(dto);
        }
        // 计算完成后 需要修改合同的结算状态 - 待结算 - 已结算
        if (CollUtil.isNotEmpty(contractProductSettlementDTOList)) {
            List<Long> contractIds = contractProductSettlementDTOList.stream().map(CrmContractProductSettlementDTO::getContractId).collect(Collectors.toList());
            bpmOAContractApi.updateSettlementFlagByIds(contractIds);
        }
    }

    @Override
    public void generateSalesPerformanceJob() {
        LocalDateTime now = LocalDateTime.now().plusMonths(1L);
        List<UserLiveTreeListVO> userLiveList = userLiveTreeService.getUserLiveList();
        List<SalesPerformanceSettlementDO> list = new ArrayList<>();
        for (UserLiveTreeListVO vo : userLiveList) {
            SalesPerformanceSettlementDO salesPerformanceSettlementDO = new SalesPerformanceSettlementDO();
            salesPerformanceSettlementDO.setUserId(vo.getUserId());
            salesPerformanceSettlementDO.setYear(String.valueOf(now.getYear()));
            salesPerformanceSettlementDO.setMonth(String.format("%02d", now.getMonthValue()));
            list.add(salesPerformanceSettlementDO);
        }
        if (CollUtil.isNotEmpty(list)) {
            salesPerformanceSettlementMapper.insertBatch(list);
        }
    }

    @Override
    public void autoConfirmJob() {
        LocalDateTime now = LocalDateTime.now().minusMonths(1L);
        salesPerformanceSettlementMapper.update(new SalesPerformanceSettlementDO().setConfirmFlag(1),
                new LambdaQueryWrapper<SalesPerformanceSettlementDO>()
                        .eq(SalesPerformanceSettlementDO::getYear, String.valueOf(now.getYear()))
                        .eq(SalesPerformanceSettlementDO::getMonth, String.format("%02d", now.getMonthValue()))
                        .eq(SalesPerformanceSettlementDO::getConfirmFlag, 0));
    }

    /**
     * 表达式 10<=n && n<=20
     *
     * @param originalExpr
     * @param n
     * @return
     */
    public static boolean calculation(String originalExpr, BigDecimal n) {
        boolean result = false;
        try {
            // 执行OGNL表达式
            result = evaluateOgnlExpression(originalExpr, n);
        } catch (IllegalArgumentException | OgnlException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static boolean evaluateOgnlExpression(String ognlExpr, BigDecimal n) throws OgnlException {
        Map<String, Object> context = new HashMap<>();
        context.put("n", n);
        Object result = Ognl.getValue(ognlExpr, context);
        return (Boolean) result;
    }
}
