package com.ssm.manage.service.impl;

import cn.hutool.core.text.StrBuilder;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmCourseAccountDao;
import com.ssm.manage.dao.SsmCourseDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.mapper.CourseAccountMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.CourseAccountResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmCourseAccountServiceImpl extends BaseServiceImpl<CourseAccount> implements SsmCourseAccountService {
    @Autowired
    private SsmCourseAccountDao dao;
    @Autowired
    private SsmCourseDao ssmCourseDao;

    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmRechargeAccountGiveService ssmRechargeAccountGiveService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private PromotionRechargeListService promotionRechargeListService;

    @Autowired
    private SsmDocPromotionProjectService ssmDocPromotionProjectService;

    @Autowired
    private SsmDocPromotionService ssmDocPromotionService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmCancelDebtListService ssmCancelDebtListService;

    @Autowired
    private SsmRepayPromotionMxService ssmRepayPromotionMxService;
    @Autowired
    private SsmCardChangeInProjectService ssmCardChangeInProjectService;

    @Autowired
    private SsmCardChangeService ssmCardChangeService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

//    @Autowired
//    private SsmStoreParaService ssmStoreParaService;



    @Autowired
    private SsmPromotionStoreService ssmPromotionStoreService;

    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private SsmPromotionProjectService ssmPromotionProjectService;

    @Autowired
    private SsmRepayTradeCourseService ssmRepayTradeCourseService;

    @Autowired
    private SsmCourseService ssmCourseService;

    @Autowired
    private SsmRefundCourseService ssmRefundCourseService;

    @Autowired
    private SsmRefundOrderService ssmRefundOrderService;


    @Autowired
    private SsmCancelDebtMxService ssmCancelDebtMxService;

    @Autowired
    private SsmPromotionService ssmPromotionService;

    @Autowired
    private SsmRepayTradeService ssmRepayTradeService;
    @Autowired
    private SsmRepayService ssmRepayService;

    @Autowired
    private SsmRepayAccountListService ssmRepayAccountListService;


    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Override
    public SsmCourseAccountDao getDao() {
        return dao;
    }

    private static String staffKey = "staffKey";

    @Override
    public CourseAccount setCourseAccount(CourseList courseList, CourseAccount courseAccount, StoreParament storeParament) {
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");

        Integer consumeCount = 0;
        Integer restCount = 0;

        //欠款
        if (courseList.getIsDebt() == 1) {
            //可用比率 = 门店参数/100
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);
            //restCount = BigDecimalUtils.div(BigDecimalUtils.multiply(courseList.getCourseReatmentAmount(),BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString())), courseList.getAmount()).setScale(0,BigDecimal.ROUND_DOWN).intValue();
//            restCount = courseList.getNumberTimes();
            restCount = courseList.getCollectionCashAmount().divide(courseList.getPriceMember(),2,BigDecimal.ROUND_HALF_UP).intValue();

            consumeCount = BigDecimalUtils.multiply(BigDecimalUtils.div(BigDecimalUtils.multiply(courseList.getCourseReatmentAmount(),BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString())), courseList.getAmount()), consumeRito).setScale(0,BigDecimal.ROUND_DOWN).intValue();
            courseAccount.setCourseRestPrice(courseList.getCourseReatmentAmount());
            courseAccount.setCourseConsumePrice(courseList.getCourseReatmentAmount().multiply(consumeRito));
        } else {
            restCount = courseList.getNumberTimes();
            consumeCount = courseList.getNumberTimes();
            courseAccount.setCourseRestPrice(courseList.getCourseReatmentAmount());
            courseAccount.setCourseConsumePrice(courseList.getCourseReatmentAmount());
        }

        courseAccount.setCourseProjectId(courseList.getProjctId());
        courseAccount.setCourseProjectName(courseList.getProjectName());
        courseAccount.setCourseProjectMoney(courseList.getAmount());
        courseAccount.setCourseCount(courseList.getNumberTimes());
        courseAccount.setCourseProjectMoneys(courseList.getAmount());
        courseAccount.setCourseCounts(courseList.getNumberTimes());
        courseAccount.setCourseStandardCount(courseList.getMinumumTimes());
        //标准价改为最少销售次数 * 单价
        courseAccount.setCourseStandardMoney(BigDecimalUtils.multiply(BigDecimalUtils.bigDecimal(courseList.getMinumumTimes().toString()),courseList.getPriceMember()));
        courseAccount.setCourseConsumeCount(consumeCount);
        courseAccount.setCourseRestCount(restCount);
        courseAccount.setState(1);
        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            if (courseList.getIsAddition() == 1){
                date = courseList.getAdditionDate();
            }
            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
//            if(null == project.getValidTime()){
//                throw new SmsException(ResponseCode.MSG,"项目没有设置有效期");
//            }
            courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
        }
        courseAccount.setCourseRestCount(courseList.getMinumumTimes());
        return courseAccount;
    }

    @Override
    public CourseAccount setCourseAccountS(CourseList courseList, CourseAccount courseAccount, StoreParament storeParament) throws SmsException {
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");

        Integer consumeCount = 0;
        Integer restCount = 0;

        //欠款
        if (courseList.getIsDebt() == 1) {
            //可用比率 = 门店参数/100
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);
            //restCount = BigDecimalUtils.div(BigDecimalUtils.multiply(courseList.getCourseReatmentAmount(),BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString())), courseList.getAmount()).setScale(0,BigDecimal.ROUND_DOWN).intValue();
//            restCount = courseList.getNumberTimes();
            if(courseList.getPriceMember().equals(new BigDecimal("0"))){
                courseList.setPriceMember(courseList.getSalesPrice());
            }
            restCount = courseList.getCollectionCashAmount().divide(courseList.getPriceMember(),2,BigDecimal.ROUND_HALF_UP).intValue();//现付金额/项目单价=可用次数

            consumeCount = BigDecimalUtils.multiply(BigDecimalUtils.div(BigDecimalUtils.multiply(courseList.getCourseReatmentAmount(),BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString())), courseList.getAmount()), consumeRito).setScale(0,BigDecimal.ROUND_DOWN).intValue();
            courseAccount.setCourseRestPrice(courseList.getCourseReatmentAmount());
            courseAccount.setCourseConsumePrice(courseList.getCourseReatmentAmount().multiply(consumeRito));
        } else {
            restCount = courseList.getNumberTimes();
            consumeCount = courseList.getNumberTimes();
            courseAccount.setCourseRestPrice(courseList.getCourseReatmentAmount());
            courseAccount.setCourseConsumePrice(courseList.getCourseReatmentAmount());
        }
        courseAccount.setCourseProjectId(courseList.getProjctId());
        courseAccount.setCourseProjectName(courseList.getProjectName());
        courseAccount.setCourseProjectMoney(courseList.getAmount());
        courseAccount.setCourseCount(courseList.getNumberTimes());
        courseAccount.setCourseProjectMoneys(courseList.getAmount());
        courseAccount.setCourseCounts(courseList.getNumberTimes());
        courseAccount.setCourseStandardCount(courseList.getMinumumTimes());
        //标准价改为最少销售次数 * 单价
        courseAccount.setCourseStandardMoney(BigDecimalUtils.multiply(BigDecimalUtils.bigDecimal(courseList.getMinumumTimes().toString()),courseList.getPriceMember()));
        courseAccount.setCourseConsumeCount(consumeCount);
        courseAccount.setCourseRestCount(restCount);
        courseAccount.setState(1);
        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            if (courseList.getIsAddition() == 1){
                date = courseList.getAdditionDate();
            }
            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
            if(null != project.getValidTime() && 0 != project.getValidTime()){
                courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
            }
        }
        courseAccount.setCourseRestCount(courseList.getNumberTimes());

        return courseAccount;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addCourseAccount(CourseAccount courseAccount) throws SmsException {
        int i = 0;
        try {
            i = dao.saveNotNull(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.addCourseAccount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int updateStore(CourseAccount courseAccount) {
        CourseAccount courseAccount1 = new CourseAccount();
        courseAccount1.setId(courseAccount.getId());
        courseAccount1.setStoreId(courseAccount.getStoreId());
        courseAccount1.setStoreName(courseAccount.getStoreName());
        return dao.updateByPrimaryKeySelective(courseAccount);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int repayCourseAccount(RepayAccountListRequest repayAccountListRequest, RepayTradeRequest repayTradeRequest, RepayList repayList) throws SmsException {
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setId(repayAccountListRequest.getAccountId());
        CourseAccount courseAccount1 = dao.selectByPrimaryKey(courseAccount.getId());
        if(courseAccount1.getCourseConsumePrice().compareTo(repayAccountListRequest.getPayMoney())==-1){
            throw new SmsException(ResponseCode.MSG,"疗程支付卡："+courseAccount1.getCourseProjectName()+"金额不足");
        }
        if(courseAccount1.getCourseConsumeCount()<repayAccountListRequest.getPayNumber()){
            throw new SmsException(ResponseCode.MSG,"疗程支付卡："+courseAccount1.getCourseProjectName()+"次数不足");
        }
        if(repayAccountListRequest.getPayNumber()<=0){
            throw new SmsException(ResponseCode.MSG,"疗程支付卡："+courseAccount1.getCourseProjectName()+"的支付次数必须大于等于1");
        }
        courseAccount1.setCourseRestPrice(courseAccount1.getCourseRestPrice().subtract(repayAccountListRequest.getPayMoney()));
        courseAccount1.setCourseConsumePrice(courseAccount1.getCourseConsumePrice().subtract(repayAccountListRequest.getPayMoney()));
        courseAccount1.setCourseRestCount(courseAccount1.getCourseRestCount()-repayAccountListRequest.getPayNumber());
        courseAccount1.setCourseConsumeCount(courseAccount1.getCourseConsumeCount()-repayAccountListRequest.getPayNumber());
        if(courseAccount1.getCourseRestCount()>0){
            courseAccount1.setPrice(courseAccount1.getCourseRestPrice().divide(BigDecimal.valueOf(courseAccount1.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
        }
        courseAccount1.setExpenditureMoney(courseAccount1.getExpenditureMoney().add(repayAccountListRequest.getPayMoney()));
        int update = dao.updateByPrimaryKeySelective(courseAccount1);
        if(update == 0){
            throw new SmsException(ResponseCode.MSG,"扣除疗程账户出错");
        }
        AccountTradeRecord tradeRecord = this.setAccountTradeRecord(courseAccount1, repayAccountListRequest, repayTradeRequest,repayList);
        tradeRecord.setOrderStatu(0);
        ssmAccountTradeRecordService.addRecord(tradeRecord);
        return update;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int cancelRepayCourseAccount(RepayAccountListRequest repayAccountListRequest, RepayTradeRequest repayTradeRequest, RepayList repayList) throws SmsException {
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setId(repayAccountListRequest.getAccountId());
        CourseAccount courseAccount1 = dao.selectByPrimaryKey(courseAccount.getId());
        courseAccount1.setCourseRestPrice(courseAccount1.getCourseRestPrice().add(repayAccountListRequest.getPayMoney()));
        courseAccount1.setCourseConsumePrice(courseAccount1.getCourseConsumePrice().add(repayAccountListRequest.getPayMoney()));
        courseAccount1.setCourseRestCount(courseAccount1.getCourseRestCount()+repayAccountListRequest.getPayNumber());
        courseAccount1.setCourseConsumeCount(courseAccount1.getCourseConsumeCount()+repayAccountListRequest.getPayNumber());
        courseAccount1.setPrice(courseAccount1.getCourseRestPrice().divide(BigDecimal.valueOf(courseAccount1.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
        courseAccount1.setExpenditureMoney(courseAccount1.getExpenditureMoney().subtract(repayAccountListRequest.getPayMoney()));
        int update = dao.updateByPrimaryKeySelective(courseAccount1);
        if(update == 0){
            throw new SmsException(ResponseCode.MSG,"返回疗程账户出错");
        }
        AccountTradeRecord tradeRecord = this.setAccountTradeRecord(courseAccount1, repayAccountListRequest, repayTradeRequest,repayList);
        tradeRecord.setOrderStatu(1);
        ssmAccountTradeRecordService.addRecord(tradeRecord);
        return update;
    }

    public AccountTradeRecord setAccountTradeRecord(CourseAccount rechargeAccount,
                                                    RepayAccountListRequest repayAccountListRequest,
                                                    RepayTradeRequest repayTradeRequest,RepayList repayList){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeRequest.getStoreName());
        accountTradeRecord.setMemberId(repayTradeRequest.getMemberId());
        accountTradeRecord.setMemberName(repayTradeRequest.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeRequest.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeRequest.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getCourseProjectName());
        if(repayList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.course_pay_Repay);
            accountTradeRecord.setAccountSpendMoney(repayAccountListRequest.getPayMoney());
            accountTradeRecord.setAccountSpendCount(repayAccountListRequest.getPayNumber());
            accountTradeRecord.setInputDate(new Date());
            accountTradeRecord.setInputBy(repayList.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.course_pay_Repay_cancel);
            accountTradeRecord.setAccountInMoney(repayAccountListRequest.getPayMoney());
            accountTradeRecord.setInputDate(repayList.getCancelDate());
            accountTradeRecord.setInputBy(repayList.getCancelBy());
            accountTradeRecord.setAccountGiftSpendMoney(BigDecimal.valueOf(0));
            accountTradeRecord.setAccountInCount(repayAccountListRequest.getPayNumber());
        }
        accountTradeRecord.setDocId(repayList.getId());
        accountTradeRecord.setDocNum(repayList.getRepayNum());
        accountTradeRecord.setDocType(Constant.doc_type_repay);
        accountTradeRecord.setTradeId(repayTradeRequest.getTradeId());
        accountTradeRecord.setTradeName(repayTradeRequest.getTradeName());
        accountTradeRecord.setTradeMoney(repayTradeRequest.getDebtMoney());
        accountTradeRecord.setAccountRestCount(rechargeAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(rechargeAccount.getCourseConsumeCount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCourseConsumePrice());
        accountTradeRecord.setDebtMoney(BigDecimal.valueOf(0));
        accountTradeRecord.setPrice(repayTradeRequest.getDebtMoney());

        accountTradeRecord.setCardMoney(repayTradeRequest.getPayRechargeMoney());
        accountTradeRecord.setCashMoney(repayTradeRequest.getPayMoney());
        return accountTradeRecord;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount(CourseAccount courseAccount, Integer subCount, Integer type) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - subCount);
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCount);

        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));

        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));
//        //是否使用有效期
//        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
//        if ("1".equals(parament.getParamentValue())) {
//            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
//            //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
//            if (1 == type) {
//                courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
//            }
//        }

        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().add(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));
        if(courseAccount.getCourseRestCount()>0){
            BigDecimal subtract = courseAccount.getCourseProjectMoney().subtract(courseAccount.getExpenditureMoney());
            if(subtract.compareTo(BigDecimal.valueOf(0))!=0){
                courseAccount.setPrice(subtract.divide(BigDecimal.valueOf(courseAccount.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
            }
        }

        //校验次数
        this.volidAccount(courseAccount);

        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCountNew(CourseAccount courseAccount, Integer subCount, Integer type) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - subCount);
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCount);

        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));

        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));

        if(courseAccount.getCourseRestCount()!=0 && courseAccount.getCourseRestCount()==courseAccount.getCourseConsumeCount()){

            courseAccount.setPrice(courseAccount.getCourseRestPrice().divide(new BigDecimal(courseAccount.getCourseRestCount().toString()),2,BigDecimal.ROUND_HALF_UP));
        }
        if(courseAccount.getCourseRestCount()==0){
            courseAccount.setCourseRestPrice(BigDecimal.ZERO);
            courseAccount.setCourseConsumePrice(BigDecimal.ZERO);
        }


//        //是否使用有效期
//        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
//        if ("1".equals(parament.getParamentValue())) {
//            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
//            //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
//            if (1 == type) {
//                courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
//            }
//        }

        if(courseAccount.getExpenditureMoney()==null){
            courseAccount.setExpenditureMoney(BigDecimal.ZERO);
        }
        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().add(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));
//        if(courseAccount.getCourseRestCount()>0){
//            BigDecimal subtract = courseAccount.getCourseProjectMoney().subtract(courseAccount.getExpenditureMoney());
//            if(subtract.compareTo(BigDecimal.valueOf(0))!=0){
//                courseAccount.setPrice(subtract.divide(BigDecimal.valueOf(courseAccount.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
//            }
//        }

        //校验次数
        this.volidAccount(courseAccount);

        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount1(CardChangeList cardChangeList,CourseAccount courseAccount, Integer subCount, Integer type,BigDecimal outMoney) throws SmsException {
        int i = 0;
        //如果转出金额跟账户余额一致，删除账户信息，删除欠款记录
        cancelDebt(cardChangeList, courseAccount, outMoney);
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - subCount);
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCount);

        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(outMoney));
        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(outMoney));



        if(courseAccount.getCourseRestPrice().subtract(outMoney).compareTo(BigDecimal.ZERO)==-1){
            courseAccount.setCourseRestPrice(BigDecimal.ZERO);
        }
        if(courseAccount.getCourseConsumePrice().subtract(outMoney).compareTo(BigDecimal.ZERO)==-1){
            courseAccount.setCourseConsumePrice(BigDecimal.ZERO);
        }
//        //是否使用有效期
//        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
//        if ("1".equals(parament.getParamentValue())) {
//            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
//            //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
//            if (1 == type) {
//                courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
//            }
//        }

            courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().add(outMoney));
            if(courseAccount.getCourseRestCount()>0){
                BigDecimal subtract = courseAccount.getCourseProjectMoney().subtract(courseAccount.getExpenditureMoney());
                if(subtract.compareTo(BigDecimal.valueOf(0))!=0){
                    courseAccount.setPrice(subtract.divide(BigDecimal.valueOf(courseAccount.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
                }
            }

            //校验次数
            this.volidAccount(courseAccount);

            try {
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("ssmCourseAccountServiceImpl.subCount:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }

        return courseAccount;
    }

    private void cancelDebt(CardChangeList cardChangeList, CourseAccount courseAccount, BigDecimal outMoney) {
        if(courseAccount.getCourseRestPrice().compareTo(outMoney)==0){
            DebtList debtList = new DebtList();
            //疗程单据
            String docNum = courseAccount.getCourseNum();
            debtList.setDocNum(docNum);
            //疗程账号
            debtList.setAccountId(courseAccount.getId());
//            debtList.setDebtMoney(BigDecimal.valueOf(0));
            debtList = ssmDebtService.selectOne(debtList);
            if(debtList!=null){
//                courseAccount.setCourseRestCount(0);
//                courseAccount.setCourseConsumeCount(0);
                CancelDebtList cancelDebtList = new CancelDebtList();
                cancelDebtList.setStoreId(courseAccount.getStoreId());
                cancelDebtList.setStoreName(courseAccount.getStoreName());
                cancelDebtList.setMemberId(courseAccount.getMemberId());
                cancelDebtList.setMemberName(courseAccount.getMemberName());
                cancelDebtList.setMobilePhone(debtList.getMobilePhone());
                CourseList courseList = new CourseList();
                String substring = docNum.substring(docNum.length()-11, docNum.length() - 3);
//            System.out.println(substring);
                StrBuilder strBuilder = new StrBuilder(substring);
                StrBuilder insert = strBuilder.insert(6, "-").insert(4, "-");
//            System.out.println(insert);
                CourseListRequest courseListRequest = new CourseListRequest();
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                try {
                    Date parse = dateFormat.parse(String.valueOf(insert));
                    courseList.setDate(parse);
                    courseListRequest.setDate(parse);

                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                CourseVo courseVo = new CourseVo();
                courseList.setCourseReatmentNum(docNum);

                courseListRequest.setDocId(docNum);
                if(docNum.startsWith("ZLC") || docNum.startsWith("LCNT")){
                    List<CourseList> courseListList = new ArrayList<>();
                    CardChangeInProject cardChangeInProject = new CardChangeInProject();
                    cardChangeInProject.setDocNum(docNum);
                    List<CardChangeInProject> select = ssmCardChangeInProjectService.select(cardChangeInProject);
                    for (CardChangeInProject changeInProject : select) {
                        CourseList courseList1 = new CourseList();
                        BeanUtils.copyProperties(changeInProject,courseList1);
                        courseListList.add(courseList1);
                    }
                    courseVo.setCourseLists(courseListList);
                }else {
                    courseVo = ssmCourseService.selectCourseOne(courseListRequest);
                }
                courseList = courseVo.getCourseLists().get(0);
//                BeanUtils.copyProperties(courseVo,courseList);
                cancelDebtList.setDocId(courseList.getId());
                cancelDebtList.setDocNum(docNum);
                cancelDebtList.setDocType("LCNT");
                cancelDebtList.setDocDate(courseList.getDate());
                cancelDebtList.setTradeId(courseList.getProjctId());
                cancelDebtList.setTradeName(courseList.getProjectName());
                cancelDebtList.setTradeMoney(courseList.getSalesPrice());
                cancelDebtList.setDebtMoney(courseList.getDebtMoney());
                cancelDebtList.setSalesAchievement(courseList.getSalesAchievement());
                cancelDebtList.setSalesCommission(courseList.getSalesCommission());
                cancelDebtList.setCardSalesAchievement(courseList.getCardSalesAchievement());
                cancelDebtList.setCardSalesCommission(courseList.getCardSalesCommission());
                if(courseList.getSaleOneNumber()!=null){
                    cancelDebtList.setSaleOneNumber(courseList.getSaleOneNumber());
                    cancelDebtList.setSaleOneRatio(courseList.getSaleOneRatio());
                    cancelDebtList.setSaleOneStaffName(courseList.getSaleOneStaffName());
                    cancelDebtList.setSaleOneStaffId(courseList.getSaleOneStaffId());
                }
                if(courseList.getSaleTwoNumber()!=null){
                    cancelDebtList.setSaleTwoNumber(courseList.getSaleTwoNumber());
                    cancelDebtList.setSaleTwoRatio(courseList.getSaleTwoRatio());
                    cancelDebtList.setSaleTwoStaffName(courseList.getSaleTwoStaffName());
                    cancelDebtList.setSaleTwoStaffId(courseList.getSaleTwoStaffId());
                }
                if(courseList.getSaleThreeNumber()!=null){
                    cancelDebtList.setSaleThreeNumber(courseList.getSaleThreeNumber());
                    cancelDebtList.setSaleThreeRatio(courseList.getSaleThreeRatio());
                    cancelDebtList.setSaleThreeStaffName(courseList.getSaleThreeStaffName());
                    cancelDebtList.setSaleThreeStaffId(courseList.getSaleThreeStaffId());
                }
                if(courseList.getSaleFourNumber()!=null){
                    cancelDebtList.setSaleFourNumber(courseList.getSaleFourNumber());
                    cancelDebtList.setSaleFourRatio(courseList.getSaleFourRatio());
                    cancelDebtList.setSaleFourStaffName(courseList.getSaleFourStaffName());
                    cancelDebtList.setSaleFourStaffId(courseList.getSaleFourStaffId());
                }
                cancelDebtList.setAccountId(courseAccount.getId());
                cancelDebtList.setState(3);
                cancelDebtList.setRepayCount(0);
                cancelDebtList.setRepayConsumeCount(0);
                cancelDebtList.setRepayMoney(BigDecimal.valueOf(0));
                cancelDebtList.setRepayConsumeMoney(BigDecimal.valueOf(0));
                cancelDebtList.setCancelMoney(courseList.getDebtMoney());
                cancelDebtList.setCancelNum(courseList.getNumberTimes());
                cancelDebtList.setCourseRestCount(0);
                cancelDebtList.setCourseConsumeCount(0);
                cancelDebtList.setCourseRestPrice(BigDecimal.valueOf(0));
                cancelDebtList.setCourseConsumePrice(BigDecimal.valueOf(0));
                cancelDebtList.setDebtId(debtList.getId());
                cancelDebtList.setUpdateId(cardChangeList.getInputId());
                cancelDebtList.setUpdateName(cardChangeList.getInputBy());
                cancelDebtList.setUpdateDate(new Date());
                cancelDebtList.setInsertId(cardChangeList.getInputId());
                cancelDebtList.setInsertName(cardChangeList.getInputBy());
                cancelDebtList.setInsertDate(new Date());
                cancelDebtList.setOrderCode(docNum.substring(docNum.length()-11));
                cancelDebtList.setBeforePrice(courseList.getSalesPrice());
                cancelDebtList.setBeforeRestMoney(courseAccount.getCourseRestPrice());
                cancelDebtList.setBeforeConsumeCount(courseAccount.getCourseRestCount());
                cancelDebtList.setBackPrice(courseList.getSalesPrice());
                cancelDebtList.setBackRestMoney(BigDecimal.valueOf(0));
                cancelDebtList.setBackConsumeMoney(BigDecimal.valueOf(0));
                cancelDebtList.setBackRestCount(0);
                cancelDebtList.setBackConsumeCount(0);
                cancelDebtList.setBeforeGiftRestMoney(BigDecimal.valueOf(0));
                cancelDebtList.setBeforeGiftConsumeMoney(BigDecimal.valueOf(0));
                cancelDebtList.setBackGiftRestMoney(BigDecimal.valueOf(0));
                cancelDebtList.setBackGiftConsumeMoney(BigDecimal.valueOf(0));
                cancelDebtList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//            List<CancelDebtList> cancelDebtLists = new ArrayList<>();
//            cancelDebtLists.add(cancelDebtList);
                ssmCancelDebtListService.insert(cancelDebtList);
            }

        }
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount(CourseAccount courseAccount, Integer subCount, BigDecimal money) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - subCount);
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCount);

        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(money));

        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(money));
//        //是否使用有效期
//        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
//        if ("1".equals(parament.getParamentValue())) {
//            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
//            //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
//            if (1 == type) {
//                courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
//            }
//        }
        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().add(money));
        //校验次数
        this.volidAccount(courseAccount);

        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount(CourseAccount courseAccount, Integer subCount, Integer type,Integer subCountCoun) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - courseAccount.getCourseCounts());
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCountCoun);

        courseAccount.setCourseRestPrice(BigDecimal.valueOf(0));

        courseAccount.setCourseConsumePrice(BigDecimal.valueOf(0));
        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
            //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
            if (1 == type) {
                if(courseAccount.getEndTime()!=null)
                courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
            }
        }


        //校验次数
        this.volidAccount(courseAccount);

        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount(CourseAccount courseAccount, Integer subCount, Integer type,BigDecimal rechargeMoney) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - subCount);
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCount);

        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(rechargeMoney));

        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(rechargeMoney));
//        courseAccount.setPrice(courseAccount.getCourseRestPrice().divide(BigDecimal.valueOf(courseAccount.getCourseRestCount())));
//        //是否使用有效期
//        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
//        if ("1".equals(parament.getParamentValue())) {
//            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
//            //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
//            if (1 == type) {
//                courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
//            }
//        }


        //校验次数
        this.volidAccount(courseAccount);

        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount(CourseAccount courseAccount, Integer subCount, Integer type,CourseList courseList) throws SmsException {
        int i = 0;

        DebtListRequest debtListRequest = new DebtListRequest();
        debtListRequest.setDocId(courseList.getId());
        debtListRequest.setMemberId(courseList.getMemberId());
        debtListRequest.setStoreId(courseList.getStoreId());
        DebtList debtList = new DebtList();
        debtList.setDocId(courseList.getId());
        debtList.setMemberId(courseList.getMemberId());
        debtList.setStoreId(courseList.getStoreId());
        DebtList debtList1 = ssmDebtService.selectOne(debtList);


        if(0 == courseList.getIsDebt()){//没有欠款
            courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - courseAccount.getCourseCounts());
            courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCount);

            courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));

            courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));
            //是否使用有效期
            StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
            if ("1".equals(parament.getParamentValue())) {
                BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
                //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
                if (1 == type) {
                    if(null != courseAccount.getEndTime() && null != project.getValidTime() && 0!= project.getValidTime()){
                        courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
                    }

                }
            }

            if (courseAccount.getCourseRestCount() < 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余次数");
            }

            if (courseAccount.getCourseConsumeCount() < 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余可用次数");
            }
            try {
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("ssmCourseAccountServiceImpl.subCount:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            return courseAccount;
        }else if(1 == courseList.getIsDebt()&&debtList1.getState()==1){ //有欠款，以还款
            courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() -  courseAccount.getCourseCounts());
            courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - subCount);

            courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));

            courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(subCount.toString()))));
            //是否使用有效期
            StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
            if ("1".equals(parament.getParamentValue())) {
                BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
                //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
                if(null != courseAccount.getEndTime() && null != project.getValidTime() && 0!= project.getValidTime()){
                    courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
                }
            }

            if (courseAccount.getCourseRestCount() < 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余次数");
            }

            if (courseAccount.getCourseConsumeCount() < 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余可用次数");
            }
            try {
                this.volidAccount(courseAccount);
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("ssmCourseAccountServiceImpl.subCount:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            return courseAccount;
        }else{


            courseAccount.setCourseRestCount(courseAccount.getCourseCounts() -  courseAccount.getCourseCounts());
            courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - debtList1.getRepayConsumeCount());

            courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(courseList.getCourseReatmentAmount()));

            courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(courseList.getCourseReatmentAmount().multiply(debtList1.getRepayConsumeMoney())));
            //是否使用有效期
            StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
            if ("1".equals(parament.getParamentValue())) {
                BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
                //type 0 正常扣减次数 不需要计算账户结束时间 type 1 疗程 促销作废 需计算账户结束时间
                if(null != courseAccount.getEndTime() && null != project.getValidTime() && 0!= project.getValidTime()){
                    courseAccount.setEndTime(DateUtils.diffMonth(courseAccount.getEndTime(), -project.getValidTime()));
                }
            }

            if (courseAccount.getCourseRestCount() < 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余次数");
            }

            if (courseAccount.getCourseConsumeCount() < 0){
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余可用次数");
            }
//        if (courseAccount.getCourseConsumeCount() < 0){
//            throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余可用次数");
//        }

            try {
                this.volidAccount(courseAccount);
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("ssmCourseAccountServiceImpl.subCount:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            return courseAccount;

        }

    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount addCount(CourseAccount courseAccount, Integer addCount) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() + addCount);
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() + addCount);
        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(addCount.toString()))));
        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(addCount.toString()))));
        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().subtract(courseAccount.getPrice().multiply(BigDecimalUtils.bigDecimal(addCount.toString()))));
        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount addCountNew(CourseAccount courseAccount, CashList cashList) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() + cashList.getNumberTimes());
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() + cashList.getNumberTimes());
        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(cashList.getTransactionPrice()));
        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(cashList.getTransactionPrice()));
        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().subtract(cashList.getTransactionPrice()));
        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount addCount(CourseAccount courseAccount, Integer addCount,BigDecimal rechargeMoney) throws SmsException {
        int i = 0;
        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() + addCount);
        courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() + addCount);
        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(rechargeMoney));
        courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(rechargeMoney));
        courseAccount.setPrice(courseAccount.getCourseRestPrice().divide(BigDecimal.valueOf(courseAccount.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().subtract(rechargeMoney));
        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount(CourseAccount courseAccount) throws SmsException {
        int i = 0;
      try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.subCount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<CourseAccount> selectList(CourseAccountRequest courseAccountRequest) {
//        BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(courseAccountRequest.getStoreId());

        List<CourseAccount> objects = new ArrayList<>();
        List<CourseAccount> objectsa = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
//        storeRequest.setId(courseAccountRequest.getStoreId());
//        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
//        for (BaseStores pagesorganization : pagesorganizations) {
//
//        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
//        if(baseStore1.getParentId()!=null){
//            if(courseAccountRequest.getIfstorid()!=null){
//                criteria.andEqualTo("storeId", courseAccountRequest.getIfstorid());
//            }
//        }
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());
        if(null != courseAccountRequest.getCourseProjectId()){
            criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
        }

        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccountRequest.getStoreId(), Constant.allow_valid);
        if(null != parament) {
//            if ("1".equals(parament.getParamentValue())) {
//                criteria.andGreaterThanOrEqualTo("endTime", DateUtils.ymdFormat(new Date()));
//            }
        }
            if (courseAccountRequest.getCourseProjectId() != null) {
                criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseProjectName())) {
                criteria.andLike("courseProjectName", "%" + courseAccountRequest.getCourseProjectName() + "%");
            }

            //疗程退相关条件
            if (courseAccountRequest.getCourseTypes() != null){
                criteria.andIn("courseType",courseAccountRequest.getCourseTypes());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseType())){
                criteria.andEqualTo("courseType",courseAccountRequest.getCourseType());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseNum())){//疗程退查询促销活动时 展示促销疗程账户 次数为0页展示
                criteria.andEqualTo("courseNum",courseAccountRequest.getCourseNum());
            }else {
//                criteria.andGreaterThanOrEqualTo("courseConsumeCount", 1);
                criteria.andGreaterThanOrEqualTo("courseRestCount", 1);
                //criteria.andGreaterThanOrEqualTo("courseRestPrice", 1);
            }
            List<CourseAccount> courseAccounts = dao.selectByExample(example);
            objects.addAll(courseAccounts);
//            for (CourseAccount courseAccount : courseAccounts) {
//
//                objects.add(courseAccount);
//            }

        for (CourseAccount courseAccount : objects) {
            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if (null != baseProject) {
                courseAccount.setCourseProjectNum(baseProject.getProjectNum());
            }
            StoreRequest storeRequest1 = new StoreRequest();
            storeRequest1.setId(courseAccount.getStoreId());
            BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
            courseAccount.setStoreNum(baseStore.getStoreNum());
            if (parament==null || (parament!=null && parament.getParamentValue().equals("0"))) {
                objectsa.add(courseAccount);
            } else {
                if (null == baseProject.getUnifiedDue()) {
                    if (null == courseAccount.getEndTime()) {
                        objectsa.add(courseAccount);
                    } else {

                        if (null != courseAccount.getPromotionDocId()) {
                            DocPromotion docPromotion = ssmDocPromotionService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                            //DocPromotionProject docPromotionProject = ssmDocPromotionProjectService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                            PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion.getPromotionId());
                            //适用门店对象0:所有门店/1:指定门店
                            if (promotionList.getSuitableStore() == 0) {
                                if (null == courseAccount.getEndTime()) {
                                    objectsa.add(courseAccount);
                                } else if (null != courseAccount.getEndTime() && courseAccount.getEndTime().after(new Date())) {
                                    objectsa.add(courseAccount);
                                }
                            } else {
                                PromotionStore promotionStore = new PromotionStore();
                                promotionStore.setPromotionId(promotionList.getId());
                                List<PromotionStore> promotionStores = ssmPromotionStoreService.selectList(promotionStore);
                                for (PromotionStore store : promotionStores) {
                                    if (Objects.equals(courseAccount.getStoreId(), store.getStoreId())) {
                                        objectsa.add(courseAccount);
                                    }
                                }
                            }
                        } else {
                            if ("1".equals(parament.getParamentValue())) {
                                if (courseAccount.getEndTime().after(new Date())) {
                                    objectsa.add(courseAccount);
                                }
                            } else {
                                objectsa.add(courseAccount);
                            }
                        }


                    /*if ("1".equals(parament.getParamentValue())) {
                        if(courseAccount.getEndTime().after(new Date())){
                            objectsa.add(courseAccount);
                        }
                    }else{
                        objectsa.add(courseAccount);
                    }*/
                    }

                } else {
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    try {
                        Date parse = format.parse(baseProject.getUnifiedDue());
                        if (new Date().before(parse)) {
                            if (null == courseAccount.getEndTime()) {
                                objectsa.add(courseAccount);
                            } else {

                                if (null != courseAccount.getPromotionDocId()) {
                                    DocPromotion docPromotion = ssmDocPromotionService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                                    //DocPromotionProject docPromotionProject = ssmDocPromotionProjectService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                                    PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion.getPromotionId());
                                    //适用门店对象0:所有门店/1:指定门店
                                    if (promotionList.getSuitableStore() == 0) {
                                        if (null == courseAccount.getEndTime()) {
                                            objectsa.add(courseAccount);
                                        } else if (null != courseAccount.getEndTime() && courseAccount.getEndTime().after(new Date())) {
                                            objectsa.add(courseAccount);
                                        }
                                    } else {
                                        PromotionStore promotionStore = new PromotionStore();
                                        promotionStore.setPromotionId(promotionList.getId());
                                        List<PromotionStore> promotionStores = ssmPromotionStoreService.selectList(promotionStore);
                                        for (PromotionStore store : promotionStores) {
                                            if (Objects.equals(courseAccount.getStoreId(), store.getStoreId())) {
                                                objectsa.add(courseAccount);
                                            }
                                        }
                                    }
                                } else {
                                    if ("1".equals(parament.getParamentValue())) {
                                        if (courseAccount.getEndTime().after(new Date())) {
                                            objectsa.add(courseAccount);
                                        }
                                    } else {
                                        objectsa.add(courseAccount);
                                    }
                                }

                            /*if ("1".equals(parament.getParamentValue())) {
                                if(courseAccount.getEndTime().after(new Date())){
                                    objectsa.add(courseAccount);
                                }
                            }else{
                                objectsa.add(courseAccount);
                            }*/
                            }
//                        objectsa.add(courseAccount);
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        for (CourseAccount courseAccount : objectsa) {
            DebtList debtList = new DebtList();
            debtList.setDocNum(courseAccount.getCourseNum());
            List<DebtList> select = ssmDebtService.select(debtList);
            BaseProject baseProject = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
//            courseAccount.setProjectNum(baseProject.getProjectNum());
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if(baseProject.getUnifiedDue()==null){
                Date parse = null;
                try {
                    parse = simpleDateFormat.parse("2099-01-01 00:00:00");
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                courseAccount.setEndTime(parse);
            }
            if(baseProject.getUnifiedDue()!=null){
                Date parse = null;
                try {
                    parse = simpleDateFormat.parse(baseProject.getUnifiedDue());
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                courseAccount.setEndTime(parse);
            }
            BigDecimal reduce = select.stream().map(DebtList::getDebtMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            if(select!=null && reduce.compareTo(BigDecimal.valueOf(0))==1){
                courseAccount.setDebtMoney(reduce);
            }
        }
        return objectsa;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<CourseAccount> selectListdeal(CourseAccountRequest courseAccountRequest) {
        List<CourseAccount> objects = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(courseAccountRequest.getStoreId());
        List<Long> storeid=new ArrayList<>();
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            storeid.add(pagesorganization.getId());
        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
        criteria.andIn("storeId", storeid);
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());

        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccountRequest.getStoreId(), Constant.allow_valid);
        if(null != parament){
            if ("1".equals(parament.getParamentValue())) {
                criteria.andGreaterThanOrEqualTo("endTime", DateUtils.ymdFormat(new Date()));
            }

            if (courseAccountRequest.getCourseProjectId() != null) {
                criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseProjectName())) {
                criteria.andLike("courseProjectName", "%" + courseAccountRequest.getCourseProjectName() + "%");
            }

            //疗程退相关条件
            if (courseAccountRequest.getCourseTypes() != null){
                criteria.andIn("courseType",courseAccountRequest.getCourseTypes());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseType())){
                criteria.andEqualTo("courseType",courseAccountRequest.getCourseType());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseNum())){//疗程退查询促销活动时 展示促销疗程账户 次数为0页展示
                criteria.andEqualTo("courseNum",courseAccountRequest.getCourseNum());
            }else {
                criteria.andGreaterThanOrEqualTo("courseConsumeCount", 1);
            }
            List<CourseAccount> courseAccounts = dao.selectByExample(example);
            for (CourseAccount courseAccount : courseAccounts) {
                objects.add(courseAccount);
            }
        }
        for (CourseAccount courseAccount : objects) {
//            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
//            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseRestCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
            //courseAccount.setPrice((BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount())).setScale(2)).multiply(BigDecimal.valueOf(1)));
            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseRestCount())));
            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseConsumeCount())));
            courseAccount.setPrice(courseAccount.getPrice().setScale(2));
            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if(null != baseProject){
                courseAccount.setCourseProjectNum(baseProject.getProjectNum());
            }
            StoreRequest storeRequest1 = new StoreRequest();
            storeRequest1.setId(courseAccount.getStoreId());
            BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
            courseAccount.setStoreNum(baseStore.getStoreNum());
        }

        return objects;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<CourseAccount> selectListdeals(CourseAccountRequest courseAccountRequest) {
        List<CourseAccount> objects = new ArrayList<>();
        List<CourseAccount> objectss = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(courseAccountRequest.getStoreId());
        List<Long> storeid=new ArrayList<>();
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            storeid.add(pagesorganization.getId());
        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
        criteria.andIn("storeId", storeid);
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());
        criteria.andGreaterThanOrEqualTo("courseRestCount", 1);
        //是否使用有效期
//        StoreParament parament = StoreParaUtils.getStorePara(courseAccountRequest.getStoreId(), Constant.allow_valid);
//        if(null != parament){
//            if ("1".equals(parament.getParamentValue())) {
//                criteria.andGreaterThanOrEqualTo("endTime", DateUtils.ymdFormat(new Date()));
//            }
//
//            if (courseAccountRequest.getCourseProjectId() != null) {
//                criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
//            }
//            if (StringUtils.isNotBlank(courseAccountRequest.getCourseProjectName())) {
//                criteria.andLike("courseProjectName", "%" + courseAccountRequest.getCourseProjectName() + "%");
//            }
//
//            //疗程退相关条件
//            if (courseAccountRequest.getCourseTypes() != null){
//                criteria.andIn("courseType",courseAccountRequest.getCourseTypes());
//            }
//            if (StringUtils.isNotBlank(courseAccountRequest.getCourseType())){
//                criteria.andEqualTo("courseType",courseAccountRequest.getCourseType());
//            }
//            if (StringUtils.isNotBlank(courseAccountRequest.getCourseNum())){//疗程退查询促销活动时 展示促销疗程账户 次数为0页展示
//                criteria.andEqualTo("courseNum",courseAccountRequest.getCourseNum());
//            }else {
//                criteria.andGreaterThanOrEqualTo("courseRestCount", 1);
//            }
//            List<CourseAccount> courseAccounts = dao.selectByExample(example);
//            for (CourseAccount courseAccount : courseAccounts) {
//                objects.add(courseAccount);
//            }
//        }
        List<CourseAccount> courseAccounts = dao.selectByExample(example);
        for (CourseAccount courseAccount : courseAccounts) {
            objects.add(courseAccount);
        }
        for (CourseAccount courseAccount : objects) {

            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if (null != baseProject) {
                courseAccount.setCourseProjectNum(baseProject.getProjectNum());
            }
            StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
            if(null != parament) {
                if (!"1".equals(parament.getParamentValue())) {
                    objectss.add(courseAccount);
                } else {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    try {
                        StoreRequest storeRequest1 = new StoreRequest();
                        storeRequest1.setId(courseAccount.getStoreId());
                        BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
                        courseAccount.setStoreNum(baseStore.getStoreNum());
                        if (null == baseProject.getUnifiedDue()) {
                            if(null !=courseAccount.getEndTime()){
                                if(!courseAccount.getEndTime().before(new Date())){
                                    objectss.add(courseAccount);
                                }
                            }else{
                                objectss.add(courseAccount);
                            }
                        } else {
                            Date parse = simpleDateFormat.parse(baseProject.getUnifiedDue());
                            if (!parse.before(new Date())) {
                                if(null !=courseAccount.getEndTime()){
                                    if(!courseAccount.getEndTime().before(new Date())){
                                        objectss.add(courseAccount);
                                    }
                                }else{
                                    objectss.add(courseAccount);
                                }
                            }
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }

            }else{
                objectss.add(courseAccount);
            }

        }
        for (BaseStores pagesorganization : pagesorganizations) {
            for (CourseAccount courseAccount : objectss) {
                if(courseAccount.getStoreId().equals(pagesorganization.getId())){
                    courseAccount.setStoreNum(pagesorganization.getStoreNum());
                }
            }
        }
        return objectss;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<CourseAccount> selectListdealsalls(CourseAccountRequest courseAccountRequest) {
        List<CourseAccount> objects = new ArrayList<>();
        List<CourseAccount> objectss = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(courseAccountRequest.getStoreId());
        List<Long> storeid=new ArrayList<>();
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            storeid.add(pagesorganization.getId());
        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
        criteria.andIn("storeId", storeid);
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());
        List<CourseAccount> courseAccounts = dao.selectByExample(example);
        for (CourseAccount courseAccount : courseAccounts) {
            BaseProject baseProject5 = new BaseProject();
            baseProject5.setId(courseAccount.getCourseProjectId());
            BaseProject baseProjects = ssmProjectService.selectOne(baseProject5);
            if (null != baseProjects) {
                courseAccount.setCourseProjectNum(baseProjects.getProjectNum());
            }
            StoreParament paramentz = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
            if ("1".equals(paramentz.getParamentValue())){
                BaseProject baseProject = new BaseProject();
                baseProject.setId(courseAccount.getCourseProjectId());
                BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                courseAccount.setCourseProjectNum(baseProject1.getProjectNum());
                if(null == baseProject1.getUnifiedDue()){
                    if(null == courseAccount.getEndTime()){
                        if(courseAccount.getCourseRestCount()<=0){
                            objects.add(courseAccount);
                        }
                    }else{
                        if(courseAccount.getEndTime().before(new Date()) || courseAccount.getCourseRestCount()<=0){
                            objects.add(courseAccount);
                        }
                    }

                }else{
                    Date date=null;
                    try {
                        date = format.parse(baseProject1.getUnifiedDue());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if(null != courseAccount.getEndTime()){
                        if(courseAccount.getEndTime().before(new Date())|| date.before(new Date()) || courseAccount.getCourseRestCount()<=0){
                                objects.add(courseAccount);
                        }
                    }else{
                        if(date.before(new Date()) || courseAccount.getCourseRestCount()<=0){
                            objects.add(courseAccount);
                        }
                    }
                }
            }else{

                

                if(courseAccount.getCourseRestCount()<=0){
                    objects.add(courseAccount);
                }
//                BaseProject baseProject = new BaseProject();
//                baseProject.setId(courseAccount.getCourseProjectId());
//                BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                courseAccount.setCourseProjectNum(baseProject1.getProjectNum());
//                if(null == baseProject1.getUnifiedDue()){
//                    courseAccount.setCourseProjectNum(baseProject1.getProjectNum());
//                    if(courseAccount.getCourseConsumeCount()<=0){
//                        objects.add(courseAccount);
//                    }
//                }else{
//                    Date date=null;
//                    try {
//                        date = format.parse(baseProject1.getUnifiedDue());
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }
//                    if(date.before(new Date()) || courseAccount.getCourseConsumeCount()<=0){
//                        objects.add(courseAccount);
//                    }
//                }

            }
        }
        for (BaseStores pagesorganization : pagesorganizations) {
            for (CourseAccount courseAccount : objects) {
                if(courseAccount.getStoreId().equals(pagesorganization.getId())){
                    courseAccount.setStoreNum(pagesorganization.getStoreNum());
                }
            }
        }

        return objects;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<CourseAccount> selectListdelay(CourseAccountRequest courseAccountRequest) {
        List<CourseAccount> objects = new ArrayList<>();
        List<CourseAccount> objectss = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(courseAccountRequest.getStoreId());
        List<Long> storeid=new ArrayList<>();
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            storeid.add(pagesorganization.getId());
        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
        criteria.andIn("storeId", storeid);
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());
        List<CourseAccount> courseAccounts = dao.selectByExample(example);
        for (CourseAccount courseAccount : courseAccounts) {
            BaseProject baseProject5 = new BaseProject();
            baseProject5.setId(courseAccount.getCourseProjectId());
            BaseProject baseProjects = ssmProjectService.selectOne(baseProject5);
            if (null != baseProjects) {
                courseAccount.setCourseProjectNum(baseProjects.getProjectNum());
            }
            StoreParament paramentz = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
            if ("1".equals(paramentz.getParamentValue())){
                BaseProject baseProject = new BaseProject();
                baseProject.setId(courseAccount.getCourseProjectId());
                BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                courseAccount.setCourseProjectNum(baseProject1.getProjectNum());
                if(null == baseProject1.getUnifiedDue()){
                    if(null == courseAccount.getEndTime()){
                       /* if(courseAccount.getCourseRestCount()<=0){
                            objects.add(courseAccount);
                        }*/
                    }else{
                        //|| courseAccount.getCourseRestCount()<=0
                        if(courseAccount.getEndTime().before(new Date()) && courseAccount.getCourseRestCount()>=1){
                            objects.add(courseAccount);
                        }
                    }

                }else{
                    Date date=null;
                    try {
                        date = format.parse(baseProject1.getUnifiedDue());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if(null != courseAccount.getEndTime()){
                        //|| courseAccount.getCourseRestCount()<=0
                        if(courseAccount.getEndTime().before(new Date())|| date.before(new Date()) ){
                            if( courseAccount.getCourseRestCount()>=1){
                                objects.add(courseAccount);
                            }
                        }
                    }else{
                        //|| courseAccount.getCourseRestCount()<=0
                        if(date.before(new Date()) && courseAccount.getCourseRestCount()>=1){
                            objects.add(courseAccount);
                        }
                    }
                }
            }else{



                /*if(courseAccount.getCourseRestCount()<=0){
                    objects.add(courseAccount);
                }*/
//                BaseProject baseProject = new BaseProject();
//                baseProject.setId(courseAccount.getCourseProjectId());
//                BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
//                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                courseAccount.setCourseProjectNum(baseProject1.getProjectNum());
//                if(null == baseProject1.getUnifiedDue()){
//                    courseAccount.setCourseProjectNum(baseProject1.getProjectNum());
//                    if(courseAccount.getCourseConsumeCount()<=0){
//                        objects.add(courseAccount);
//                    }
//                }else{
//                    Date date=null;
//                    try {
//                        date = format.parse(baseProject1.getUnifiedDue());
//                    } catch (ParseException e) {
//                        e.printStackTrace();
//                    }
//                    if(date.before(new Date()) || courseAccount.getCourseConsumeCount()<=0){
//                        objects.add(courseAccount);
//                    }
//                }

            }
        }
        for (BaseStores pagesorganization : pagesorganizations) {
            for (CourseAccount courseAccount : objects) {
                if(courseAccount.getStoreId().equals(pagesorganization.getId())){
                    courseAccount.setStoreNum(pagesorganization.getStoreNum());
                }
            }
        }

        return objects;
    }







    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<CourseAccount> selectListdealsall(CourseAccountRequest courseAccountRequest) {
        List<CourseAccount> objects = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(courseAccountRequest.getStoreId());
        List<Long> storeid=new ArrayList<>();
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            storeid.add(pagesorganization.getId());
        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
        criteria.andIn("storeId", storeid);
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());

        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccountRequest.getStoreId(), Constant.allow_valid);
        if(null != parament){
            if (courseAccountRequest.getCourseProjectId() != null) {
                criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseProjectName())) {
                criteria.andLike("courseProjectName", "%" + courseAccountRequest.getCourseProjectName() + "%");
            }

            //疗程退相关条件
            if (courseAccountRequest.getCourseTypes() != null){
                criteria.andIn("courseType",courseAccountRequest.getCourseTypes());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseType())){
                criteria.andEqualTo("courseType",courseAccountRequest.getCourseType());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseNum())){//疗程退查询促销活动时 展示促销疗程账户 次数为0页展示
                criteria.andEqualTo("courseNum",courseAccountRequest.getCourseNum());
            }else {
                criteria.andGreaterThanOrEqualTo("courseRestCount", 1);
            }
            List<CourseAccount> courseAccounts = dao.selectByExample(example);
            for (CourseAccount courseAccount : courseAccounts) {
                objects.add(courseAccount);
            }
        }
        for (CourseAccount courseAccount : objects) {
//            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
//            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseRestCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
            //courseAccount.setPrice((BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount())).setScale(2)).multiply(BigDecimal.valueOf(1)));
            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseRestCount())));
            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseConsumeCount())));
            courseAccount.setPrice(courseAccount.getPrice().setScale(2));
            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if(null != baseProject){
                courseAccount.setCourseProjectNum(baseProject.getProjectNum());
            }
            StoreRequest storeRequest1 = new StoreRequest();
            storeRequest1.setId(courseAccount.getStoreId());
            BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
            courseAccount.setStoreNum(baseStore.getStoreNum());
        }

        return objects;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<CourseAccount> selectListDisable(CourseAccountRequest courseAccountRequest) {
        List<CourseAccount> objects = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
//        storeRequest.setId(courseAccountRequest.getStoreId());
//        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
//        for (BaseStores pagesorganization : pagesorganizations) {
//
//        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
        criteria.andEqualTo("storeId", courseAccountRequest.getStoreId());
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());

        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccountRequest.getStoreId(), Constant.allow_valid);
        if(null != parament){
            if ("1".equals(parament.getParamentValue())) {
                criteria.andGreaterThanOrEqualTo("endTime", DateUtils.ymdFormat(new Date())).orEqualTo(null);
            }

            if (courseAccountRequest.getCourseProjectId() != null) {
                criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseProjectName())) {
                criteria.andLike("courseProjectName", "%" + courseAccountRequest.getCourseProjectName() + "%");
            }

            //疗程退相关条件
            if (courseAccountRequest.getCourseTypes() != null){
                criteria.andIn("courseType",courseAccountRequest.getCourseTypes());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseType())){
                criteria.andEqualTo("courseType",courseAccountRequest.getCourseType());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseNum())){//疗程退查询促销活动时 展示促销疗程账户 次数为0页展示
                criteria.andEqualTo("courseNum",courseAccountRequest.getCourseNum());
            }else {
                criteria.andEqualTo("courseConsumeCount", 0);
                criteria.andGreaterThanOrEqualTo("courseRestCount", 1);
            }
            List<CourseAccount> courseAccounts = dao.selectByExample(example);
            for (CourseAccount courseAccount : courseAccounts) {
                objects.add(courseAccount);
            }
        }
        for (CourseAccount courseAccount : objects) {
//            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
//            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseRestCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
            //courseAccount.setPrice((BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount())).setScale(2)).multiply(BigDecimal.valueOf(1)));
            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseRestCount())));
            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseConsumeCount())));
            courseAccount.setPrice(courseAccount.getPrice().setScale(2));
            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if(null != baseProject){
                courseAccount.setCourseProjectNum(baseProject.getProjectNum());
            }

        }

        return objects;
    }

    @Override
    public List<CourseAccount> selectRefundList(CourseAccountRequest courseAccountRequest) {
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(courseAccountRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        List<Long> storeIds = new ArrayList<>();
        for (BaseStores pagesorganization : pagesorganizations) {
            storeIds.add(pagesorganization.getId());
        }
        courseAccountRequest.setStoreIds(storeIds);
        List<CourseAccount> courseAccounts = dao.selectRefundList(courseAccountRequest);
        for (CourseAccount courseAccount : courseAccounts) {
            BaseProject baseProject = new BaseProject();
            baseProject.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
            courseAccount.setCourseProjectNum(baseProject1.getProjectNum());
        }
        return courseAccounts;
    }


    @Override
    public List<CourseAccount> selectRefundListone(CourseAccountRequest courseAccountRequest) {

        List<Long> storeIds = new ArrayList<>();
        storeIds.add(courseAccountRequest.getStoreId());
        courseAccountRequest.setStoreIds(storeIds);
        List<CourseAccount> courseAccounts = dao.selectRefundList(courseAccountRequest);
        List<Long> ids = new ArrayList<>();
        //查询所有已经退的疗程
        RefundCourse refundCourse = new RefundCourse();
        refundCourse.setMemberId(courseAccountRequest.getMemberId());
        refundCourse.setStoreId(courseAccountRequest.getStoreId());
        //这是已经申请了退款的疗程
        List<RefundCourse> refundCourses = ssmRefundCourseService.select(refundCourse);
        for (CourseAccount courseAccount : courseAccounts) {
            String courseNum = courseAccount.getCourseNum();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            if(courseNum.startsWith("ZLC")||courseNum.startsWith("LCNT")){
                CardChangeInProject inProject = new CardChangeInProject();
                inProject.setDocNum(courseNum);
                inProject.setProjectId(courseAccount.getCourseProjectId());
                CardChangeInProject changeInProject = ssmCardChangeInProjectService.selectOne(inProject);
                List<AchiCommEntity> achiCommList = this.getAchiCommList(changeInProject);
                //查询管理员和高管
                Salesman salesman = new Salesman();
                salesman.setOrderNum(courseNum);
                List<Salesman> salesmanList = new ArrayList<>();
                salesmanList.addAll(ssmSalesmanService.select(salesman));


                //有欠款查询欠款单
                if(changeInProject.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    RepayTradeList repayTradeList = new RepayTradeList();
                    repayTradeList.setDocNum(courseNum);
                    List<RepayTradeList> repayTradeLists = ssmRepayTradeService.selectList(repayTradeList);
                    if(repayTradeLists!=null && repayTradeLists.size()>0) {
                        for (RepayTradeList tradeList : repayTradeLists) {
                            if (tradeList.getTradeId().equals(changeInProject.getProjectId())) {
                                achiCommList.addAll(this.getAchiCommList(tradeList));
                                salesman.setOrderId(tradeList.getId().toString());
                                salesman.setOrderNum(null);
                                salesmanList.addAll(ssmSalesmanService.select(salesman));
                            }
                        }
                    }
                }

                List<BaseStaff> baseStaffs = ssmBaseStaffService.selectByAllSalemans();
                List<Salesman> salesmenl = new ArrayList<>();
                for (Salesman salesman1 : salesmanList) {
                    for (BaseStaff baseStaff : baseStaffs) {
                        if(salesman1.getStaffName().equals(baseStaff.getStaffName()) && salesman1.getBrandNumber().equals(baseStaff.getBrandNumber())
//                                &&baseStaff.getStoreId()==salesman1.getStoreId()
                        ){
                            salesman1.setStaffId(baseStaff.getId());
                        }
                    }
                }
                Map<Integer, List<Salesman>> salesmanMap = salesmanList.stream().collect(Collectors.groupingBy(Salesman::getStaffType));
                Iterator<Map.Entry<Integer, List<Salesman>>> salesmanIterator = salesmanMap.entrySet().iterator();
                //分类，分高管和管理员
                while (salesmanIterator.hasNext()){
                    List<Salesman> salesmans = salesmanIterator.next().getValue();
                    Map<String, List<Salesman>> stringListMap = salesmans.stream().collect(Collectors.groupingBy(Salesman::getBrandNumber));
                    Iterator<Map.Entry<String, List<Salesman>>> entryIterator = stringListMap.entrySet().iterator();
                    BigDecimal salesmanMoney = salesmans.stream().map(item -> item.getRatio().divide(new BigDecimal("100")).multiply(item.getMoney())).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //分类，根据员工进行分类
                    while (entryIterator.hasNext()){
                        List<Salesman> value = entryIterator.next().getValue();
                        Salesman salesman1 = new Salesman();
                        if(value!=null && value.size()>0) {
                            salesman1 = value.get(0);
                        }
                        BigDecimal reduce = value.stream().map(item -> item.getRatio().divide(new BigDecimal("100")).multiply(item.getMoney())).reduce(BigDecimal.ZERO, BigDecimal::add);
                        salesman1.setRatio(reduce.divide(salesmanMoney,4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")));
                        salesmenl.add(salesman1);
                    }
                }
                courseAccount.setSalesmanList(salesmenl);

                BigDecimal reduce = achiCommList.stream().map(AchiCommEntity::getTotalPerformance).reduce(BigDecimal.ZERO, BigDecimal::add);
//                for (AchiCommEntity achiCommEntity : achiCommList) {
//                    achiCommEntity.setSaleRatio(achiCommEntity.getTotalPerformance().divide(reduce,4,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
//                }
                Map<Long, List<AchiCommEntity>> collect = achiCommList.stream().collect(Collectors.groupingBy(AchiCommEntity::getSaleStaffId));
                Iterator<Map.Entry<Long, List<AchiCommEntity>>> iterator = collect.entrySet().iterator();
                List<AchiCommEntity> achiCommEntityList = new ArrayList<>();
                while (iterator.hasNext()){
                    List<AchiCommEntity> value = iterator.next().getValue();
                    BigDecimal reduce1 = value.stream().map(AchiCommEntity::getSaleRatio).reduce(BigDecimal.ZERO, BigDecimal::add);
                    AchiCommEntity achiCommEntity = new AchiCommEntity();
                    achiCommEntity.setBrandNumber(value.get(0).getBrandNumber());
                    achiCommEntity.setSaleStaffName(value.get(0).getSaleStaffName());
                    achiCommEntity.setSaleStaffId(value.get(0).getSaleStaffId());
                    achiCommEntity.setSaleRatio(reduce1);
                    achiCommEntityList.add(achiCommEntity);
                }
                courseAccount.setEntities(achiCommEntityList);

            }
            else if(courseNum.startsWith("LC")){
                String substring = courseNum.substring(courseNum.length() - 11, courseNum.length() - 3);
                StrBuilder strBuilder = new StrBuilder(substring);
                Date parse;
                StrBuilder insert = strBuilder.insert(6, "-").insert(4, "-");
                try {
                    parse = dateFormat.parse(String.valueOf(insert));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                CourseListRequest courseListRequest = new CourseListRequest();
                courseListRequest.setDate(parse);
                courseListRequest.setDocId(courseNum);
                courseListRequest.setProjctId(courseAccount.getCourseProjectId());
                List<CourseList> courseListList = ssmCourseDao.selectCourseOne(courseListRequest);
                CourseList courseList = courseListList.get(0);
                List<AchiCommEntity> achiCommList = this.getAchiCommList(courseList);
                //查询管理员和高管
                Salesman salesman = new Salesman();
                salesman.setOrderNum(courseNum);
                List<Salesman> salesmanList = new ArrayList<>();
                salesmanList.addAll(ssmSalesmanService.select(salesman));
                //有欠款查询欠款单
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    RepayTradeList repayTradeList = new RepayTradeList();
                    repayTradeList.setDocNum(courseNum);
                    List<RepayTradeList> repayTradeLists = ssmRepayTradeService.selectList(repayTradeList);

                    if(repayTradeLists!=null && repayTradeLists.size()>0) {
                        for (RepayTradeList tradeList : repayTradeLists) {
                            if (tradeList.getTradeId().equals(courseList.getProjctId())) {
                                achiCommList.addAll(this.getAchiCommList(tradeList));
                                salesman.setOrderId(tradeList.getId().toString());
                                salesman.setOrderNum(null);
                                salesmanList.addAll(ssmSalesmanService.select(salesman));
                            }
                        }
                    }
                }
                List<BaseStaff> baseStaffs = ssmBaseStaffService.selectByAllSalemans();
                List<Salesman> salesmenl = new ArrayList<>();
                for (Salesman salesman1 : salesmanList) {
                    for (BaseStaff baseStaff : baseStaffs) {
                        if(salesman1.getStaffName().equals(baseStaff.getStaffName()) && salesman1.getBrandNumber().equals(baseStaff.getBrandNumber())
//                                &&baseStaff.getStoreId()==salesman1.getStoreId()
                        ){
                            salesman1.setStaffId(baseStaff.getId());
                        }
                    }
                }
                Map<Integer, List<Salesman>> salesmanMap = salesmanList.stream().collect(Collectors.groupingBy(Salesman::getStaffType));
                Iterator<Map.Entry<Integer, List<Salesman>>> salesmanIterator = salesmanMap.entrySet().iterator();
                //分类，分高管和管理员
                while (salesmanIterator.hasNext()){
                    List<Salesman> salesmans = salesmanIterator.next().getValue();
                    Map<String, List<Salesman>> stringListMap = salesmans.stream().collect(Collectors.groupingBy(Salesman::getBrandNumber));
                    Iterator<Map.Entry<String, List<Salesman>>> entryIterator = stringListMap.entrySet().iterator();
                    BigDecimal salesmanMoney = salesmans.stream().map(item -> item.getRatio().divide(new BigDecimal("100")).multiply(item.getMoney())).reduce(BigDecimal.ZERO, BigDecimal::add);
                    //分类，根据员工进行分类
                    while (entryIterator.hasNext()){
                        List<Salesman> value = entryIterator.next().getValue();
                        Salesman salesman1 = new Salesman();
                        if(value!=null && value.size()>0) {
                            salesman1 = value.get(0);
                        }
                        BigDecimal reduce = value.stream().map(item -> item.getRatio().divide(new BigDecimal("100")).multiply(item.getMoney())).reduce(BigDecimal.ZERO, BigDecimal::add);
                        salesman1.setRatio(reduce.divide(salesmanMoney,4,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("100")));
                        salesmenl.add(salesman1);
                    }
                }
                courseAccount.setSalesmanList(salesmenl);
                Map<Long, List<AchiCommEntity>> collect = achiCommList.stream().collect(Collectors.groupingBy(AchiCommEntity::getSaleStaffId));
                Iterator<Map.Entry<Long, List<AchiCommEntity>>> iterator = collect.entrySet().iterator();
                BigDecimal all = achiCommList.stream().map(item->item.getSaleRatio().divide(BigDecimal.valueOf(100)).multiply(item.getMoney())).reduce(BigDecimal.ZERO, BigDecimal::add);
                List<AchiCommEntity> achiCommEntityList = new ArrayList<>();
                while (iterator.hasNext()){
                    List<AchiCommEntity> value = iterator.next().getValue();
                    BigDecimal reduce1 = value.stream().map(item->item.getSaleRatio().divide(BigDecimal.valueOf(100)).multiply(item.getMoney())).reduce(BigDecimal.ZERO, BigDecimal::add);
                    AchiCommEntity achiCommEntity = new AchiCommEntity();
                    achiCommEntity.setBrandNumber(value.get(0).getBrandNumber());
                    achiCommEntity.setSaleStaffName(value.get(0).getSaleStaffName());
                    achiCommEntity.setSaleStaffId(value.get(0).getSaleStaffId());
                    achiCommEntity.setSaleRatio(reduce1.divide(all,4,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal.valueOf(100)));
                    achiCommEntityList.add(achiCommEntity);
                }
                courseAccount.setEntities(achiCommEntityList);

            }
            else if (courseNum.startsWith("CS")) {

            }
            //促销活动
            else {
                DocPromotion docPromotion = new DocPromotion();
                docPromotion.setDocNum(courseNum);
                List<DocPromotion> select = ssmDocPromotionService.select(docPromotion);
                docPromotion = select.get(0);
                List<AchiCommEntity> achiCommList = this.getAchiCommList(docPromotion);
                if(docPromotion.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    RepayTradeList repayTradeList = new RepayTradeList();
                    repayTradeList.setDocNum(courseNum);
                    List<RepayTradeList> repayTradeLists = ssmRepayTradeService.selectList(repayTradeList);
                    if(repayTradeLists!=null && repayTradeLists.size()>0){
                    for (RepayTradeList tradeList : repayTradeLists) {
                        if(tradeList.getTradeId().equals(courseAccount.getCourseProjectId())){
                            achiCommList.addAll(this.getAchiCommList(tradeList));
                        }
                    }
                    }
                }
                Map<Long, List<AchiCommEntity>> collect = achiCommList.stream().collect(Collectors.groupingBy(AchiCommEntity::getSaleStaffId));
                Iterator<Map.Entry<Long, List<AchiCommEntity>>> iterator = collect.entrySet().iterator();
                List<AchiCommEntity> achiCommEntityList = new ArrayList<>();
                while (iterator.hasNext()){
                    List<AchiCommEntity> value = iterator.next().getValue();
                    BigDecimal reduce1 = value.stream().map(AchiCommEntity::getSaleRatio).reduce(BigDecimal.ZERO, BigDecimal::add);
                    AchiCommEntity achiCommEntity = new AchiCommEntity();
                    achiCommEntity.setBrandNumber(value.get(0).getBrandNumber());
                    achiCommEntity.setSaleStaffName(value.get(0).getSaleStaffName());
                    achiCommEntity.setSaleStaffId(value.get(0).getSaleStaffId());
                    achiCommEntity.setSaleRatio(reduce1);
                    achiCommEntityList.add(achiCommEntity);
                }
                courseAccount.setEntities(achiCommEntityList);

            }
//            Long accountId = courseAccount.getId();
//            for (RefundCourse refundCours : refundCourses) {
//                Long courseAccountId = refundCours.getCourseAccountId();
//                //如果账户可用金额少于0，就不显示该疗程
////                if(courseAccountId.equals(accountId)){
////                    System.out.println("------------");
////                    if(refundCours.getBackConsumeMoney()==null || refundCours.getBackConsumeMoney().compareTo(BigDecimalUtils.bigDecimal("0"))==0){
////                        ids.add(refundCours.getCourseAccountId());
////                    }
////                }
//            }
            BaseProject baseProject = new BaseProject();
            baseProject.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
            courseAccount.setCourseProjectNum(baseProject1.getProjectNum());

        }
        List<CourseAccount> collect = courseAccounts.stream().filter(item -> !ids.contains(item.getId())).collect(Collectors.toList());
        return collect;
    }
    public List<AchiCommEntity> getAchiCommList(RepayTradeList repayTradeList){
//        repayTradeList.setRepayMoney(repayTradeList.getRepayMoney().negate());
//        repayTradeList.setPayMoney(repayTradeList.getPayMoney().negate());
//        repayTradeList.setAchievementAmount(repayTradeList.getAchievementAmount().negate());
//        repayTradeList.setCommissionAmount(repayTradeList.getCommissionAmount().negate());
//        repayTradeList.setCardAchievementAmount(repayTradeList.getCardAchievementAmount().negate());
//        repayTradeList.setCardCommissionAmount(repayTradeList.getCardCommissionAmount().negate());
        //疗程欠款单，充值开卡添加提成
        BigDecimal coursDebteRecharge = BigDecimal.valueOf(0);
        BigDecimal coursDebteRechargechia = BigDecimal.valueOf(0);

        //疗程欠款单，疗程付款扣或添提成
        BigDecimal courseDebteCourse = BigDecimal.valueOf(0);

        //卡付还款的总金额
        BigDecimal cardTotalMoney=BigDecimal.valueOf(0);
        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");

        RepayAccountList repayAccountList = new RepayAccountList();
        repayAccountList.setRepayTradeId(repayTradeList.getId());

        RepayAccountList repayAccountList1 = new RepayAccountList();
        repayAccountList1.setRepayTradeId(repayTradeList.getId());
        List<RepayAccountList> select1 = ssmRepayAccountListService.select(repayAccountList1);
        if(repayTradeList.getDocType().equals("card_use") || repayTradeList.getDocType().equals("card_change")){
            for (RepayAccountList accountList : select1) {
                cardTotalMoney=cardTotalMoney.add(accountList.getPayMoney());
                if(accountList.getAccountType()==0){
                    //充值卡
                    DebtList debtList = new DebtList();
                    debtList.setId(repayTradeList.getDebtId());
                    DebtList debtList1 = ssmDebtService.selectByPrimaryKey(debtList.getId());
                    CourseAccount courseAccount = new CourseAccount();
                    courseAccount.setId(debtList1.getAccountId());
                    CourseAccount courseAccount1 = this.selectByPrimaryKey(courseAccount.getId());
                    BaseProject baseProject = new BaseProject();
                    baseProject.setId(courseAccount1.getCourseProjectId());
                    BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
                    baseProject1.setBrokerage(baseProject1.getBrokerage().negate());
                    BigDecimal cardSalesAchievement = baseProject1.getCardSalesAchievement();
                    BigDecimal cardSalesCommission = baseProject1.getCardSalesCommission();
                    if(cardSalesAchievement.compareTo(BigDecimal.valueOf(1))==1){
                        coursDebteRechargechia = coursDebteRechargechia.add(cardSalesAchievement);
                        //固定
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            coursDebteRecharge=coursDebteRecharge.add(cardSalesCommission);
                        }else{//比例
                            coursDebteRecharge=coursDebteRecharge.add(cardSalesCommission.multiply(cardSalesAchievement));
                        }
                    }else{//比例
                        BigDecimal multiply = cardSalesAchievement.multiply(accountList.getPayMoney());
                        coursDebteRechargechia = coursDebteRechargechia.add(multiply);
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            coursDebteRecharge=coursDebteRecharge.add(cardSalesCommission);
                        }else{//比例
                            coursDebteRecharge=coursDebteRecharge.add(cardSalesCommission.multiply(multiply));
                        }
                    }
                }else{
                    BigDecimal chia = BigDecimal.valueOf(0);
                    BigDecimal comm = BigDecimal.valueOf(0);
                    BigDecimal chiaout = BigDecimal.valueOf(0);
                    BigDecimal commout = BigDecimal.valueOf(0);
                    //疗程卡
                    DebtList debtList = new DebtList();
                    debtList.setId(repayTradeList.getDebtId());
                    DebtList debtList1 = ssmDebtService.selectByPrimaryKey(debtList.getId());
                    CourseAccount courseAccount = new CourseAccount();
                    courseAccount.setId(debtList1.getAccountId());
                    CourseAccount courseAccount1 = this.selectByPrimaryKey(courseAccount.getId());
                    BaseProject baseProject = new BaseProject();
                    baseProject.setId(courseAccount1.getCourseProjectId());
                    BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
                    BigDecimal cardSalesAchievement = baseProject1.getCardSalesAchievement();
                    BigDecimal cardSalesCommission = baseProject1.getCardSalesCommission();
                    if(cardSalesAchievement.compareTo(BigDecimal.valueOf(1))==1){
                        //固定
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            comm=comm.add(cardSalesCommission);
                        }else{//比例
                            comm=comm.add(cardSalesCommission.multiply(cardSalesAchievement));
                        }
                    }else{//比例
                        BigDecimal multiply = cardSalesAchievement.multiply(accountList.getPayMoney());
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            comm=comm.add(cardSalesCommission);
                        }else{//比例
                            comm=comm.add(cardSalesCommission.multiply(multiply));
                        }
                    }
                    CourseAccount courseAccount3 = new CourseAccount();
                    courseAccount3.setId(accountList.getAccountId());
                    courseAccount3 = this.selectByPrimaryKey(courseAccount3.getId());
                    BaseProject baseProject3 = new BaseProject();
                    baseProject3.setId(courseAccount3.getCourseProjectId());
                    baseProject3 = ssmProjectService.selectByPrimaryKey(baseProject3.getId());
                    cardSalesAchievement = baseProject3.getCardSalesAchievement();
                    cardSalesCommission = baseProject3.getCardSalesCommission();
                    if(cardSalesAchievement.compareTo(BigDecimal.valueOf(1))==1){
                        //固定
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            commout=commout.add(cardSalesCommission);
                        }else{//比例
                            commout=commout.add(cardSalesCommission.multiply(cardSalesAchievement));
                        }
                    }else{//比例
                        BigDecimal multiply = cardSalesAchievement.multiply(accountList.getPayMoney());
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            commout=commout.add(cardSalesCommission);
                        }else{//比例
                            commout=commout.add(cardSalesCommission.multiply(multiply));
                        }
                    }
                    //本条疗程的提点
                    BigDecimal bigDecimals = BigDecimal.valueOf(0);
                    if(commout.compareTo(comm)==1){ //扣
                        bigDecimals= commout.subtract(comm);
                        courseDebteCourse=courseDebteCourse.subtract(bigDecimals);
                    }else if(commout.compareTo(comm)==-1){ //加
                        bigDecimals= comm.subtract(commout);
                        courseDebteCourse=courseDebteCourse.add(bigDecimals);
                    }
                }
            }
//            repayTradeList.setCommissionAmount(repayTradeList.getCommissionAmount());
//            repayTradeList.setCardAchievementAmount(repayTradeList.getCardAchievementAmount());
            repayTradeList.setCardCommissionAmount(repayTradeList.getCardCommissionAmount().add(coursDebteRecharge).add(courseDebteCourse));
            //之前的repayTradeList.setPayMoney(repayTradeList.getPayMoney().add(cardTotalMoney));
            repayTradeList.setPayMoney(repayTradeList.getPayMoney());
            if (null != repayTradeList.getSaleOneStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                //achiCommEntity.setProjectId(String.valueOf(repayTradeList.get()));
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleOneNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleOneStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleOneStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleOneIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleOneRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils
                        .add(BigDecimalUtils
                                        .multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils
                                                .div(repayTradeList.getSaleOneRatio(),hundredBD)),
                                BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils
                                        .div(repayTradeList.getSaleOneRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }

                //计算卡付
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));

                entities.add(achiCommEntity);
            }
            if (null != repayTradeList.getSaleTwoStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleTwoNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleTwoStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleTwoStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleTwoIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleTwoRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));

                entities.add(achiCommEntity);
            }
            if (null != repayTradeList.getSaleThreeStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleThreeNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleThreeStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleThreeStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleThreeIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleThreeRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));

                entities.add(achiCommEntity);
            }
            if (null != repayTradeList.getSaleFourStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleFourNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleFourStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleFourStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleFourIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleFourRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));

                entities.add(achiCommEntity);
            }
        }
        else {//项目促销
            for (RepayAccountList accountList : select1) {
                cardTotalMoney=cardTotalMoney.add(accountList.getPayMoney());
                if(accountList.getAccountType()==0){
                    //充值卡
                    DocPromotion docPromotion = new DocPromotion();
                    docPromotion.setId(repayTradeList.getDocId());
                    DocPromotion docPromotion1 = ssmDocPromotionService.selectOne(docPromotion);
                    BigDecimal cardSalesCommission = docPromotion1.getCardSalesCommission();
                    if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                        coursDebteRecharge=coursDebteRecharge.add(cardSalesCommission);
                    }else{//比例
                        coursDebteRecharge=coursDebteRecharge.add(cardSalesCommission.multiply(accountList.getPayMoney()));
                    }
                }else{
                    BigDecimal chia = BigDecimal.valueOf(0);
                    BigDecimal comm = BigDecimal.valueOf(0);
                    BigDecimal chiaout = BigDecimal.valueOf(0);
                    BigDecimal commout = BigDecimal.valueOf(0);
                    //疗程卡
                    DebtList debtList = new DebtList();
                    debtList.setId(repayTradeList.getDebtId());
                    DebtList debtList1 = ssmDebtService.selectByPrimaryKey(debtList.getId());

                    List<DocPromotionProject> docPromotionProjects=new ArrayList<>();
                    DocPromotion docPromotion=ssmDocPromotionService.selectByPrimaryKey(debtList1.getDocId());
                    DocPromotionProject docPromotionProject=new DocPromotionProject();
                    docPromotionProject.setDocNum(docPromotion.getDocNum());
                    docPromotionProjects=ssmDocPromotionProjectService.select(docPromotionProject);
                    if(docPromotionProjects.size()>0){
                        for(DocPromotionProject docPromotionProject1:docPromotionProjects){
                            BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(docPromotionProject1.getProjectId());
                            BigDecimal cardSalesAchievement = baseProject1.getCardSalesAchievement();
                            BigDecimal cardSalesCommission = baseProject1.getCardSalesCommission();
                            if(cardSalesAchievement.compareTo(BigDecimal.valueOf(1))==1){
                                //固定
                                if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                                    comm=comm.add(cardSalesCommission);
                                }else{//比例
                                    comm=comm.add(cardSalesCommission.multiply(cardSalesAchievement));
                                }
                            }else{//比例
                                BigDecimal multiply = cardSalesAchievement.multiply(accountList.getPayMoney());
                                if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                                    comm=comm.add(cardSalesCommission);
                                }else{//比例
                                    comm=comm.add(cardSalesCommission.multiply(multiply));
                                }
                            }
                        }
                    }

                    /*CourseAccount courseAccount = new CourseAccount();
                    courseAccount.setId(debtList1.getAccountId());
                    CourseAccount courseAccount1 = ssmCourseAccountService.selectByPrimaryKey(courseAccount.getId());
                    BaseProject baseProject = new BaseProject();
                    baseProject.setId(courseAccount1.getCourseProjectId());
                    BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
                    BigDecimal cardSalesAchievement = baseProject1.getCardSalesAchievement();
                    BigDecimal cardSalesCommission = baseProject1.getCardSalesCommission();
                    if(cardSalesAchievement.compareTo(BigDecimal.valueOf(1))==1){
                        //固定
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            comm=comm.add(cardSalesCommission);
                        }else{//比例
                            comm=comm.add(cardSalesCommission.multiply(cardSalesAchievement));
                        }
                    }else{//比例
                        BigDecimal multiply = cardSalesAchievement.multiply(accountList.getPayMoney());
                        if(cardSalesCommission.compareTo(BigDecimal.valueOf(1))==1){ //固定
                            comm=comm.add(cardSalesCommission);
                        }else{//比例
                            comm=comm.add(cardSalesCommission.multiply(multiply));
                        }
                    }*/

                    BigDecimal cardSalesCommission1 = docPromotion.getCardSalesCommission();
                    if(cardSalesCommission1.compareTo(BigDecimal.valueOf(1))==1){ //固定
                        commout=commout.add(cardSalesCommission1);
                    }else{//比例
                        commout=commout.add(cardSalesCommission1.multiply(accountList.getPayMoney()));
                    }
                    //本条疗程的提点
                    BigDecimal bigDecimals = BigDecimal.valueOf(0);
                    if(commout.compareTo(comm)==1){ //扣
                        bigDecimals= commout.subtract(comm);
                        courseDebteCourse=courseDebteCourse.subtract(bigDecimals);
                    }else if(commout.compareTo(comm)==-1){ //加
                        bigDecimals= comm.subtract(commout);
                        courseDebteCourse=courseDebteCourse.add(bigDecimals);
                    }
                }
            }
            repayTradeList.setCardCommissionAmount(repayTradeList.getCardCommissionAmount().add(coursDebteRecharge).add(courseDebteCourse));

            //之前的repayTradeList.setPayMoney(repayTradeList.getPayMoney().add(cardTotalMoney));
            repayTradeList.setPayMoney(repayTradeList.getPayMoney());
            if (null != repayTradeList.getSaleOneStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                //achiCommEntity.setProjectId(String.valueOf(repayTradeList.get()));
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleOneNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleOneStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleOneStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleOneIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleOneRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                //计算卡付
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleOneRatio(),hundredBD)));
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                entities.add(achiCommEntity);
            }
            if (null != repayTradeList.getSaleTwoStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleTwoNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleTwoStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleTwoStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleTwoIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleTwoRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleTwoRatio(),hundredBD)));

                entities.add(achiCommEntity);
            }
            if (null != repayTradeList.getSaleThreeStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleThreeNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleThreeStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleThreeStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleThreeIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleThreeRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleThreeRatio(),hundredBD)));

                entities.add(achiCommEntity);
            }
            if (null != repayTradeList.getSaleFourStaffId()){
                AchiCommEntity achiCommEntity = new AchiCommEntity();
                achiCommEntity.setMoney(repayTradeList.getPayMoney());
                achiCommEntity.setMemberNum(String.valueOf(repayTradeList.getMemberId()));
                achiCommEntity.setMemberName(repayTradeList.getMemberName());
                achiCommEntity.setDocNum(repayTradeList.getRepayNum());
                achiCommEntity.setDocType(repayTradeList.getDocType());
                achiCommEntity.setType(Constant.doc_type_repay);
                achiCommEntity.setDocDate(repayTradeList.getRepayDate());
                achiCommEntity.setTradeName(repayTradeList.getTradeName());
                achiCommEntity.setBrandNumber(repayTradeList.getSaleFourNumber());
                achiCommEntity.setSaleStaffId(repayTradeList.getSaleFourStaffId());
                achiCommEntity.setSaleStaffName(repayTradeList.getSaleFourStaffName());
                achiCommEntity.setSaleIdentityCard(repayTradeList.getSaleFourIdentity());
                achiCommEntity.setSaleRatio(repayTradeList.getSaleFourRatio());
                achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD))));
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)),
                        BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD))));
                achiCommEntity.setCashAchi(BigDecimalUtils.multiply(repayTradeList.getAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(repayTradeList.getCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                achiCommEntity.setCardAchi(BigDecimalUtils.multiply(repayTradeList.getCardAchievementAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                achiCommEntity.setCardComm(BigDecimalUtils.multiply(repayTradeList.getCardCommissionAmount(),BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));
                if(null == achiCommEntity.getCashAchi()){
                    achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardAchi() ){
                    achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCashComm()){
                    achiCommEntity.setCashComm(BigDecimal.valueOf(0));
                }
                if(null == achiCommEntity.getCardComm()){
                    achiCommEntity.setCardComm(BigDecimal.valueOf(0));
                }
                achiCommEntity.setTotalPerformance(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
                achiCommEntity.setCooperationAchi(repayTradeList.getPayMoney().subtract(achiCommEntity.getTotalPerformance()));
                achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
                achiCommEntity.setNTMoney(BigDecimalUtils.multiply(cardTotalMoney,BigDecimalUtils.div(repayTradeList.getSaleFourRatio(),hundredBD)));

                entities.add(achiCommEntity);
            }
        }

        return entities;
    }

    public List<AchiCommEntity> getAchiCommList(CardChangeInProject courseList){
        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");

        BaseProject baseProject = ssmProjectService.selectByPrimaryKey(courseList.getProjectId());
        BigDecimal cooperationCashAchi=new BigDecimal("0");//合作现付业绩
        //isCooperation 比例brokerage 1是比例 0是固定smokeCommissionWay
        if(baseProject.getIsCooperation()==1){
            if(baseProject.getSmokeCommissionWay()!=null&&baseProject.getSmokeCommissionWay()==1){//合作按比例
                cooperationCashAchi=baseProject.getBrokerage().multiply(courseList.getChangeInPayMoney());
            }else{//合作按固定
                cooperationCashAchi=baseProject.getBrokerage();
            }
        }
        courseList.setChangeInPayMoney(courseList.getChangeInPayMoney().subtract(cooperationCashAchi));
        courseList.setAchievementAmount(courseList.getChangeInMoney());
        courseList.setCommissionAmount(courseList.getAchievementAmount().multiply(courseList.getSalesCommission()));
        if (null != courseList.getSaleOneStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getTransactionMoney());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjectId()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleOneNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleOneRatio());

            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils
                    .add(BigDecimalUtils
                                    .multiply(courseList.getAchievementAmount(),
                                            BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)),
                            BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeInPayMoney(),courseList.getSalesAchievement()),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.multiply(achiCommEntity.getCashAchi(),courseList.getSalesCommission()),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));

            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeOutMoney(),courseList.getCardSalesAchievement()),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()).multiply(BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));

            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleTwoStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getTransactionMoney());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjectId()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleTwoNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleTwoRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeInPayMoney(),courseList.getSalesAchievement()),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.multiply(achiCommEntity.getCashAchi(),courseList.getSalesCommission()),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeOutMoney(),courseList.getCardSalesAchievement()),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()).multiply(BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));

            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleThreeStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getTransactionMoney());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjectId()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleThreeNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleThreeRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeInPayMoney(),courseList.getSalesAchievement()),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.multiply(achiCommEntity.getCashAchi(),courseList.getSalesCommission()),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeOutMoney(),courseList.getCardSalesAchievement()),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()).multiply(BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));

            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleFourStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getTransactionMoney());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjectId()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_card_change);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleFourNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleFourRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeInPayMoney(),courseList.getSalesAchievement()),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.multiply(achiCommEntity.getCashAchi(),courseList.getSalesCommission()),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseList.getChangeOutMoney(),courseList.getCardSalesAchievement()),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()).multiply(BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));
            entities.add(achiCommEntity);
        }
        return entities;
    }

    public List<AchiCommEntity> getAchiCommList(CourseList courseList) {
        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");

        BaseProject baseProject = ssmProjectService.selectByPrimaryKey(courseList.getProjctId());

        if (null != courseList.getSaleOneStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleOneNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleOneRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils
                    .add(BigDecimalUtils
                                    .multiply(courseList.getAchievementAmount().setScale(4,BigDecimal.ROUND_HALF_UP),
                                            courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                            BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),  courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),  courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));

            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(),  courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),  courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleOneRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleOneRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleOneRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }

            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleTwoStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleTwoNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleTwoRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount().setScale(4,BigDecimal.ROUND_HALF_UP), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleTwoRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleTwoRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleTwoRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }

            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleThreeStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleThreeNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleThreeRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount().setScale(4,BigDecimal.ROUND_HALF_UP), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));


            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleThreeRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleThreeRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleThreeRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }
            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleFourStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleFourNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleFourRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleFourRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleFourRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleFourRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }
            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleFiveStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleFiveNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleFiveStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleFiveStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleFiveIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleFiveRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleFiveRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleFiveRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleFiveRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }
            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }


            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleSixStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleSixNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleSixStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleSixStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleSixIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleSixRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleSixRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleSixRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleSixRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }
            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleSevenStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleSevenNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleSevenStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleSevenStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleSevenIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleSevenRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleSevenRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleSevenRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleSevenRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }
            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleEightStaffId() && courseList.getSaleEightStaffId() != 0) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(courseList.getCourseReatmentAmount());
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getProjctId()));
            achiCommEntity.setDocNum(courseList.getCourseReatmentNum());
            achiCommEntity.setDocType(Constant.doc_type_card_use);
            achiCommEntity.setDocDate(courseList.getDate());
            achiCommEntity.setTradeName(courseList.getProjectName());
            achiCommEntity.setBrandNumber(courseList.getSaleEightNumber());
            achiCommEntity.setSaleStaffId(courseList.getSaleEightStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleEightStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleEightIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleEightRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(), courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

            if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 0) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleEightRatio())
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleEightRatio()));
                }
            } else if (baseProject.getIsCooperation() != null && baseProject.getIsCooperation() == 1
                    && baseProject.getSmokeCommissionWay() != null && baseProject.getSmokeCommissionWay() == 1) {
                if(courseList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())).multiply( courseList.getSaleEightRatio().divide(hundredBD,4,BigDecimal.ROUND_HALF_UP)));

                }
            }
            if (null == achiCommEntity.getCashAchi()) {
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardAchi()) {
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCashComm()) {
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if (null == achiCommEntity.getCardComm()) {
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(), achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(), achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }

        return entities;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repay(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        CourseAccount courseAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        CourseList courseList = new CourseList();
        courseList.setDate(debtList.getDocDate());
        courseList.setId(debtList.getDocId());
        CourseList courseList1 = ssmCourseService.selectOneS(courseList);

        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //查询欠款可用比率
        StoreParament storeParament = StoreParaUtils.getStorePara(repayList.getStoreId(), Constant.debt_usable);
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);
        Integer courseConsumeCount = courseAccount.getCourseConsumeCount();
        //当前疗程账户收款金额 = 账户疗程金额 - 欠款金额
        BigDecimal courseMoney = BigDecimalUtils.subtract(courseAccount.getCourseProjectMoney(), debtList.getDebtMoney());
        //疗程剩余次数重新计算 = courseMoney / 疗程账户项目金额 * 次数
        Integer restCount = BigDecimalUtils.div(BigDecimalUtils.multiply(courseMoney, BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString())), courseAccount.getCourseProjectMoney()).intValue();
        //疗程剩余可用次数重新计算
        Integer consumeCount = 0;
        if (debtList.getState() == 1) {//无欠款
            consumeCount = restCount;
        } else {// 有欠款时 疗程剩余可用次数 = restCount * 可用比率
            consumeCount = BigDecimalUtils.multiply(BigDecimalUtils.bigDecimal(restCount.toString()), consumeRito).intValue();
        }

        CourseList courseList2 = new CourseList();
        courseList2.setId(debtList.getDocId());
        courseList2.setDate(debtList.getDocDate());
        CourseList courseList3 = ssmCourseService.selectOneS(courseList2);

        Integer courseRestCount = courseAccount.getCourseRestCount();

        BigDecimal price = courseAccount.getPrice();



        BigDecimal add = courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney());
        BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
        int i1 = divide.intValue();
        if(divide.compareTo(BigDecimal.valueOf(i1))==0){
            courseAccount.setCourseRestCount(i1);
        }else{
            courseAccount.setCourseRestCount(i1+1);
        }

        courseRestCount  =courseAccount.getCourseRestCount()-courseRestCount;

        //还款 添加疗程次数
        int addRestCount = restCount - debtList.getRepayCount();
        int addConsumeCount = consumeCount - debtList.getRepayConsumeCount();
        //还款 更新疗程账户 剩余次数 可消费次数
        //courseAccount.setCourseRestCount(courseRestCount + addRestCount);
        courseAccount.setCourseConsumeCount(courseConsumeCount + (consumeCount - debtList.getRepayConsumeCount()));
        courseAccount.setCourseConsumeCount(courseConsumeCount + (consumeCount - debtList.getRepayConsumeCount()));

        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));

        BigDecimal multiply = courseList1.getCourseReatmentAmount().multiply(consumeRito);
        BigDecimal subtract = courseList1.getCourseReatmentAmount().subtract(multiply);
        BigDecimal decimal = courseAccount.getCourseConsumePrice().add(subtract).add(repayTradeList.getPayMoney()).setScale(0, BigDecimal.ROUND_HALF_UP);
        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
        courseAccount.setPrice(courseAccount.getCourseRestPrice().divide(BigDecimalUtils.bigDecimal(courseAccount.getCourseRestCount().toString()),2,BigDecimal.ROUND_HALF_UP));

        //添加次数更新到欠款单中
        debtList.setRepayCount(restCount);
        debtList.setRepayConsumeCount(consumeCount);

        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("SsmCourseAccountServiceImpl.repay:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0) {
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, courseAccount, repayList, courseRestCount);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            ssmDebtService.updateNotNull(debtList);
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayNew(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        CourseAccount courseAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        repayTradeList.setBeforePrice(courseAccount.getPrice());
        repayTradeList.setBeforeRestMoney(courseAccount.getCourseRestPrice());
        repayTradeList.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
        repayTradeList.setBeforeRestCount(courseAccount.getCourseRestCount());
        repayTradeList.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());
        if(Constant.doc_type_card_change.equals(repayTradeList.getDocType())){
            CardChangeList cardChangeList = new CardChangeList();
            cardChangeList.setId(debtList.getDocId());
            CardChangeList cardChangeList1 = ssmCardChangeService.selectByPrimaryKey(cardChangeList.getId());

            CardChangeInProject courseList = new CardChangeInProject();
            courseList.setDocNum(cardChangeList1.getDocNum());
            courseList.setStoreId(cardChangeList1.getStoreId());
            CardChangeInProject courseList1 = ssmCardChangeInProjectService.selectOne(courseList);
            BigDecimal courseProjectMoney = courseAccount.getCourseProjectMoney();



            BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
            //查询欠款可用比率
            StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(), Constant.cardCangeListDebtUsable);
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);

            BigDecimal price = courseAccount.getPrice();
            //查询取消欠款
            CancelDebtList cancelDebtList = new CancelDebtList();
            cancelDebtList.setDebtId(debtList.getId());
            cancelDebtList.setState(3);
            List<CancelDebtList> select = ssmCancelDebtListService.select(cancelDebtList);
            BigDecimal cancelMoney = BigDecimal.valueOf(0);
            int cancelcount = 0;
            for (CancelDebtList list : select) {
                cancelMoney=cancelMoney.add(list.getCancelMoney());
                cancelcount=cancelcount+list.getCancelNum();
            }

            //取消的总次数
            Integer CancelNum=0;
            //取消的总金额
            BigDecimal CancelMoney=BigDecimal.valueOf(0);
            for (CancelDebtList list : select) {
                CancelNum=CancelNum+list.getCancelNum();
                CancelMoney=CancelMoney.add(list.getCancelMoney());
            }

            BigDecimal totalMoney = BigDecimal.valueOf(0);
            //取消过欠款
            if(CancelMoney.compareTo(BigDecimal.valueOf(0))==1){
//        if(select.size()>0){
//判断是否已经全额还款
                RepayTradeList repayTradeList1 = new RepayTradeList();
                repayTradeList1.setDocId(cardChangeList1.getId());
                repayTradeList1.setMemberId(cardChangeList1.getMemberId());
                repayTradeList1.setDocType(Constant.doc_type_card_change);
                List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
                for (RepayTradeList tradeList : select1) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select2) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(courseList1.getChangeOutMoney().add(courseList1.getChangeInPayMoney().add(repayTradeList.getPayMoney()))).compareTo(courseProjectMoney)==0){ //已经全额还款
//                courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
//                courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
//                //当前属于次数
//                Integer courseRestCount = courseAccount.getCourseRestCount();
//                BigDecimal add = courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney());
////                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
//                BigDecimal divide = courseAccount.getCourseRestPrice().divide(price, 2, BigDecimal.ROUND_HALF_UP);
//                int i1 = divide.intValue();
//                courseAccount.setCourseConsumeCount(i1);

                    if(courseAccount.getCourseRestCount()==courseAccount.getCourseCounts()-cancelcount){
                        courseAccount.setCourseRestPrice(courseAccount.getCourseProjectMoneys().subtract(cancelMoney));
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }else{
                        //花掉的次数
//                    int i1 = courseAccount.getCourseCount() - courseAccount.getCourseRestCount();
//                    BigDecimal price1 = courseAccount.getPrice();
//                    //应扣金额
//                    BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }
                }else{
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(repayTradeList.getPayMoney().multiply(consumeRito)));
//                BigDecimal add = courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney());
//                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }

            }else { //没有取消欠款
                //判断是否已经全额还款
                RepayTradeList repayTradeList1 = new RepayTradeList();
                repayTradeList1.setDocId(cardChangeList1.getId());
                repayTradeList1.setMemberId(cardChangeList1.getMemberId());
                repayTradeList1.setDocType(Constant.doc_type_card_change);
                List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
                for (RepayTradeList tradeList : select1) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select2) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(courseList1.getChangeOutMoney().add(courseList1.getChangeInPayMoney().add(repayTradeList.getPayMoney()))).compareTo(courseProjectMoney)==0){ //已经全额还款
//                courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
//                courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
//                //当前属于次数
//                Integer courseRestCount = courseAccount.getCourseRestCount();
//                BigDecimal add = courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney());
////                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
//                BigDecimal divide = courseAccount.getCourseRestPrice().divide(price, 2, BigDecimal.ROUND_HALF_UP);
//                int i1 = divide.intValue();
//                if(divide.compareTo(BigDecimal.valueOf(i1))==0){
//                    courseAccount.setCourseConsumeCount(i1);
//                }else{
//                    courseAccount.setCourseConsumeCount(i1+1);
//                }
//                if(courseAccount.getCourseConsumeCount()>courseRestCount){
//                    courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount()-1);
//                }
                    if(courseAccount.getCourseRestCount()==courseAccount.getCourseCounts()){
                        courseAccount.setCourseRestPrice(courseAccount.getCourseProjectMoneys());
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }else{
                        //花掉的次数
//                    int i1 = courseAccount.getCourseCounts() - courseAccount.getCourseRestCount();
//                    BigDecimal price1 = courseAccount.getPrice();
//                    //应扣金额
//                    BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }
                }else{
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(repayTradeList.getPayMoney().multiply(consumeRito)));
//                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }
            }

//添加次数更新到欠款单中
//        debtList.setRepayCount(restCount);
//        debtList.setRepayConsumeCount(consumeCount);

            try {
                repayTradeList.setBackPrice(courseAccount.getPrice());
                repayTradeList.setBackRestMoney(courseAccount.getCourseRestPrice());
                repayTradeList.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                repayTradeList.setBackRestCount(courseAccount.getCourseRestCount());
                repayTradeList.setBackConsumeCount(courseAccount.getCourseConsumeCount());
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repay:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, courseAccount, repayList, courseAccount.getCourseRestCount());
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }
            return i;
        }else{
            CourseList courseList = new CourseList();
            courseList.setDate(debtList.getDocDate());
            courseList.setId(debtList.getDocId());
            CourseList courseList1 = ssmCourseService.selectOneS(courseList);
            BigDecimal courseProjectMoney = courseAccount.getCourseProjectMoney();

            BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
            //查询欠款可用比率
            StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(), Constant.debt_usable);
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);

            BigDecimal price = courseAccount.getPrice();
            //查询取消欠款
            CancelDebtList cancelDebtList = new CancelDebtList();
            cancelDebtList.setDebtId(debtList.getId());
            cancelDebtList.setState(3);
            List<CancelDebtList> select = ssmCancelDebtListService.select(cancelDebtList);
            BigDecimal cancelMoney = BigDecimal.valueOf(0);
            int cancelcount = 0;
            for (CancelDebtList list : select) {
                cancelMoney=cancelMoney.add(list.getCancelMoney());
                cancelcount=cancelcount+list.getCancelNum();
            }

            //取消的总次数
            Integer CancelNum=0;
            //取消的总金额
            BigDecimal CancelMoney=BigDecimal.valueOf(0);
            for (CancelDebtList list : select) {
                CancelNum=CancelNum+list.getCancelNum();
                CancelMoney=CancelMoney.add(list.getCancelMoney());
            }

            BigDecimal totalMoney = BigDecimal.valueOf(0);
            //取消过欠款
            if(CancelMoney.compareTo(BigDecimal.valueOf(0))==1){
//        if(select.size()>0){
//判断是否已经全额还款
                RepayTradeList repayTradeList1 = new RepayTradeList();
                repayTradeList1.setDocId(courseList1.getId());
                repayTradeList1.setMemberId(courseList1.getMemberId());
                repayTradeList1.setDocType("card_use");
                List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
                for (RepayTradeList tradeList : select1) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select2) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(courseList1.getCollectionCashAmount().add(courseList1.getCollectionRechargeAmount().add(repayTradeList.getPayMoney()))).compareTo(courseProjectMoney)==0){ //已经全额还款
//                courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
//                courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
//                //当前属于次数
//                Integer courseRestCount = courseAccount.getCourseRestCount();
//                BigDecimal add = courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney());
////                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
//                BigDecimal divide = courseAccount.getCourseRestPrice().divide(price, 2, BigDecimal.ROUND_HALF_UP);
//                int i1 = divide.intValue();
//                courseAccount.setCourseConsumeCount(i1);

                    if(courseAccount.getCourseRestCount()==courseAccount.getCourseCounts()-cancelcount){
                        courseAccount.setCourseRestPrice(courseAccount.getCourseProjectMoneys().subtract(cancelMoney));
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }else{
                        //花掉的次数
//                    int i1 = courseAccount.getCourseCount() - courseAccount.getCourseRestCount();
//                    BigDecimal price1 = courseAccount.getPrice();
//                    //应扣金额
//                    BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }
                }else{
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(repayTradeList.getPayMoney().multiply(consumeRito)));
//                BigDecimal add = courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney());
//                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }

            }else { //没有取消欠款
                //判断是否已经全额还款
                RepayTradeList repayTradeList1 = new RepayTradeList();
                repayTradeList1.setDocId(courseList1.getId());
                repayTradeList1.setMemberId(courseList1.getMemberId());
                repayTradeList1.setDocType("card_use");
                List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
                for (RepayTradeList tradeList : select1) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2!=null&&repayList2.getIsCancel()!=null)
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select2) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(courseList1.getCollectionCashAmount().add(courseList1.getCollectionRechargeAmount().add(repayTradeList.getPayMoney()))).compareTo(courseProjectMoney)==0){ //已经全额还款
//                courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
//                courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
//                //当前属于次数
//                Integer courseRestCount = courseAccount.getCourseRestCount();
//                BigDecimal add = courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney());
////                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
//                BigDecimal divide = courseAccount.getCourseRestPrice().divide(price, 2, BigDecimal.ROUND_HALF_UP);
//                int i1 = divide.intValue();
//                if(divide.compareTo(BigDecimal.valueOf(i1))==0){
//                    courseAccount.setCourseConsumeCount(i1);
//                }else{
//                    courseAccount.setCourseConsumeCount(i1+1);
//                }
//                if(courseAccount.getCourseConsumeCount()>courseRestCount){
//                    courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount()-1);
//                }
                    if(courseAccount.getCourseRestCount()==courseAccount.getCourseCounts()){
                        courseAccount.setCourseRestPrice(courseAccount.getCourseProjectMoneys());
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }else{
                        //花掉的次数
//                    int i1 = courseAccount.getCourseCounts() - courseAccount.getCourseRestCount();
//                    BigDecimal price1 = courseAccount.getPrice();
//                    //应扣金额
//                    BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                        courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
                        courseAccount.setCourseConsumeCount(courseAccount.getCourseRestCount());
                    }
                }else{
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(repayTradeList.getPayMoney()));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(repayTradeList.getPayMoney().multiply(consumeRito)));
//                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }
            }

//添加次数更新到欠款单中
//        debtList.setRepayCount(restCount);
//        debtList.setRepayConsumeCount(consumeCount);

            try {
                repayTradeList.setBackPrice(courseAccount.getPrice());
                repayTradeList.setBackRestMoney(courseAccount.getCourseRestPrice());
                repayTradeList.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
                repayTradeList.setBackRestCount(courseAccount.getCourseRestCount());
                repayTradeList.setBackConsumeCount(courseAccount.getCourseConsumeCount());
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repay:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, courseAccount, repayList, courseAccount.getCourseRestCount());
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }
            return i;
        }

    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayPromotion(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setPromotionDocId(debtList.getDocId());
        List<CourseAccount> select = dao.select(courseAccount);
        for (CourseAccount account : select) {
            if(account.getCourseType().equals("1")){
                account.setCourseRestPrice(account.getCourseRestPrice().add(account.getUnrecordedAmount().subtract(account.getCancelMoney())));
                account.setCourseConsumePrice(account.getCourseRestPrice());
                account.setCourseRestCount(account.getCourseRestCount()+(account.getUnrecordedNumber()-account.getCancelNum()));
                account.setCourseConsumeCount(account.getCourseRestCount());
                account.setPrice(account.getCourseRestPrice().divide(BigDecimalUtils.bigDecimal(account.getCourseRestCount().toString()),2,BigDecimal.ROUND_HALF_UP));
            }else{//赠品，先校验是否存在取消了欠款，有则不再赠送，无则赠送
                CancelDebtList cancelDebtList = new CancelDebtList();
                cancelDebtList.setDebtId(debtList.getId());
                cancelDebtList.setState(3);
                List<CancelDebtList> select1 = ssmCancelDebtListService.select(cancelDebtList);
                if(null == select1 || select1.size()==0){
                    account.setCourseRestPrice(account.getCourseRestPrice().add(account.getUnrecordedAmount().subtract(account.getCancelMoney())));
                    account.setCourseConsumePrice(account.getCourseRestPrice());
                    account.setCourseRestCount(account.getCourseRestCount()+(account.getUnrecordedNumber()-account.getCancelNum()));
                    account.setCourseConsumeCount(account.getCourseRestCount());
                    account.setPrice(account.getCourseRestPrice().divide(BigDecimalUtils.bigDecimal(account.getCourseRestCount().toString()),2,BigDecimal.ROUND_HALF_UP));
                }
            }
            try {
                DocPromotion docPromotion = ssmDocPromotionService.selectByPrimaryKey(debtList.getDocId());
                repayTradeList.setAchievementAmount(repayTradeList.getRepayMoney());
                repayTradeList.setCommissionAmount(repayTradeList.getRepayMoney().multiply(docPromotion.getSalesCommission()));
                repayTradeList.setCardAchievementAmount(BigDecimal.valueOf(0));
                repayTradeList.setCardCommissionAmount(BigDecimal.valueOf(0));
                i = dao.updateByPrimaryKeySelective(account);
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repay:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                AccountTradeRecord tradeRecord = this.setAccountTradeRecordPomtion(repayTradeList, account, repayList, account.getUnrecordedNumber());
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }
        }

        return 1;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayPromotionNew(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setPromotionDocId(debtList.getDocId());
        List<CourseAccount> select = dao.select(courseAccount);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //查询欠款可用比率
//        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(), Constant.promotionUsable);
        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(), Constant.debt_usable);
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);


        //促销购买订单
        DocPromotion docPromotion2 = new DocPromotion();
        docPromotion2.setId(debtList.getDocId());
        DocPromotion docPromotion3 = ssmDocPromotionService.selectByPrimaryKey(docPromotion2.getId());




        //促销的总金额
        BigDecimal amount = docPromotion3.getAmount();

        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> select1 = ssmCancelDebtListService.select(cancelDebtList);

        //总的取消欠款次数
        int cancelTotalCount =0;
        //总的取消欠款金额
        BigDecimal canceltotalMoney = BigDecimal.valueOf(0);
        for (CourseAccount account : select) {
            for (CancelDebtList list : select1) {
                CancelDebtMx cancelDebtMx = new CancelDebtMx();
                cancelDebtMx.setCancelDebtId(list.getId());
                cancelDebtMx.setCourseId(account.getId());
                List<CancelDebtMx> select2 = ssmCancelDebtMxService.select(cancelDebtMx);
                for (CancelDebtMx debtMx : select2) {
                    cancelTotalCount=cancelTotalCount+debtMx.getCancelNum();
                    canceltotalMoney=canceltotalMoney.add(debtMx.getCancelMoney());
                }
            }
        }

        for (CourseAccount account : select) {
            RepayPromotionMx repayPromotionMx = new RepayPromotionMx();
            repayPromotionMx.setRepayTradeId(repayTradeList.getId());
            repayPromotionMx.setAccountId(account.getId());
            repayPromotionMx.setBeforePrice(account.getPrice());
            repayPromotionMx.setBeforeRestMoney(account.getCourseRestPrice());
            repayPromotionMx.setBeforeConsumeMoney(account.getCourseConsumePrice());
            repayPromotionMx.setBeforeRestCount(account.getCourseRestCount());
            repayPromotionMx.setBeforeConsumeCount(account.getCourseConsumeCount());

            BigDecimal courseRestPrice = account.getCourseRestPrice();
            BigDecimal courseConsumePrice = account.getCourseConsumePrice();
            int cancelBS= 0;
            BigDecimal totalMoney = BigDecimal.valueOf(0);
            //本疗程的取消1欠款次数
            int cancelCount =0;
            //本疗程的取消1欠款金额
            BigDecimal cancelMoney = BigDecimal.valueOf(0);
            for (CancelDebtList list : select1) {
                CancelDebtMx cancelDebtMx = new CancelDebtMx();
                cancelDebtMx.setCancelDebtId(list.getId());
                cancelDebtMx.setCourseId(account.getId());
                List<CancelDebtMx> select2 = ssmCancelDebtMxService.select(cancelDebtMx);
                for (CancelDebtMx debtMx : select2) {
                    cancelBS=1;
                    cancelCount=cancelCount+debtMx.getCancelNum();
                    cancelMoney=cancelMoney.add(debtMx.getCancelMoney());
                }
            }
            BigDecimal price = account.getPrice();
            //取消过欠款
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(repayTradeList.getDocId());
            repayTradeList1.setMemberId(repayTradeList.getMemberId());
            repayTradeList1.setDocType("promotion_card_use");
            List<RepayTradeList> select2 = ssmRepayTradeService.select(repayTradeList1);
            if(cancelBS>0){
                for (RepayTradeList tradeList : select2) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select3) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(docPromotion3.getCollectionCashAmount().add(docPromotion3.getCollectionRechargeAmount().add(repayTradeList.getPayMoney()))).compareTo(docPromotion3.getAmount().subtract(canceltotalMoney))==0) { //已经全额还款
                    //全部还完
                    if(account.getCourseType().equals("1")){
                        if(account.getCourseRestCount()==account.getCourseCounts()-cancelTotalCount){
                            account.setCourseRestPrice(account.getCourseProjectMoneys().subtract(cancelMoney));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }else{
                            //花掉的次数
                            int i1 = account.getCourseCount() - account.getCourseRestCount();
                            BigDecimal price1 = account.getPrice();
                            //应扣金额
                            BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                            account.setCourseRestPrice(account.getCourseProjectMoneys().subtract(account.getExpenditureMoney()).subtract(cancelMoney));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }
                    }
                }
                else{
                    if(account.getCourseType().equals("1")){

                        BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys().subtract(cancelMoney),repayTradeList.getPayMoney()).divide(amount.subtract(canceltotalMoney), 8, RoundingMode.HALF_UP);
                        //BigDecimal multiply = account.getCourseProjectMoneys().subtract(cancelMoney).divide(amount.subtract(canceltotalMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(repayTradeList.getPayMoney());
                        account.setCourseRestPrice(account.getCourseRestPrice().add(multiply));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().add(consumeRito.multiply(multiply)));
//                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
                        BigDecimal divide = account.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }

                }


                }
            else {
                //没取消过
                //判断是否全额还款
                for (RepayTradeList tradeList : select2) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select3) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(docPromotion3.getCollectionCashAmount().add(docPromotion3.getCollectionRechargeAmount().add(repayTradeList.getPayMoney()))).compareTo(docPromotion3.getAmount().subtract(canceltotalMoney))==0) { //已经全额还款
                    //全部还完
                    if(account.getCourseType().equals("1")){
                        //促销购买的
                        //account.setCourseRestPrice(account.getCourseRestPrice().add());
                        BigDecimal multiply = account.getCourseProjectMoneys().divide(amount.subtract(canceltotalMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(repayTradeList.getPayMoney());
//                        account.setCourseRestPrice(account.getCourseRestPrice().add(multiply));
//                        account.setCourseConsumePrice(account.getCourseRestPrice());
//                        account.setCourseConsumeCount(account.getCourseRestCount());
                        if(account.getCourseRestCount()==account.getCourseCounts()){
                            account.setCourseRestPrice(account.getCourseProjectMoneys().multiply(BigDecimal.valueOf(account.getCourseRestCount())));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }else{
                            //花掉的次数
                            int i1 = account.getCourseCounts() - account.getCourseRestCount();
                            BigDecimal price1 = account.getPrice();
                            //应扣金额
                            BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                            account.setCourseRestPrice(account.getPrice().multiply(BigDecimal.valueOf(account.getCourseCount())).subtract(subMoney));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }

                    }else{
                        //促销赠送的
                        account.setCourseRestPrice(account.getCourseProjectMoneys());
                        account.setCourseConsumePrice(account.getCourseRestPrice());
                        account.setCourseRestCount(account.getCourseCounts());
                        account.setCourseConsumeCount(account.getCourseRestCount());
                    }
                }else{
                    //只还部分
                    if(account.getCourseType().equals("1")){
                        //促销购买的
                        BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoney().multiply(BigDecimal.valueOf(account.getCourseStandardCount())),repayTradeList.getPayMoney()).divide(amount.subtract(canceltotalMoney), 8, RoundingMode.HALF_UP);
//                        BigDecimal multiply = account.getCourseProjectMoneys().divide(amount.subtract(canceltotalMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(repayTradeList.getPayMoney());
                        BigDecimal multiply1 = multiply.multiply(consumeRito);
                        account.setCourseRestPrice(account.getCourseRestPrice().add(multiply));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().add(multiply1));
//                        account.setCourseConsumePrice(account.getCourseRestPrice().multiply(consumeRito));
                        BigDecimal divide = account.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }
                }

            }
            RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
            repayTradeCourse.setCourseId(account.getId());
            repayTradeCourse.setRepayTradeId(repayTradeList.getId());
            repayTradeCourse.setMoney(account.getCourseRestPrice().subtract(courseRestPrice));
            repayTradeCourse.setCoumMoney(account.getCourseConsumePrice().subtract(courseConsumePrice));
            repayTradeCourse.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            int save = ssmRepayTradeCourseService.save(repayTradeCourse);
            if(save==0){
                throw new SmsException(ResponseCode.MSG,"保留本次还款添加金额记录出错");
            }
            try {


                DocPromotion docPromotion = ssmDocPromotionService.selectByPrimaryKey(debtList.getDocId());

                PromotionProject promotionProject=new PromotionProject();
                BigDecimal cashAchiSum=new BigDecimal("0");//合作现付业绩
                BigDecimal RechargeAchiSum=new BigDecimal("0");//合作卡付业绩
                promotionProject.setPromotionId(docPromotion.getPromotionId());
                promotionProject.setPromotionNum(docPromotion.getPromotionNum());
                List<PromotionProject> list=ssmPromotionProjectService.select(promotionProject);
                for(PromotionProject promotionProject1:list){
                    BaseProject baseProject=ssmProjectService.selectByPrimaryKey(promotionProject1.getProjectId());
                    //是否是合作项目,1=合作项目
                    if(baseProject.getIsCooperation()==1){
                        //项目总金额/促销包总金额=这个项目总支付金额得占比
                        BigDecimal projectMix=promotionProject1.getProjectTotalMoney().divide(docPromotion.getPrice()).setScale(4,BigDecimal.ROUND_HALF_UP);
                        //拿项目支付占比*还款金额=在这个促销疗程包中还款金额
                        BigDecimal projectMoneyCash=projectMix.multiply(repayTradeList.getRepayMoney());//现付
                        BigDecimal projectMoneyRecharge=projectMix.multiply(repayTradeList.getPayRechargeMoney());//卡付
                        if(baseProject.getSmokeCommissionWay()==1) {//合作按比例
                            cashAchiSum=cashAchiSum.add(projectMoneyCash.multiply(baseProject.getBrokerage()));
                            RechargeAchiSum=RechargeAchiSum.add(projectMoneyRecharge.multiply(baseProject.getBrokerage()));
                        }else{
                            cashAchiSum=cashAchiSum.add(baseProject.getBrokerage());
                            RechargeAchiSum=RechargeAchiSum.add(baseProject.getBrokerage());
                        }
                    }
                }
                BigDecimal RepayMoney=repayTradeList.getRepayMoney();//现付
                RepayMoney=RepayMoney.subtract(cashAchiSum);
                BigDecimal PayRechargeMoney=repayTradeList.getPayRechargeMoney();//卡付（疗程包付、充值卡付）
                PayRechargeMoney=PayRechargeMoney.subtract(RechargeAchiSum);

                //现付
                repayTradeList.setAchievementAmount(RepayMoney);
                if (BigDecimalUtils.compareTo(docPromotion.getSalesCommission(), BigDecimalUtils.bigDecimal("1")) == 1) {//对比>1为固定提成;<1为比列提成
                    repayTradeList.setCommissionAmount(docPromotion.getSalesCommission());
                }else{
                    repayTradeList.setCommissionAmount(RepayMoney.multiply(docPromotion.getSalesCommission()));
                }
                //卡付
                repayTradeList.setCardAchievementAmount(PayRechargeMoney);
                if (BigDecimalUtils.compareTo(docPromotion.getCardSalesCommission(), BigDecimalUtils.bigDecimal("1")) == 1) {//对比>1为固定提成;<1为比列提成
                    repayTradeList.setCardCommissionAmount(docPromotion.getCardSalesCommission());
                }else{
                    repayTradeList.setCardCommissionAmount(PayRechargeMoney.multiply(docPromotion.getCardSalesCommission()));
                }

                repayPromotionMx.setBackPrice(account.getPrice());
                repayPromotionMx.setBackRestMoney(account.getCourseRestPrice());
                repayPromotionMx.setBackConsumeMoney(account.getCourseConsumePrice());
                repayPromotionMx.setBackRestCount(account.getCourseRestCount());
                repayPromotionMx.setBackConsumeCount(account.getCourseConsumeCount());
                repayPromotionMx.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                i = dao.updateByPrimaryKeySelective(account);
                if(i>0){
                    ssmRepayPromotionMxService.save(repayPromotionMx);
                }
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repay:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                BigDecimal subtract = (repayPromotionMx.getBackRestMoney().subtract(repayPromotionMx.getBeforeRestMoney())).abs();
                AccountTradeRecord tradeRecord = this.setAccountTradeRecordPomtion(repayTradeList, account, repayList, account.getUnrecordedNumber(),subtract);
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }

        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayPromotionNewByRecharge(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setPromotionDocId(debtList.getDocId());
        List<CourseAccount> select = dao.select(courseAccount);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //查询欠款可用比率
//        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(), Constant.promotionUsable);
        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(), Constant.debt_usable);
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);


        //促销购买订单
        DocPromotion docPromotion2 = new DocPromotion();
        docPromotion2.setId(debtList.getDocId());
        DocPromotion docPromotion3 = ssmDocPromotionService.selectByPrimaryKey(docPromotion2.getId());

        //促销的总金额
        BigDecimal amount = docPromotion3.getAmount();

        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> select1 = ssmCancelDebtListService.select(cancelDebtList);

        //总的取消欠款次数
        int cancelTotalCount =0;
        //总的取消欠款金额
        BigDecimal canceltotalMoney = BigDecimal.valueOf(0);
        for (CourseAccount account : select) {
            for (CancelDebtList list : select1) {
                CancelDebtMx cancelDebtMx = new CancelDebtMx();
                cancelDebtMx.setCancelDebtId(list.getId());
                cancelDebtMx.setCourseId(account.getId());
                List<CancelDebtMx> select2 = ssmCancelDebtMxService.select(cancelDebtMx);
                for (CancelDebtMx debtMx : select2) {
                    cancelTotalCount=cancelTotalCount+debtMx.getCancelNum();
                    canceltotalMoney=canceltotalMoney.add(debtMx.getCancelMoney());
                }
            }
        }

        //判断，如果是已经全部还款
        //如果是买就送
        PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion3.getPromotionId());
        if(promotionList.getType()==1) {
            if (debtList.getDebtMoney().compareTo(BigDecimal.ZERO) == 0) {
                //判断是否有进行取消欠款的操作
                if (cancelTotalCount == 0) {
                    PromotionListRequest promotionListRequest = new PromotionListRequest();
                    promotionListRequest.setId(docPromotion3.getPromotionId());
                    List<PromotionRechargeList> promotionRechargeLists = promotionRechargeListService.selectList(promotionListRequest);
                    if (promotionRechargeLists != null && promotionRechargeLists.size() > 0) {
                        for (PromotionRechargeList promotionRechargeList : promotionRechargeLists) {
                            //判断是否有这个充值卡账号
                            Example example = new Example(RechargeAccount.class);
                            Example.Criteria criteria = example.createCriteria();
                            criteria.andEqualTo("rechargeTypeId", promotionRechargeList.getRechargeId());
                            criteria.andEqualTo("memberId", docPromotion3.getMemberId());
                            List<RechargeAccount> rechargeAccounts = ssmRechargeAccountService.selectByExample(example);
                            RechargeAccount beforeAccount = null;
                            if (rechargeAccounts.size() > 0) {
                                beforeAccount = rechargeAccounts.get(0);
                                if (beforeAccount.getState() == 0) {
                                    beforeAccount.setState(1);
//                                    ssmRechargeAccountService.updateByPrimaryKey(beforeAccount);
                                }
                            }
//                            第一次充值 无充值账户
                            if (null == beforeAccount) {
                                Long rechargeAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                                RechargeAccount account = new RechargeAccount();
                                account.setId(rechargeAccountId);
                                //对充值账户进行赋值
                                account.setMemberId(docPromotion3.getMemberId());
                                account.setMemberName(docPromotion3.getMemberName());
                                account.setCardRechargeMoney(promotionRechargeList.getRechargeMoney());
                                account.setCardRestMoney(BigDecimal.ZERO);
                                account.setRechargeTypeId(promotionRechargeList.getRechargeId());
                                account.setRechargeTypeName(promotionRechargeList.getRechargeName());
                                account.setRechargeTypeNum(promotionRechargeList.getRechargeNum());
                                RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(promotionRechargeList.getRechargeId());
                                account.setType(rechargeType.getType());
                                account.setDiscount(new BigDecimal(promotionRechargeList.getRechargeDiscount().toString()));
                                account.setCardGiftMoney(promotionRechargeList.getRechargeMoney());
                                account.setStoreId(docPromotion3.getStoreId());
                                account.setStoreName(docPromotion3.getStoreName());
                                account.setCardConsumeMoney(BigDecimal.ZERO);
                                account.setGiftConsumeMoney(promotionRechargeList.getRechargeMoney());
                                account.setState(1);
                                account.setCardNum(0);
                                account.setFirstCharge(0L);
                                //account.setCardRechargeMoney(rechargeType.getFirstAmount());
                                ssmRechargeAccountService.addRechargeAccount(account);
                                //判断是否仅本门店使用,如果是给充值赠送明细加一条记录
                                if (promotionRechargeList.getRechargeMoneyType() == 1) {
                                    RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
                                    rechargeAccountGive.setAccountId(account.getId());
                                    rechargeAccountGive.setMemberId(account.getMemberId());
                                    rechargeAccountGive.setMemberName(account.getMemberName());
                                    rechargeAccountGive.setRechargeNum(docPromotion3.getDocNum());
                                    rechargeAccountGive.setStoreId(account.getStoreId());
                                    rechargeAccountGive.setStoreName(docPromotion3.getStoreName());
                                    rechargeAccountGive.setGiftConsumeMoney(promotionRechargeList.getRechargeMoney());
                                    rechargeAccountGive.setRechargeDate(docPromotion3.getDocDate());
                                    rechargeAccountGive.setRechargeTypeId(promotionRechargeList.getRechargeId());
                                    rechargeAccountGive.setRechargeTypeName(promotionRechargeList.getRechargeName());
                                    ssmRechargeAccountGiveService.save(rechargeAccountGive);
                                }
                                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion3, promotionRechargeList, account);
                                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                            }
                        }
                    }
                }
            }
        }



        for (CourseAccount account : select) {
            RepayPromotionMx repayPromotionMx = new RepayPromotionMx();
            repayPromotionMx.setRepayTradeId(repayTradeList.getId());
            repayPromotionMx.setAccountId(account.getId());
            repayPromotionMx.setBeforePrice(account.getPrice());
            repayPromotionMx.setBeforeRestMoney(account.getCourseRestPrice());
            repayPromotionMx.setBeforeConsumeMoney(account.getCourseConsumePrice());
            repayPromotionMx.setBeforeRestCount(account.getCourseRestCount());
            repayPromotionMx.setBeforeConsumeCount(account.getCourseConsumeCount());

            BigDecimal courseRestPrice = account.getCourseRestPrice();
            BigDecimal courseConsumePrice = account.getCourseConsumePrice();
            int cancelBS= 0;
            BigDecimal totalMoney = BigDecimal.valueOf(0);
            //本疗程的取消1欠款次数
            int cancelCount =0;
            //本疗程的取消1欠款金额
            BigDecimal cancelMoney = BigDecimal.valueOf(0);
            for (CancelDebtList list : select1) {
                CancelDebtMx cancelDebtMx = new CancelDebtMx();
                cancelDebtMx.setCancelDebtId(list.getId());
                cancelDebtMx.setCourseId(account.getId());
                List<CancelDebtMx> select2 = ssmCancelDebtMxService.select(cancelDebtMx);
                for (CancelDebtMx debtMx : select2) {
                    cancelBS=1;
                    cancelCount=cancelCount+debtMx.getCancelNum();
                    cancelMoney=cancelMoney.add(debtMx.getCancelMoney());
                }
            }
            BigDecimal price = account.getPrice();
            //取消过欠款
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(repayTradeList.getDocId());
            repayTradeList1.setMemberId(repayTradeList.getMemberId());
            repayTradeList1.setDocType("promotion_card_use");
            List<RepayTradeList> select2 = ssmRepayTradeService.select(repayTradeList1);
            if(cancelBS>0){
                for (RepayTradeList tradeList : select2) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select3) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(docPromotion3.getCollectionCashAmount().add(docPromotion3.getCollectionRechargeAmount().add(repayTradeList.getPayMoney()))).compareTo(docPromotion3.getAmount().subtract(canceltotalMoney))==0) { //已经全额还款
                    //全部还完
                    if(account.getCourseType().equals("1")){
                        if(account.getCourseRestCount()==account.getCourseCounts()-cancelTotalCount){
                            account.setCourseRestPrice(account.getCourseProjectMoneys().subtract(cancelMoney));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }else{
                            //花掉的次数
                            int i1 = account.getCourseCount() - account.getCourseRestCount();
                            BigDecimal price1 = account.getPrice();
                            //应扣金额
                            BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                            account.setCourseRestPrice(account.getCourseProjectMoneys().subtract(account.getExpenditureMoney()).subtract(cancelMoney));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }
                    }
                }
                else{
                    if(account.getCourseType().equals("1")){

                        BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys().subtract(cancelMoney),repayTradeList.getPayMoney()).divide(amount.subtract(canceltotalMoney), 8, RoundingMode.HALF_UP);
                        //BigDecimal multiply = account.getCourseProjectMoneys().subtract(cancelMoney).divide(amount.subtract(canceltotalMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(repayTradeList.getPayMoney());
                        account.setCourseRestPrice(account.getCourseRestPrice().add(multiply));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().add(consumeRito.multiply(multiply)));
//                BigDecimal divide = add.divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(BigDecimalUtils.add(courseAccount.getCourseRestPrice(),repayTradeList.getPayMoney()).divide(price,2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP),2,BigDecimal.ROUND_HALF_UP);
                        BigDecimal divide = account.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }

                }


            }
            else {
                //没取消过
                //判断是否全额还款
                for (RepayTradeList tradeList : select2) {
                    RepayList repayList1 = new RepayList();
                    repayList1.setRepayNum(tradeList.getRepayNum());
                    repayList1.setStoreId(tradeList.getStoreId());
                    RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                    if(repayList2.getIsCancel()==0){
                        totalMoney=totalMoney.add(tradeList.getPayMoney());
                        RepayAccountList repayAccountList = new RepayAccountList();
                        repayAccountList.setRepayTradeId(tradeList.getId());
                        List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountList);
                        for (RepayAccountList accountList : select3) {
                            totalMoney=totalMoney.add(accountList.getPayMoney());
                        }
                    }
                }
                if(totalMoney.add(docPromotion3.getCollectionCashAmount().add(docPromotion3.getCollectionRechargeAmount().add(repayTradeList.getPayMoney()))).compareTo(docPromotion3.getAmount().subtract(canceltotalMoney))==0) { //已经全额还款
                    //全部还完
                    if(account.getCourseType().equals("1")){
                        //促销购买的
                        //account.setCourseRestPrice(account.getCourseRestPrice().add());
                        BigDecimal multiply = account.getCourseProjectMoneys().divide(amount.subtract(canceltotalMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(repayTradeList.getPayMoney());
//                        account.setCourseRestPrice(account.getCourseRestPrice().add(multiply));
//                        account.setCourseConsumePrice(account.getCourseRestPrice());
//                        account.setCourseConsumeCount(account.getCourseRestCount());
                        if(account.getCourseRestCount()==account.getCourseCounts()){
                            account.setCourseRestPrice(account.getCourseProjectMoneys().multiply(BigDecimal.valueOf(account.getCourseRestCount())));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }else{
                            //花掉的次数
                            int i1 = account.getCourseCounts() - account.getCourseRestCount();
                            BigDecimal price1 = account.getPrice();
                            //应扣金额
                            BigDecimal subMoney = price1.multiply(BigDecimal.valueOf(i1));
                            account.setCourseRestPrice(account.getPrice().multiply(BigDecimal.valueOf(account.getCourseCount())).subtract(subMoney));
                            account.setCourseConsumePrice(account.getCourseRestPrice());
                            account.setCourseConsumeCount(account.getCourseRestCount());
                        }

                    }else{
                        //促销赠送的
                        account.setCourseRestPrice(account.getCourseProjectMoneys());
                        account.setCourseConsumePrice(account.getCourseRestPrice());
                        account.setCourseRestCount(account.getCourseCounts());
                        account.setCourseConsumeCount(account.getCourseRestCount());
                        //
                    }
                }else{
                    //只还部分
                    if(account.getCourseType().equals("1")){
                        //促销购买的
                        BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoney().multiply(BigDecimal.valueOf(account.getCourseStandardCount())),repayTradeList.getPayMoney()).divide(amount.subtract(canceltotalMoney), 8, RoundingMode.HALF_UP);
//                        BigDecimal multiply = account.getCourseProjectMoneys().divide(amount.subtract(canceltotalMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(repayTradeList.getPayMoney());
                        BigDecimal multiply1 = multiply.multiply(consumeRito);
                        account.setCourseRestPrice(account.getCourseRestPrice().add(multiply));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().add(multiply1));
//                        account.setCourseConsumePrice(account.getCourseRestPrice().multiply(consumeRito));
                        BigDecimal divide = account.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }
                }

            }
            RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
            repayTradeCourse.setCourseId(account.getId());
            repayTradeCourse.setRepayTradeId(repayTradeList.getId());
            repayTradeCourse.setMoney(account.getCourseRestPrice().subtract(courseRestPrice));
            repayTradeCourse.setCoumMoney(account.getCourseConsumePrice().subtract(courseConsumePrice));
            repayTradeCourse.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            int save = ssmRepayTradeCourseService.save(repayTradeCourse);
            if(save==0){
                throw new SmsException(ResponseCode.MSG,"保留本次还款添加金额记录出错");
            }
            try {


                DocPromotion docPromotion = ssmDocPromotionService.selectByPrimaryKey(debtList.getDocId());

                PromotionProject promotionProject=new PromotionProject();
                BigDecimal cashAchiSum=new BigDecimal("0");//合作现付业绩
                BigDecimal RechargeAchiSum=new BigDecimal("0");//合作卡付业绩
                promotionProject.setPromotionId(docPromotion.getPromotionId());
                promotionProject.setPromotionNum(docPromotion.getPromotionNum());
                List<PromotionProject> list=ssmPromotionProjectService.select(promotionProject);
                for(PromotionProject promotionProject1:list){
                    BaseProject baseProject=ssmProjectService.selectByPrimaryKey(promotionProject1.getProjectId());
                    //是否是合作项目,1=合作项目
                    if(baseProject.getIsCooperation()==1){
                        //项目总金额/促销包总金额=这个项目总支付金额得占比
                        BigDecimal projectMix=promotionProject1.getProjectTotalMoney().divide(docPromotion.getPrice()).setScale(4,BigDecimal.ROUND_HALF_UP);
                        //拿项目支付占比*还款金额=在这个促销疗程包中还款金额
                        BigDecimal projectMoneyCash=projectMix.multiply(repayTradeList.getRepayMoney());//现付
                        BigDecimal projectMoneyRecharge=projectMix.multiply(repayTradeList.getPayRechargeMoney());//卡付
                        if(baseProject.getSmokeCommissionWay()==1) {//合作按比例
                            cashAchiSum=cashAchiSum.add(projectMoneyCash.multiply(baseProject.getBrokerage()));
                            RechargeAchiSum=RechargeAchiSum.add(projectMoneyRecharge.multiply(baseProject.getBrokerage()));
                        }else{
                            cashAchiSum=cashAchiSum.add(baseProject.getBrokerage());
                            RechargeAchiSum=RechargeAchiSum.add(baseProject.getBrokerage());
                        }
                    }
                }
                BigDecimal RepayMoney=repayTradeList.getRepayMoney();//现付
                RepayMoney=RepayMoney.subtract(cashAchiSum);
                BigDecimal PayRechargeMoney=repayTradeList.getPayRechargeMoney();//卡付（疗程包付、充值卡付）
                PayRechargeMoney=PayRechargeMoney.subtract(RechargeAchiSum);

                //现付
                repayTradeList.setAchievementAmount(RepayMoney);
                if (BigDecimalUtils.compareTo(docPromotion.getSalesCommission(), BigDecimalUtils.bigDecimal("1")) == 1) {//对比>1为固定提成;<1为比列提成
                    repayTradeList.setCommissionAmount(docPromotion.getSalesCommission());
                }else{
                    repayTradeList.setCommissionAmount(RepayMoney.multiply(docPromotion.getSalesCommission()));
                }
                //卡付
                repayTradeList.setCardAchievementAmount(PayRechargeMoney);
                if (BigDecimalUtils.compareTo(docPromotion.getCardSalesCommission(), BigDecimalUtils.bigDecimal("1")) == 1) {//对比>1为固定提成;<1为比列提成
                    repayTradeList.setCardCommissionAmount(docPromotion.getCardSalesCommission());
                }else{
                    repayTradeList.setCardCommissionAmount(PayRechargeMoney.multiply(docPromotion.getCardSalesCommission()));
                }

                repayPromotionMx.setBackPrice(account.getPrice());
                repayPromotionMx.setBackRestMoney(account.getCourseRestPrice());
                repayPromotionMx.setBackConsumeMoney(account.getCourseConsumePrice());
                repayPromotionMx.setBackRestCount(account.getCourseRestCount());
                repayPromotionMx.setBackConsumeCount(account.getCourseConsumeCount());
                repayPromotionMx.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                i = dao.updateByPrimaryKeySelective(account);
                if(i>0){
                    ssmRepayPromotionMxService.save(repayPromotionMx);
                }
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repay:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                BigDecimal subtract = (repayPromotionMx.getBackRestMoney().subtract(repayPromotionMx.getBeforeRestMoney())).abs();
                AccountTradeRecord tradeRecord = this.setAccountTradeRecordPomtion(repayTradeList, account, repayList, account.getUnrecordedNumber(),subtract);
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }

        }
        return 1;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayCancel(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        CourseAccount courseAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        RefundCourse refundCourse = new RefundCourse();
        refundCourse.setCourseAccountId(courseAccount.getId());
        List<RefundCourse> refundCourse1 = ssmRefundCourseService.select(refundCourse);
        for (RefundCourse course : refundCourse1) {
            RefundOrderList refundOrderList = new RefundOrderList();
            refundOrderList.setRefundNum(course.getRefundNum());
            refundOrderList.setStoreId(course.getStoreId());
            List<RefundOrderList> refundOrderList1 = ssmRefundOrderService.select(refundOrderList);
            for (RefundOrderList orderList : refundOrderList1) {
                if(orderList.getState()==3){
                    throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"该疗程存在疗程退，不允许作废还款单");
                }
            }
        }

        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //查询欠款可用比率
        StoreParament storeParament = this.getStorePara(repayList.getStoreId(), "debtUsable");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);
        Integer courseConsumeCount = courseAccount.getCourseConsumeCount();
        //当前疗程账户收款金额 = 账户疗程金额 - 欠款金额
        BigDecimal courseMoney = BigDecimalUtils.subtract(courseAccount.getCourseProjectMoney(), debtList.getDebtMoney());
        //疗程剩余次数重新计算 = courseMoney / 疗程账户项目金额 * 次数
        Integer restCount = BigDecimalUtils.div(BigDecimalUtils.multiply(courseMoney, BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString())), courseAccount.getCourseProjectMoney()).intValue();
        Integer consumeCount = BigDecimalUtils.div(BigDecimalUtils.multiply(BigDecimalUtils.multiply(courseMoney,consumeRito), BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString())), courseAccount.getCourseProjectMoney()).intValue();
        // 有欠款时 疗程剩余可用次数 = restCount * 可用比率
        //Integer consumeCount = BigDecimalUtils.multiply(BigDecimalUtils.bigDecimal(restCount.toString()), consumeRito).intValue();

        CourseList courseList2 = new CourseList();
        courseList2.setId(debtList.getDocId());
        courseList2.setDate(debtList.getDocDate());
        CourseList courseList3 = ssmCourseService.selectOneS(courseList2);

        Integer courseRestCount = courseAccount.getCourseRestCount();

        BigDecimal add = courseList3.getCollectionCashAmount();

        BigDecimal subtract2 = courseAccount.getCourseRestPrice().subtract(repayTradeList.getPayMoney());
        BigDecimal divide = subtract2.divide(courseAccount.getCourseProjectMoneys().divide(BigDecimalUtils.bigDecimal(courseAccount.getCourseCounts().toString()),2,BigDecimal.ROUND_HALF_UP),2);
        int i1 = divide.intValue();
        courseAccount.setCourseRestCount(i1);

        courseRestCount=courseAccount.getCourseRestCount()-courseRestCount;

        //还款作废 扣减疗程次数
        int subRestCount = debtList.getRepayCount() - restCount;
        int subRestCounts = debtList.getRepayCount() - consumeCount;
        int subConsumeCount = debtList.getRepayConsumeCount() - consumeCount ;
        //还款 更新疗程账户 剩余次数 可消费次数
        //courseAccount.setCourseRestCount(courseRestCount - subRestCount);
        courseAccount.setCourseConsumeCount(courseConsumeCount - subRestCounts);
        courseAccount.setCourseConsumeCount(courseConsumeCount - subRestCounts);
        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(repayTradeList.getPayMoney()));
        courseAccount.setPrice(courseAccount.getCourseProjectMoney().divide(BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString()),2,BigDecimal.ROUND_HALF_UP));
        BigDecimal multiply = courseMoney.multiply(consumeRito);
        //花掉的剩余金额
        BigDecimal subtract1 = courseMoney.subtract(courseAccount.getCourseRestPrice());


        BigDecimal subtract = multiply.subtract(subtract1);
        //BigDecimal multiply = courseAccount.getCourseRestPrice().multiply(consumeRito);

        courseAccount.setCourseConsumePrice(subtract);

        //添加次数更新到欠款单中
        debtList.setRepayCount(restCount);
        debtList.setRepayConsumeCount(consumeCount);
        //校验次数
        this.volidAccount(courseAccount);
        try {
            i = dao.updateByPrimaryKeySelective(courseAccount);
        } catch (Exception e) {
            log.error("SsmCourseAccountServiceImpl.repayCancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0) {
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, courseAccount, repayList, courseRestCount);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            ssmDebtService.updateNotNull(debtList);
        }
        return i;
    }
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayCancelNew(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        if(Constant.doc_type_card_change.equals(repayTradeList.getDocType())){
            CourseAccount courseAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
            if(repayTradeList.getBackPrice().compareTo(courseAccount.getPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackRestMoney().compareTo(courseAccount.getCourseRestPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackConsumeMoney().compareTo(courseAccount.getCourseConsumePrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackRestCount() != courseAccount.getCourseRestCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackConsumeCount() != courseAccount.getCourseConsumeCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            RefundCourse refundCourse = new RefundCourse();
            refundCourse.setCourseAccountId(courseAccount.getId());
            List<RefundCourse> refundCourse1 = ssmRefundCourseService.select(refundCourse);
            for (RefundCourse course : refundCourse1) {
                RefundOrderList refundOrderList = new RefundOrderList();
                refundOrderList.setRefundNum(course.getRefundNum());
                refundOrderList.setStoreId(course.getStoreId());
                List<RefundOrderList> refundOrderList1 = ssmRefundOrderService.select(refundOrderList);
                for (RefundOrderList orderList : refundOrderList1) {
                    if(orderList.getState()==3){
                        throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"该疗程存在疗程退，不允许作废还款单");
                    }
                }
            }

            CardChangeList cardChangeList = new CardChangeList();
            cardChangeList.setId(debtList.getDocId());
            CardChangeList cardChangeList1 = ssmCardChangeService.selectByPrimaryKey(cardChangeList.getId());

            CardChangeInProject courseList = new CardChangeInProject();
            courseList.setDocNum(cardChangeList1.getDocNum());
            courseList.setStoreId(cardChangeList1.getStoreId());
            CardChangeInProject courseLists = ssmCardChangeInProjectService.selectOne(courseList);

//            CourseList courseList = new CourseList();
//            courseList.setId(debtList.getDocId());
//            courseList.setDate(debtList.getDocDate());
//            CourseList courseLists = ssmCourseService.selectListSalem(courseList).get(0);

            RepayAccountList repayAccountList = new RepayAccountList();
            repayAccountList.setRepayTradeId(repayTradeList.getId());
            List<RepayAccountList> select1 = ssmRepayAccountListService.select(repayAccountList);
            //卡付总金额
            BigDecimal reduce = select1.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

            //查询取消欠款
            CancelDebtList cancelDebtList = new CancelDebtList();
            cancelDebtList.setDebtId(debtList.getId());
            cancelDebtList.setState(3);
            List<CancelDebtList> select = ssmCancelDebtListService.select(cancelDebtList);

            //取消的总次数
            Integer CancelNum=0;

            BigDecimal CancelMoney=BigDecimal.valueOf(0);
            for (CancelDebtList list : select) {
                CancelNum=CancelNum+list.getCancelNum();
                CancelMoney=CancelMoney.add(list.getCancelMoney());
            }

            BigDecimal price = courseAccount.getPrice();

            BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
            //查询欠款可用比率
            StoreParament storeParament = this.getStorePara(debtList.getStoreId(), "cardCangeListDebtUsable");
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);
            //本单的还款金额
            //要判断是否全额还款还是部分还款
            BigDecimal totalMoney = BigDecimal.valueOf(0);
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(repayTradeList.getDocId());
            repayTradeList1.setMemberId(repayTradeList.getMemberId());
            repayTradeList1.setDocType(Constant.doc_type_card_change);
            List<RepayTradeList> select2 = ssmRepayTradeService.select(repayTradeList1);
            for (RepayTradeList tradeList : select2) {
                RepayList repayList1 = new RepayList();
                repayList1.setRepayNum(tradeList.getRepayNum());
                repayList1.setStoreId(tradeList.getStoreId());
                RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                if(repayList2.getIsCancel()==0){
                    totalMoney=totalMoney.add(tradeList.getPayMoney());
                    RepayAccountList repayAccountListl = new RepayAccountList();
                    repayAccountListl.setRepayTradeId(tradeList.getId());
                    List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountListl);
                    for (RepayAccountList accountList : select3) {
                        totalMoney=totalMoney.add(accountList.getPayMoney());
                    }
                }
            }
            if(CancelMoney.compareTo(BigDecimal.valueOf(0))==1){
                if(totalMoney.add(courseLists.getChangeInPayMoney().add(courseLists.getChangeOutMoney())).compareTo(courseLists.getTransactionMoney().subtract(CancelMoney))==0) { //已经全额还款
                    //全部还完
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    BigDecimal multiply = BigDecimalUtils.subtract(courseAccount.getCourseProjectMoney(), add).multiply(consumeRito);
                    courseAccount.setCourseConsumePrice(multiply.subtract(courseAccount.getExpenditureMoney()));
//                courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice().multiply(consumeRito));

                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }else{
                    //只还部分
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(add.multiply(consumeRito)));
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }
            }else{
                if(totalMoney.add(courseLists.getChangeInPayMoney().add(courseLists.getChangeOutMoney())).compareTo(courseLists.getTransactionMoney())==0) { //已经全额还款
                    //全部还完
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    BigDecimal multiply = BigDecimalUtils.subtract(courseAccount.getCourseProjectMoney(), add).multiply(consumeRito);
                    courseAccount.setCourseConsumePrice(multiply.subtract(courseAccount.getExpenditureMoney()));
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }else{
                    //只还部分
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(add.multiply(consumeRito)));
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }
            }
//
//
//
//        //校验次数
//        this.volidAccount(courseAccount);
            try {
                courseAccount.setPrice(repayTradeList.getBeforePrice());
                courseAccount.setCourseRestPrice(repayTradeList.getBeforeRestMoney());
                courseAccount.setCourseConsumePrice(repayTradeList.getBeforeConsumeMoney());
                courseAccount.setCourseRestCount(repayTradeList.getBeforeRestCount());
                courseAccount.setCourseConsumeCount(repayTradeList.getBeforeConsumeCount());
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repayCancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, courseAccount, repayList, courseAccount.getCourseRestCount());
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }
            return i;
        }else{
            CourseAccount courseAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
            if(repayTradeList.getBackPrice().compareTo(courseAccount.getPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackRestMoney().compareTo(courseAccount.getCourseRestPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackConsumeMoney().compareTo(courseAccount.getCourseConsumePrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackRestCount() != courseAccount.getCourseRestCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayTradeList.getBackConsumeCount() != courseAccount.getCourseConsumeCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            RefundCourse refundCourse = new RefundCourse();
            refundCourse.setCourseAccountId(courseAccount.getId());
            List<RefundCourse> refundCourse1 = ssmRefundCourseService.select(refundCourse);
            for (RefundCourse course : refundCourse1) {
                RefundOrderList refundOrderList = new RefundOrderList();
                refundOrderList.setRefundNum(course.getRefundNum());
                refundOrderList.setStoreId(course.getStoreId());
                List<RefundOrderList> refundOrderList1 = ssmRefundOrderService.select(refundOrderList);
                for (RefundOrderList orderList : refundOrderList1) {
                    if(orderList.getState()==3){
                        throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"该疗程存在疗程退，不允许作废还款单");
                    }
                }
            }

            CourseList courseList = new CourseList();
            courseList.setId(debtList.getDocId());
            courseList.setDate(debtList.getDocDate());
            CourseList courseLists = ssmCourseService.selectListSalem(courseList).get(0);

            RepayAccountList repayAccountList = new RepayAccountList();
            repayAccountList.setRepayTradeId(repayTradeList.getId());
            List<RepayAccountList> select1 = ssmRepayAccountListService.select(repayAccountList);
            //卡付总金额
            BigDecimal reduce = select1.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

            //查询取消欠款
            CancelDebtList cancelDebtList = new CancelDebtList();
            cancelDebtList.setDebtId(debtList.getId());
            cancelDebtList.setState(3);
            List<CancelDebtList> select = ssmCancelDebtListService.select(cancelDebtList);

            //取消的总次数
            Integer CancelNum=0;

            BigDecimal CancelMoney=BigDecimal.valueOf(0);
            for (CancelDebtList list : select) {
                CancelNum=CancelNum+list.getCancelNum();
                CancelMoney=CancelMoney.add(list.getCancelMoney());
            }

            BigDecimal price = courseAccount.getPrice();

            BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
            //查询欠款可用比率
            StoreParament storeParament = this.getStorePara(debtList.getStoreId(), "debtUsable");
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);
            //本单的还款金额
            //要判断是否全额还款还是部分还款
            BigDecimal totalMoney = BigDecimal.valueOf(0);
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(repayTradeList.getDocId());
            repayTradeList1.setMemberId(repayTradeList.getMemberId());
            repayTradeList1.setDocType("card_use");
            List<RepayTradeList> select2 = ssmRepayTradeService.select(repayTradeList1);
            for (RepayTradeList tradeList : select2) {
                RepayList repayList1 = new RepayList();
                repayList1.setRepayNum(tradeList.getRepayNum());
                repayList1.setStoreId(tradeList.getStoreId());
                RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                if(repayList2.getIsCancel()==0){
                    totalMoney=totalMoney.add(tradeList.getPayMoney());
                    RepayAccountList repayAccountListl = new RepayAccountList();
                    repayAccountListl.setRepayTradeId(tradeList.getId());
                    List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountListl);
                    for (RepayAccountList accountList : select3) {
                        totalMoney=totalMoney.add(accountList.getPayMoney());
                    }
                }
            }
            if(CancelMoney.compareTo(BigDecimal.valueOf(0))==1){
                if(totalMoney.add(courseLists.getCollectionCashAmount().add(courseLists.getCollectionRechargeAmount())).compareTo(courseLists.getAmount().subtract(CancelMoney))==0) { //已经全额还款
                    //全部还完
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    BigDecimal multiply = BigDecimalUtils.subtract(courseAccount.getCourseProjectMoney(), add).multiply(consumeRito);
                    courseAccount.setCourseConsumePrice(multiply.subtract(courseAccount.getExpenditureMoney()));
//                courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice().multiply(consumeRito));

                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }else{
                    //只还部分
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(add.multiply(consumeRito)));
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }
            }else{
                if(totalMoney.add(courseLists.getCollectionCashAmount().add(courseLists.getCollectionRechargeAmount())).compareTo(courseLists.getAmount())==0) { //已经全额还款
                    //全部还完
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    BigDecimal multiply = BigDecimalUtils.subtract(courseAccount.getCourseProjectMoney(), add).multiply(consumeRito);
                    courseAccount.setCourseConsumePrice(multiply.subtract(courseAccount.getExpenditureMoney()));
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }else{
                    //只还部分
                    BigDecimal add = repayTradeList.getPayMoney().add(reduce);
                    courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(add));
                    courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().subtract(add.multiply(consumeRito)));
                    BigDecimal divide = courseAccount.getCourseConsumePrice().divide(price, 4,RoundingMode.HALF_UP);
                    int i1 = divide.intValue();
                    courseAccount.setCourseConsumeCount(i1);
                }
            }
//
//
//
//        //校验次数
//        this.volidAccount(courseAccount);
            try {
                courseAccount.setPrice(repayTradeList.getBeforePrice());
                courseAccount.setCourseRestPrice(repayTradeList.getBeforeRestMoney());
                courseAccount.setCourseConsumePrice(repayTradeList.getBeforeConsumeMoney());
                courseAccount.setCourseRestCount(repayTradeList.getBeforeRestCount());
                courseAccount.setCourseConsumeCount(repayTradeList.getBeforeConsumeCount());
                i = dao.updateByPrimaryKeySelective(courseAccount);
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repayCancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, courseAccount, repayList, courseAccount.getCourseRestCount());
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }
            return i;
        }

    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayCancelPromotion(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i=0;
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setPromotionDocId(debtList.getDocId());
        List<CourseAccount> select = dao.select(courseAccount);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //查询欠款可用比率
        StoreParament storeParament = this.getStorePara(debtList.getStoreId(), "promotionUsable");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);

        //促销单
        DocPromotion docPromotion = new DocPromotion();
        docPromotion.setId(debtList.getId());
        DocPromotion docPromotion1 = ssmDocPromotionService.selectByPrimaryKey(docPromotion.getId());

        for (CourseAccount account : select) {
            if(account.getCourseType().equals("1")){
                account.setCourseRestPrice(account.getCourseRestPrice().subtract(account.getUnrecordedAmount().subtract(account.getCancelMoney())));
                //支付金额
                BigDecimal subtract = account.getCourseProjectMoney().subtract(account.getUnrecordedAmount().subtract(account.getCancelMoney()));
                //花掉的
                BigDecimal subtract1 = subtract.subtract(account.getCourseRestPrice());
                //初始可用的
                BigDecimal multiply = subtract.multiply(consumeRito);

                BigDecimal subtract3 = multiply.subtract(subtract1);

                account.setCourseConsumePrice(subtract3);

                account.setCourseRestCount(account.getCourseRestCount()-(account.getUnrecordedNumber()-account.getCancelNum()));

                //支付的次数
                Integer cashCount = account.getCourseCount() - (account.getUnrecordedNumber()-account.getCancelNum());
                //花掉的
                int i1 = cashCount - account.getCourseRestCount();
                //初始可用的
                int i2 = multiply.divide(account.getPrice(), 2, BigDecimal.ROUND_HALF_UP).intValue();
                int i3 = i2 - i1;
                account.setCourseConsumeCount(i3);
            }else{
                CancelDebtList cancelDebtList = new CancelDebtList();
                cancelDebtList.setDocId(debtList.getDocId());
                cancelDebtList.setState(3);
                List<CancelDebtList> select1 = ssmCancelDebtListService.select(cancelDebtList);
                if(select1.size()==0){
                    account.setCourseRestPrice(account.getCourseRestPrice().subtract(account.getUnrecordedAmount().subtract(account.getCancelMoney())));
                    //支付金额
                    BigDecimal subtract = account.getCourseProjectMoney().subtract(account.getUnrecordedAmount().subtract(account.getCancelMoney()));
                    //花掉的
                    BigDecimal subtract1 = subtract.subtract(account.getCourseRestPrice());
                    //初始可用的
                    BigDecimal multiply = subtract.multiply(consumeRito);

                    BigDecimal subtract3 = multiply.subtract(subtract1);

                    account.setCourseConsumePrice(subtract3);

                    account.setCourseRestCount(account.getCourseRestCount()-(account.getUnrecordedNumber()-account.getCancelNum()));

                    //支付的次数
                    Integer cashCount = account.getCourseCount() - (account.getUnrecordedNumber()-account.getCancelNum());
                    //花掉的
                    int i1 = cashCount - account.getCourseRestCount();
                    //初始可用的
                    int i2 = multiply.divide(account.getPrice(), 2, BigDecimal.ROUND_HALF_UP).intValue();
                    int i3 = i2 - i1;
                    account.setCourseConsumeCount(i3);

                }
            }

            //校验次数
            try {
                this.volidAccount(account);
                i = dao.updateByPrimaryKeySelective(account);
            }catch (SmsException e){
                throw new SmsException(ResponseCode.MSG,e.getMessage());
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repayCancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                AccountTradeRecord tradeRecord = this.setAccountTradeRecordPomtion(repayTradeList, account, repayList, account.getUnrecordedNumber());
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }

        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayCancelPromotionNew(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;

        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setPromotionDocId(debtList.getDocId());
        List<CourseAccount> select = dao.select(courseAccount);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //查询欠款可用比率
        StoreParament storeParament = this.getStorePara(debtList.getStoreId(), "debtUsable");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);

        //促销单
        DocPromotion docPromotion = new DocPromotion();
        docPromotion.setId(debtList.getDocId());
        DocPromotion docPromotion1 = ssmDocPromotionService.selectByPrimaryKey(docPromotion.getId());

        RepayAccountList repayAccountList = new RepayAccountList();
        repayAccountList.setRepayTradeId(repayTradeList.getId());
//        List<RepayAccountList> select1 = ssmRepayAccountListService.select(repayAccountList);
        //卡付总金额
//        BigDecimal reduce = select1.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal totalMoney = BigDecimal.valueOf(0);
        RepayTradeList repayTradeList1 = new RepayTradeList();
        repayTradeList1.setDocId(repayTradeList.getDocId());
        repayTradeList1.setMemberId(repayTradeList.getMemberId());
        repayTradeList1.setDocType("promotion_card_use");
        List<RepayTradeList> select2 = ssmRepayTradeService.select(repayTradeList1);
        for (RepayTradeList tradeList : select2) {
            RepayList repayList1 = new RepayList();
            repayList1.setRepayNum(tradeList.getRepayNum());
            repayList1.setStoreId(tradeList.getStoreId());
            RepayList repayList2 = ssmRepayService.selectOne(repayList1);
            if(repayList2.getIsCancel()==0){
                totalMoney=totalMoney.add(tradeList.getPayMoney());
                RepayAccountList repayAccountListl = new RepayAccountList();
                repayAccountListl.setRepayTradeId(tradeList.getId());
                List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountListl);
                for (RepayAccountList accountList : select3) {
                    totalMoney=totalMoney.add(accountList.getPayMoney());
                }
            }
        }

        //查询取消欠款
        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> selectCancel = ssmCancelDebtListService.select(cancelDebtList);

        //取消的总次数
        Integer CancelTotalNum=0;
        BigDecimal CancelTotaMoney=BigDecimal.valueOf(0);
        for (CancelDebtList list : selectCancel) {
            CancelDebtMx cancelDebtMx = new CancelDebtMx();
            cancelDebtMx.setCancelDebtId(list.getId());
            List<CancelDebtMx> select3 = ssmCancelDebtMxService.select(cancelDebtMx);
            for (CancelDebtMx debtMx : select3) {
                CancelTotalNum=CancelTotalNum+debtMx.getCancelNum();
                CancelTotaMoney=CancelTotaMoney.add(debtMx.getCancelMoney());
            }
        }

        for (CourseAccount account : select) {
            RepayPromotionMx repayPromotionMx = new RepayPromotionMx();
            repayPromotionMx.setRepayTradeId(repayTradeList.getId());
            repayPromotionMx.setAccountId(account.getId());
            RepayPromotionMx repayPromotionMx1 = ssmRepayPromotionMxService.selectOne(repayPromotionMx);

            if(repayPromotionMx1.getBackPrice().compareTo(account.getPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackRestMoney().compareTo(account.getCourseRestPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackConsumeMoney().compareTo(account.getCourseConsumePrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackRestCount() != account.getCourseRestCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackConsumeCount() != account.getCourseConsumeCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }

            int cancelBS= 0;
            //本次疗程的总次数
            Integer CancelNum=0;
            BigDecimal CancelMoney=BigDecimal.valueOf(0);
            for (CancelDebtList list : selectCancel) {
                CancelDebtMx cancelDebtMx = new CancelDebtMx();
                cancelDebtMx.setCourseId(account.getId());
                cancelDebtMx.setCancelDebtId(list.getId());
                List<CancelDebtMx> select3 = ssmCancelDebtMxService.select(cancelDebtMx);
                for (CancelDebtMx debtMx : select3) {
                    cancelBS=1;
                    CancelNum=CancelNum+debtMx.getCancelNum();
                    CancelMoney=CancelMoney.add(debtMx.getCancelMoney());
                }
            }

            RefundCourse refundCourse = new RefundCourse();
            refundCourse.setCourseAccountId(account.getId());
            List<RefundCourse> refundCourse1 = ssmRefundCourseService.select(refundCourse);
            for (RefundCourse course : refundCourse1) {
                RefundOrderList refundOrderList = new RefundOrderList();
                refundOrderList.setRefundNum(course.getRefundNum());
                refundOrderList.setStoreId(course.getStoreId());
                List<RefundOrderList> refundOrderList1 = ssmRefundOrderService.select(refundOrderList);
                for (RefundOrderList orderList : refundOrderList1) {
                    if(orderList.getState()==3){
                        throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"该疗程存在疗程退，不允许作废还款单");
                    }
                }
            }

            /**
             * 暂时不适应以下方法
             */

            //取消过次数
            if(cancelBS>0){
                if (totalMoney.add(docPromotion1.getCollectionCashAmount().add(docPromotion1.getCollectionRechargeAmount())).compareTo(docPromotion1.getAmount().subtract(CancelTotaMoney)) == 0) { //已经全额还款
//                    全部还款
//                    BigDecimal add = repayTradeList.getPayMoney();
//                    BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys().subtract(CancelMoney),add).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, RoundingMode.HALF_UP);
//
////                    BigDecimal multiply = account.getCourseProjectMoneys().subtract(CancelMoney).divide((docPromotion1.getAmount().subtract(CancelTotaMoney)), 4, RoundingMode.HALF_UP).multiply(add);
////                    BigDecimal multiply = account.getCourseProjectMoneys().divide((docPromotion1.getAmount().subtract(CancelTotaMoney)), 4, RoundingMode.HALF_UP).multiply(add);
//                    account.setCourseRestPrice(account.getCourseRestPrice().subtract(multiply));
//
//                    BigDecimal multiply1 = BigDecimalUtils.subtract(account.getCourseProjectMoneys().subtract(CancelMoney), multiply).multiply(consumeRito);
//
//
//                    account.setCourseConsumePrice(multiply1.subtract(account.getExpenditureMoney()));
//                    BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
//                    int i1 = divide.intValue();
//                    account.setCourseConsumeCount(i1);
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }


                }else{
                    //部分还款
//                    BigDecimal add = repayTradeList.getPayMoney();
//                    BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys().subtract(CancelMoney),add).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, RoundingMode.HALF_UP);
//
////                    BigDecimal multiply = account.getCourseProjectMoneys().subtract(CancelMoney).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(add);
//                    account.setCourseRestPrice(account.getCourseRestPrice().subtract(multiply));
//                    account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(multiply.multiply(consumeRito)));
//                    BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4, RoundingMode.HALF_UP);
//                    int i1 = divide.intValue();
//                    account.setCourseConsumeCount(i1);
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }
                }
            }
            else{
                //没取消过
                //要判断是否全额还款还是部分还款

                if (totalMoney.add(docPromotion1.getCollectionCashAmount().add(docPromotion1.getCollectionRechargeAmount())).compareTo(docPromotion1.getAmount().subtract(CancelTotaMoney)) == 0) { //已经全额还款
                    //已经全部还完
                    //本次作废的还款金额
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }else{
                        account.setCourseRestPrice(account.getCourseProjectMoneys().subtract(account.getCourseRestPrice()));
                        account.setCourseConsumePrice(account.getCourseProjectMoneys().subtract(account.getCourseConsumePrice()));
                        account.setCourseRestCount(account.getCourseCounts()-account.getCourseRestCount());
                        account.setCourseConsumeCount(account.getCourseCounts()-account.getCourseConsumeCount());
                    }
                }else{
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }
                    //部分还款
//                    BigDecimal add = repayTradeList.getPayMoney();
//                    BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys(),add).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, RoundingMode.HALF_UP);
//
////                    BigDecimal multiply = account.getCourseProjectMoneys().divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(add);
//                    account.setCourseRestPrice(account.getCourseRestPrice().subtract(multiply));
//                    account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(multiply.multiply(consumeRito)));
////                    account.setCourseConsumePrice(account.getCourseRestPrice().multiply(consumeRito));
//                    BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4, RoundingMode.HALF_UP);
//                    int i1 = divide.intValue();
//                    account.setCourseConsumeCount(i1);
                }
            }



            //校验次数
            try {
                account.setPrice(repayPromotionMx1.getBeforePrice());
                account.setCourseRestPrice(repayPromotionMx1.getBeforeRestMoney());
                account.setCourseConsumePrice(repayPromotionMx1.getBeforeConsumeMoney());
                account.setCourseRestCount(repayPromotionMx1.getBeforeRestCount());
                account.setCourseConsumeCount(repayPromotionMx1.getBeforeConsumeCount());
                this.volidAccount(account);
                i = dao.updateByPrimaryKeySelective(account);
            }catch (SmsException e){
                throw new SmsException(ResponseCode.MSG,e.getMessage());
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repayCancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                BigDecimal subtract = repayPromotionMx1.getBackRestMoney().subtract(repayPromotionMx1.getBeforeRestMoney());
                AccountTradeRecord tradeRecord = this.setAccountTradeRecordPomtion(repayTradeList, account, repayList, account.getUnrecordedNumber(),subtract);
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }
        }

        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int cancelPromotionRecharge(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;

        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setPromotionDocId(debtList.getDocId());
        List<CourseAccount> select = dao.select(courseAccount);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //查询欠款可用比率
        StoreParament storeParament = this.getStorePara(debtList.getStoreId(), "debtUsable");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);

        //促销单
        DocPromotion docPromotion = new DocPromotion();
        docPromotion.setId(debtList.getDocId());
        DocPromotion docPromotion1 = ssmDocPromotionService.selectByPrimaryKey(docPromotion.getId());

        RepayAccountList repayAccountList = new RepayAccountList();
        repayAccountList.setRepayTradeId(repayTradeList.getId());
//        List<RepayAccountList> select1 = ssmRepayAccountListService.select(repayAccountList);
        //卡付总金额
//        BigDecimal reduce = select1.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

        BigDecimal totalMoney = BigDecimal.valueOf(0);
        RepayTradeList repayTradeList1 = new RepayTradeList();
        repayTradeList1.setDocId(repayTradeList.getDocId());
        repayTradeList1.setMemberId(repayTradeList.getMemberId());
        repayTradeList1.setDocType("promotion_card_use");
        List<RepayTradeList> select2 = ssmRepayTradeService.select(repayTradeList1);
        for (RepayTradeList tradeList : select2) {
            RepayList repayList1 = new RepayList();
            repayList1.setRepayNum(tradeList.getRepayNum());
            repayList1.setStoreId(tradeList.getStoreId());
            RepayList repayList2 = ssmRepayService.selectOne(repayList1);
            if(repayList2.getIsCancel()==0){
                totalMoney=totalMoney.add(tradeList.getPayMoney());
                RepayAccountList repayAccountListl = new RepayAccountList();
                repayAccountListl.setRepayTradeId(tradeList.getId());
                List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountListl);
                for (RepayAccountList accountList : select3) {
                    totalMoney=totalMoney.add(accountList.getPayMoney());
                }
            }
        }

        //查询取消欠款
        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> selectCancel = ssmCancelDebtListService.select(cancelDebtList);

        //取消的总次数
        Integer CancelTotalNum=0;
        BigDecimal CancelTotaMoney=BigDecimal.valueOf(0);
        for (CancelDebtList list : selectCancel) {
            CancelDebtMx cancelDebtMx = new CancelDebtMx();
            cancelDebtMx.setCancelDebtId(list.getId());
            List<CancelDebtMx> select3 = ssmCancelDebtMxService.select(cancelDebtMx);
            for (CancelDebtMx debtMx : select3) {
                CancelTotalNum=CancelTotalNum+debtMx.getCancelNum();
                CancelTotaMoney=CancelTotaMoney.add(debtMx.getCancelMoney());
            }
        }

        //先判断是全额还款的，进行作废充值赠送卡
        if(repayList.getPayMoney().compareTo(debtList.getDebtMoney())==0){
            //查询促销项目进行判断促销项目是什么类型
            PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion1.getPromotionId());
            //如果是买就送
            if(promotionList.getType()==1){
                //查询充值列表，判断是否有送充值卡
                PromotionListRequest promotionListRequest = new PromotionListRequest();
                promotionListRequest.setId(promotionList.getId());
                List<PromotionRechargeList> promotionRechargeListList = promotionRechargeListService.selectList(promotionListRequest);
                //根据充值卡类别和会员id查询充值卡账户并且进行扣钱
                if(promotionRechargeListList!=null && promotionRechargeListList.size()>0){
                    for (PromotionRechargeList promotionRechargeList : promotionRechargeListList) {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setMemberId(docPromotion1.getMemberId());
                        rechargeAccount.setRechargeTypeId(promotionRechargeList.getRechargeId());
                        //查询一个充值账户进行扣减金额
                        rechargeAccount = ssmRechargeAccountService.selectByMemberIdAndRechargeTypeIdAndMoney(rechargeAccount);
                        if(rechargeAccount.getCardGiftMoney().compareTo(promotionRechargeList.getRechargeMoney())==-1
                                || rechargeAccount.getGiftConsumeMoney().compareTo(promotionRechargeList.getRechargeMoney())==-1){
                            throw new SmsException(ResponseCode.MSG,"赠送的充值卡金额不足，无法作废");
                        }
                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().subtract(promotionRechargeList.getRechargeMoney()));
                        rechargeAccount.setGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney().subtract(promotionRechargeList.getRechargeMoney()));
                        DocPromotion docPromotion2 = new DocPromotion();
                        BeanUtils.copyProperties(docPromotion1,docPromotion2);
                        docPromotion2.setIsCancel(1);
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion2,promotionRechargeList,rechargeAccount);
                        ssmRechargeAccountService.updateByPrimaryKey(rechargeAccount);
                        //如果是仅本门店使用的，还要对赠送明细进行金额扣减
                        if(promotionRechargeList.getRechargeMoneyType()==1){
                            RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
                            rechargeAccountGive.setAccountId(rechargeAccount.getId());
                            List<RechargeAccountGive> select11 = ssmRechargeAccountGiveService.select(rechargeAccountGive);
                            List<RechargeAccountGive> collect = select11.stream().filter(item -> item.getStoreId() == docPromotion1.getStoreId() || item.getStoreId().toString().equals(docPromotion1.getStoreId().toString())).collect(Collectors.toList());
                            rechargeAccountGive = collect.get(0);
                            if(rechargeAccountGive.getGiftConsumeMoney().compareTo(promotionRechargeList.getRechargeMoney())==-1){
                                throw new SmsException(ResponseCode.MSG,"赠送的充值卡金额不足，无法作废");
                            }
                            rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().subtract(promotionRechargeList.getRechargeMoney()));
                            ssmRechargeAccountGiveService.updateByGifMoney(rechargeAccountGive);
                        }
                        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

                    }
                }
            }
        }


        for (CourseAccount account : select) {
            RepayPromotionMx repayPromotionMx = new RepayPromotionMx();
            repayPromotionMx.setRepayTradeId(repayTradeList.getId());
            repayPromotionMx.setAccountId(account.getId());
            RepayPromotionMx repayPromotionMx1 = ssmRepayPromotionMxService.selectOne(repayPromotionMx);

            if(repayPromotionMx1.getBackPrice().compareTo(account.getPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackRestMoney().compareTo(account.getCourseRestPrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackConsumeMoney().compareTo(account.getCourseConsumePrice())!=0){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackRestCount() != account.getCourseRestCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }
            if(repayPromotionMx1.getBackConsumeCount() != account.getCourseConsumeCount()){
                throw new SmsException(ResponseCode.MSG,"该卡包已经进行其他交易，无法作废");
            }

            int cancelBS= 0;
            //本次疗程的总次数
            Integer CancelNum=0;
            BigDecimal CancelMoney=BigDecimal.valueOf(0);
            for (CancelDebtList list : selectCancel) {
                CancelDebtMx cancelDebtMx = new CancelDebtMx();
                cancelDebtMx.setCourseId(account.getId());
                cancelDebtMx.setCancelDebtId(list.getId());
                List<CancelDebtMx> select3 = ssmCancelDebtMxService.select(cancelDebtMx);
                for (CancelDebtMx debtMx : select3) {
                    cancelBS=1;
                    CancelNum=CancelNum+debtMx.getCancelNum();
                    CancelMoney=CancelMoney.add(debtMx.getCancelMoney());
                }
            }

            RefundCourse refundCourse = new RefundCourse();
            refundCourse.setCourseAccountId(account.getId());
            List<RefundCourse> refundCourse1 = ssmRefundCourseService.select(refundCourse);
            for (RefundCourse course : refundCourse1) {
                RefundOrderList refundOrderList = new RefundOrderList();
                refundOrderList.setRefundNum(course.getRefundNum());
                refundOrderList.setStoreId(course.getStoreId());
                List<RefundOrderList> refundOrderList1 = ssmRefundOrderService.select(refundOrderList);
                for (RefundOrderList orderList : refundOrderList1) {
                    if(orderList.getState()==3){
                        throw new SmsException(ResponseCode.DATA_NOT_ALLOW_UPDATESSSS,"该疗程存在疗程退，不允许作废还款单");
                    }
                }
            }

            /**
             * 暂时不适应以下方法
             */

            //取消过次数
            if(cancelBS>0){
                if (totalMoney.add(docPromotion1.getCollectionCashAmount().add(docPromotion1.getCollectionRechargeAmount())).compareTo(docPromotion1.getAmount().subtract(CancelTotaMoney)) == 0) { //已经全额还款
//                    全部还款
//                    BigDecimal add = repayTradeList.getPayMoney();
//                    BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys().subtract(CancelMoney),add).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, RoundingMode.HALF_UP);
//
////                    BigDecimal multiply = account.getCourseProjectMoneys().subtract(CancelMoney).divide((docPromotion1.getAmount().subtract(CancelTotaMoney)), 4, RoundingMode.HALF_UP).multiply(add);
////                    BigDecimal multiply = account.getCourseProjectMoneys().divide((docPromotion1.getAmount().subtract(CancelTotaMoney)), 4, RoundingMode.HALF_UP).multiply(add);
//                    account.setCourseRestPrice(account.getCourseRestPrice().subtract(multiply));
//
//                    BigDecimal multiply1 = BigDecimalUtils.subtract(account.getCourseProjectMoneys().subtract(CancelMoney), multiply).multiply(consumeRito);
//
//
//                    account.setCourseConsumePrice(multiply1.subtract(account.getExpenditureMoney()));
//                    BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
//                    int i1 = divide.intValue();
//                    account.setCourseConsumeCount(i1);
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }


                }else{
                    //部分还款
//                    BigDecimal add = repayTradeList.getPayMoney();
//                    BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys().subtract(CancelMoney),add).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, RoundingMode.HALF_UP);
//
////                    BigDecimal multiply = account.getCourseProjectMoneys().subtract(CancelMoney).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(add);
//                    account.setCourseRestPrice(account.getCourseRestPrice().subtract(multiply));
//                    account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(multiply.multiply(consumeRito)));
//                    BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4, RoundingMode.HALF_UP);
//                    int i1 = divide.intValue();
//                    account.setCourseConsumeCount(i1);
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }
                }
            }
            else{
                //没取消过
                //要判断是否全额还款还是部分还款

                if (totalMoney.add(docPromotion1.getCollectionCashAmount().add(docPromotion1.getCollectionRechargeAmount())).compareTo(docPromotion1.getAmount().subtract(CancelTotaMoney)) == 0) { //已经全额还款
                    //已经全部还完
                    //本次作废的还款金额
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }else{
                        account.setCourseRestPrice(account.getCourseProjectMoneys().subtract(account.getCourseRestPrice()));
                        account.setCourseConsumePrice(account.getCourseProjectMoneys().subtract(account.getCourseConsumePrice()));
                        account.setCourseRestCount(account.getCourseCounts()-account.getCourseRestCount());
                        account.setCourseConsumeCount(account.getCourseCounts()-account.getCourseConsumeCount());
                    }
                }else{
                    if(account.getCourseType().equals("1")){
                        RepayTradeCourse repayTradeCourse = new RepayTradeCourse();
                        repayTradeCourse.setCourseId(account.getId());
                        repayTradeCourse.setRepayTradeId(repayTradeList.getId());
                        RepayTradeCourse repayTradeCourse1 = ssmRepayTradeCourseService.selectOne(repayTradeCourse);
                        account.setCourseRestPrice(account.getCourseRestPrice().subtract(repayTradeCourse1.getMoney()));
                        account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(repayTradeCourse1.getCoumMoney()));
                        BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4,RoundingMode.HALF_UP);
                        int i1 = divide.intValue();
                        account.setCourseConsumeCount(i1);
                    }
                    //部分还款
//                    BigDecimal add = repayTradeList.getPayMoney();
//                    BigDecimal multiply = BigDecimalUtils.multiply(account.getCourseProjectMoneys(),add).divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, RoundingMode.HALF_UP);
//
////                    BigDecimal multiply = account.getCourseProjectMoneys().divide(docPromotion1.getAmount().subtract(CancelTotaMoney), 4, BigDecimal.ROUND_HALF_UP).multiply(add);
//                    account.setCourseRestPrice(account.getCourseRestPrice().subtract(multiply));
//                    account.setCourseConsumePrice(account.getCourseConsumePrice().subtract(multiply.multiply(consumeRito)));
////                    account.setCourseConsumePrice(account.getCourseRestPrice().multiply(consumeRito));
//                    BigDecimal divide = account.getCourseConsumePrice().divide(account.getPrice(), 4, RoundingMode.HALF_UP);
//                    int i1 = divide.intValue();
//                    account.setCourseConsumeCount(i1);
                }
            }



            //校验次数
            try {
                account.setPrice(repayPromotionMx1.getBeforePrice());
                account.setCourseRestPrice(repayPromotionMx1.getBeforeRestMoney());
                account.setCourseConsumePrice(repayPromotionMx1.getBeforeConsumeMoney());
                account.setCourseRestCount(repayPromotionMx1.getBeforeRestCount());
                account.setCourseConsumeCount(repayPromotionMx1.getBeforeConsumeCount());
                this.volidAccount(account);
                i = dao.updateByPrimaryKeySelective(account);
            }catch (SmsException e){
                throw new SmsException(ResponseCode.MSG,e.getMessage());
            } catch (Exception e) {
                log.error("SsmCourseAccountServiceImpl.repayCancel:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0) {
                BigDecimal subtract = repayPromotionMx1.getBackRestMoney().subtract(repayPromotionMx1.getBeforeRestMoney());
                AccountTradeRecord tradeRecord = this.setAccountTradeRecordPomtion(repayTradeList, account, repayList, account.getUnrecordedNumber(),subtract);
                ssmAccountTradeRecordService.addRecord(tradeRecord);
                ssmDebtService.updateNotNull(debtList);
            }
        }

        return i;
    }

    public AccountTradeRecord setAccountTradeRecord(RepayTradeList repayTradeList, CourseAccount courseAccount, RepayList repayList, int addCount) {
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayTradeList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeList.getStoreName());
        accountTradeRecord.setMemberId(repayTradeList.getMemberId());
        accountTradeRecord.setMemberName(repayTradeList.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeList.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());

        if (repayList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_course_repay);
            accountTradeRecord.setAccountInCount(addCount);
            accountTradeRecord.setInputDate(repayList.getRepayDate());
            accountTradeRecord.setInputBy(repayList.getInputBy());
            accountTradeRecord.setAccountInMoney(repayList.getPayMoney());
            accountTradeRecord.setOrderStatu(0);
        } else {
            accountTradeRecord.setAccountType(Constant.account_type_course_repay_cancel);
            accountTradeRecord.setInputDate(repayList.getCancelDate());
            accountTradeRecord.setAccountInCount(addCount);
            accountTradeRecord.setInputBy(repayList.getCancelBy());
            accountTradeRecord.setAccountSpendMoney(repayList.getPayMoney());
            accountTradeRecord.setOrderStatu(1);
        }
        accountTradeRecord.setDocId(repayList.getId());
        accountTradeRecord.setDocNum(repayList.getRepayNum());
        accountTradeRecord.setDocType(Constant.doc_type_repay);
        accountTradeRecord.setTradeId(repayTradeList.getTradeId());
        accountTradeRecord.setTradeName(repayTradeList.getTradeName());
        accountTradeRecord.setTradeMoney(repayTradeList.getTradeMoney());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        accountTradeRecord.setPrice(repayList.getPayMoney());
        accountTradeRecord.setAccountRestMoney(courseAccount.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(courseAccount.getCourseConsumePrice());
        return accountTradeRecord;
    }

    public AccountTradeRecord setAccountTradeRecordPomtion(RepayTradeList repayTradeList, CourseAccount courseAccount, RepayList repayList, int addCount) {
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayTradeList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeList.getStoreName());
        accountTradeRecord.setMemberId(repayTradeList.getMemberId());
        accountTradeRecord.setMemberName(repayTradeList.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeList.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());

        if (repayList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_course_repay_promotion);
            accountTradeRecord.setAccountInCount(addCount);
            accountTradeRecord.setInputDate(repayList.getRepayDate());
            accountTradeRecord.setInputBy(repayList.getInputBy());
            accountTradeRecord.setAccountInMoney(repayList.getPayMoney());
            accountTradeRecord.setOrderStatu(0);
        } else {
            accountTradeRecord.setAccountType(Constant.account_type_course_repay_cancel_promotion);
            accountTradeRecord.setInputDate(repayList.getCancelDate());
            accountTradeRecord.setAccountInCount(addCount);
            accountTradeRecord.setInputBy(repayList.getCancelBy());
            accountTradeRecord.setAccountSpendMoney(repayList.getPayMoney());
            accountTradeRecord.setOrderStatu(1);

        }
        accountTradeRecord.setDocId(repayList.getId());
        accountTradeRecord.setDocNum(repayList.getRepayNum());
        accountTradeRecord.setDocType(Constant.doc_type_repay_promotion);
        accountTradeRecord.setTradeId(courseAccount.getId());
        accountTradeRecord.setTradeName(courseAccount.getCourseProjectName());
        accountTradeRecord.setTradeMoney(repayTradeList.getTradeMoney());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        accountTradeRecord.setPrice(repayList.getPayMoney());
        accountTradeRecord.setAccountRestMoney(courseAccount.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(courseAccount.getCourseConsumePrice());
        return accountTradeRecord;
    }

    public AccountTradeRecord setAccountTradeRecordPomtion(RepayTradeList repayTradeList, CourseAccount courseAccount, RepayList repayList, int addCount,BigDecimal Money) {
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayTradeList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeList.getStoreName());
        accountTradeRecord.setMemberId(repayTradeList.getMemberId());
        accountTradeRecord.setMemberName(repayTradeList.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeList.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());

        if (repayList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_course_repay_promotion);
            accountTradeRecord.setAccountInCount(addCount);
            accountTradeRecord.setInputDate(repayList.getRepayDate());
            accountTradeRecord.setInputBy(repayList.getInputBy());
            if(courseAccount.getCourseType().equals("2")){
                accountTradeRecord.setAccountInMoney(BigDecimal.valueOf(0));
            }else{
                accountTradeRecord.setAccountInMoney(Money);
            }

            accountTradeRecord.setOrderStatu(0);
        } else {
            accountTradeRecord.setAccountType(Constant.account_type_course_repay_cancel_promotion);
            accountTradeRecord.setInputDate(repayList.getCancelDate());
            accountTradeRecord.setAccountInCount(addCount);
            accountTradeRecord.setInputBy(repayList.getCancelBy());
            if(courseAccount.getCourseType().equals("2")){
                accountTradeRecord.setAccountSpendMoney(BigDecimal.valueOf(0));
            }else{
                accountTradeRecord.setAccountSpendMoney(Money);
            }
            accountTradeRecord.setOrderStatu(1);

        }
        accountTradeRecord.setDocId(repayList.getId());
        accountTradeRecord.setDocNum(repayList.getRepayNum());
        accountTradeRecord.setDocType(Constant.doc_type_repay_promotion);
        accountTradeRecord.setTradeId(courseAccount.getId());
        accountTradeRecord.setTradeName(courseAccount.getCourseProjectName());
        accountTradeRecord.setTradeMoney(repayTradeList.getTradeMoney());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        accountTradeRecord.setPrice(repayList.getPayMoney());
        accountTradeRecord.setAccountRestMoney(courseAccount.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(courseAccount.getCourseConsumePrice());
        return accountTradeRecord;
    }

    public StoreParament getStorePara(Long storeId, String key) {
        StoreParament storeParament = new StoreParament();
        storeParament.setStoreId(storeId);
        storeParament.setParamentName(key);
        storeParament = ssmStoreParaService.selectOne(storeParament);
        return storeParament;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateState(Long id, int state) {
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setState(state);
        courseAccount.setId(id);
        return dao.updateByPrimaryKeySelective(courseAccount);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount subCount(RefundCourse refundCourse) throws SmsException {
        CourseAccount courseAccount = dao.selectByPrimaryKey(refundCourse.getCourseAccountId());
        if(BigDecimalUtils.compareTo(courseAccount.getCourseRestPrice(),courseAccount.getCourseConsumePrice())!=0 &&BigDecimalUtils.compareTo(courseAccount.getCourseRestPrice(),refundCourse.getCourseRefundMoney())!=0 && BigDecimalUtils.compareTo(courseAccount.getCourseConsumePrice(),refundCourse.getCourseRefundMoney())==-1 ){
            throw new SmsException(ResponseCode.MSG,"存在欠款时，取款的金额最大只能等于可用金额，或者全部退");
        }

        refundCourse.setBeforePrice(courseAccount.getPrice());
        refundCourse.setBeforeRestMoney(courseAccount.getCourseRestPrice());
        refundCourse.setBeforeConsumeMoney(courseAccount.getCourseConsumePrice());
        refundCourse.setBeforeRestCount(courseAccount.getCourseRestCount());
        refundCourse.setBeforeConsumeCount(courseAccount.getCourseConsumeCount());

        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().add(refundCourse.getCourseRefundMoney()));

        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() - refundCourse.getRefundNumber());
        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().subtract(refundCourse.getCourseRefundMoney()));

        if(courseAccount.getCourseRestCount() != 0){
            if(courseAccount.getCourseProjectMoney().subtract(courseAccount.getExpenditureMoney()).compareTo(BigDecimal.valueOf(0))==1){
                courseAccount.setPrice((courseAccount.getCourseProjectMoney().subtract(courseAccount.getExpenditureMoney())).divide(BigDecimal.valueOf(courseAccount.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
            }
        }
        if(courseAccount.getCourseConsumeCount() >= refundCourse.getRefundNumber()){
            courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() - refundCourse.getRefundNumber());
//            StoreParament storeParament = new StoreParament();
//            storeParament.setStoreId(courseAccount.getStoreId());
//            storeParament.setParamentName(Constant.debt_usable);
//            storeParament = ssmStoreParaService.selectOne(storeParament);
            courseAccount.setCourseConsumePrice(new BigDecimal(
//                    storeParament.getParamentValue())
//                    .divide(BigDecimal.valueOf(100),4,4)
//                    .multiply(
                    String.valueOf(courseAccount.getCourseRestPrice())
                    )
            );
        }else{
            courseAccount.setCourseConsumeCount(0);
            courseAccount.setCourseConsumePrice(BigDecimal.valueOf(0));
        }

        this.volidAccount(courseAccount);

        refundCourse.setBackPrice(courseAccount.getPrice());
        refundCourse.setBackRestMoney(courseAccount.getCourseRestPrice());
        refundCourse.setBackConsumeMoney(courseAccount.getCourseConsumePrice());
        refundCourse.setBackRestCount(courseAccount.getCourseRestCount());
        refundCourse.setBackConsumeCount(courseAccount.getCourseConsumeCount());
        ssmRefundCourseService.updateByPrimaryKey(refundCourse);
        dao.updateByPrimaryKeySelective(courseAccount);
        return courseAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public CourseAccount addCount(RefundCourse refundCourse) throws SmsException {
        CourseAccount courseAccount = dao.selectByPrimaryKey(refundCourse.getCourseAccountId());
        if((refundCourse.getBackPrice()==null?BigDecimal.ZERO:refundCourse.getBackPrice()).compareTo(courseAccount.getPrice())!=0){
            throw new SmsException(ResponseCode.MSG,"该卡包审核后已经进行其他交易，无法审核");
        }
        if(refundCourse.getBackRestMoney().compareTo(courseAccount.getCourseRestPrice())!=0){
            throw new SmsException(ResponseCode.MSG,"该卡包审核后已经进行其他交易，无法审核");
        }
        if(refundCourse.getBackConsumeMoney().compareTo(courseAccount.getCourseConsumePrice())!=0){
            throw new SmsException(ResponseCode.MSG,"该卡包审核后已经进行其他交易，无法审核");
        }
        if(refundCourse.getBackRestCount() != courseAccount.getCourseRestCount()){
            throw new SmsException(ResponseCode.MSG,"该卡包审核后已经进行其他交易，无法审核");
        }
        if(refundCourse.getBackConsumeCount() != courseAccount.getCourseConsumeCount()){
            throw new SmsException(ResponseCode.MSG,"该卡包审核后已经进行其他交易，无法审核");
        }

        courseAccount.setCourseRestCount(courseAccount.getCourseRestCount() + refundCourse.getRefundNumber());
        courseAccount.setCourseRestPrice(courseAccount.getCourseRestPrice().add(refundCourse.getCourseRefundMoney()));
        courseAccount.setPrice(courseAccount.getCourseRestPrice().divide(BigDecimal.valueOf(courseAccount.getCourseRestCount()),2,BigDecimal.ROUND_HALF_UP));
        if(refundCourse.getCourseConsumeCount().compareTo(refundCourse.getRefundNumber())>-1){
            courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() + refundCourse.getRefundNumber());
            courseAccount.setCourseConsumePrice(courseAccount.getCourseConsumePrice().add(refundCourse.getCourseRefundMoney()));
        }else{
            courseAccount.setCourseConsumeCount(courseAccount.getCourseConsumeCount() + refundCourse.getCourseConsumeCount());
            courseAccount.setCourseConsumePrice(BigDecimal.valueOf(0));
        }
        courseAccount.setExpenditureMoney(courseAccount.getExpenditureMoney().subtract(refundCourse.getCourseRefundMoney()));
        courseAccount.setPrice(refundCourse.getBeforePrice());
        courseAccount.setCourseRestPrice(refundCourse.getBeforeRestMoney());
        courseAccount.setCourseConsumePrice(refundCourse.getBeforeConsumeMoney());
        courseAccount.setCourseRestCount(refundCourse.getBeforeRestCount());
        courseAccount.setCourseConsumeCount(refundCourse.getBeforeConsumeCount());
        dao.updateByPrimaryKeySelective(courseAccount);
        return courseAccount;
    }

    public CourseAccount volidAccount(CourseAccount courseAccount) throws SmsException {
        if (courseAccount.getCourseRestCount() < 0){
            throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余次数");

        }
        if (courseAccount.getCourseConsumeCount() < 0){
            throw new SmsException(ResponseCode.IS_INSUFFICIENT,"疗程账户剩余可用次数");
        }
        return courseAccount;
    }

    @Override
    public CourseAccount addCourseAccount(CourseAccount courseAccount, PromotionProject promotionProject, Integer limitCount) throws SmsException {
        int i = 0;

        Integer restCount = promotionProject.getTimes() * limitCount;
        Integer consumeCount = promotionProject.getTimes() * limitCount;

        courseAccount.setCourseProjectId(promotionProject.getProjectId());
        courseAccount.setCourseProjectName(promotionProject.getProjectName());

        courseAccount.setCourseCount(promotionProject.getTimes() * limitCount);
        //促销添加的账户不在按次数和单价重新计算 直接使用设置时的包内价
//        courseAccount.setCourseProjectMoney(BigDecimalUtils.multiply(promotionProject.getPriceMember(),BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString())));
//        courseAccount.setCourseProjectMoney(promotionProject.getProjectTotalMoney().multiply(BigDecimal.valueOf(limitCount)));
        courseAccount.setCourseProjectMoney(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(courseAccount.getCourseCount())));

//        courseAccount.setCourseRestPrice(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(restCount)));
//        courseAccount.setCourseConsumePrice(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(restCount)));
        courseAccount.setCourseRestPrice(promotionProject.getProjectTotalMoney());
        courseAccount.setCourseConsumePrice(promotionProject.getProjectTotalMoney());

        courseAccount.setCourseConsumeCount(consumeCount);
        courseAccount.setCourseRestCount(restCount);
        courseAccount.setCourseStandardCount(promotionProject.getTimes()*limitCount);
//        courseAccount.setCourseStandardMoney(promotionProject.getStandardMoney().multiply(BigDecimal.valueOf(limitCount)));
        courseAccount.setCourseStandardMoney(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(courseAccount.getCourseStandardCount())));
        courseAccount.setState(1);
//        courseAccount.setPrice(promotionProject.getProjectTotalMoney().divide(BigDecimal.valueOf(promotionProject.getTimes()),3,BigDecimal.ROUND_HALF_UP));
        courseAccount.setPrice(promotionProject.getPriceMember());

        courseAccount.setCourseCounts(courseAccount.getCourseCount());
        courseAccount.setCourseProjectMoneys(courseAccount.getCourseProjectMoney());

        //有效期为空，截至日期不为空
        if ((null == promotionProject.getValidTime() || 0 == promotionProject.getValidTime()) && null != promotionProject.getUseEndDate()){
            //使用截至日期
            courseAccount.setEndTime(promotionProject.getUseEndDate());
        }else if (null != promotionProject.getValidTime() && 0 != promotionProject.getValidTime()){
            Date date = new Date();
            courseAccount.setEndTime(DateUtils.diffMonth(date, promotionProject.getValidTime()));
        }

        //是否使用有效期
        /*StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
            //PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(promotionProject.getPromotionId());
            *//*Integer validTime = promotionList.getValidTime();
            if (null != validTime){
                courseAccount.setEndTime(DateUtils.diffMonth(date, validTime));
            }else {
                if(null != project.getValidTime() && 0 != project.getValidTime()){
                    courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
                }
            }*//*
            if(null != project.getValidTime() && 0 != project.getValidTime()){
                courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
            }

        }*/
        try {
            i = dao.saveNotNull(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.addCourseAccount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    public CourseAccount addCourseAccountByPromotionRecharge(CourseAccount courseAccount, PromotionProject promotionProject, Integer limitCount) throws SmsException {
        int i = 0;

        Integer restCount = promotionProject.getTimes() * limitCount;
        Integer consumeCount = promotionProject.getTimes() * limitCount;

        courseAccount.setCourseProjectId(promotionProject.getProjectId());
        courseAccount.setCourseProjectName(promotionProject.getProjectName());

        courseAccount.setCourseCount(promotionProject.getTimes() * limitCount);
        //促销添加的账户不在按次数和单价重新计算 直接使用设置时的包内价
//        courseAccount.setCourseProjectMoney(BigDecimalUtils.multiply(promotionProject.getPriceMember(),BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString())));
//        courseAccount.setCourseProjectMoney(promotionProject.getProjectTotalMoney().multiply(BigDecimal.valueOf(limitCount)));
        courseAccount.setCourseProjectMoney(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(courseAccount.getCourseCount())));

//        courseAccount.setCourseRestPrice(promotionProject.getProjectTotalMoney().multiply(BigDecimal.valueOf(limitCount)));
        courseAccount.setCourseRestPrice(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(restCount)));
//        courseAccount.setCourseConsumePrice(promotionProject.getProjectTotalMoney().multiply(BigDecimal.valueOf(limitCount)));
        courseAccount.setCourseConsumePrice(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(restCount)));

        courseAccount.setCourseConsumeCount(consumeCount);
        courseAccount.setCourseRestCount(restCount);
        courseAccount.setCourseStandardCount(promotionProject.getTimes()*limitCount);
//        courseAccount.setCourseStandardMoney(promotionProject.getStandardMoney().multiply(BigDecimal.valueOf(limitCount)));
        courseAccount.setCourseStandardMoney(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(courseAccount.getCourseStandardCount())));
        courseAccount.setState(1);
//        courseAccount.setPrice(promotionProject.getProjectTotalMoney().divide(BigDecimal.valueOf(promotionProject.getTimes()),3,BigDecimal.ROUND_HALF_UP));
        courseAccount.setPrice(promotionProject.getPriceMember());

        courseAccount.setCourseCounts(courseAccount.getCourseCount());
        courseAccount.setCourseProjectMoneys(courseAccount.getCourseProjectMoney());

        //有效期为空，截至日期不为空
        if ((null == promotionProject.getValidTime() || 0 == promotionProject.getValidTime()) && null != promotionProject.getUseEndDate()){
            //使用截至日期
            courseAccount.setEndTime(promotionProject.getUseEndDate());
        }else if (null != promotionProject.getValidTime() && 0 != promotionProject.getValidTime()){
            Date date = new Date();
            courseAccount.setEndTime(DateUtils.diffMonth(date, promotionProject.getValidTime()));
        }

        //是否使用有效期
        /*StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
            //PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(promotionProject.getPromotionId());
            *//*Integer validTime = promotionList.getValidTime();
            if (null != validTime){
                courseAccount.setEndTime(DateUtils.diffMonth(date, validTime));
            }else {
                if(null != project.getValidTime() && 0 != project.getValidTime()){
                    courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
                }
            }*//*
            if(null != project.getValidTime() && 0 != project.getValidTime()){
                courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
            }

        }*/
        courseAccount.setPrice(BigDecimal.ZERO);
        courseAccount.setCourseRestPrice(BigDecimal.ZERO);
        courseAccount.setCourseConsumePrice(BigDecimal.ZERO);
        courseAccount.setCourseProjectMoney(BigDecimal.ZERO);
        courseAccount.setCourseStandardMoney(BigDecimal.ZERO);
        try {
            i = dao.saveNotNull(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.addCourseAccount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }
    @Override
    public CourseAccount addCourseAccount(CourseAccount courseAccount, PromotionProject promotionProject, Integer limitCount,DocPromotion docPromotion, BigDecimal TotalMoney) throws SmsException {
        int i = 0;
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
//        StoreParament storePara = StoreParaUtils.getStorePara(docPromotion.getStoreId(), Constant.promotionUsable);
        StoreParament storePara = StoreParaUtils.getStorePara(docPromotion.getStoreId(), Constant.debt_usable);
        //可用比率 = 门店参数/100
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storePara.getParamentValue()), hundredBd);

        Integer restCount = promotionProject.getTimes() * limitCount;
        Integer consumeCount = promotionProject.getTimes() * limitCount;

        courseAccount.setCourseProjectId(promotionProject.getProjectId());
        courseAccount.setCourseProjectName(promotionProject.getProjectName());

        courseAccount.setCourseCount(promotionProject.getTimes() * limitCount);
        //促销添加的账户不在按次数和单价重新计算 直接使用设置时的包内价
//        courseAccount.setCourseProjectMoney(BigDecimalUtils.multiply(promotionProject.getPriceMember(),BigDecimalUtils.bigDecimal(courseAccount.getCourseCount().toString())));
        courseAccount.setCourseProjectMoney(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(limitCount)));

        //计算当前项目占有的付款金额
        //支付金额
        BigDecimal add = docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount());

        BigDecimal courseRestPrice = add.multiply(promotionProject.getProjectTotalMoney().divide(TotalMoney, 7, BigDecimal.ROUND_HALF_UP));
        courseAccount.setPromotionDocId(docPromotion.getId());
        if(0==promotionProject.getType()){
            courseAccount.setCourseRestPrice(courseRestPrice);
            courseAccount.setCourseConsumePrice(courseRestPrice.multiply(consumeRito));

            courseAccount.setCourseConsumeCount((courseAccount.getCourseConsumePrice().divide(promotionProject.getPriceMember(),7,BigDecimal.ROUND_HALF_UP)).intValue());
            courseAccount.setCourseRestCount((courseRestPrice.divide(promotionProject.getPriceMember(),7,BigDecimal.ROUND_HALF_UP)).intValue());
            courseAccount.setCourseStandardCount(promotionProject.getTimes()*limitCount);
            courseAccount.setCourseStandardMoney(promotionProject.getPriceMember().multiply(BigDecimal.valueOf(limitCount)));
            courseAccount.setState(1);
            courseAccount.setPrice(promotionProject.getPriceMember());

            courseAccount.setCourseCounts(courseAccount.getCourseCount());
            courseAccount.setCourseProjectMoneys(courseAccount.getCourseProjectMoney());
            courseAccount.setUnrecordedNumber(restCount-courseAccount.getCourseRestCount());
            courseAccount.setUnrecordedAmount(
//                    BigDecimalUtils.subtract(
                    docPromotion.getDebtMoney()
                            .multiply(
                                    courseAccount.getPrice()
                                    .multiply(BigDecimal.valueOf(courseAccount.getCourseCount()))
                                            .divide(docPromotion.getAmount(),4,BigDecimal.ROUND_HALF_UP))
//                    courseAccount.getCourseRestPrice())
                    );
        }else{
            courseAccount.setCourseRestPrice(BigDecimal.valueOf(0));
            courseAccount.setCourseConsumePrice(BigDecimal.valueOf(0));

            courseAccount.setCourseConsumeCount(0);
            courseAccount.setCourseRestCount(0);
            courseAccount.setCourseStandardCount(promotionProject.getTimes()*limitCount);
            courseAccount.setCourseStandardMoney(promotionProject.getStandardMoney().multiply(BigDecimal.valueOf(limitCount)));
            courseAccount.setState(1);
            courseAccount.setPrice(promotionProject.getPriceMember());

            courseAccount.setCourseCounts(courseAccount.getCourseCount());
            courseAccount.setCourseProjectMoneys(courseAccount.getCourseProjectMoney());
            courseAccount.setUnrecordedNumber(restCount);
            courseAccount.setUnrecordedAmount(promotionProject.getProjectTotalMoney().multiply(BigDecimal.valueOf(limitCount)));
        }
        courseAccount.setCancelMoney(BigDecimal.valueOf(0));
        courseAccount.setCancelNum(0);
        courseAccount.setCourseRestCount(restCount);

        //有效期为空，截至日期不为空
        if ((null == promotionProject.getValidTime() || 0 == promotionProject.getValidTime()) && null != promotionProject.getUseEndDate()){
            //使用截至日期
            courseAccount.setEndTime(promotionProject.getUseEndDate());
        }else if (null != promotionProject.getValidTime() && 0 != promotionProject.getValidTime()){
            Date date = new Date();
            courseAccount.setEndTime(DateUtils.diffMonth(date, promotionProject.getValidTime()));
        }

        //是否使用有效期
        /*StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());

            *//*PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(promotionProject.getPromotionId());
            Integer validTime = promotionList.getValidTime();
            if (null != validTime){
                courseAccount.setEndTime(DateUtils.diffMonth(date, validTime));
            }else {
                if(null != project.getValidTime() && 0 != project.getValidTime()){
                    courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
                }
            }*//*

            if(null != project.getValidTime() && 0 != project.getValidTime()){
                courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
            }
        }*/
        try {
            i = dao.saveNotNull(courseAccount);
        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.addCourseAccount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    public CourseAccount subCourseAccount(DocPromotion promotion, PromotionProject promotionProject) throws SmsException {
        return null;
    }

    @Override
    public int update(CourseAccountRequest courseAccountRequest, String phone) {
        int i = 0;
        CourseAccount courseAccount = new CourseAccount();
        BeanUtils.copyProperties(courseAccountRequest, courseAccount);
        //设置录单人信息
        if (redisClient.hasKey(getStaffKey(phone))){
            StaffResponse staffResponse = redisClient.get(getStaffKey(phone));
            courseAccount.setUpdateId(staffResponse.getId());
            courseAccount.setUpdateBy(staffResponse.getStaffName());
            courseAccount.setUpdateTime(new Date());
        }
        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccountRequest.getStoreId(), Constant.allow_valid);
//        if ("1".equals(parament.getParamentValue())) {
//            i = dao.updateByPrimaryKeySelective(courseAccount);
//        }
        i = dao.updateByPrimaryKeySelective(courseAccount);
        return i;
    }

    @Override
    public int insertBatch(List<CourseAccount> list, Long storeId, String storeName) {
        for (CourseAccount courseAccount : list) {
            courseAccount.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            courseAccount.setStoreId(storeId);
            courseAccount.setStoreName(storeName);
        }
        return dao.insertBatch(list);
    }

    @Override
    public List<CourseAccountResponse> memberCourse(CourseAccountRequest courseAccountRequest) {
        return dao.memberCourse(courseAccountRequest);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public CourseAccount addCourseAccount(CourseAccount courseAccount, CardChangeList cardChangeList, CardChangeInProject cardChangeInProject) throws SmsException {
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        Integer consumeCount = 0;
        Integer restCount = 0;
        int i=0;
        //欠款
        if (BigDecimalUtils.compareTo(cardChangeList.getDebtMoney(), BigDecimalUtils.bigDecimal("0")) == 1) {
            //可用比率 = 门店参数/100
            StoreParament storeParament = StoreParaUtils.getStorePara(cardChangeList.getStoreId(), Constant.cardCangeListDebtUsable);
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()), hundredBd);
            courseAccount.setCourseRestPrice(cardChangeList.getChangeOutMoney().add(cardChangeList.getChangeInPayMoney()));
            courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice().multiply(consumeRito));
            restCount = BigDecimalUtils.div(BigDecimalUtils.multiply(cardChangeInProject.getChangeInMoney(),BigDecimalUtils.bigDecimal(cardChangeInProject.getChangeInTime().toString())), cardChangeInProject.getTransactionMoney()).setScale(0,BigDecimal.ROUND_DOWN).intValue();
            consumeCount = BigDecimalUtils.multiply(BigDecimalUtils.div(BigDecimalUtils.multiply(cardChangeList.getChangeOutMoney().add(cardChangeList.getChangeInPayMoney()),BigDecimalUtils.bigDecimal(cardChangeInProject.getChangeInTime().toString())), cardChangeInProject.getTransactionMoney()), consumeRito).setScale(0,BigDecimal.ROUND_DOWN).intValue();
        } else {
            restCount = cardChangeInProject.getChangeInTime();
            consumeCount = cardChangeInProject.getChangeInTime();
            courseAccount.setCourseRestPrice(cardChangeList.getChangeOutMoney().add(cardChangeList.getChangeInPayMoney()));
            courseAccount.setCourseConsumePrice(courseAccount.getCourseRestPrice());
        }


        courseAccount.setCourseProjectId(cardChangeInProject.getProjectId());
        courseAccount.setCourseProjectName(cardChangeInProject.getProjectName());
        courseAccount.setCourseProjectMoney(cardChangeInProject.getTransactionMoney());
        courseAccount.setCourseCount(cardChangeInProject.getChangeInTime());
        courseAccount.setCourseProjectMoneys(cardChangeInProject.getTransactionMoney());
        courseAccount.setCourseCounts(cardChangeInProject.getChangeInTime());
        courseAccount.setCourseStandardCount(cardChangeInProject.getMinumumTimes());

        //标准价改为最少销售次数 * 单价
        courseAccount.setCourseStandardMoney(BigDecimalUtils.multiply(BigDecimalUtils.bigDecimal(cardChangeInProject.getMinumumTimes().toString()),cardChangeInProject.getPriceMember()));
        courseAccount.setCourseConsumeCount(consumeCount);
        courseAccount.setCourseRestCount(restCount);
        courseAccount.setState(1);
        courseAccount.setExpenditureMoney(BigDecimal.valueOf(0));
        courseAccount.setPrice(courseAccount.getCourseProjectMoney().divide(BigDecimalUtils.bigDecimal(courseAccount.getCourseRestCount().toString()),4,BigDecimal.ROUND_HALF_UP));
        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccount.getStoreId(), Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            if (cardChangeList.getIsAddition() == 1){
                date = cardChangeList.getAdditionDate();
            }
            BaseProject project = ssmProjectService.selectByPrimaryKey(courseAccount.getCourseProjectId());
            if(null != project.getValidTime() && 0 != project.getValidTime()){
                courseAccount.setEndTime(DateUtils.diffMonth(date, project.getValidTime()));
            }

        }
        try {

            i = dao.updateByPrimaryKeySelective(courseAccount);
            CourseAccount courseAccount1 = dao.selectByPrimaryKey(courseAccount.getId());
            if(null == courseAccount1){
                dao.saveNotNull(courseAccount);
            }else{
                dao.updateByPrimaryKeySelective(courseAccount);
            }

        } catch (Exception e) {
            log.error("ssmCourseAccountServiceImpl.addCourseAccount:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return courseAccount;
    }

    @Override
    public List<CourseAccount> selectListByJZ(CourseAccountRequest courseAccountRequest) {
        List<CourseAccount> objects = new ArrayList<>();
        List<CourseAccount> objectsa = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
//        storeRequest.setId(courseAccountRequest.getStoreId());
//        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
//        for (BaseStores pagesorganization : pagesorganizations) {
//
//        }
        courseAccountRequest.setStoreId(courseAccountRequest.getStoreId());
        Example example = new Example(CourseAccount.class);
        Example.Criteria criteria = example.createCriteria();
        example.setOrderByClause("id asc");
        if(courseAccountRequest.getIfstorid()!=null){
            criteria.andEqualTo("storeId", courseAccountRequest.getIfstorid());
        }
        criteria.andEqualTo("memberId", courseAccountRequest.getMemberId());
        if(null != courseAccountRequest.getCourseProjectId()){
            criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
        }

        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(courseAccountRequest.getStoreId(), Constant.allow_valid);
        if(null != parament){
//            if ("1".equals(parament.getParamentValue())) {
//                criteria.andGreaterThanOrEqualTo("endTime", DateUtils.ymdFormat(new Date()));
//            }

            if (courseAccountRequest.getCourseProjectId() != null) {
                criteria.andEqualTo("courseProjectId", courseAccountRequest.getCourseProjectId());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseProjectName())) {
                criteria.andLike("courseProjectName", "%" + courseAccountRequest.getCourseProjectName() + "%");
            }

            //疗程退相关条件
            if (courseAccountRequest.getCourseTypes() != null){
                criteria.andIn("courseType",courseAccountRequest.getCourseTypes());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseType())){
                criteria.andEqualTo("courseType",courseAccountRequest.getCourseType());
            }
            if (StringUtils.isNotBlank(courseAccountRequest.getCourseNum())){//疗程退查询促销活动时 展示促销疗程账户 次数为0页展示
                criteria.andEqualTo("courseNum",courseAccountRequest.getCourseNum());
            }else {
                criteria.andGreaterThanOrEqualTo("courseConsumeCount", 1);
                //criteria.andGreaterThanOrEqualTo("courseRestPrice", 1);
            }
            List<CourseAccount> courseAccounts = dao.selectByExample(example);
            for (CourseAccount courseAccount : courseAccounts) {

                objects.add(courseAccount);
            }
        }
        for (CourseAccount courseAccount : objects) {
//            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
//            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(BigDecimal.valueOf(courseAccount.getCourseRestCount()),BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount()))));
            //courseAccount.setPrice((BigDecimalUtils.div(courseAccount.getCourseProjectMoney(),BigDecimal.valueOf(courseAccount.getCourseStandardCount())).setScale(2)).multiply(BigDecimal.valueOf(1)));
//            courseAccount.setCourseRestPrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseRestCount())));
//            courseAccount.setCourseConsumePrice(BigDecimalUtils.multiply(courseAccount.getPrice(),BigDecimal.valueOf(courseAccount.getCourseConsumeCount())));
            //courseAccount.setPrice(courseAccount.getPrice().setScale(2));
            BaseProject baseProject1 = new BaseProject();
            baseProject1.setId(courseAccount.getCourseProjectId());
            BaseProject baseProject = ssmProjectService.selectOne(baseProject1);
            if(null != baseProject){
                courseAccount.setCourseProjectNum(baseProject.getProjectNum());
            }
            StoreRequest storeRequest1 = new StoreRequest();
            storeRequest1.setId(courseAccount.getStoreId());
            BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest1);
            courseAccount.setStoreNum(baseStore.getStoreNum());
            if(null == baseProject.getUnifiedDue()){
                if(null == courseAccount.getEndTime()){
                    objectsa.add(courseAccount);
                }else{

                    if (null != courseAccount.getPromotionDocId()){
                        DocPromotion docPromotion = ssmDocPromotionService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                        //DocPromotionProject docPromotionProject = ssmDocPromotionProjectService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                        PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion.getPromotionId());
                        //适用门店对象0:所有门店/1:指定门店
                        if (promotionList.getSuitableStore() == 0){
                            if (null == courseAccount.getEndTime()){
                                objectsa.add(courseAccount);
                            }else if (null != courseAccount.getEndTime() && courseAccount.getEndTime().after(new Date())){
                                objectsa.add(courseAccount);
                            }
                        }else {
                            PromotionStore promotionStore = new PromotionStore();
                            promotionStore.setPromotionId(promotionList.getId());
                            List<PromotionStore> promotionStores = ssmPromotionStoreService.selectList(promotionStore);
                            for (PromotionStore store : promotionStores) {
                                if (Objects.equals(courseAccount.getStoreId(), store.getStoreId())){
                                    objectsa.add(courseAccount);
                                }
                            }
                        }
                    }else {
                        if ("1".equals(parament.getParamentValue())) {
                            if(courseAccount.getEndTime().after(new Date())){
                                objectsa.add(courseAccount);
                            }
                        }else{
                            objectsa.add(courseAccount);
                        }
                    }


                    /*if ("1".equals(parament.getParamentValue())) {
                        if(courseAccount.getEndTime().after(new Date())){
                            objectsa.add(courseAccount);
                        }
                    }else{
                        objectsa.add(courseAccount);
                    }*/
                }

            }
            else{
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                try {
                    Date parse = format.parse(baseProject.getUnifiedDue());
                    if(new Date().before(parse)){
                        if(null == courseAccount.getEndTime()){
                            objectsa.add(courseAccount);
                        }else{

                            if (null != courseAccount.getPromotionDocId()){
                                DocPromotion docPromotion = ssmDocPromotionService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                                //DocPromotionProject docPromotionProject = ssmDocPromotionProjectService.selectByPrimaryKey(courseAccount.getPromotionDocId());
                                PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion.getPromotionId());
                                //适用门店对象0:所有门店/1:指定门店
                                if (promotionList.getSuitableStore() == 0){
                                    if (null == courseAccount.getEndTime()){
                                        objectsa.add(courseAccount);
                                    }else if (null != courseAccount.getEndTime() && courseAccount.getEndTime().after(new Date())){
                                        objectsa.add(courseAccount);
                                    }
                                }else {
                                    PromotionStore promotionStore = new PromotionStore();
                                    promotionStore.setPromotionId(promotionList.getId());
                                    List<PromotionStore> promotionStores = ssmPromotionStoreService.selectList(promotionStore);
                                    for (PromotionStore store : promotionStores) {
                                        if (Objects.equals(courseAccount.getStoreId(), store.getStoreId())){
                                            objectsa.add(courseAccount);
                                        }
                                    }
                                }
                            }else {
                                if ("1".equals(parament.getParamentValue())) {
                                    if(courseAccount.getEndTime().after(new Date())){
                                        objectsa.add(courseAccount);
                                    }
                                }else{
                                    objectsa.add(courseAccount);
                                }
                            }

                            /*if ("1".equals(parament.getParamentValue())) {
                                if(courseAccount.getEndTime().after(new Date())){
                                    objectsa.add(courseAccount);
                                }
                            }else{
                                objectsa.add(courseAccount);
                            }*/
                        }
//                        objectsa.add(courseAccount);
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
        }
        for (CourseAccount courseAccount : objectsa) {
            if(courseAccount.getCourseNum()!=null) {
                DebtList debtList = new DebtList();
                debtList.setDocNum(courseAccount.getCourseNum());
                DebtList debtList1 = ssmDebtService.selectOne(debtList);
                if (debtList1 != null && debtList1.getDebtMoney() != null) {
                    courseAccount.setDebtMoney(debtList1.getDebtMoney());
                }
            }
        }
//        System.out.println(objectsa.get(0).getCourseConsumeCount());
//        System.out.println(objectsa.get(0).getCourseConsumeCount()==objectsa.get(0).getCourseRestCount());
//        System.out.println(objectsa.get(0).getCourseRestCount());
//        List<CourseAccount> collect = objectsa.stream().filter(courseAccount -> courseAccount.getDebtMoney()==null||courseAccount.getDebtMoney().compareTo(BigDecimal.valueOf(0)) != 1).collect(Collectors.toList());
        List<CourseAccount> collect = objectsa.stream().filter(courseAccount -> courseAccount.getCourseRestCount()==courseAccount.getCourseConsumeCount() || courseAccount.getCourseRestCount().toString().equals(courseAccount.getCourseConsumeCount().toString())).collect(Collectors.toList());

        return collect;
    }

    @Autowired
    private CourseAccountMapper mapper;
    @Override
    public List<CourseAccount> selectListByMemberList(CourseAccountRequest courseAccountRequest) {
        CourseAccount courseAccount = new CourseAccount();
        courseAccount.setMemberId(courseAccountRequest.getMemberId());
        return mapper.select(courseAccount);
    }

    @Override
    public List<CourseAccount> exportachi(CourseAccountRequest courseAccountRequest) {
        return mapper.selectByExport(courseAccountRequest);
    }

    @Override
    public PageInfo<CourseAccount> exportachiByPage(CourseAccountRequest courseAccountRequest) {
        PageHelper.startPage(courseAccountRequest.getPageNum(),courseAccountRequest.getPageSize());
        List<CourseAccount> list = mapper.selectByExport(courseAccountRequest);
        PageInfo<CourseAccount> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }


    public String getStaffKey(String phone){
        return staffKey + phone;
    }
    public List<AchiCommEntity> getAchiCommList(DocPromotion courseList){

        PromotionProject promotionProject=new PromotionProject();
        BigDecimal cashRechargeAchiSum=new BigDecimal("0");//合作总业绩
        promotionProject.setPromotionId(courseList.getPromotionId());
        promotionProject.setPromotionNum(courseList.getPromotionNum());
        List<PromotionProject> list=ssmPromotionProjectService.select(promotionProject);
        for(PromotionProject promotionProject1:list){
            BaseProject baseProject=ssmProjectService.selectByPrimaryKey(promotionProject1.getProjectId());
            //是否是合作项目,1=合作项目
            if(baseProject.getIsCooperation()==1){
                //项目总金额/促销包总金额=这个项目总支付金额得占比
                BigDecimal projectMix=promotionProject1.getProjectTotalMoney().divide(courseList.getPrice(),4,BigDecimal.ROUND_HALF_UP);
                //拿项目支付占比*(现付+卡付)=在这个促销疗程包中支付金额
                BigDecimal projectMoney=projectMix.multiply(
                        (courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount()))
                );
                if(baseProject.getSmokeCommissionWay()==1) {//合作按比例
                    cashRechargeAchiSum=cashRechargeAchiSum.add(projectMoney.multiply(baseProject.getBrokerage()));
                }else{
                    cashRechargeAchiSum=cashRechargeAchiSum.add(baseProject.getBrokerage());
                }
            }
        }
        cashRechargeAchiSum=cashRechargeAchiSum.divide(new BigDecimal("100"));


        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");
        if (null != courseList.getSaleOneStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setCooperationAchi(cashRechargeAchiSum.multiply(courseList.getSaleOneRatio()));
            achiCommEntity.setMoney(courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount()));
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getPromotionNum()));
            achiCommEntity.setMoney(courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount()));
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getPromotionNum()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_promotion);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setBrandNumber(courseList.getSaleOneNumber());
            achiCommEntity.setTradeName(courseList.getPromotionName());
            achiCommEntity.setSaleStaffId(courseList.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleOneRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleOneRatio(),hundredBD)));
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleTwoStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setCooperationAchi(cashRechargeAchiSum.multiply(courseList.getSaleTwoRatio()));
            achiCommEntity.setMoney(courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount()));
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getPromotionNum()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_promotion);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setBrandNumber(courseList.getSaleTwoNumber());
            achiCommEntity.setTradeName(courseList.getPromotionName());
            achiCommEntity.setSaleStaffId(courseList.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleTwoRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleTwoRatio(),hundredBD)));
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleThreeStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setCooperationAchi(cashRechargeAchiSum.multiply(courseList.getSaleThreeRatio()));
            achiCommEntity.setMoney(courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount()));
            achiCommEntity.setMemberNum(String.valueOf(courseList.getMemberId()));
            achiCommEntity.setMemberName(courseList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(courseList.getPromotionNum()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_promotion);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setBrandNumber(courseList.getSaleThreeNumber());
            achiCommEntity.setTradeName(courseList.getPromotionName());
            achiCommEntity.setSaleStaffId(courseList.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleThreeRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleThreeRatio(),hundredBD)));
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != courseList.getSaleFourStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setCooperationAchi(cashRechargeAchiSum.multiply(courseList.getSaleFourRatio()));
            achiCommEntity.setDocNum(courseList.getDocNum());
            achiCommEntity.setDocType(Constant.doc_type_promotion);
            achiCommEntity.setDocDate(courseList.getDocDate());
            achiCommEntity.setBrandNumber(courseList.getSaleFourNumber());
            achiCommEntity.setTradeName(courseList.getPromotionName());
            achiCommEntity.setSaleStaffId(courseList.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(courseList.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(courseList.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(courseList.getSaleFourRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD))));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)),
                    BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD))));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(courseList.getAchievementAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            achiCommEntity.setCashComm(BigDecimalUtils.multiply(courseList.getCommissionAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCardAchievementAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(courseList.getCardCommissionAmount(),BigDecimalUtils.div(courseList.getSaleFourRatio(),hundredBD)));
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        return entities;
    }

    public AccountTradeRecord setAccountTradeRecord(DocPromotion docPromotion,PromotionRechargeList promotionRechargeList, RechargeAccount rechargeAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(docPromotion.getStoreId());
        accountTradeRecord.setStoreName(docPromotion.getStoreName());
        accountTradeRecord.setMemberId(rechargeAccount.getMemberId());
        accountTradeRecord.setMemberName(rechargeAccount.getMemberName());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setMemberPhone(docPromotion.getMobilePhone());
        if(docPromotion.getIsCancel() == 0) {
//            if(rechargeList.getLiftType()==1){
//                accountTradeRecord.setDocType(Constant.doc_type_recharge_upgrade_in);
//            }else if(rechargeList.getLiftType()==2){
//                accountTradeRecord.setDocType(Constant.doc_type_recharge_demotion_in);
//            }else{
//                accountTradeRecord.setDocType(Constant.doc_type_recharge);
//            }
            accountTradeRecord.setOrderStatu(0);
            accountTradeRecord.setAccountType(Constant.account_type_recharge);
            accountTradeRecord.setInputDate(docPromotion.getDocDate());
            accountTradeRecord.setInputBy(docPromotion.getInputBy());
            accountTradeRecord.setAccountInMoney(rechargeAccount.getCardRestMoney());
            accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
            accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        }else {
            accountTradeRecord.setOrderStatu(1);
            accountTradeRecord.setAccountType(Constant.account_type_recharge_cancel);
            accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney().subtract(promotionRechargeList.getRechargeMoney()));
            accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(promotionRechargeList.getRechargeMoney()));
            accountTradeRecord.setInputDate(docPromotion.getCancelDate());
            accountTradeRecord.setInputBy(docPromotion.getCancelBy());
            accountTradeRecord.setAccountGiftSpendMoney(BigDecimal.ZERO);
        }
        accountTradeRecord.setDocId(docPromotion.getId());
        accountTradeRecord.setDocNum(docPromotion.getDocNum());
        accountTradeRecord.setDocType(Constant.doc_type_promotion_recharge);
        accountTradeRecord.setDebtMoney(BigDecimal.ZERO);

        accountTradeRecord.setIsAddition(0);
        accountTradeRecord.setTradeId(rechargeAccount.getRechargeTypeId());
        accountTradeRecord.setPrice(BigDecimal.ZERO);
        accountTradeRecord.setTradeName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setTradeMoney(BigDecimal.ZERO);


        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCashMoney(docPromotion.getCollectionCashAmount());
        accountTradeRecord.setCardMoney(docPromotion.getCollectionRechargeAmount());
        return accountTradeRecord;
    }

}
