package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.extendEntity.StoreDaily;
import com.ssm.manage.mapper.CourseListMapper;
import com.ssm.manage.mapper.CourseListMemberInitMapper;
import com.ssm.manage.response.*;
import com.ssm.manage.service.SsmDebtService;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmCourseDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.query.*;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.CommonUtils;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
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 javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmCourseServiceImpl extends BaseServiceImpl<CourseList> implements SsmCourseService {
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private CourseListMemberInitMapper courseListMemberInitMapper;

    @Autowired
    SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private SsmCollectionTypeService ssmCollectionTypeService;
    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;
    @Autowired
    private SsmTransactionRecordService ssmTransactionRecordService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;


    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmMemberCsService ssmMemberCsService;

    @Autowired
    private SsmCourseDao dao;

    @Autowired
    private CourseListMapper courseListMapper;

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

    private static String staffKey = "staffKey";

    @Override
    public void createTable() {
        String date = DateUtils.YMFormat(DateUtils.diffMonth(new Date(), 1));
        dao.createTable(date);
    }

    @Override
    public PageInfo<CourseListResponse> selectPage(CourseListRequest courseListRequest) throws SmsException, ParseException {
        Date date = DateUtils.YMParse(courseListRequest.getSelectDate());
        courseListRequest.setDate(date);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), date) < 0) {
            throw new SmsException(ResponseCode.NO_DATA);
        }
        PageInfo<CourseList> pageInfo = dao.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo.getList()) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
//            //隐藏手机号码
//            String memberPhone = CommonUtils.mobileHide(courseList.getMobilePhone());
//            courseListResponse.setMobilePhone(memberPhone);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(courseList.getId()));
            List<PayList> list = ssmPayService.select(payList);
            //查询充值卡付列表(通过账户交易记录)
            List<RechargeAccountResponse> rechargeConsumeList = this.setRechargeAccountList(courseList);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            courseListResponse.setPayLists(list);
            courseListResponse.setEntities(entities);
            courseListResponse.setRechargeConsumeList(rechargeConsumeList);
            listResponses.add(courseListResponse);
        }
        for (CourseListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
            salesman.setOrderType(2);
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderNum(listRespons.getCourseReatmentNum());
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        PageInfo<CourseListResponse> p = new PageInfo<>(listResponses);
        p.setTotal(pageInfo.getTotal());
        return p;
    }


    @Override
    public PageInfo<CourseListResponse> selectPageNew(CourseListRequest courseListRequest) throws SmsException, ParseException {
//        Date date = DateUtils.YMParse(courseListRequest.getSelectDate());
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM");
        Date date = sm.parse(courseListRequest.getSelectDate());
        courseListRequest.setDate(date);
//        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
//        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())),date) < 0){
//            throw new SmsException(ResponseCode.NO_DATA);
//        }
        List<Long> lists = new ArrayList<>();
        if (courseListRequest.getSelectType() == 0) {
            lists = courseListRequest.getStoreList();
        } else {
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
            if (null == baseStore1.getParentId() && (courseListRequest.getStoreList().size() < 0 || courseListRequest.getStoreList() == null)) {
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(courseListRequest.getStoreId());
                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());
                lists = collect;
            } else {
                lists.add(courseListRequest.getStoreId());
            }

        }
        courseListRequest.setStoreList(lists);
        PageInfo<CourseList> pageInfo = dao.selectPageNew(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo.getList()) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
//            //隐藏手机号码
//            String memberPhone = CommonUtils.mobileHide(courseList.getMobilePhone());
//            courseListResponse.setMobilePhone(memberPhone);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(courseList.getCourseReatmentNum()));
            List<PayList> list = ssmPayService.select(payList);

            //查询充值卡付列表(通过账户交易记录)
            List<RechargeAccountResponse> rechargeConsumeList = this.setRechargeAccountList(courseList);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            courseListResponse.setPayLists(list);
//            if(entities!=null && entities.size()>0){
//                for (AchiCommEntity entity : entities) {
//                    if(entity.getSaleStaffId()!=null) {
//                        BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(entity.getSaleStaffId());
//                        entity.setBrandNumber(baseStaff.getBrandNumber());
//                    }
//                }
//            }
            courseListResponse.setEntities(entities);
            courseListResponse.setRechargeConsumeList(rechargeConsumeList);
            listResponses.add(courseListResponse);
        }
        for (CourseListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
            salesman.setOrderType(2);
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderNum(listRespons.getCourseReatmentNum());
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        List<CourseListResponse> k = listResponses.stream().filter(item -> item.getCourseReatmentNum().startsWith("LC")).collect(Collectors.toList());
        for (CourseListResponse courseListResponse : k) {
            if(courseListResponse.getInputId()!=null){
                BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(courseListResponse.getInputId());
                courseListResponse.setInputNum(baseStaff.getStaffNum());
            }

        }
        PageInfo<CourseListResponse> p = new PageInfo<>(k);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<CourseListResponse> pageDetail(CourseListRequest courseListRequest) throws SmsException, ParseException {
//        Date date = DateUtils.YMParse(courseListRequest.getSelectDate());
//        courseListRequest.setDate(date);
        //Date date = DateUtil.parse(courseListRequest.getSelectDate(),"yyyy-MM-dd");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(courseListRequest.getSelectDate());
        courseListRequest.setDate(parse);
        PageInfo<CourseList> pageInfo = dao.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo.getList()) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
//            //隐藏手机号码
//            String memberPhone = CommonUtils.mobileHide(courseList.getMobilePhone());
//            courseListResponse.setMobilePhone(memberPhone);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(courseList.getCourseReatmentNum());
            List<PayList> list = ssmPayService.select(payList);
            //查询充值卡付列表(通过账户交易记录)
            List<RechargeAccountResponse> rechargeConsumeList = this.setRechargeAccountList(courseList);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            courseListResponse.setPayLists(list);
            courseListResponse.setEntities(entities);
            courseListResponse.setRechargeConsumeList(rechargeConsumeList);
            listResponses.add(courseListResponse);
        }
        for (CourseListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
            salesman.setOrderType(2);
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderNum(listRespons.getCourseReatmentNum());
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        PageInfo<CourseListResponse> p = new PageInfo<>(listResponses);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    /*
     * 充值卡付列表设置返回值
     * */
    public List<RechargeAccountResponse> setRechargeAccountList(CourseList courseList) {
        List<RechargeAccountResponse> list = new ArrayList<>();
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setDocType(Constant.doc_type_card_use);
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume);
        accountTradeRecordRequest.setDocNum(courseList.getCourseReatmentNum());
        accountTradeRecordRequest.setInputDate(courseList.getDate());
        List<AccountTradeRecord> recordList = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
        for (AccountTradeRecord accountTradeRecord : recordList) {
            RechargeAccountResponse rechargeAccountResponse = new RechargeAccountResponse();
//            RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(accountTradeRecord.getAccountId());
//            BeanUtils.copyProperties(rechargeAccount,rechargeAccountResponse);
            rechargeAccountResponse.setCardRestMoney(accountTradeRecord.getAccountRestMoney());
            rechargeAccountResponse.setCardConsumeMoney(accountTradeRecord.getAccountConsumeMoney());
            rechargeAccountResponse.setCardGiftMoney(accountTradeRecord.getAccountGiftRestMoney());
            rechargeAccountResponse.setGiftConsumeMoney(accountTradeRecord.getAccountGiftConsumeMoney());
            rechargeAccountResponse.setSpendMoney(accountTradeRecord.getAccountSpendMoney());
            rechargeAccountResponse.setRechargeTypeName(accountTradeRecord.getAccountName());
            list.add(rechargeAccountResponse);
        }
        return list;
    }

    /*public List<RechargeAccountResponse> setRechargeAccountList1(CourseList courseList){
        List<RechargeAccountResponse> list = new ArrayList<>();
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setDocType(Constant.doc_type_card_change);
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume);
        accountTradeRecordRequest.setDocId(courseList.getId());
        accountTradeRecordRequest.setInputDate(courseList.getDate());
        List<AccountTradeRecord> recordList = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
        for (AccountTradeRecord accountTradeRecord : recordList) {
            RechargeAccountResponse rechargeAccountResponse = new RechargeAccountResponse();
//            RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(accountTradeRecord.getAccountId());
//            BeanUtils.copyProperties(rechargeAccount,rechargeAccountResponse);
            rechargeAccountResponse.setCardRestMoney(accountTradeRecord.getAccountRestMoney());
            rechargeAccountResponse.setCardConsumeMoney(accountTradeRecord.getAccountConsumeMoney());
            rechargeAccountResponse.setCardGiftMoney(accountTradeRecord.getAccountGiftRestMoney());
            rechargeAccountResponse.setGiftConsumeMoney(accountTradeRecord.getAccountGiftConsumeMoney());
            rechargeAccountResponse.setSpendMoney(accountTradeRecord.getAccountSpendMoney());
            rechargeAccountResponse.setRechargeTypeName(accountTradeRecord.getAccountName());
            list.add(rechargeAccountResponse);
        }
        return list;
    }*/

    /*
     * 业务员列表设置返回值
     * */
    public List<AchiCommEntity> getAchiCommList(CourseList courseList) {
        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");
        BigDecimal allAchi = courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount());
        if(allAchi.compareTo(BigDecimal.ZERO)==0){
            allAchi = new BigDecimal("1");
        }

        BigDecimal cashRatio = courseList.getCollectionCashAmount().divide(allAchi, 10, BigDecimal.ROUND_HALF_UP);
        BigDecimal cardRatio = courseList.getCollectionRechargeAmount().divide(allAchi, 10, BigDecimal.ROUND_HALF_UP);
        if(courseList.getCardSalesCommission()==null){
            courseList.setCardSalesCommission(BigDecimal.ZERO);
        }
        BaseProject baseProject = ssmProjectService.selectByPrimaryKey(courseList.getProjctId());
        courseList.setCooperAchi(BigDecimal.valueOf(0));
        if (null != courseList.getSaleOneStaffId()) {
            AchiCommEntity achiCommEntity = new AchiCommEntity();

            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply(courseList.getSaleOneRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleOneRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleOneRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }


            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleOneRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleOneRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleOneRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(BigDecimalUtils.multiply(achiCommEntity.getCardAchi()==null?BigDecimal.ZERO:achiCommEntity.getCardAchi(),courseList.getCardSalesCommission()==null?BigDecimal.ZERO:courseList.getCardSalesCommission()));
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(achiCommEntity.getCashComm().add(achiCommEntity.getCardComm()));
            achiCommEntity.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleOneRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleOneRatio().divide(BigDecimal.valueOf(100))));

            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleTwoRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleTwoRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleTwoRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()==null?BigDecimal.ZERO:courseList.getCardSalesCommission()));
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(achiCommEntity.getCashComm().add(achiCommEntity.getCardComm()));

            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP).multiply(courseList.getSaleTwoRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleTwoRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleTwoRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }

            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.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleTwoRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleTwoRatio().divide(BigDecimal.valueOf(100))));

            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleThreeRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleThreeRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleThreeRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.add(achiCommEntity.getCashComm()==null?BigDecimal.ZERO:achiCommEntity.getCashComm(),
                    achiCommEntity.getCardComm()==null?BigDecimal.ZERO:achiCommEntity.getCardComm()));

            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP).multiply(courseList.getSaleThreeRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleThreeRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),4,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleThreeRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()==null?BigDecimal.ZERO:courseList.getCardSalesCommission()));
            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.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleThreeRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleThreeRatio().divide(BigDecimal.valueOf(100))));

            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleFourRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleFourRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleFourRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()));
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(achiCommEntity.getCashComm().add(achiCommEntity.getCardComm()));
            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP).multiply(courseList.getSaleFourRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleFourRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleFourRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }
            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.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleFourRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleFourRatio().divide(BigDecimal.valueOf(100))));

            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleFiveRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleFiveRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleFiveRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()));
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(achiCommEntity.getCashComm().add(achiCommEntity.getCardComm()));

            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP).multiply(courseList.getSaleFiveRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleFiveRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleFiveRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }
            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.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleFiveRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleFiveRatio().divide(BigDecimal.valueOf(100))));

            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleSixRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleSixRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleSixRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()));
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(achiCommEntity.getCashComm().add(achiCommEntity.getCardComm()));
            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP).multiply(courseList.getSaleSixRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleSixRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleSixRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }
            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.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleSixRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleSixRatio().divide(BigDecimal.valueOf(100))));

            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleSevenRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleSevenRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleSevenRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()));
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(achiCommEntity.getCashComm().add(achiCommEntity.getCardComm()));
            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP).multiply(courseList.getSaleSevenRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleSevenRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleSevenRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }
            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.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleSevenRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleSevenRatio().divide(BigDecimal.valueOf(100))));

            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.setCashAchi(BigDecimalUtils.multiply(courseList.getCollectionCashAmount().subtract(cashRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getSalesAchievement())
                    , courseList.getSaleEightRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            if(baseProject.getSalesCommission().compareTo(BigDecimal.valueOf(1))==1){
                achiCommEntity.setCashComm(baseProject.getSalesCommission().multiply(courseList.getSaleEightRatio().divide(hundredBD)));
            }else {

                achiCommEntity.setCashComm(achiCommEntity.getCashAchi().multiply(baseProject.getSalesCommission()));
            }
            achiCommEntity.setCardAchi(BigDecimalUtils.multiply(courseList.getCollectionRechargeAmount().subtract(cardRatio.multiply(courseList.getCooperAchi()))
//                    .multiply(courseList.getCardSalesAchievement())
                    ,  courseList.getSaleEightRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP)));
            achiCommEntity.setCardComm(achiCommEntity.getCardAchi().multiply(courseList.getCardSalesCommission()));
            achiCommEntity.setSaleAchievementAmount(achiCommEntity.getCashAchi().add(achiCommEntity.getCardAchi()));
            achiCommEntity.setSaleCommissionAmount(achiCommEntity.getCashComm().add(achiCommEntity.getCardComm()));

            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(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP).multiply(courseList.getSaleEightRatio().divide(hundredBD))
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())))
                    );
                    courseList.setCooperAchi(baseProject.getBrokerage().divide(courseList.getAmount(),5,BigDecimal.ROUND_HALF_UP)
                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney()))));
                }else {
                    achiCommEntity.setCooperationAchi(baseProject.getBrokerage().divide(new BigDecimal("100")).multiply(courseList.getSaleEightRatio()));
                    courseList.setCooperAchi(baseProject.getBrokerage());
                }
            } 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,10,BigDecimal.ROUND_HALF_UP))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                    courseList.setCooperAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
//                            .multiply((courseList.getAmount().subtract(courseList.getDebtMoney())).divide(courseList.getAmount(),10,BigDecimal.ROUND_HALF_UP))
                                    .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100)))
                    );
                }else {
                    achiCommEntity.setCooperationAchi((courseList.getAchievementAmount().add(courseList.getCardAchievementAmount()))
                            .multiply( courseList.getSaleEightRatio().divide(hundredBD,10,BigDecimal.ROUND_HALF_UP))
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                    courseList.setCooperAchi(courseList.getAchievementAmount().add(courseList.getCardAchievementAmount())
                            .multiply(baseProject.getBrokerage().divide(BigDecimal.valueOf(100))));
                }
            }
            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.setCashCoopAchi(cashRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleEightRatio().divide(BigDecimal.valueOf(100))));
            achiCommEntity.setCardCoopAchi(cardRatio.multiply(courseList.getCooperAchi()).multiply(courseList.getSaleEightRatio().divide(BigDecimal.valueOf(100))));

            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 addCourse(CourseListRequest courseListRequest) throws SmsException {
        int i = 0;
        CourseList courseList = new CourseList();
        BeanUtils.copyProperties(courseListRequest, courseList);
        //查询门店参数折扣卡购买疗程是否允许折扣 0不折扣 1折扣
        //查询store_parament，根据店铺id和buycourse查询  todo 不需要更改
        //生成疗程单号
        String storeNum = ssmBaseStoreService.selectByPrimaryKey(courseList.getStoreId()).getStoreNum();
        String courseReatmentNum = "";
        //单据，只需要生成一次
        if(courseReatmentNum.length()==0 || courseReatmentNum.equals("")){
            courseReatmentNum = this.getDocNum(courseList, storeNum);
        }
        StoreParament parament = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.buycourse);
        //查询对应充值账户
        List<RechargeAccountRequest> rechargeAccountList = courseListRequest.getRechargeAccountList();
        StoreParament debtPara = new StoreParament();
        //不存在欠款 校验金额   todo  需要进行修改
        if (0 == courseList.getIsDebt()) {
            if (null != rechargeAccountList && rechargeAccountList.size() > 0) {
                BigDecimal discountMoneyTotal = BigDecimalUtils.bigDecimal("0");
                BigDecimal giftMoneyTotal = BigDecimalUtils.bigDecimal("0");
                for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                    RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccountRequest.getId());
                    //判断账户剩余可用金额是否小于卡付金额
                    if (BigDecimalUtils.compareTo(BigDecimalUtils.add(rechargeAccount.getCardConsumeMoney(),
                            rechargeAccount.getGiftConsumeMoney()), rechargeAccountRequest.getSpendMoney()) == -1) {
                        throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "账户可消费金额小于卡付金额");
                    }
                }
                //折扣卡购买疗程是否允许折扣 0不折扣 1折扣
                if ("1".equals(parament.getParamentValue())) {
                    BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
                    for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                        //计算卡付金额抵扣金额
                        BigDecimal discountMoney = BigDecimalUtils.bigDecimal("0");
                        if (rechargeAccountRequest.getType() == 1) {
                            //折扣卡
                            discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                            discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                        } else if (rechargeAccountRequest.getType() == 0) {
                            giftMoneyTotal = BigDecimalUtils.add(giftMoneyTotal, rechargeAccountRequest.getSpendMoney());
                        } else if (rechargeAccountRequest.getType() == 2) {
                            discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                            discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                            giftMoneyTotal = BigDecimalUtils.add(giftMoneyTotal, BigDecimalUtils.div(rechargeAccountRequest.getFreePaymentAmount(), BigDecimalUtils.div(rechargeAccountRequest.getDiscountFreeAmount(), hundredBd)));
                        }
                    }

                    BigDecimal amount = BigDecimalUtils.bigDecimal("0");
                    //折扣卡购买疗程 允许使用容差 并且没有现付
                    if (BigDecimalUtils.compareTo(discountMoneyTotal, BigDecimalUtils.bigDecimal("0")) == 1 &&
                            BigDecimalUtils.compareTo(courseList.getCollectionCashAmount(), BigDecimalUtils.bigDecimal("0")) == 0) {
                        //总支付金额 = 总卡付金额抵扣金额 + 积分付
                        amount = BigDecimalUtils.add(discountMoneyTotal, courseList.getCollectionIntegralAmount(), 2);
                        //容差值< (成交金额-总支付金额) 即支付金额和成交金额不相等
                        StoreParament balance = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.balance);
                        if (null != balance && BigDecimalUtils.compareTo(BigDecimalUtils.bigDecimal(balance.getParamentValue()), BigDecimalUtils.subtract(courseList.getCourseReatmentAmount(), amount).abs()) < 0) {
                            throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                        }
                    } else {
                        //总支付金额 = 折扣卡付抵扣金额 + 赠送卡使用金额 + 总现付 + 积分付
                        amount = BigDecimalUtils.add(BigDecimalUtils.add(BigDecimalUtils.add(discountMoneyTotal, giftMoneyTotal), courseList.getCollectionCashAmount()), courseList.getCollectionIntegralAmount(), 2);
                        if (BigDecimalUtils.compareTo(amount, courseList.getCourseReatmentAmount()) != 0) {
                            throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                        }
                    }
                } else {//不折扣
                    //判断支付金额是否和成交金额相等
                    if (BigDecimalUtils.compareTo(courseList.getAmount(), courseList.getCourseReatmentAmount()) != 0) {
                        throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "实收金额和成交金额不相等");
                    }
                }
            } else {//没有卡付
                //判断支付金额是否和成交金额相等
                if (BigDecimalUtils.compareTo(courseList.getAmount(), courseList.getCourseReatmentAmount()) != 0) {
                    throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "实收金额和成交金额不相等");
                }
            }
        } else {//存在欠款  查询是否允许欠款
            StoreParament allowDebtPara = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.allow_debt);
            //不允许欠款 提示信息
            if ("0".equals(allowDebtPara.getParamentValue())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "疗程");
            } else {
                StoreParament debtRatio = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.debt_ratio);
                //实际收款
                BigDecimal courseReatmentAmount = courseListRequest.getCourseReatmentAmount();
                BigDecimal multiply = courseListRequest.getSalesPrice().multiply(BigDecimal.valueOf(Double.valueOf(courseListRequest.getNumberTimes())));
                //最少支付金额
                BigDecimal multiply1 = multiply.multiply(BigDecimal.valueOf(Double.valueOf(debtRatio.getParamentValue())).divide(BigDecimal.valueOf(100)));
                BigDecimal subtract = multiply.subtract(multiply1);
                if (subtract.compareTo(courseReatmentAmount) > -1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.DEBT_NOT_PERMISSIONA, "疗程");
                }

                //查询门店欠款可用比率参数
                debtPara = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.debt_usable);
            }
        }
        //校验单价 todo
//        BigDecimal amount = courseList.getAmount();
//        BigDecimal price = amount.divide(BigDecimal.valueOf(courseList.getNumberTimes()),2,BigDecimal.ROUND_HALF_UP);
//        if(price.compareTo(courseList.getSalesPrice())!=0){
//            throw new SmsException(ResponseCode.MSG,"单价乘以次数不等于总金额");
//        }

        //生成疗程id
        Long courseId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        courseList.setId(courseId);
        //如果使用积分支付将门店会员积分进行扣减
        if (0 != courseList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(courseList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() - courseList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }

        //计算卡付现付业绩提成
        List<PayList> payLists = courseListRequest.getPayLists();
        courseList = this.setAchiComm(courseList, rechargeAccountList, payLists);

        //设置业务员
        List<StaffRequest> staffLists = courseListRequest.getStaffLists();
        BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
        if (null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100)) != 0 && reduce3.compareTo(BigDecimal.valueOf(0)) != 0) {
            throw new SmsException(ResponseCode.MSG, "业务员业绩占比和不等于100");
        }
        this.setStaffValue(staffLists, courseList);


        courseList.setCourseReatmentNum(courseReatmentNum);
        //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
        Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        CourseAccount courseAccount = new CourseAccount();
        BeanUtils.copyProperties(courseList, courseAccount);
        courseAccount.setId(courseAccountId);
        courseAccount.setCourseType("0");
        courseAccount.setCourseNum(courseReatmentNum);
        courseList.setCourseAccountId(courseAccountId);
        courseAccount.setPrice(courseList.getSalesPrice());
        //courseAccount.set
        //对疗程账户进行赋值
        courseAccount = ssmCourseAccountService.setCourseAccountS(courseList, courseAccount, debtPara);
        ssmCourseAccountService.addCourseAccount(courseAccount);

        //插入疗程单据
        courseList.setDate(new Date());
        //不走补单 正常开单 补单时间默认为开单时间
        if (0 == courseList.getIsAddition()) {
            courseList.setAdditionDate(new Date());
        }
        courseList.setIsCancel(0);

        //如果使用充值卡支付 对使用的充值账户金额扣减
        if (BigDecimalUtils.compareTo(courseList.getCollectionRechargeAmount(), BigDecimalUtils.bigDecimal("0")) == 1) {
            //计算扣减金额 并添加账户交易记录
            ssmRechargeAccountService.subMoney(rechargeAccountList, courseList);
        }

        //欠款 添加欠款记录
        if (1 == courseList.getIsDebt()) {
            DebtListRequest debtListRequest = new DebtListRequest();
            BeanUtils.copyProperties(courseList, debtListRequest);
            debtListRequest.setTradeId(courseList.getProjctId());
            debtListRequest.setTradeName(courseList.getProjectName());
            debtListRequest.setTradeMoney(courseList.getAmount());
            debtListRequest.setDocId(courseId);
            debtListRequest.setDocNum(courseReatmentNum);
            debtListRequest.setDocType(Constant.doc_type_card_use);
            debtListRequest.setAccountId(courseAccountId);
            debtListRequest.setStaffLists(staffLists);
            debtListRequest.setState(0);
            debtListRequest.setDocDate(courseList.getDate());
            debtListRequest.setRepayCount(courseAccount.getCourseRestCount());
            debtListRequest.setRepayConsumeCount(courseAccount.getCourseConsumeCount());
            debtListRequest.setRepayMoney(courseList.getCourseReatmentAmount());
            if (null == BigDecimalUtils.div(BigDecimalUtils.bigDecimal(debtPara.getParamentValue()), BigDecimalUtils.bigDecimal("100"))) {
                debtListRequest.setRepayConsumeMoney(BigDecimalUtils.bigDecimal("1"));
            } else {
                debtListRequest.setRepayConsumeMoney(BigDecimalUtils.div(BigDecimalUtils.bigDecimal(debtPara.getParamentValue()), BigDecimalUtils.bigDecimal("100")));
            }
            ssmDebtService.addDebt(debtListRequest);
        }
        //设置录单人信息
        if (redisClient.hasKey(getStaffKey(courseListRequest.getStaffPhone()))) {
            StaffResponse staffResponse = redisClient.get(getStaffKey(courseListRequest.getStaffPhone()));
            courseList.setInputId(staffResponse.getId());
            courseList.setInputBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(courseListRequest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            courseList.setInputId(staffResponse.getId());
            courseList.setInputBy(staffResponse.getStaffName());
        }
        try {
            BaseProject baseProject = new BaseProject();
            baseProject.setId(courseListRequest.getProjctId());
            BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
            courseList.setSalesAchievement(baseProject1.getSalesAchievement());
            courseList.setSalesCommission(baseProject1.getSalesCommission());
            courseList.setCardAchievementAmount(baseProject1.getCardSalesAchievement());
            courseList.setCardSalesCommission(baseProject1.getCardSalesCommission());

            //现付
            if (courseList.getSalesAchievement().compareTo(BigDecimal.valueOf(1)) == 1) {
                courseList.setAchievementAmount(courseList.getSalesAchievement());
                if (courseList.getSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                    courseList.setCommissionAmount(courseList.getSalesCommission());
                } else {
                    courseList.setCommissionAmount(courseList.getSalesCommission().multiply(courseList.getAchievementAmount()));
                }
            } else {
                courseList.setAchievementAmount(courseList.getCollectionCashAmount().multiply(courseList.getSalesAchievement()));
                if (courseList.getSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                    courseList.setCommissionAmount(courseList.getSalesCommission());
                } else {
                    courseList.setCommissionAmount(courseList.getSalesCommission().multiply(courseList.getAchievementAmount()));
                }
            }

            //卡付
            if (courseList.getCardSalesAchievement().compareTo(BigDecimal.valueOf(1)) == 1) {
                courseList.setCardAchievementAmount(courseList.getCardSalesAchievement());
                if (courseList.getCardSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                    courseList.setCardCommissionAmount(courseList.getCardSalesCommission());
                } else {
                    courseList.setCardCommissionAmount(courseList.getCardSalesCommission().multiply(courseList.getCardAchievementAmount()));
                }
            } else {
                courseList.setCardAchievementAmount(courseList.getCollectionRechargeAmount().multiply(courseList.getCardSalesAchievement()));
                if (courseList.getCardSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                    courseList.setCardCommissionAmount(courseList.getCardSalesCommission());
                } else {
                    courseList.setCardCommissionAmount(courseList.getCardSalesCommission().multiply(courseList.getCardAchievementAmount()));
                }
            }


            courseList.setProjectNum(courseListRequest.getProjectNum());
            i = dao.addCourse(courseList);
            //todo  高管信息为空，发生错误
            if (null != courseListRequest.getSalesmens() && courseListRequest.getSalesmens().size() > 0) {
                HttpSession session = courseListRequest.getSession();
                //添加高管的当前单据门店信息
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(Long.valueOf(String.valueOf(session.getAttribute("storeId"))));
                BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
                //高管业绩
                List<Salesman> salesmens = courseListRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if (null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100)) != 0 && reduce5.compareTo(BigDecimal.valueOf(0)) != 0) {
                    throw new SmsException(ResponseCode.MSG, "高管业绩占比和不等于100");
                }
                if (null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100)) != 0 && reduce6.compareTo(BigDecimal.valueOf(0)) != 0) {
                    throw new SmsException(ResponseCode.MSG, "管理员业绩占比和不等于100");
                }
                for (Salesman salesmen : salesmens) {
                    salesmen.setOrderId(String.valueOf(courseList.getId()));
                    salesmen.setOrderNum(courseReatmentNum);
                    salesmen.setOrderType(2);
                    salesmen.setOrderDate(new Date());
                    salesmen.setState(0);
                    salesmen.setMoney(courseListRequest.getCollectionRechargeAmount().add(courseListRequest.getCollectionCashAmount()));
                    salesmen.setProjectId(courseAccount.getCourseProjectId());
                    salesmen.setStoreNum(baseStore1.getStoreNum());
                    salesmen.setStoreName(baseStore1.getStoreName());
                    salesmen.setStoreIdOrder(baseStore1.getId());
                    salesmen.setOperatorBy(courseList.getInputBy());
                    salesmen.setIsAddition(courseList.getIsAddition());
                }
                ssmSalesmanService.addBatch(salesmens);
            }
        } catch (Exception e) {
            log.error("SsmCourseServiceImpl.addCourse:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加现付支付方式
        if (null != payLists && payLists.size() > 0) {
            List<PayList> collect = payLists.stream().filter(item -> item.getPayMoney().compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList());
            if (collect != null && collect.size() > 0) {
                for (PayList payList : collect) {
                    payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    payList.setDocId(String.valueOf(courseId));
                    payList.setType(Constant.doc_type_card_use);
                    payList.setStoreId(courseListRequest.getStoreId());
                }
                ssmPayService.addPayList(collect);
            }
        }

        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseList, courseAccount);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

//        TransactionRecord transactionRecord = this.setTransactionRecord(courseList,courseAccount);
//        ssmTransactionRecordService.add(transactionRecord);


        //将疗程单据信息添加到评价表
        MemberCsRequest memberCsRequest = new MemberCsRequest();
        BeanUtils.copyProperties(courseList, memberCsRequest);
        memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberCsRequest.setDocId(courseId);
        memberCsRequest.setDocNum(courseReatmentNum);
        memberCsRequest.setDocType(Constant.doc_type_card_use);
        memberCsRequest.setDocDate(courseList.getDate());
        memberCsRequest.setTradeId(courseList.getProjctId());
        memberCsRequest.setTradeName(courseList.getProjectName());
        memberCsRequest.setTradeMoney(courseList.getAmount());
        memberCsRequest.setTradeCount(courseList.getNumberTimes());
        StringBuffer staffIds = new StringBuffer();
        StringBuffer staffNames = new StringBuffer();
        if (staffLists.size() > 0) {
            for (StaffRequest staffRequest : staffLists) {
                staffIds = staffIds.append(staffRequest.getId()).append(",");
                staffNames = staffNames.append(staffRequest.getStaffName()).append(",");
            }
        }
        memberCsRequest.setStaffIds(staffIds.toString());
        memberCsRequest.setStaffNames(staffNames.toString());
        ssmMemberCsService.addMemberCs(memberCsRequest);
        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addCourse1(CourseListRequestNew courseListRequestNew) throws SmsException {
        int i = 0;
        int x = 0;
//        int subNumber = 0;
        String storeNum = ssmBaseStoreService.selectByPrimaryKey(courseListRequestNew.getStoreId()).getStoreNum();
        String courseReatmentNum = "";
        StoreParament debtRatiox = StoreParaUtils.getStorePara(courseListRequestNew.getStoreId(), Constant.debt_ratio);
        BigDecimal shifu = courseListRequestNew.getCourseLists().stream().map(item->item.getCollectionCashAmount().add(item.getCollectionRechargeAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal yingfu = courseListRequestNew.getCourseLists().stream().map(item -> item.getSalesPrice().multiply(BigDecimal.valueOf(Double.valueOf(item.getNumberTimes())))).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zuidaqiankuan = yingfu.multiply(BigDecimal.valueOf(Double.valueOf(debtRatiox.getParamentValue())).divide(new BigDecimal("100")));
        BigDecimal zuishaozhifu = yingfu.subtract(zuidaqiankuan);

        for (CourseListVo courseListVo : courseListRequestNew.getCourseLists()) {

            CourseList courseList = new CourseList();
            BeanUtils.copyProperties(courseListVo,courseList);
            //插入疗程单据
            courseList.setDate(new Date());

            //不走补单 正常开单 补单时间默认为开单时间
            if (1 == courseList.getIsAddition()) {
//                courseList.setAdditionDate(new Date());
                    courseList.setDate(courseList.getAdditionDate());
                    courseListVo.setDate(courseList.getAdditionDate());
            }



            courseList.setDebtMoney(courseListVo.getDebtMoney());
            courseList.setCourseReatmentAmount(courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount()));
            //查询门店参数折扣卡购买疗程是否允许折扣 0不折扣 1折扣
            //查询store_parament，根据店铺id和buycourse查询  todo 不需要更改
            //生成疗程单号
            courseList.setStoreName(courseListRequestNew.getStoreName());
            courseList.setStoreId(courseListRequestNew.getStoreId());
            //单据，只需要生成一次
            if(courseReatmentNum.length()==0 || courseReatmentNum.equals("")){
                courseReatmentNum = this.getDocNum(courseList, "LC"+storeNum);
            }
            StoreParament parament = StoreParaUtils.getStorePara(courseListRequestNew.getStoreId(), Constant.buycourse);
            //查询对应充值账户
            List<RechargeAccountRequest> rechargeAccountList = courseListVo.getRechargeAccountList();
            StoreParament debtPara = new StoreParament();
            //不存在欠款 校验金额   todo  需要进行修改
            if (0 == courseList.getIsDebt()) {
                if (null != rechargeAccountList && rechargeAccountList.size() > 0) {
                    BigDecimal discountMoneyTotal = BigDecimalUtils.bigDecimal("0");
                    BigDecimal giftMoneyTotal = BigDecimalUtils.bigDecimal("0");
                        for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                            RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccountRequest.getId());
                            //判断账户剩余可用金额是否小于卡付金额
                            if (BigDecimalUtils.compareTo(BigDecimalUtils.add(rechargeAccount.getCardConsumeMoney(),rechargeAccount.getGiftConsumeMoney()),
                                    rechargeAccountRequest.getSpendMoney()) == -1) {
                                throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "账户可消费金额小于卡付金额");
                            }
                        }
                    //折扣卡购买疗程是否允许折扣 0不折扣 1折扣
                    if ("1".equals(parament.getParamentValue())) {
                        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
                        for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                            //计算卡付金额抵扣金额
                            BigDecimal discountMoney = BigDecimalUtils.bigDecimal("0");
                            if (rechargeAccountRequest.getType() == 1) {
                                //折扣卡
                                discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                                discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                            } else if (rechargeAccountRequest.getType() == 0) {
                                giftMoneyTotal = BigDecimalUtils.add(giftMoneyTotal, rechargeAccountRequest.getSpendMoney());
                            } else if (rechargeAccountRequest.getType() == 2) {
                                discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                                discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                                giftMoneyTotal = BigDecimalUtils.add(giftMoneyTotal, BigDecimalUtils.div(rechargeAccountRequest.getFreePaymentAmount(), BigDecimalUtils.div(rechargeAccountRequest.getDiscountFreeAmount(), hundredBd)));
                            }
                        }

                        BigDecimal amount = BigDecimalUtils.bigDecimal("0");
                        //折扣卡购买疗程 允许使用容差 并且没有现付
                        if (BigDecimalUtils.compareTo(discountMoneyTotal, BigDecimalUtils.bigDecimal("0")) == 1 &&
                                BigDecimalUtils.compareTo(courseList.getCollectionCashAmount(), BigDecimalUtils.bigDecimal("0")) == 0) {
                            //总支付金额 = 总卡付金额抵扣金额 + 积分付
                            amount = BigDecimalUtils.add(discountMoneyTotal, courseList.getCollectionIntegralAmount(), 2);
                            //容差值< (成交金额-总支付金额) 即支付金额和成交金额不相等
                            StoreParament balance = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.balance);
                            if (null != balance && BigDecimalUtils.compareTo(BigDecimalUtils.bigDecimal(balance.getParamentValue()), BigDecimalUtils.subtract(courseList.getCourseReatmentAmount(), amount).abs()) < 0) {
                                throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                            }
                        } else {
                            //总支付金额 = 折扣卡付抵扣金额 + 赠送卡使用金额 + 总现付 + 积分付
                            amount = BigDecimalUtils.add(BigDecimalUtils.add(BigDecimalUtils.add(discountMoneyTotal, giftMoneyTotal), courseList.getCollectionCashAmount()), courseList.getCollectionIntegralAmount(), 2);
                            if (BigDecimalUtils.compareTo(amount, courseList.getCourseReatmentAmount()) != 0) {
                                throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                            }
                        }
                    } else {//不折扣
                        //判断支付金额是否和成交金额相等
                        StoreParament balance = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.balance);
                        if (BigDecimalUtils.compareTo(courseList.getAmount(), courseList.getCourseReatmentAmount()) != 0) {
                            if(courseList.getAmount().subtract(courseList.getCourseReatmentAmount()).abs().compareTo(new BigDecimal(balance.getParamentValue()))>0){
                                throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "实收金额和成交金额不相等");
                            }
                        }
                    }
                } else {//没有卡付
                    //判断支付金额是否和成交金额相等
                    if (BigDecimalUtils.compareTo(courseList.getAmount(), courseList.getCourseReatmentAmount()) != 0) {
                        StoreParament balance = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.balance);
                        if(courseList.getAmount().subtract(courseList.getCourseReatmentAmount()).abs().compareTo(new BigDecimal(balance.getParamentValue()))>0){
                            throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "实收金额和成交金额不相等");
                        }
                    }
                }
            }
            else {//存在欠款  查询是否允许欠款
                StoreParament allowDebtPara = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.allow_debt);
                //不允许欠款 提示信息
                if ("0".equals(allowDebtPara.getParamentValue())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "疗程");
                } else {
/**
                    StoreParament debtRatio = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.debt_ratio);
                    //实际收款
                    BigDecimal courseReatmentAmount = courseList.getCourseReatmentAmount();
                    BigDecimal multiply = courseList.getSalesPrice().multiply(BigDecimal.valueOf(Double.valueOf(courseList.getNumberTimes())));
                    //最少支付金额
                    BigDecimal multiply1 = multiply.multiply(BigDecimal.valueOf(Double.valueOf(debtRatio.getParamentValue())).divide(BigDecimal.valueOf(100)));
                    BigDecimal subtract = multiply.subtract(multiply1);
                    if (subtract.compareTo(courseReatmentAmount) > -1) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.DEBT_NOT_PERMISSIONA, "疗程");
                    }
**/
                    if(zuishaozhifu.compareTo(shifu)>-1){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.DEBT_NOT_PERMISSIONA, "疗程");
                    }
                    //查询门店欠款可用比率参数
                    debtPara = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.debt_usable);
                }
            }
            //校验单价 todo
//        BigDecimal amount = courseList.getAmount();
//        BigDecimal price = amount.divide(BigDecimal.valueOf(courseList.getNumberTimes()),2,BigDecimal.ROUND_HALF_UP);
//        if(price.compareTo(courseList.getSalesPrice())!=0){
//            throw new SmsException(ResponseCode.MSG,"单价乘以次数不等于总金额");
//        }

            //生成疗程id
            Long courseId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            courseList.setId(courseId);
            //如果使用积分支付将门店会员积分进行扣减
            if (null != courseList.getIntegral() && 0 != courseList.getIntegral()) {
                StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(courseList.getMemberId());
                storeMember.setIntegral(storeMember.getIntegral() - courseList.getIntegral());
                ssmStoreMemberService.updateByPrimaryKey(storeMember);
            }

            //计算卡付现付业绩提成
            List<PayList> payLists = courseListRequestNew.getPayLists();
            courseList.setStoreId(courseListRequestNew.getStoreId());
            courseList = this.setAchiComm(courseList, rechargeAccountList, payLists);

            //设置业务员
            List<StaffRequest> staffLists = courseListRequestNew.getStaffLists();
            BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100)) != 0 && reduce3.compareTo(BigDecimal.valueOf(0)) != 0) {
                throw new SmsException(ResponseCode.MSG, "业务员业绩占比和不等于100");
            }
            this.setStaffValue(staffLists, courseList);


            courseList.setCourseReatmentNum(courseReatmentNum);
            //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
            Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            CourseAccount courseAccount = new CourseAccount();
            BeanUtils.copyProperties(courseList, courseAccount);
            courseAccount.setId(courseAccountId);
            courseAccount.setCourseType("0");

            courseAccount.setCourseNum(courseReatmentNum);
            courseList.setCourseAccountId(courseAccountId);
            courseAccount.setPrice(courseList.getSalesPrice());
            courseAccount.setAnotherName(courseListVo.getAnotherName());
            if(courseAccount.getAnotherName()==null || courseAccount.equals("")){
                courseAccount.setAnotherName(courseListVo.getProjectName());
            }
            //courseAccount.set
            //对疗程账户进行赋值
            courseAccount = ssmCourseAccountService.setCourseAccountS(courseList, courseAccount, debtPara);
            ssmCourseAccountService.addCourseAccount(courseAccount);


            courseList.setIsCancel(0);

            //如果使用充值卡支付 对使用的充值账户金额扣减
            if (BigDecimalUtils.compareTo(courseList.getCollectionRechargeAmount(), BigDecimalUtils.bigDecimal("0")) == 1 ) {//&& subNumber ==0
                //计算扣减金额 并添加账户交易记录
                ssmRechargeAccountService.subMoney(rechargeAccountList, courseList);
//                subNumber++;
            }

            //欠款 添加欠款记录
            if (1 == courseList.getIsDebt() || courseList.getDebtMoney().compareTo(BigDecimalUtils.bigDecimal("0"))>0) {
                DebtListRequest debtListRequest = new DebtListRequest();
                BeanUtils.copyProperties(courseList, debtListRequest);
                debtListRequest.setTradeId(courseList.getProjctId());
                debtListRequest.setTradeName(courseList.getProjectName());
                debtListRequest.setTradeMoney(courseList.getAmount());
                debtListRequest.setDocId(courseId);
                debtListRequest.setDocNum(courseReatmentNum);
                debtListRequest.setDocType(Constant.doc_type_card_use);
                debtListRequest.setAccountId(courseAccountId);
                debtListRequest.setStaffLists(staffLists);
                debtListRequest.setState(0);
                debtListRequest.setDocDate(courseList.getDate());
                debtListRequest.setRepayCount(courseAccount.getCourseRestCount());
                debtListRequest.setRepayConsumeCount(courseAccount.getCourseConsumeCount());
                debtListRequest.setRepayMoney(courseList.getCourseReatmentAmount());
                if (null == BigDecimalUtils.div(BigDecimalUtils.bigDecimal(debtPara.getParamentValue()), BigDecimalUtils.bigDecimal("100"))) {
                    debtListRequest.setRepayConsumeMoney(BigDecimalUtils.bigDecimal("1"));
                } else {
                    debtListRequest.setRepayConsumeMoney(BigDecimalUtils.div(BigDecimalUtils.bigDecimal(debtPara.getParamentValue()), BigDecimalUtils.bigDecimal("100")));
                }
                ssmDebtService.addDebt(debtListRequest);
            }
            //设置录单人信息
            if (redisClient.hasKey(getStaffKey(courseListRequestNew.getStaffPhone()))) {
                StaffResponse staffResponse = redisClient.get(getStaffKey(courseListRequestNew.getStaffPhone()));
                courseList.setInputId(staffResponse.getId());
                courseList.setInputBy(staffResponse.getStaffName());
            }
            Set<String> keys = redisClient.keys(getStaffKey(courseListRequestNew.getStaffPhone()) + "*");
            //从redis查询 设置录单人信息 app使用
            if (keys.size() > 0) {
                String key = new ArrayList<>(keys).get(0);
                StaffResponse staffResponse = redisClient.get(key);
                courseList.setInputId(staffResponse.getId());
                courseList.setInputBy(staffResponse.getStaffName());
            }
            BaseProject baseProject = new BaseProject();
            baseProject.setId(courseList.getProjctId());
            BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
            //todo 加上购买日期判断
//            if(baseProject1.getSalesDeadline()!=null){
//                String salesDeadline = baseProject1.getSalesDeadline();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date parse;
//                try {
//                     parse = simpleDateFormat.parse(salesDeadline);
//                } catch (ParseException e) {
//                    throw new RuntimeException(e);
//                }
//                if(parse.before(new Date())){
//                    throw new SmsException(ResponseCode.MSG,baseProject1.getProjectName()+"项目超过购买时间，不允许购买");
//                }
//            }
            try {
                courseList.setSalesAchievement(baseProject1.getSalesAchievement());
                courseList.setSalesCommission(baseProject1.getSalesCommission());
//                courseList.setCardAchievementAmount(baseProject1.getCardSalesAchievement());
                courseList.setCardSalesCommission(baseProject1.getCardSalesCommission());

                //现付
                if ((courseList.getSalesAchievement()==null?BigDecimal.ZERO:courseList.getSalesAchievement()).compareTo(BigDecimal.valueOf(1)) == 1) {
//                    courseList.setAchievementAmount(courseList.getSalesAchievement());
                    if (courseList.getSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCommissionAmount(courseList.getSalesCommission());
                    } else {
                        courseList.setCommissionAmount(courseList.getSalesCommission().multiply(courseList.getCollectionCashAmount()));
                    }
                } else {
//                    courseList.setAchievementAmount(courseList.getCollectionCashAmount().multiply(courseList.getSalesAchievement()));
                    if (courseList.getSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCommissionAmount(courseList.getSalesCommission());
                    } else {
                        courseList.setCommissionAmount(courseList.getSalesCommission().multiply(courseList.getCollectionCashAmount()));
                    }
                }

                //卡付
                if ((courseList.getCardSalesAchievement()==null?BigDecimal.ZERO:courseList.getCardSalesAchievement()).compareTo(BigDecimal.valueOf(1)) == 1) {
//                    courseList.setCardAchievementAmount(courseList.getCardSalesAchievement());
                    if (courseList.getCardSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCardCommissionAmount((courseList.getCardSalesAchievement()==null?BigDecimal.ZERO:courseList.getCardSalesAchievement()));
                    } else {
                        courseList.setCardCommissionAmount((courseList.getCardSalesAchievement()==null?BigDecimal.ZERO:courseList.getCardSalesAchievement()).multiply(courseList.getCollectionRechargeAmount()));
                    }
                } else {
//                    courseList.setCardAchievementAmount(courseList.getCollectionRechargeAmount().multiply(courseList.getCardSalesAchievement()));
                    if ((courseList.getCardSalesCommission()==null?BigDecimal.valueOf(0):courseList.getCardSalesCommission()).compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCardCommissionAmount((courseList.getCardSalesCommission()==null?BigDecimal.valueOf(0):courseList.getCardSalesCommission()));
                    } else {
                        courseList.setCardCommissionAmount((courseList.getCardSalesCommission()==null?BigDecimal.valueOf(0):courseList.getCardSalesCommission())
                                .multiply(courseList.getCollectionRechargeAmount()));
                    }
                }


                courseList.setProjectNum(courseList.getProjectNum());
                i += dao.addCourse(courseList);
                //todo  高管信息为空，发生错误
                if (null != courseListRequestNew.getSalesmens() && courseListRequestNew.getSalesmens().size() > 0) {
                    HttpSession session = courseListRequestNew.getSession();
                    //添加高管的当前单据门店信息
                    StoreRequest storeRequest = new StoreRequest();
                    storeRequest.setId(Long.valueOf(String.valueOf(courseListRequestNew.getStoreId())));//session.getAttribute("storeId")
                    BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
                    //高管业绩
                    List<Salesman> salesmens = courseListRequestNew.getSalesmens();
                    BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                    if (null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100)) != 0 && reduce5.compareTo(BigDecimal.valueOf(0)) != 0) {
                        throw new SmsException(ResponseCode.MSG, "高管业绩占比和不等于100");
                    }
                    if (null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100)) != 0 && reduce6.compareTo(BigDecimal.valueOf(0)) != 0) {
                        throw new SmsException(ResponseCode.MSG, "管理员业绩占比和不等于100");
                    }
                    for (Salesman salesmen : salesmens) {
                        salesmen.setOrderId(String.valueOf(courseList.getId()));
                        salesmen.setOrderNum(courseReatmentNum);
                        salesmen.setOrderType(2);
                        salesmen.setOrderDate(courseList.getDate());
                        salesmen.setState(0);
                        salesmen.setMoney(courseList.getCollectionCashAmount());
                        salesmen.setProjectId(courseAccount.getCourseProjectId());
                        salesmen.setStoreNum(baseStore1.getStoreNum());
                        salesmen.setStoreName(baseStore1.getStoreName());
                        salesmen.setStoreIdOrder(baseStore1.getId());
                        salesmen.setOperatorBy(courseList.getInputBy());
                        salesmen.setIsAddition(courseList.getIsAddition());
                        salesmen.setStaffId(salesmen.getId());
                    }
                    ssmSalesmanService.addBatch(salesmens);
                }
            } catch (Exception e) {
                log.error("SsmCourseServiceImpl.addCourse:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            //添加现付支付方式
            if (null != payLists && payLists.size() > 0 && x==0) {
                List<PayList> collect = payLists.stream().filter(item -> item.getPayMoney().compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList());
                if (collect != null && collect.size() > 0) {
                    for (PayList payList : collect) {
                        payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        payList.setDocId(courseReatmentNum);
                        payList.setType(Constant.doc_type_card_use);
                        payList.setStoreId(courseList.getStoreId());
                        payList.setPayDate(courseList.getDate());
                        payList.setIsCancel(0);
                    }
                    ssmPayService.addPayList(collect);
                }
                x++;
            }

            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseList, courseAccount);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);

//        TransactionRecord transactionRecord = this.setTransactionRecord(courseList,courseAccount);
//        ssmTransactionRecordService.add(transactionRecord);


            //将疗程单据信息添加到评价表
            MemberCsRequest memberCsRequest = new MemberCsRequest();
            BeanUtils.copyProperties(courseList, memberCsRequest);
            memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            memberCsRequest.setDocId(courseId);
            memberCsRequest.setDocNum(courseReatmentNum);
            memberCsRequest.setDocType(Constant.doc_type_card_use);
            memberCsRequest.setDocDate(courseList.getDate());
            memberCsRequest.setTradeId(courseList.getProjctId());
            memberCsRequest.setTradeName(courseList.getProjectName());
            memberCsRequest.setTradeMoney(courseList.getAmount());
            memberCsRequest.setTradeCount(courseList.getNumberTimes());
            StringBuffer staffIds = new StringBuffer();
            StringBuffer staffNames = new StringBuffer();
            if (staffLists.size() > 0) {
                for (StaffRequest staffRequest : staffLists) {
                    staffIds = staffIds.append(staffRequest.getId()).append(",");
                    staffNames = staffNames.append(staffRequest.getStaffName()).append(",");
                }
            }
            memberCsRequest.setStaffIds(staffIds.toString());
            memberCsRequest.setStaffNames(staffNames.toString());
            ssmMemberCsService.addMemberCs(memberCsRequest);


        }
        return i;
    }

    @Override
    public StoreDaily selectDocId(StoreDailyRequest storeDailyRequest) {
        return dao.selectDocId(storeDailyRequest);
    }

    public List<RechargeAccountResponse> selectRechargeAccountList(CourseList courseList) {
        List<RechargeAccountResponse> list = new ArrayList<>();
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setDocType(Constant.doc_type_card_use);
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume);
//        accountTradeRecordRequest.setDocNum(courseList.getCourseReatmentNum());
        accountTradeRecordRequest.setDocId(courseList.getId());
        accountTradeRecordRequest.setInputDate(courseList.getDate());
//        List<AccountTradeRecord> select = ssmAccountTradeRecordService.select(accountTradeRecord1);
        List<AccountTradeRecord> recordList = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
        for (AccountTradeRecord accountTradeRecord : recordList) {
            RechargeAccountResponse rechargeAccountResponse = new RechargeAccountResponse();
//            RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(accountTradeRecord.getAccountId());
//            BeanUtils.copyProperties(rechargeAccount,rechargeAccountResponse);
            rechargeAccountResponse.setCardRestMoney(accountTradeRecord.getAccountRestMoney());
            rechargeAccountResponse.setCardConsumeMoney(accountTradeRecord.getAccountConsumeMoney());
            rechargeAccountResponse.setCardGiftMoney(accountTradeRecord.getAccountGiftRestMoney());
            rechargeAccountResponse.setGiftConsumeMoney(accountTradeRecord.getAccountGiftConsumeMoney());
            rechargeAccountResponse.setSpendMoney(accountTradeRecord.getAccountSpendMoney());
            rechargeAccountResponse.setRechargeTypeName(accountTradeRecord.getAccountName());
            list.add(rechargeAccountResponse);
        }
        return list;
    }
    @Override
    public CourseVo selectCourseOne(CourseListRequest courseListRequest) {
//        List<CourseListResponse> collect = new ArrayList<>();
        //根据订单支付方式
        PayList payList = new PayList();
        payList.setDocId(courseListRequest.getDocId());
        List<PayList> select = ssmPayService.select(payList);
        List<CourseList> courseLists = dao.selectCourseOne(courseListRequest);
        List<RechargeAccountResponse> rechargelist = new ArrayList<>();
        List<AchiCommEntity> achiCommList = new ArrayList<>();
        for (CourseList list : courseLists) {
            List<RechargeAccountResponse> rechargeAccountResponses = this.selectRechargeAccountList(list);
            CourseAccount courseAccount = new CourseAccount();
            courseAccount.setCourseNum(list.getCourseReatmentNum());
            courseAccount.setCourseProjectId(list.getProjctId());
            List<CourseAccount> select1 = ssmCourseAccountService.select(courseAccount);
            if(select1!=null && select1.size()>0){
                list.setAnotherName(select1.get(0).getAnotherName());
            }
            achiCommList = this.getAchiCommList(list);
//            if(achiCommList!=null&&achiCommList.size()>0){
//                for (AchiCommEntity achiCommEntity : achiCommList) {
//                    if(achiCommEntity.getSaleStaffId()!=null) {
//                        BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(achiCommEntity.getSaleStaffId());
//                        achiCommEntity.setBrandNumber(baseStaff.getBrandNumber());
//                    }
//                }
//            }
            rechargelist.addAll(rechargeAccountResponses);
        }
        CourseVo courseVo = new CourseVo();
        courseVo.setPayLists(select);
        courseVo.setRechargeConsumeList(rechargelist);
        courseVo.setCourseLists(courseLists);
        courseVo.setEntities(achiCommList);

        return courseVo;
    }

    @Override
    public List<CourseDayVo> selectByDay(StoreDailyRequest storeDailyRequest) {
        return dao.selectByDay(storeDailyRequest);
    }

    @Override
    public List<CourseDayVo> selectCourseCoopation(StoreDailyRequest storeDailyRequest) {
        return dao.selectCourseCoopation(storeDailyRequest);
    }

    @Override
    public List<CourseList> selectCourseByProjectAndDocId(CourseList courseList) {
        return dao.selectCourseByProjectAndDocId(courseList);
    }

    @Override
    public CourseVo selectCourseOneByError(CourseListRequest courseListRequest) {
        CourseVo courseVo = new CourseVo();
        CourseList courseList = new CourseList();
        courseList.setDate(courseListRequest.getDate());
        courseList.setId(courseListRequest.getId());
        List<CourseList> courseLists = dao.selectList(courseList);
        if(courseLists!=null && courseLists.size()>0){

            PayList payList = new PayList();
            payList.setDocId(courseLists.get(0).getCourseReatmentNum());
            List<PayList> select = ssmPayService.select(payList);
            courseVo.setPayLists(select);
        }
        List<RechargeAccountResponse> rechargelist = new ArrayList<>();
        List<AchiCommEntity> achiCommList = new ArrayList<>();
        for (CourseList list : courseLists) {
            List<RechargeAccountResponse> rechargeAccountResponses = this.selectRechargeAccountList(list);
            achiCommList = this.getAchiCommList(list);
            if(achiCommList!=null&&achiCommList.size()>0){
                for (AchiCommEntity achiCommEntity : achiCommList) {
                    if(achiCommEntity.getSaleStaffId()!=null) {
                        BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(achiCommEntity.getSaleStaffId());
                        achiCommEntity.setBrandNumber(baseStaff.getBrandNumber());
                    }
                }
            }
            rechargelist.addAll(rechargeAccountResponses);
        }


        courseVo.setRechargeConsumeList(rechargelist);
        courseVo.setCourseLists(courseLists);
        courseVo.setEntities(achiCommList);

        return courseVo;

    }

    @Override
    public List<StoreDaily> selectByDayGroupByDateAndStoreId(StoreDailyRequest storeDailyRequest) {
        return dao.selectByDayGroupByDateAndStoreId(storeDailyRequest);
    }

    @Override
    public List<CourseList> selectGroupCourse(CourseListRequest courseListRequest) {
        return mapper.selectGroupCourse(courseListRequest);
    }

    @Override
    public StoreDaily NegativeKazinByDate(StoreDailyRequest storeDailyRequest) {
        return mapper.NegativeKazinByDate(storeDailyRequest);
    }

    /*
     * 生成疗程单号 年月日+编码 20200823
     * */
    public String getDocNum(CourseList courseList1, String storeNum) {
        //查询数据库充值单编码最新的一个
        String ymdDate = DateUtils.YMDFormat(courseList1.getDate());
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(courseList1.getDate());
        courseListRequest.setSelectDate(storeNum + ymdDate);
        courseListRequest.setStoreId(courseList1.getStoreId());
        storeNum = storeNum;
        List<CourseList> courseLists = dao.getDocNum(courseListRequest);
        String courseReatmentNum;
        String num;
        int mm = 0;
        if (courseLists != null && courseLists.size() > 0) {
            CourseList courseList = courseLists.get(0);
            int a = storeNum.length();
            mm = Integer.parseInt(courseList.getCourseReatmentNum().substring(8 + a)) + 1;
            if (mm < 10) {
                num = "00" + mm;
            } else if (mm < 100) {
                num = "0" + mm;
            } else {
                num = String.valueOf(mm);
            }
            courseReatmentNum = storeNum + ymdDate + num;

        } else {
            num = "001";
            courseReatmentNum = storeNum + ymdDate + num;
        }
        return courseReatmentNum;
    }

    /*
     * 业务员赋值
     * */
    public void setStaffValue(List<StaffRequest> staffLists, CourseList courseList) {

        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0) {
                courseList.setSaleOneStaffId(staffRequest.getId());
                courseList.setSaleOneStaffName(staffRequest.getStaffName());
                courseList.setSaleOneIdentity(staffRequest.getIdentityCard());
                courseList.setSaleOneRatio(staffRequest.getRatio());
                courseList.setSaleOneNumber(staffRequest.getBrandNumber());
            } else if (i == 1) {
                courseList.setSaleTwoStaffId(staffRequest.getId());
                courseList.setSaleTwoStaffName(staffRequest.getStaffName());
                courseList.setSaleTwoIdentity(staffRequest.getIdentityCard());
                courseList.setSaleTwoRatio(staffRequest.getRatio());
                courseList.setSaleTwoNumber(staffRequest.getBrandNumber());
            } else if (i == 2) {
                courseList.setSaleThreeStaffId(staffRequest.getId());
                courseList.setSaleThreeStaffName(staffRequest.getStaffName());
                courseList.setSaleThreeIdentity(staffRequest.getIdentityCard());
                courseList.setSaleThreeRatio(staffRequest.getRatio());
                courseList.setSaleThreeNumber(staffRequest.getBrandNumber());
            } else if (i == 3) {
                courseList.setSaleFourStaffId(staffRequest.getId());
                courseList.setSaleFourStaffName(staffRequest.getStaffName());
                courseList.setSaleFourIdentity(staffRequest.getIdentityCard());
                courseList.setSaleFourRatio(staffRequest.getRatio());
                courseList.setSaleFourNumber(staffRequest.getBrandNumber());
            } else if (i == 4) {
                courseList.setSaleFiveStaffId(staffRequest.getId());
                courseList.setSaleFiveStaffName(staffRequest.getStaffName());
                courseList.setSaleFiveIdentity(staffRequest.getIdentityCard());
                courseList.setSaleFiveRatio(staffRequest.getRatio());
                courseList.setSaleFiveNumber(staffRequest.getBrandNumber());
            } else if (i == 5) {
                courseList.setSaleSixStaffId(staffRequest.getId());
                courseList.setSaleSixStaffName(staffRequest.getStaffName());
                courseList.setSaleSixIdentity(staffRequest.getIdentityCard());
                courseList.setSaleSixRatio(staffRequest.getRatio());
                courseList.setSaleSixNumber(staffRequest.getBrandNumber());
            } else if (i == 6) {
                courseList.setSaleSevenStaffId(staffRequest.getId());
                courseList.setSaleSevenStaffName(staffRequest.getStaffName());
                courseList.setSaleSevenIdentity(staffRequest.getIdentityCard());
                courseList.setSaleSevenRatio(staffRequest.getRatio());
                courseList.setSaleSevenNumber(staffRequest.getBrandNumber());
            } else if (i == 7) {
                courseList.setSaleEightStaffId(staffRequest.getId());
                courseList.setSaleEightStaffName(staffRequest.getStaffName());
                courseList.setSaleEightIdentity(staffRequest.getIdentityCard());
                courseList.setSaleEightRatio(staffRequest.getRatio());
                courseList.setSaleEightNumber(staffRequest.getBrandNumber());
            }


        }
    }
    public CourseList setAchiComm(CourseList courseList, List<RechargeAccountRequest> rechargeAccountRequestList, List<PayList> payLists){
        //查询会员是否有积分
        StoreParament parament = StoreParaUtils.getStorePara(courseList.getStoreId(),Constant.member_integral);
        BaseProject project = ssmProjectService.selectByPrimaryKey(courseList.getProjctId());
        //合作项目抽佣比例
//        BigDecimal cooperationRatio = project.getBrokerage();
        if(project.getBrokerage()==null){
            project.setBrokerage(BigDecimal.valueOf(0));
        }
        if(project.getIsCooperation()==0){
            courseList.setIsCooperation(0);
        }
        if(project.getIsCooperation()==1 && project.getSmokeCommissionWay()==1){
            courseList.setIsCooperation(1);
        }
        if(project.getIsCooperation()==1 && project.getSmokeCommissionWay()==0){
            courseList.setIsCooperation(2);
        }
        courseList.setBrokerage(project.getBrokerage());

        BigDecimal cooperationCashAchi=new BigDecimal("0");//合作现付业绩
        BigDecimal cooperationRechargeAchi=new BigDecimal("0");//合作卡付业绩
        BigDecimal cashRechargeAchiSum=new BigDecimal("0");//合作总业绩
        //isCooperation 比例brokerage 1是比例 0是固定smokeCommissionWay
        if(project.getIsCooperation()==1){
            if(project.getSmokeCommissionWay()==1){//合作按比例
                //合作项目现付业绩
                cooperationCashAchi=cooperationCashAchi.add(project.getBrokerage().multiply(courseList.getCollectionCashAmount()).divide(new BigDecimal("100")));
                //合作项目卡付业绩
                cooperationRechargeAchi=cooperationRechargeAchi.add(project.getBrokerage().multiply(courseList.getCollectionRechargeAmount().divide(new BigDecimal("100"))));
            }else{//合作按固定
                //方法1：现付和卡付对比，取最大值先扣，不够再补上


                //方法2：卡付和现付/总付金额，获取现付和卡付的支付比例*合作项目固定金额
                BigDecimal sum=courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount());
                //（卡付（或现付）/总付款金额=卡付（或现付）比例）
                BigDecimal Cash=courseList.getCollectionCashAmount().divide(sum,10,BigDecimal.ROUND_HALF_UP);
                BigDecimal Recharge=courseList.getCollectionRechargeAmount().divide(sum,10,BigDecimal.ROUND_HALF_UP);
                cooperationCashAchi=cooperationCashAchi.add(
                        project.getBrokerage()
                                .divide(project.getPriceMember(),10,BigDecimal.ROUND_HALF_UP).
                        multiply(sum).multiply(Cash).setScale(2,BigDecimal.ROUND_HALF_UP));
                cooperationRechargeAchi=cooperationRechargeAchi.add(project.getBrokerage().multiply(Recharge).setScale(2,BigDecimal.ROUND_HALF_UP));
            }
        }
        cashRechargeAchiSum=cashRechargeAchiSum.add(cooperationCashAchi).add(cooperationRechargeAchi).divide(new BigDecimal("100"));
//        courseList.setCollectionCashAmount(courseList.getCollectionCashAmount().subtract(cooperationCashAchi));//业绩-合作项目现付业绩
        courseList.setAchievementAmount(courseList.getCollectionCashAmount()
//                .subtract(cooperationCashAchi)
        );//业绩-合作项目现付业绩
        courseList.setCardAchievementAmount(courseList.getCollectionRechargeAmount()
//                .subtract(cooperationRechargeAchi)
        );//业绩-合作项目现付业绩
//        courseList.setCollectionRechargeAmount(courseList.getCollectionRechargeAmount().subtract(cooperationRechargeAchi));//业绩-合作项目卡付业绩.

        BigDecimal times = BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString());
        //现付销售业绩标准  >0 <1比率   >1固定金额
        BigDecimal achiRatio = courseList.getSalesAchievement();
        //现付销售提成标准  >0 <1比率   >1固定金额
        BigDecimal commRatio = courseList.getSalesCommission();
        //有积分
        if ("1".equals(parament.getParamentValue())){
            //查询积分支付是否计算业绩提成
            StoreParament storeParament = StoreParaUtils.getStorePara(courseList.getStoreId(),"integral");
            if (null != payLists && payLists.size() > 0 || BigDecimalUtils.compareTo(courseList.getCollectionIntegralAmount(), BigDecimalUtils.bigDecimal("0")) == 1 && project.getIsCooperation() == 0){
//暂时取消业绩提成校验
//                //业绩比率
//                if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
//                    }
//                }else {//业绩固定金额
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
//                                BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
//                    }
//                }
//                //提成比率
//                if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
//                }else {//提成固定金额
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
//                                BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));
//                    }
//                }

                //业绩比率
//                if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
//                }else {//业绩固定金额
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
//                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
//
//                }
                //提成比率
                if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
                }else {//提成固定金额
                    courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));

                }
            }

            //合作项目计算业绩提成
            if (null != payLists && payLists.size() > 0 || com.ssm.core.utils.BigDecimalUtils.compareTo(courseList.getCollectionIntegralAmount(), com.ssm.core.utils.BigDecimalUtils.bigDecimal("0")) == 1 && project.getIsCooperation() == 1){

                //业绩比率
                if (com.ssm.core.utils.BigDecimalUtils.compareTo(achiRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(achiRatio, com.ssm.core.utils.BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
//                    }
                }else {//业绩固定金额
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(
//                                com.ssm.core.utils.BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
//                    }
                }
                //提成比率
                if (com.ssm.core.utils.BigDecimalUtils.compareTo(commRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
                    courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
                }else {//提成固定金额
                    if ("1".equals(storeParament.getParamentValue())) {
                        courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(
                                com.ssm.core.utils.BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));
                    }
                }
            }
        }

        //无积分 或者不计算业绩提成
        if (null != payLists && payLists.size() > 0 && project.getIsCooperation() == 0) {
            //比率
//            if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, courseList.getCollectionCashAmount()));
//            }else {//固定金额
//                courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils
//                        .multiply(BigDecimalUtils
//                                .div(courseList.getCollectionCashAmount(), courseList.getAmount()), achiRatio), times));
//            }
            //提成比率
            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
            }else {//提成固定金额
                courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), commRatio), times));
            }
        }

        //无积分 或者不计算业绩提成 合作项目
        if (null != payLists && payLists.size() > 0 && project.getIsCooperation() == 1) {
            //比率
//            if (com.ssm.core.utils.BigDecimalUtils.compareTo(achiRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(achiRatio, courseList.getCollectionCashAmount()));
//            }else {//固定金额
//                courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), achiRatio), times));
//            }
            //提成比率
            if (com.ssm.core.utils.BigDecimalUtils.compareTo(commRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
                courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
            }else {//提成固定金额
                courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), commRatio), times));
            }
        }





//
//        StoreParament storeParament = this.getStorePara(courseList.getStoreId(),"integral");
//        BigDecimal times = BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString());
//        //积分付计入业绩和提成 提成标准是按比例提成 计算现付业绩提成
//        if (null != payLists && payLists.size() > 0) {
//            //现付销售业绩标准  >0 <1比率   >1固定金额
//            BigDecimal achiRatio = courseList.getSalesAchievement();
//            //现付销售提成标准  >0 <1比率   >1固定金额
//            BigDecimal commRatio = courseList.getSalesCommission();
//            //比率
//            if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                if ("0".equals(storeParament.getParamentValue())) {
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
//                } else {
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, courseList.getCollectionCashAmount()));
//                }
//            }else {//固定金额
//                if ("0".equals(storeParament.getParamentValue())) {
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
//                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
//                }else {
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), achiRatio), times));
//                }
//            }
//            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
////                if ("0".equals(storeParament.getParamentValue())) {
////                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
////                }else {
//                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
////                }
//            }else {
//                if ("0".equals(storeParament.getParamentValue())) {
//                    courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
//                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));
//                }else {
//                    courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), commRatio), times));
//                }
//            }
//        }
        if (null != rechargeAccountRequestList && rechargeAccountRequestList.size() > 0 && project.getIsCooperation() == 0){
            //卡付销售业绩标准  >0 <1比率   >=1固定金额
            BigDecimal cardAchiRatio = courseList.getCardSalesAchievement();
            //卡付销售提成标准  >0 <1比率   >=1固定金额
            BigDecimal cardCommRatio = courseList.getCardSalesCommission();
//            if (BigDecimalUtils.compareTo(cardAchiRatio,BigDecimalUtils.bigDecimal("1")) != 1){
//                courseList.setCardAchievementAmount(BigDecimalUtils.multiply(cardAchiRatio,courseList.getCollectionRechargeAmount()));
//            }else {
//                courseList.setCardAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionRechargeAmount(),courseList.getCourseReatmentAmount()),cardAchiRatio), times));
//            }
            if (BigDecimalUtils.compareTo(cardCommRatio,BigDecimalUtils.bigDecimal("1")) != 1) {
                courseList.setCardCommissionAmount(BigDecimalUtils.multiply(cardCommRatio, courseList.getCardAchievementAmount()));

            }else {
                courseList.setCardCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionRechargeAmount(),courseList.getCourseReatmentAmount()),cardCommRatio), times));
            }
        }

        //充值卡付 合作项目
        if (null != rechargeAccountRequestList && rechargeAccountRequestList.size() > 0 && project.getIsCooperation() == 1){
            //卡付销售业绩标准  >0 <1比率   >=1固定金额
            BigDecimal cardAchiRatio = courseList.getCardSalesAchievement();
            //卡付销售提成标准  >0 <1比率   >=1固定金额
            BigDecimal cardCommRatio = courseList.getCardSalesCommission();
//            if (com.ssm.core.utils.BigDecimalUtils.compareTo(cardAchiRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1){
//                courseList.setCardAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(cardAchiRatio, courseList.getCollectionRechargeAmount()));
//            }else {
//                courseList.setCardAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionRechargeAmount(),courseList.getCourseReatmentAmount()),cardAchiRatio), times));
//            }
            if (com.ssm.core.utils.BigDecimalUtils.compareTo(cardCommRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
                courseList.setCardCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(cardCommRatio, courseList.getCardAchievementAmount()));

            }else {
                courseList.setCardCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionRechargeAmount(),courseList.getCourseReatmentAmount()),cardCommRatio), times));
            }
        }

        return courseList;
    }


//    public CourseList setAchiComm(CourseList courseList, List<RechargeAccountRequest> rechargeAccountRequestList, List<PayList> payLists) {
//        //查询会员是否有积分
//        StoreParament parament = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.member_integral);
//        BaseProject project = ssmProjectService.selectByPrimaryKey(courseList.getProjctId());
//        //合作项目抽佣比例
//        //BigDecimal cooperationRatio = project.getBrokerage();
//
//        BigDecimal cooperationCashAchi = new BigDecimal("0");//合作现付业绩
//        BigDecimal cooperationRechargeAchi = new BigDecimal("0");//合作卡付业绩
//        BigDecimal cashRechargeAchiSum = new BigDecimal("0");//合作总业绩
//        //isCooperation 比例brokerage 1是比例 0是固定smokeCommissionWay
//        if (project.getIsCooperation() == 1) {
//            if (project.getSmokeCommissionWay() == 1) {//合作按比例
//                //合作项目现付业绩
//                cooperationCashAchi = cooperationCashAchi.add(project.getBrokerage().multiply(courseList.getCollectionCashAmount()).divide(new BigDecimal("100")));
//                //合作项目卡付业绩
//                cooperationRechargeAchi = cooperationRechargeAchi.add(project.getBrokerage().multiply(courseList.getCollectionRechargeAmount()));
//            } else {//合作按固定
//                //方法1：现付和卡付对比，取最大值先扣，不够再补上
//
//
//                //方法2：卡付和现付/总付金额，获取现付和卡付的支付比例*合作项目固定金额
//                BigDecimal sum = courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount());
//                //（卡付（或现付）/总付款金额=卡付（或现付）比例）
//                BigDecimal Cash = courseList.getCollectionCashAmount().divide(sum, 10, BigDecimal.ROUND_HALF_UP);
//                BigDecimal Recharge = courseList.getCollectionRechargeAmount().divide(sum, 10, BigDecimal.ROUND_HALF_UP);
//                cooperationCashAchi = cooperationCashAchi.add(project.getBrokerage().multiply(Cash).setScale(2, BigDecimal.ROUND_HALF_UP));
//                cooperationRechargeAchi = cooperationRechargeAchi.add(project.getBrokerage().multiply(Recharge).setScale(2, BigDecimal.ROUND_HALF_UP));
//            }
//        }
//        cashRechargeAchiSum = cashRechargeAchiSum.add(cooperationCashAchi).add(cooperationRechargeAchi).divide(new BigDecimal("100"));
//        courseList.setCollectionCashAmount(courseList.getCollectionCashAmount().subtract(cooperationCashAchi));//业绩-合作项目现付业绩
//        courseList.setCollectionRechargeAmount(courseList.getCollectionRechargeAmount().subtract(cooperationRechargeAchi));//业绩-合作项目卡付业绩.
//
//        BigDecimal times = BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString());
//        //现付销售业绩标准  >0 <1比率   >1固定金额
//        BigDecimal achiRatio = courseList.getSalesAchievement();
//        //现付销售提成标准  >0 <1比率   >1固定金额
//        BigDecimal commRatio = courseList.getSalesCommission();
//        //有积分
//        if ("1".equals(parament.getParamentValue())) {
//            //查询积分支付是否计算业绩提成
//            StoreParament storeParament = StoreParaUtils.getStorePara(courseList.getStoreId(), "integral");
//            if (null != payLists && payLists.size() > 0 || BigDecimalUtils.compareTo(courseList.getCollectionIntegralAmount(), BigDecimalUtils.bigDecimal("0")) == 1 && project.getIsCooperation() == 0) {
////暂时取消业绩提成校验
////                //业绩比率
////                if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
////                    if ("1".equals(storeParament.getParamentValue())) {
////                        courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
////                    }
////                }else {//业绩固定金额
////                    if ("1".equals(storeParament.getParamentValue())) {
////                        courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
////                                BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
////                    }
////                }
////                //提成比率
////                if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
////                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
////                }else {//提成固定金额
////                    if ("1".equals(storeParament.getParamentValue())) {
////                        courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
////                                BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));
////                    }
////                }
//
//                //业绩比率
//                if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
//                } else {//业绩固定金额
//                    courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
//                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
//
//                }
//                //提成比率
//                if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
//                } else {//提成固定金额
//                    courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
//                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));
//
//                }
//            }
//
//            //合作项目计算业绩提成
//            if (null != payLists && payLists.size() > 0 || com.ssm.core.utils.BigDecimalUtils.compareTo(courseList.getCollectionIntegralAmount(), com.ssm.core.utils.BigDecimalUtils.bigDecimal("0")) == 1 && project.getIsCooperation() == 1) {
//
//                //业绩比率
//                if (com.ssm.core.utils.BigDecimalUtils.compareTo(achiRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(achiRatio, com.ssm.core.utils.BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
//                    }
//                } else {//业绩固定金额
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(
//                                com.ssm.core.utils.BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
//                    }
//                }
//                //提成比率
//                if (com.ssm.core.utils.BigDecimalUtils.compareTo(commRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                    courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
//                } else {//提成固定金额
//                    if ("1".equals(storeParament.getParamentValue())) {
//                        courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(
//                                com.ssm.core.utils.BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));
//                    }
//                }
//            }
//        }
//
//        //无积分 或者不计算业绩提成
//        if (null != payLists && payLists.size() > 0 && project.getIsCooperation() == 0) {
//            //比率
//            if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, courseList.getCollectionCashAmount()));
//            } else {//固定金额
//                courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), achiRatio), times));
//            }
//            //提成比率
//            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
//            } else {//提成固定金额
//                courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), commRatio), times));
//            }
//        }
//
//        //无积分 或者不计算业绩提成 合作项目
//        if (null != payLists && payLists.size() > 0 && project.getIsCooperation() == 1) {
//            //比率
//            if (com.ssm.core.utils.BigDecimalUtils.compareTo(achiRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(achiRatio, courseList.getCollectionCashAmount()));
//            } else {//固定金额
//                courseList.setAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), achiRatio), times));
//            }
//            //提成比率
//            if (com.ssm.core.utils.BigDecimalUtils.compareTo(commRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
//            } else {//提成固定金额
//                courseList.setCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), commRatio), times));
//            }
//        }
//
//
////
////        StoreParament storeParament = this.getStorePara(courseList.getStoreId(),"integral");
////        BigDecimal times = BigDecimalUtils.bigDecimal(courseList.getNumberTimes().toString());
////        //积分付计入业绩和提成 提成标准是按比例提成 计算现付业绩提成
////        if (null != payLists && payLists.size() > 0) {
////            //现付销售业绩标准  >0 <1比率   >1固定金额
////            BigDecimal achiRatio = courseList.getSalesAchievement();
////            //现付销售提成标准  >0 <1比率   >1固定金额
////            BigDecimal commRatio = courseList.getSalesCommission();
////            //比率
////            if (BigDecimalUtils.compareTo(achiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
////                if ("0".equals(storeParament.getParamentValue())) {
////                    courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
////                } else {
////                    courseList.setAchievementAmount(BigDecimalUtils.multiply(achiRatio, courseList.getCollectionCashAmount()));
////                }
////            }else {//固定金额
////                if ("0".equals(storeParament.getParamentValue())) {
////                    courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
////                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), achiRatio), times));
////                }else {
////                    courseList.setAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), achiRatio), times));
////                }
////            }
////            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//////                if ("0".equals(storeParament.getParamentValue())) {
//////                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount())));
//////                }else {
////                    courseList.setCommissionAmount(BigDecimalUtils.multiply(commRatio, courseList.getAchievementAmount()));
//////                }
////            }else {
////                if ("0".equals(storeParament.getParamentValue())) {
////                    courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(
////                            BigDecimalUtils.add(courseList.getCollectionCashAmount(), courseList.getCollectionIntegralAmount()), courseList.getAmount()), commRatio), times));
////                }else {
////                    courseList.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionCashAmount(), courseList.getAmount()), commRatio), times));
////                }
////            }
////        }
//        if (null != rechargeAccountRequestList && rechargeAccountRequestList.size() > 0 && project.getIsCooperation() == 0) {
//            //卡付销售业绩标准  >0 <1比率   >=1固定金额
//            BigDecimal cardAchiRatio = courseList.getCardSalesAchievement();
//            //卡付销售提成标准  >0 <1比率   >=1固定金额
//            BigDecimal cardCommRatio = courseList.getCardSalesCommission();
//            if (BigDecimalUtils.compareTo(cardAchiRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setCardAchievementAmount(BigDecimalUtils.multiply(cardAchiRatio, courseList.getCollectionRechargeAmount()));
//            } else {
//                courseList.setCardAchievementAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionRechargeAmount(), courseList.getCourseReatmentAmount()), cardAchiRatio), times));
//            }
//            if (BigDecimalUtils.compareTo(cardCommRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setCardCommissionAmount(BigDecimalUtils.multiply(cardCommRatio, courseList.getCardAchievementAmount()));
//
//            } else {
//                courseList.setCardCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(BigDecimalUtils.div(courseList.getCollectionRechargeAmount(), courseList.getCourseReatmentAmount()), cardCommRatio), times));
//            }
//        }
//
//        //充值卡付 合作项目
//        if (null != rechargeAccountRequestList && rechargeAccountRequestList.size() > 0 && project.getIsCooperation() == 1) {
//            //卡付销售业绩标准  >0 <1比率   >=1固定金额
//            BigDecimal cardAchiRatio = courseList.getCardSalesAchievement();
//            //卡付销售提成标准  >0 <1比率   >=1固定金额
//            BigDecimal cardCommRatio = courseList.getCardSalesCommission();
//            if (com.ssm.core.utils.BigDecimalUtils.compareTo(cardAchiRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setCardAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(cardAchiRatio, courseList.getCollectionRechargeAmount()));
//            } else {
//                courseList.setCardAchievementAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionRechargeAmount(), courseList.getCourseReatmentAmount()), cardAchiRatio), times));
//            }
//            if (com.ssm.core.utils.BigDecimalUtils.compareTo(cardCommRatio, com.ssm.core.utils.BigDecimalUtils.bigDecimal("1")) != 1) {
//                courseList.setCardCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(cardCommRatio, courseList.getCardAchievementAmount()));
//
//            } else {
//                courseList.setCardCommissionAmount(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.multiply(com.ssm.core.utils.BigDecimalUtils.div(courseList.getCollectionRechargeAmount(), courseList.getCourseReatmentAmount()), cardCommRatio), times));
//            }
//        }
//
//        return courseList;
//    }

    /*1
     * 账户交易记录属性赋值 疗程
     * */
    public AccountTradeRecord setAccountTradeRecord(CourseList courseList, CourseAccount courseAccount) {
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(courseList.getStoreId());
        accountTradeRecord.setStoreName(courseList.getStoreName());
        accountTradeRecord.setMemberId(courseList.getMemberId());
        accountTradeRecord.setMemberName(courseList.getMemberName());

        accountTradeRecord.setMemberIdentity(courseList.getMemberIdentity());
        accountTradeRecord.setMemberPhone(courseList.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
        accountTradeRecord.setAccountInMoney(courseList.getCourseReatmentAmount());
        if (courseList.getIsAddition() == 1) {
            accountTradeRecord.setAdditionDate(courseList.getAdditionDate());
        }
        if (courseList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_project);
            accountTradeRecord.setInputDate(courseList.getDate());
            accountTradeRecord.setInputBy(courseList.getInputBy());
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
            accountTradeRecord.setAccountInMoney(courseAccount.getCourseRestPrice());
        } else {
            accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
            accountTradeRecord.setInputDate(courseList.getCancelDate());
            accountTradeRecord.setInputBy(courseList.getCancelBy());
            accountTradeRecord.setAccountSpendCount(courseAccount.getCourseCount());
            accountTradeRecord.setAccountSpendMoney(courseAccount.getCourseRestPrice());
        }
        accountTradeRecord.setIsAddition(courseList.getIsAddition());
        accountTradeRecord.setDocId(courseList.getId());
        accountTradeRecord.setDebtMoney(courseList.getDebtMoney());
        accountTradeRecord.setPrice(courseList.getSalesPrice());
        accountTradeRecord.setDocNum(courseList.getCourseReatmentNum());
        accountTradeRecord.setDocType(Constant.doc_type_card_use);
        accountTradeRecord.setTradeId(courseAccount.getCourseProjectId());
        accountTradeRecord.setTradeName(courseAccount.getCourseProjectName());
        accountTradeRecord.setTradeMoney(courseAccount.getCourseProjectMoney());
        accountTradeRecord.setTradeCount(courseAccount.getCourseCount());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        accountTradeRecord.setAccountRestMoney(courseAccount.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(courseAccount.getCourseConsumePrice());
        accountTradeRecord.setCardMoney(courseList.getCollectionRechargeAmount());
        accountTradeRecord.setCashMoney(courseList.getCollectionCashAmount());
        return accountTradeRecord;
    }

    /*
     * 账户交易记录属性赋值 疗程
     * */
    public TransactionRecord setTransactionRecord(CourseList courseList, CourseAccount courseAccount) {
        TransactionRecord accountTradeRecord = new TransactionRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(courseList.getStoreId());
        accountTradeRecord.setStoreName(courseList.getStoreName());
        accountTradeRecord.setMemberId(courseList.getMemberId());
        accountTradeRecord.setMemberName(courseList.getMemberName());
        accountTradeRecord.setMemberIdentity(courseList.getMemberIdentity());
        accountTradeRecord.setMemberPhone(courseList.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
        BaseProject baseProject = new BaseProject();
        baseProject.setId(courseAccount.getCourseProjectId());
        baseProject = ssmProjectService.selectOne(baseProject);
        accountTradeRecord.setAccountNum(baseProject.getProjectNum());

        if (courseList.getIsCancel() == 0) {
            accountTradeRecord.setType(12);
            accountTradeRecord.setDocState(0);
            accountTradeRecord.setAccountType(Constant.account_type_project);
            accountTradeRecord.setDocDate(courseList.getDate());
            accountTradeRecord.setAccountInMoney(courseList.getCourseReatmentAmount());
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
            accountTradeRecord.setOperationBy(courseList.getInputBy());
        } else {
            accountTradeRecord.setType(14);
            accountTradeRecord.setDocState(1);
            accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
            accountTradeRecord.setDocDate(courseList.getCancelDate());
            accountTradeRecord.setCardMoney(courseList.getCourseReatmentAmount());
            accountTradeRecord.setAccountSpendCount(courseAccount.getCourseCount());
            accountTradeRecord.setOperationBy(courseList.getCancelBy());
        }
        accountTradeRecord.setDate(new Date());
        accountTradeRecord.setDocId(courseList.getId());
        accountTradeRecord.setDocNum(courseList.getCourseReatmentNum());
        accountTradeRecord.setDocProjectId(courseAccount.getCourseProjectId());
        accountTradeRecord.setDocProjectName(courseAccount.getCourseProjectName());
        baseProject.setId(courseAccount.getCourseProjectId());
        BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
        accountTradeRecord.setDocProjectNum(baseProject1.getProjectNum());
        accountTradeRecord.setTradingMoney(courseAccount.getCourseProjectMoney());
        accountTradeRecord.setTradeCount(courseAccount.getCourseCount());
        accountTradeRecord.setCashMoney(courseList.getCollectionCashAmount());
        accountTradeRecord.setDebtMoney(courseList.getDebtMoney());
        accountTradeRecord.setAccountRestMoney(courseAccount.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(courseAccount.getCourseConsumePrice());
        accountTradeRecord.setAccountRestCount(courseAccount.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(courseAccount.getCourseConsumeCount());
        return accountTradeRecord;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancel(CourseListRequest courseListRequest) throws SmsException {
        StoreParament storeParament = StoreParaUtils.getStorePara(courseListRequest.getStoreId(), Constant.service_ticke);
        int days = (int) DateUtils.getDayDiff(courseListRequest.getDate(), new Date());
        if(!"0".equals(storeParament.getParamentValue())) {
            if (Integer.parseInt(storeParament.getParamentValue()) < days) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据超过允许作废时间");
            }
        }
        int i = 0;
        PayList payList = new PayList();
        payList.setDocId(courseListRequest.getCourseReatmentNum());
        List<PayList> payListList = ssmPayService.select(payList);
        if(payListList!=null&&payListList.size()>0) {
            for (PayList list : payListList) {
                list.setIsCancel(1);
                ssmPayService.updateByNum(list);
            }
        }
        CourseList courseList = new CourseList();
        BeanUtils.copyProperties(courseListRequest, courseList);
        //判断该单据是否欠款
        if (courseListRequest.getDebtMoney().compareTo(BigDecimal.valueOf(0)) == 1) {
            DebtList debtList = new DebtList();
            debtList.setDocNum(courseListRequest.getCourseReatmentNum());
            debtList.setStoreId(courseListRequest.getStoreId());
            List<DebtList> select = ssmDebtService.select(debtList);
            for (DebtList list : select) {
                if (list.getState() == 1 || list.getState() == 2  ) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.MSG, "该单据存在未作废还款和取消欠款，请先作废");
                }
                if(list.getTradeId().equals(courseList.getProjctId()) && list.getTradeMoney().compareTo(courseList.getAmount())==0
                && (list.getAccountId()==courseList.getCourseAccountId() || list.getAccountId().toString().equals(courseList.getCourseAccountId().toString()))){
                    if(list.getDebtMoney().compareTo(courseList.getDebtMoney())!=0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.MSG,"该单据已经存在还款，不允许作废");
                    }
                }
            }
        }
        //如果使用积分支付 将积分返回
        if (courseList.getIntegral() !=null && 0 != courseList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(courseList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() + courseList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }
        //查询疗程账户
        CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(courseList.getCourseAccountId());
        if (null == courseAccount) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S, "疗程账户");
        }

        //判断当前疗程单是否是最近疗程单
        this.checkRecentCourse(courseList, courseAccount);

        //修改疗程单据状态
        courseList.setIsCancel(1);
        courseList.setCancelDate(new Date());

        //疗程账户扣减次数
        //CourseAccount afterAccount = ssmCourseAccountService.subCount(courseAccount, courseList.getNumberTimes(), 1);
        CourseAccount afterAccount = ssmCourseAccountService.subCount(courseAccount, courseList.getNumberTimes(), 1, courseList);
        //如果有使用充值卡支付 充值账户钱数增加
        if (null != courseList.getCollectionRechargeAmount()) {
            List<RechargeAccountRequest> rechargeAccountRequestList = courseListRequest.getRechargeAccountList();
            ssmRechargeAccountService.addMoney(rechargeAccountRequestList, courseList);
        }

        //设置作废人信息
        if (redisClient.hasKey(getStaffKey(courseListRequest.getStaffPhone()))) {
            StaffResponse staffResponse = redisClient.get(getStaffKey(courseListRequest.getStaffPhone()));
            courseList.setCancelId(staffResponse.getId());
            courseList.setCancelBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(courseListRequest.getStaffPhone()) + "*");
        //从redis查询 设置作废人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            courseList.setCancelId(staffResponse.getId());
            courseList.setCancelBy(staffResponse.getStaffName());
        }
        //只计算总先付卡付业绩提成
        courseList.setAchievementAmount(BigDecimalUtils.bigDecimal("0"));
        courseList.setCommissionAmount(BigDecimalUtils.bigDecimal("0"));
        courseList.setCardAchievementAmount(BigDecimalUtils.bigDecimal("0"));
        courseList.setCardCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        //单据业务员业绩提成置0
//        if (null != courseList.getSaleOneStaffId()) {
//            courseList.setSaleOneAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleOneCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != courseList.getSaleTwoStaffId()) {
//            courseList.setSaleTwoAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleTwoCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != courseList.getSaleThreeStaffId()) {
//            courseList.setSaleThreeAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleThreeCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != courseList.getSaleFourStaffId()) {
//            courseList.setSaleFourAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleFourCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }

        //欠款 删除欠款记录
        if (1 == courseList.getIsDebt()) {
            DebtListRequest debtListRequest = new DebtListRequest();
            debtListRequest.setDocId(courseList.getId());
            debtListRequest.setMemberId(courseList.getMemberId());
            debtListRequest.setStoreId(courseList.getStoreId());
            ssmDebtService.deleteDebt(debtListRequest);
        }

        try {
            i = dao.cancel(courseList);
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(courseList.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(1);
                ssmSalesmanService.updateNotNull(salesman1);
            }
        } catch (Exception e) {
            log.error("SsmCourseServiceImpl.cancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加账户交易记录
        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseList, afterAccount);
        accountTradeRecord.setOrderStatu(1);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

        //将评价单进行删除操作
        MemberCs memberCs = new MemberCs();
        memberCs.setDocId(courseList.getId());
        ssmMemberCsService.delete(memberCs);

        return i;
    }


    public void checkRecentCourse(CourseList courseList, CourseAccount courseAccount) throws SmsException {
        //判断单据购买次数和账户剩余次数是否相等
        if (courseList.getNumberTimes()-courseAccount.getCourseRestCount()!=0) {
            throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据购买后次数和账户剩余次数不相等");
        }

        //判断时间是否超过允许作废时间
        StoreParament storeParament = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.service_ticke);
        Long days = DateUtils.getDayDiff(courseList.getDate(), new Date());
        if (!"0".equals(storeParament.getParamentValue())) {
            if (days.longValue() > Long.parseLong(storeParament.getParamentValue())) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据超过允许作废时间");
            }
        }
    }

    public StoreParament getStorePara(Long storeId, String key) {
        StoreParament storeParament = new StoreParament();
        storeParament.setStoreId(storeId);
        storeParament.setParamentName(key);
        storeParament = ssmStoreParaService.selectOne(storeParament);
        return storeParament;
    }
    /*
     * 业务员赋值
     * */
    public void setStaffValue(List<StaffRequest> staffLists, DebtList debtList){

        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0){
                debtList.setSaleOneStaffId(staffRequest.getId());
                debtList.setSaleOneStaffName(staffRequest.getStaffName());
                debtList.setSaleOneIdentity(staffRequest.getIdentityCard());
                debtList.setSaleOneRatio(staffRequest.getRatio());
                debtList.setSaleOneNumber(staffRequest.getBrandNumber());
            }else if (i == 1){
                debtList.setSaleTwoStaffId(staffRequest.getId());
                debtList.setSaleTwoStaffName(staffRequest.getStaffName());
                debtList.setSaleTwoIdentity(staffRequest.getIdentityCard());
                debtList.setSaleTwoRatio(staffRequest.getRatio());
                debtList.setSaleTwoNumber(staffRequest.getBrandNumber());
            }else if (i == 2){
                debtList.setSaleThreeStaffId(staffRequest.getId());
                debtList.setSaleThreeStaffName(staffRequest.getStaffName());
                debtList.setSaleThreeIdentity(staffRequest.getIdentityCard());
                debtList.setSaleThreeRatio(staffRequest.getRatio());
                debtList.setSaleThreeNumber(staffRequest.getBrandNumber());
            }else if(i==3){
                debtList.setSaleFourStaffId(staffRequest.getId());
                debtList.setSaleFourStaffName(staffRequest.getStaffName());
                debtList.setSaleFourIdentity(staffRequest.getIdentityCard());
                debtList.setSaleFourRatio(staffRequest.getRatio());
                debtList.setSaleFourNumber(staffRequest.getBrandNumber());
            }else if (i == 4){
                debtList.setSaleFiveStaffId(staffRequest.getId());
                debtList.setSaleFiveStaffName(staffRequest.getStaffName());
                debtList.setSaleFiveIdentity(staffRequest.getIdentityCard());
                debtList.setSaleFiveRatio(staffRequest.getRatio());
                debtList.setSaleFiveNumber(staffRequest.getBrandNumber());
            }else if (i == 5){
                debtList.setSaleSixStaffId(staffRequest.getId());
                debtList.setSaleSixStaffName(staffRequest.getStaffName());
                debtList.setSaleSixIdentity(staffRequest.getIdentityCard());
                debtList.setSaleSixRatio(staffRequest.getRatio());
                debtList.setSaleSixNumber(staffRequest.getBrandNumber());
            }else if (i == 6){
                debtList.setSaleSevenStaffId(staffRequest.getId());
                debtList.setSaleSevenStaffName(staffRequest.getStaffName());
                debtList.setSaleSevenIdentity(staffRequest.getIdentityCard());
                debtList.setSaleSevenRatio(staffRequest.getRatio());
                debtList.setSaleSevenNumber(staffRequest.getBrandNumber());
            }else if (i==7){
                debtList.setSaleEightStaffId(staffRequest.getId());
                debtList.setSaleEightStaffName(staffRequest.getStaffName());
                debtList.setSaleEightIdentity(staffRequest.getIdentityCard());
                debtList.setSaleEightRatio(staffRequest.getRatio());
                debtList.setSaleEightNumber(staffRequest.getBrandNumber());
            }
        }
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateStaff(CourseListRequest courseListRequest) throws SmsException {
        StoreParament storeParament = StoreParaUtils.getStorePara(courseListRequest.getStoreId(), Constant.editOrderNum);
        int days = (int) DateUtils.getDayDiff(courseListRequest.getDate(), new Date());
        if("999".equals(storeParament.getParamentValue())) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            if(!dateFormat.format(new Date()).equals(dateFormat.format(courseListRequest.getDate()))) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "请联系管理员");
            }
        }
        if (!"0".equals(storeParament.getParamentValue())) {
            if (Integer.parseInt(storeParament.getParamentValue()) < days) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "单据超过允许修改时间");
            }
        }

        int i = 0;
//        CourseList courseList = new CourseList();
        CourseListRequest courseListRequest1 = new CourseListRequest();
        courseListRequest1.setDocId(courseListRequest.getDocId());
        courseListRequest1.setDate(courseListRequest.getDate());
        List<CourseList> courseListss = dao.selectCourseOne(courseListRequest1);
        List<PayList> payLists = courseListRequest.getPayLists();
        if(payLists!=null && payLists.size()>0){
            for (PayList payList : payLists) {
                BaseCollectionType baseCollectionType = ssmCollectionTypeService.selectByPrimaryKey(payList.getPayId());
                payList.setPayName(baseCollectionType.getCollectionTypeName());
                ssmPayService.updateByPrimaryKey(payList);
            }
        }
        for (CourseList courseList : courseListss) {
//            BeanUtils.copyProperties(courseListRequest, courseList);
            //修改疗程账户的项目别名
//            CourseAccount courseAccount = new CourseAccount();
//            courseAccount.setCourseNum(courseList.getCourseReatmentNum());
//            courseAccount.setCourseProjectId(courseList.getProjctId());
//            List<CourseAccount> select1 = ssmCourseAccountService.select(courseAccount);
//            if(select1!=null && select1.size()>0){
//                for (CourseAccount account : select1) {
//                    account.setAnotherName(courseList.getAnotherName());
//                    ssmCourseAccountService.updateByPrimaryKey(account);
//                }
//            }
            //设置业务员
            List<StaffRequest> staffLists = courseListRequest.getStaffLists();
            BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100)) != 0 && reduce3.compareTo(BigDecimal.valueOf(0)) != 0) {
                throw new SmsException(ResponseCode.MSG, "助理业绩占比和不等于100");
            }
            courseList.setSaleOneStaffId(null);
            courseList.setSaleOneStaffName(null);
            courseList.setSaleOneIdentity(null);
            courseList.setSaleOneRatio(null);
            courseList.setSaleOneNumber(null);

            courseList.setSaleTwoStaffId(null);
            courseList.setSaleTwoStaffName(null);
            courseList.setSaleTwoIdentity(null);
            courseList.setSaleTwoRatio(null);
            courseList.setSaleTwoNumber(null);

            courseList.setSaleThreeStaffId(null);
            courseList.setSaleThreeStaffName(null);
            courseList.setSaleThreeIdentity(null);
            courseList.setSaleThreeRatio(null);
            courseList.setSaleThreeNumber(null);

            courseList.setSaleFourStaffId(null);
            courseList.setSaleFourStaffName(null);
            courseList.setSaleFourIdentity(null);
            courseList.setSaleFourRatio(null);
            courseList.setSaleFourNumber(null);

            courseList.setSaleFiveStaffId(null);
            courseList.setSaleFiveStaffName(null);
            courseList.setSaleFiveIdentity(null);
            courseList.setSaleFiveRatio(null);
            courseList.setSaleFiveNumber(null);

            courseList.setSaleSixStaffId(null);
            courseList.setSaleSixStaffName(null);
            courseList.setSaleSixIdentity(null);
            courseList.setSaleSixRatio(null);
            courseList.setSaleSixNumber(null);

            courseList.setSaleSevenStaffId(null);
            courseList.setSaleSevenStaffName(null);
            courseList.setSaleSevenIdentity(null);
            courseList.setSaleSevenRatio(null);
            courseList.setSaleSevenNumber(null);

            courseList.setSaleEightStaffId(null);
            courseList.setSaleEightStaffName(null);
            courseList.setSaleEightIdentity(null);
            courseList.setSaleEightRatio(null);
            courseList.setSaleEightNumber(null);


            this.setStaffValue(staffLists, courseList);

//        //计算卡付现付业绩提成
//        List<PayList> payLists = courseListRequest.getPayLists();
//        //查询对应充值账户
//        List<RechargeAccountRequest> rechargeAccountList = courseListRequest.getRechargeAccountList();
//        courseList = this.setAchiComm(courseList,rechargeAccountList,payLists);
            //如果欠款，则修改欠款单
            if(courseList.getIsDebt()==1){
                DebtList debtList = new DebtList();
                debtList.setDocId(courseList.getId());
                List<DebtList> debtLists = ssmDebtService.select(debtList);
                for (DebtList list : debtLists) {
                    if(list.getState()==0) {
                        list.setSaleOneStaffId(null);
                        list.setSaleOneStaffName(null);
                        list.setSaleOneIdentity(null);
                        list.setSaleOneRatio(null);
                        list.setSaleOneNumber(null);

                        list.setSaleTwoStaffId(null);
                        list.setSaleTwoStaffName(null);
                        list.setSaleTwoIdentity(null);
                        list.setSaleTwoRatio(null);
                        list.setSaleTwoNumber(null);

                        list.setSaleThreeStaffId(null);
                        list.setSaleThreeStaffName(null);
                        list.setSaleThreeIdentity(null);
                        list.setSaleThreeRatio(null);
                        list.setSaleThreeNumber(null);

                        list.setSaleFourStaffId(null);
                        list.setSaleFourStaffName(null);
                        list.setSaleFourIdentity(null);
                        list.setSaleFourRatio(null);
                        list.setSaleFourNumber(null);

                        list.setSaleFiveStaffId(null);
                        list.setSaleFiveStaffName(null);
                        list.setSaleFiveIdentity(null);
                        list.setSaleFiveRatio(null);
                        list.setSaleFiveNumber(null);

                        list.setSaleSixStaffId(null);
                        list.setSaleSixStaffName(null);
                        list.setSaleSixIdentity(null);
                        list.setSaleSixRatio(null);
                        list.setSaleSixNumber(null);

                        list.setSaleSevenStaffId(null);
                        list.setSaleSevenStaffName(null);
                        list.setSaleSevenIdentity(null);
                        list.setSaleSevenRatio(null);
                        list.setSaleSevenNumber(null);

                        list.setSaleEightStaffId(null);
                        list.setSaleEightStaffName(null);
                        list.setSaleEightIdentity(null);
                        list.setSaleEightRatio(null);
                        list.setSaleEightNumber(null);
                        this.setStaffValue(staffLists, list);
                        ssmDebtService.updateNotNull(list);
                    }
                }
            }
            try {
                i = dao.updateStaff(courseList);
                CourseListRequest courseLists = new CourseListRequest();
                courseLists.setId(courseList.getId());
                courseLists.setDate(courseListRequest.getDate());
                List<CourseList> courseLists1 = dao.selectPages(courseLists);
                Salesman salesman = new Salesman();
                salesman.setOrderId(String.valueOf(courseList.getId()));
                List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                Date date = courseList.getDate();
                for (Salesman salesman1 : salesmen) {
                    date = salesman1.getOrderDate();
                    ssmSalesmanService.delete(salesman1);
                }
                BaseStore baseStore = new BaseStore();
                baseStore.setId(courseListRequest.getStoreId());
                BaseStore select = ssmBaseStoreService.selectOne(baseStore);
                List<Salesman> salesmens = courseListRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if (null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100)) != 0 && reduce5.compareTo(BigDecimal.valueOf(0)) != 0) {
                    throw new SmsException(ResponseCode.MSG, "高管业绩占比和不等于100");
                }
                if (null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100)) != 0 && reduce6.compareTo(BigDecimal.valueOf(0)) != 0) {
                    throw new SmsException(ResponseCode.MSG, "管理员业绩占比和不等于100");
                }
                for (Salesman salesmen2 : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
//                    salesmen2.setStaffId(salesmen2.getId());
                    salesmen2.setId(salesmen2.getId() + i1);
                    salesmen2.setOrderId(String.valueOf(courseList.getId()));
                    salesmen2.setOrderNum(courseList.getCourseReatmentNum());
                    salesmen2.setOrderType(2);
                    salesmen2.setOrderDate(date);
                    salesmen2.setState(0);
                    salesmen2.setMoney(courseLists1.get(0).getCollectionCashAmount());
                    salesmen2.setProjectId(courseLists1.get(0).getProjctId());
                    salesmen2.setStoreNum(select.getStoreNum());
                    salesmen2.setStoreName(select.getStoreName());
                    salesmen2.setOperatorBy(courseList.getInputBy());
                    salesmen2.setIsAddition(courseList.getIsAddition());
                    salesmen2.setStoreIdOrder(select.getId());
                }
                ssmSalesmanService.addBatch(salesmens);
            } catch (Exception e) {
                log.error("SsmCourseServiceImpl.updateStaff:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
        }

        return i;
    }
    @Autowired
    private CourseListMapper mapper;

    @Override
    public List<CourseListResponse> selectList(Long storeId, String dateStr, Date date) throws SmsException, ParseException {
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(date);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setDateStr(dateStr);
        courseListRequest.setIsCancel(0);
//        courseListRequest.setPageSize(500);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), date) < 0) {
            throw new SmsException(ResponseCode.NO_DATA);
        }

        List<CourseList> pageInfo = mapper.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            for (AchiCommEntity entity : entities) {
                if (courseList.getCourseReatmentNum().equals(entity.getDocNum())) {
                    entity.setProjectId(courseList.getProjectNum());
                }
                entity.setDocId(courseList.getId());
            }
            courseListResponse.setEntities(entities);
            listResponses.add(courseListResponse);
        }
        return listResponses;
    }

    @Override
    public List<CourseList> selectListByStarteTimeAndEndTime(Long storeId, String dateStr, Date startTime,Date endTime) throws SmsException, ParseException {
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(startTime);
        courseListRequest.setStartTime(startTime);
        courseListRequest.setEndTime(endTime);
        courseListRequest.setStoreId(storeId);
//        courseListRequest.setDateStr(dateStr);
        courseListRequest.setIsCancel(0);
//        courseListRequest.setPageSize(500);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), startTime) < 0) {
            throw new SmsException(ResponseCode.NO_DATA);
        }

        List<CourseList> pageInfo = mapper.selectPage(courseListRequest);
        return pageInfo;
    }

    @Override
    public List<CourseListResponse> selectListchia(Long storeId, Date date) throws SmsException, ParseException {
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(date);
        courseListRequest.setStoreId(storeId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(date);
        courseListRequest.setDateStr(format1);
        PageInfo<CourseList> pageInfo = dao.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo.getList()) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            for (AchiCommEntity entity : entities) {
                if (courseList.getCourseReatmentNum().equals(entity.getDocNum())) {
                    entity.setProjectId(courseList.getProjectNum());
                }
            }
            courseListResponse.setEntities(entities);
            listResponses.add(courseListResponse);
        }
        return listResponses;
    }

//    @Autowired
//    private CourseListMapper courseListMapper;
    @Override
    public List<CourseListResponse> selectListAbnormal(Long storeId, String dateStr, Date date) throws SmsException, ParseException {
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(date);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setDateStr(dateStr);
        courseListRequest.setIsCancel(0);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), date) < 0) {
            throw new SmsException(ResponseCode.NO_DATA);
        }
        List<CourseList> pageInfo = courseListMapper.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo) {
            //总业绩
            BigDecimal totalPerformance = BigDecimal.valueOf(0);
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
            courseListResponse.setProject(ssmProjectService.selectByPrimaryKey(courseList.getProjctId()));
            BaseProject baseProject = ssmProjectService.selectByPrimaryKey(courseList.getProjctId());
            courseListResponse.setProject(baseProject);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            for (AchiCommEntity entity : entities) {
                if (courseList.getCourseReatmentNum().equals(entity.getDocNum())) {
                    entity.setProjectId(courseList.getProjectNum());
                }
                totalPerformance = totalPerformance.add(entity.getCashAchi().add(entity.getCardAchi()).add(entity.getCooperationAchi()==null?BigDecimal.ZERO:entity.getCooperationAchi()));
            }
            if (totalPerformance.subtract(courseList.getCourseReatmentAmount()).abs().compareTo(new BigDecimal("0.05")) == 1) {
                courseListResponse.setEntities(entities);
                courseListResponse.setErrorMessage("请检查是否填写员工或者确认项目是否有业绩提成");
                listResponses.add(courseListResponse);
            }
            List<AchiCommEntity> collect = entities.stream().filter(item ->item.getSaleStaffId()!=null && item.getSaleRatio().compareTo(BigDecimal.valueOf(0)) == 0).collect(Collectors.toList());
            if(collect!=null && collect.size()>0){
                courseListResponse.setEntities(entities);
                courseListResponse.setErrorMessage("存在占比为零的员工存在");
                if(!listResponses.contains(courseListResponse)){
                    listResponses.add(courseListResponse);
                }
            }
        }
        return listResponses;
    }

    @Override
    public List<CourseListResponse> selectLists(Long storeId, String startDate, String endDate, Date date) throws SmsException, ParseException {
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(date);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setStartTime(DateUtils.YMDParse(startDate));
        courseListRequest.setEndTime(DateUtils.YMDParse(endDate));
        courseListRequest.setIsCancel(0);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), date) < 0) {
            throw new SmsException(ResponseCode.NO_DATA);
        }
        PageInfo<CourseList> pageInfo = dao.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo.getList()) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            courseListResponse.setEntities(entities);
            listResponses.add(courseListResponse);
        }
        return listResponses;
    }

    @Override
    public StoreDaily selectDayRecord(StoreDailyRequest storeDailyRequest) {
        return dao.selectDayRecord(storeDailyRequest);
    }

    @Override
    public StoreDaily selectOutcourse(StoreDailyRequest storeDailyRequest) {
        return dao.selectOutcourse(storeDailyRequest);
    }

    @Override
    public StoreDaily NegativeKazin(StoreDailyRequest storeDailyRequest) {
        return dao.NegativeKazin(storeDailyRequest);
    }

    public String getStaffKey(String phone) {
        return staffKey + phone;
    }

    @Override
    public List<CourseList> selectListSalem(CourseList courseList) {
        return dao.selectListSalem(courseList);
    }

    @Override
    public List<CourseList> selectByCourseListMemberInit(CourseList courseList) {
        return dao.selectByCourseListMemberInit(courseList);
    }

    @Override
    public CourseList selectOneS(CourseList courseList) {
        return dao.selectOneS(courseList);
    }

    @Override
    public int updateOne(CourseList courseList) {
        return dao.updateOne(courseList);
    }

    @Override
    public List<CourseList> selectList(CourseList courseList) {

        return dao.selectList(courseList);
    }

    @Override
    public List<CourseList> selectMemberInitList(CourseList courseList) {

        return dao.selectMemberInitList(courseList);
    }

    @Override
    public List<CourseList> selectList(CourseListRequest courseListRequest) {
        return mapper.selectByDate(courseListRequest);
    }
    @Override
    public List<CourseList> selectListByMemberInitList(CourseListRequest courseListRequest) {
        return courseListMemberInitMapper.selectByDate(courseListRequest);
    }

    @Override
    public List<CourseList> selectList2(CourseList courseList) {

        return dao.selectList2(courseList);
    }

    /**
     * 查询单品贡献率
     *
     * @param storeId
     * @param date
     * @return
     * @throws SmsException
     * @throws ParseException
     */
    @Override
    public List<CourseListResponse> selectListContribution(Long storeId, Date date) throws SmsException, ParseException {
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(date);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setIsCancel(0);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), date) < 0) {
            throw new SmsException(ResponseCode.NO_DATA);
        }
        PageInfo<CourseList> pageInfo = dao.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo.getList()) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            for (AchiCommEntity entity : entities) {
                if (courseList.getCourseReatmentNum().equals(entity.getDocNum())) {
                    entity.setProjectId(courseList.getProjectNum());
                }
                entity.setDocId(courseList.getId());
            }
            courseListResponse.setEntities(entities);
            listResponses.add(courseListResponse);
        }
        return listResponses;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int memberInit(CourseListRequestNew courseListRequestNew) throws SmsException {
        int i = 0;
        int x = 0;
//        int subNumber = 0;
        String storeNum = ssmBaseStoreService.selectByPrimaryKey(courseListRequestNew.getStoreId()).getStoreNum();
        String courseReatmentNum = "";
        StoreParament debtRatiox = StoreParaUtils.getStorePara(courseListRequestNew.getStoreId(), Constant.debt_ratio);
        BigDecimal shifu = courseListRequestNew.getCourseLists().stream().map(item->item.getCollectionCashAmount().add(item.getCollectionRechargeAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal yingfu = courseListRequestNew.getCourseLists().stream().map(item -> item.getSalesPrice().multiply(BigDecimal.valueOf(Double.valueOf(item.getNumberTimes())))).reduce(BigDecimal.ZERO, BigDecimal::add);
        BigDecimal zuidaqiankuan = yingfu.multiply(BigDecimal.valueOf(Double.valueOf(debtRatiox.getParamentValue())).divide(new BigDecimal("100")));
        BigDecimal zuishaozhifu = yingfu.subtract(zuidaqiankuan);

        for (CourseListVo courseListVo : courseListRequestNew.getCourseLists()) {

            CourseList courseList = new CourseList();
            BeanUtils.copyProperties(courseListVo,courseList);
            //插入疗程单据
            courseList.setDate(new Date());

            //不走补单 正常开单 补单时间默认为开单时间
            if (1 == courseList.getIsAddition()) {
//                courseList.setAdditionDate(new Date());
                courseList.setDate(courseList.getAdditionDate());
                courseListVo.setDate(courseList.getAdditionDate());
            }



            courseList.setDebtMoney(courseListVo.getDebtMoney());
            courseList.setCourseReatmentAmount(courseList.getCollectionCashAmount().add(courseList.getCollectionRechargeAmount()));
            //查询门店参数折扣卡购买疗程是否允许折扣 0不折扣 1折扣
            //查询store_parament，根据店铺id和buycourse查询  todo 不需要更改
            //生成疗程单号
            courseList.setStoreName(courseListRequestNew.getStoreName());
            courseList.setStoreId(courseListRequestNew.getStoreId());
            //单据，只需要生成一次
            if(courseReatmentNum.length()==0 || courseReatmentNum.equals("")){
                courseReatmentNum = this.getDocNum(courseList, "CS"+storeNum);
            }
            StoreParament parament = StoreParaUtils.getStorePara(courseListRequestNew.getStoreId(), Constant.buycourse);
            //查询对应充值账户
            List<RechargeAccountRequest> rechargeAccountList = courseListVo.getRechargeAccountList();
            StoreParament debtPara = new StoreParament();
            //不存在欠款 校验金额   todo  需要进行修改
            if (0 == courseList.getIsDebt()) {
                if (null != rechargeAccountList && rechargeAccountList.size() > 0) {
                    BigDecimal discountMoneyTotal = BigDecimalUtils.bigDecimal("0");
                    BigDecimal giftMoneyTotal = BigDecimalUtils.bigDecimal("0");
                    for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                        RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccountRequest.getId());
                        //判断账户剩余可用金额是否小于卡付金额
                        if (BigDecimalUtils.compareTo(BigDecimalUtils.add(rechargeAccount.getCardConsumeMoney(),rechargeAccount.getGiftConsumeMoney()),
                                rechargeAccountRequest.getSpendMoney()) == -1) {
                            throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "账户可消费金额小于卡付金额");
                        }
                    }
                    //折扣卡购买疗程是否允许折扣 0不折扣 1折扣
                    if ("1".equals(parament.getParamentValue())) {
                        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
                        for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                            //计算卡付金额抵扣金额
                            BigDecimal discountMoney = BigDecimalUtils.bigDecimal("0");
                            if (rechargeAccountRequest.getType() == 1) {
                                //折扣卡
                                discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                                discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                            } else if (rechargeAccountRequest.getType() == 0) {
                                giftMoneyTotal = BigDecimalUtils.add(giftMoneyTotal, rechargeAccountRequest.getSpendMoney());
                            } else if (rechargeAccountRequest.getType() == 2) {
                                discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                                discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                                giftMoneyTotal = BigDecimalUtils.add(giftMoneyTotal, BigDecimalUtils.div(rechargeAccountRequest.getFreePaymentAmount(), BigDecimalUtils.div(rechargeAccountRequest.getDiscountFreeAmount(), hundredBd)));
                            }
                        }

                        BigDecimal amount = BigDecimalUtils.bigDecimal("0");
                        //折扣卡购买疗程 允许使用容差 并且没有现付
                        if (BigDecimalUtils.compareTo(discountMoneyTotal, BigDecimalUtils.bigDecimal("0")) == 1 &&
                                BigDecimalUtils.compareTo(courseList.getCollectionCashAmount(), BigDecimalUtils.bigDecimal("0")) == 0) {
                            //总支付金额 = 总卡付金额抵扣金额 + 积分付
                            amount = BigDecimalUtils.add(discountMoneyTotal, courseList.getCollectionIntegralAmount(), 2);
                            //容差值< (成交金额-总支付金额) 即支付金额和成交金额不相等
                            StoreParament balance = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.balance);
                            if (null != balance && BigDecimalUtils.compareTo(BigDecimalUtils.bigDecimal(balance.getParamentValue()), BigDecimalUtils.subtract(courseList.getCourseReatmentAmount(), amount).abs()) < 0) {
                                throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                            }
                        } else {
                            //总支付金额 = 折扣卡付抵扣金额 + 赠送卡使用金额 + 总现付 + 积分付
                            amount = BigDecimalUtils.add(BigDecimalUtils.add(BigDecimalUtils.add(discountMoneyTotal, giftMoneyTotal), courseList.getCollectionCashAmount()), courseList.getCollectionIntegralAmount(), 2);
                            if (BigDecimalUtils.compareTo(amount, courseList.getCourseReatmentAmount()) != 0) {
                                throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                            }
                        }
                    } else {//不折扣
                        //判断支付金额是否和成交金额相等
                        StoreParament balance = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.balance);
                        if (BigDecimalUtils.compareTo(courseList.getAmount(), courseList.getCourseReatmentAmount()) != 0) {
                            if(courseList.getAmount().subtract(courseList.getCourseReatmentAmount()).abs().compareTo(new BigDecimal(balance.getParamentValue()))>0){
                                throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "实收金额和成交金额不相等");
                            }
                        }
                    }
                } else {//没有卡付
                    //判断支付金额是否和成交金额相等
                    if (BigDecimalUtils.compareTo(courseList.getAmount(), courseList.getCourseReatmentAmount()) != 0) {
                        StoreParament balance = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.balance);
                        if(courseList.getAmount().subtract(courseList.getCourseReatmentAmount()).abs().compareTo(new BigDecimal(balance.getParamentValue()))>0){
                            throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "实收金额和成交金额不相等");
                        }
                    }
                }
            }
            else {//存在欠款  查询是否允许欠款
                StoreParament allowDebtPara = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.allow_debt);
                //不允许欠款 提示信息
                if ("0".equals(allowDebtPara.getParamentValue())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "疗程");
                } else {
/**
 StoreParament debtRatio = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.debt_ratio);
 //实际收款
 BigDecimal courseReatmentAmount = courseList.getCourseReatmentAmount();
 BigDecimal multiply = courseList.getSalesPrice().multiply(BigDecimal.valueOf(Double.valueOf(courseList.getNumberTimes())));
 //最少支付金额
 BigDecimal multiply1 = multiply.multiply(BigDecimal.valueOf(Double.valueOf(debtRatio.getParamentValue())).divide(BigDecimal.valueOf(100)));
 BigDecimal subtract = multiply.subtract(multiply1);
 if (subtract.compareTo(courseReatmentAmount) > -1) {
 TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
 throw new SmsException(ResponseCode.DEBT_NOT_PERMISSIONA, "疗程");
 }
 **/
                    if(zuishaozhifu.compareTo(shifu)>-1){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.DEBT_NOT_PERMISSIONA, "疗程");
                    }
                    //查询门店欠款可用比率参数
                    debtPara = StoreParaUtils.getStorePara(courseList.getStoreId(), Constant.debt_usable);
                }
            }
            //校验单价 todo
//        BigDecimal amount = courseList.getAmount();
//        BigDecimal price = amount.divide(BigDecimal.valueOf(courseList.getNumberTimes()),2,BigDecimal.ROUND_HALF_UP);
//        if(price.compareTo(courseList.getSalesPrice())!=0){
//            throw new SmsException(ResponseCode.MSG,"单价乘以次数不等于总金额");
//        }

            //生成疗程id
            Long courseId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            courseList.setId(courseId);
            //如果使用积分支付将门店会员积分进行扣减
            if (null != courseList.getIntegral() && 0 != courseList.getIntegral()) {
                StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(courseList.getMemberId());
                storeMember.setIntegral(storeMember.getIntegral() - courseList.getIntegral());
                ssmStoreMemberService.updateByPrimaryKey(storeMember);
            }

            //计算卡付现付业绩提成
            List<PayList> payLists = courseListRequestNew.getPayLists();
            courseList.setStoreId(courseListRequestNew.getStoreId());
            courseList = this.setAchiComm(courseList, rechargeAccountList, payLists);

            //设置业务员
            List<StaffRequest> staffLists = courseListRequestNew.getStaffLists();
            BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100)) != 0 && reduce3.compareTo(BigDecimal.valueOf(0)) != 0) {
                throw new SmsException(ResponseCode.MSG, "业务员业绩占比和不等于100");
            }
            this.setStaffValue(staffLists, courseList);


            courseList.setCourseReatmentNum(courseReatmentNum);
            //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
            Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            CourseAccount courseAccount = new CourseAccount();
            BeanUtils.copyProperties(courseList, courseAccount);
            courseAccount.setId(courseAccountId);
            courseAccount.setCourseType("0");

            courseAccount.setCourseNum(courseReatmentNum);
            courseList.setCourseAccountId(courseAccountId);
            courseAccount.setPrice(courseList.getSalesPrice());
            courseAccount.setAnotherName(courseListVo.getAnotherName());
            if(courseAccount.getAnotherName()==null || courseAccount.equals("")){
                courseAccount.setAnotherName(courseListVo.getProjectName());
            }
            //courseAccount.set
            //对疗程账户进行赋值
            courseAccount = ssmCourseAccountService.setCourseAccountS(courseList, courseAccount, debtPara);
            ssmCourseAccountService.addCourseAccount(courseAccount);


            courseList.setIsCancel(0);

            //如果使用充值卡支付 对使用的充值账户金额扣减
            if (BigDecimalUtils.compareTo(courseList.getCollectionRechargeAmount(), BigDecimalUtils.bigDecimal("0")) == 1 ) {//&& subNumber ==0
                //计算扣减金额 并添加账户交易记录
                ssmRechargeAccountService.subMoney(rechargeAccountList, courseList);
//                subNumber++;
            }

            //欠款 添加欠款记录
            if (1 == courseList.getIsDebt() || courseList.getDebtMoney().compareTo(BigDecimalUtils.bigDecimal("0"))>0) {
                DebtListRequest debtListRequest = new DebtListRequest();
                BeanUtils.copyProperties(courseList, debtListRequest);
                debtListRequest.setTradeId(courseList.getProjctId());
                debtListRequest.setTradeName(courseList.getProjectName());
                debtListRequest.setTradeMoney(courseList.getAmount());
                debtListRequest.setDocId(courseId);
                debtListRequest.setDocNum(courseReatmentNum);
                debtListRequest.setDocType(Constant.doc_type_card_use);
                debtListRequest.setAccountId(courseAccountId);
                debtListRequest.setStaffLists(staffLists);
                debtListRequest.setState(0);
                debtListRequest.setDocDate(courseList.getDate());
                debtListRequest.setRepayCount(courseAccount.getCourseRestCount());
                debtListRequest.setRepayConsumeCount(courseAccount.getCourseConsumeCount());
                debtListRequest.setRepayMoney(courseList.getCourseReatmentAmount());
                if (null == BigDecimalUtils.div(BigDecimalUtils.bigDecimal(debtPara.getParamentValue()), BigDecimalUtils.bigDecimal("100"))) {
                    debtListRequest.setRepayConsumeMoney(BigDecimalUtils.bigDecimal("1"));
                } else {
                    debtListRequest.setRepayConsumeMoney(BigDecimalUtils.div(BigDecimalUtils.bigDecimal(debtPara.getParamentValue()), BigDecimalUtils.bigDecimal("100")));
                }
                ssmDebtService.addDebt(debtListRequest);
            }
            //设置录单人信息
            if (redisClient.hasKey(getStaffKey(courseListRequestNew.getStaffPhone()))) {
                StaffResponse staffResponse = redisClient.get(getStaffKey(courseListRequestNew.getStaffPhone()));
                courseList.setInputId(staffResponse.getId());
                courseList.setInputBy(staffResponse.getStaffName());
            }
            Set<String> keys = redisClient.keys(getStaffKey(courseListRequestNew.getStaffPhone()) + "*");
            //从redis查询 设置录单人信息 app使用
            if (keys.size() > 0) {
                String key = new ArrayList<>(keys).get(0);
                StaffResponse staffResponse = redisClient.get(key);
                courseList.setInputId(staffResponse.getId());
                courseList.setInputBy(staffResponse.getStaffName());
            }
            BaseProject baseProject = new BaseProject();
            baseProject.setId(courseList.getProjctId());
            BaseProject baseProject1 = ssmProjectService.selectByPrimaryKey(baseProject.getId());
            //todo 加上购买日期判断
//            if(baseProject1.getSalesDeadline()!=null){
//                String salesDeadline = baseProject1.getSalesDeadline();
//                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                Date parse;
//                try {
//                     parse = simpleDateFormat.parse(salesDeadline);
//                } catch (ParseException e) {
//                    throw new RuntimeException(e);
//                }
//                if(parse.before(new Date())){
//                    throw new SmsException(ResponseCode.MSG,baseProject1.getProjectName()+"项目超过购买时间，不允许购买");
//                }
//            }
            try {
                courseList.setSalesAchievement(baseProject1.getSalesAchievement());
                courseList.setSalesCommission(baseProject1.getSalesCommission());
//                courseList.setCardAchievementAmount(baseProject1.getCardSalesAchievement());
                courseList.setCardSalesCommission(baseProject1.getCardSalesCommission());

                //现付
                if ((courseList.getSalesAchievement()==null?BigDecimal.ZERO:courseList.getSalesAchievement()).compareTo(BigDecimal.valueOf(1)) == 1) {
//                    courseList.setAchievementAmount(courseList.getSalesAchievement());
                    if (courseList.getSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCommissionAmount(courseList.getSalesCommission());
                    } else {
                        courseList.setCommissionAmount(courseList.getSalesCommission().multiply(courseList.getCollectionCashAmount()));
                    }
                } else {
//                    courseList.setAchievementAmount(courseList.getCollectionCashAmount().multiply(courseList.getSalesAchievement()));
                    if (courseList.getSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCommissionAmount(courseList.getSalesCommission());
                    } else {
                        courseList.setCommissionAmount(courseList.getSalesCommission().multiply(courseList.getCollectionCashAmount()));
                    }
                }

                //卡付
                if ((courseList.getCardSalesAchievement()==null?BigDecimal.ZERO:courseList.getCardSalesAchievement()).compareTo(BigDecimal.valueOf(1)) == 1) {
//                    courseList.setCardAchievementAmount(courseList.getCardSalesAchievement());
                    if (courseList.getCardSalesCommission().compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCardCommissionAmount((courseList.getCardSalesAchievement()==null?BigDecimal.ZERO:courseList.getCardSalesAchievement()));
                    } else {
                        courseList.setCardCommissionAmount((courseList.getCardSalesAchievement()==null?BigDecimal.ZERO:courseList.getCardSalesAchievement()).multiply(courseList.getCollectionRechargeAmount()));
                    }
                } else {
//                    courseList.setCardAchievementAmount(courseList.getCollectionRechargeAmount().multiply(courseList.getCardSalesAchievement()));
                    if ((courseList.getCardSalesCommission()==null?BigDecimal.valueOf(0):courseList.getCardSalesCommission()).compareTo(BigDecimal.valueOf(1)) == 1) {
                        courseList.setCardCommissionAmount((courseList.getCardSalesCommission()==null?BigDecimal.valueOf(0):courseList.getCardSalesCommission()));
                    } else {
                        courseList.setCardCommissionAmount((courseList.getCardSalesCommission()==null?BigDecimal.valueOf(0):courseList.getCardSalesCommission())
                                .multiply(courseList.getCollectionRechargeAmount()));
                    }
                }


                courseList.setProjectNum(courseList.getProjectNum());
                i += courseListMemberInitMapper.addCourse(courseList);
                //todo  高管信息为空，发生错误
                if (null != courseListRequestNew.getSalesmens() && courseListRequestNew.getSalesmens().size() > 0) {
                    HttpSession session = courseListRequestNew.getSession();
                    //添加高管的当前单据门店信息
                    StoreRequest storeRequest = new StoreRequest();
                    storeRequest.setId(Long.valueOf(String.valueOf(courseListRequestNew.getStoreId())));//session.getAttribute("storeId")
                    BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
                    //高管业绩
                    List<Salesman> salesmens = courseListRequestNew.getSalesmens();
                    BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                    if (null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100)) != 0 && reduce5.compareTo(BigDecimal.valueOf(0)) != 0) {
                        throw new SmsException(ResponseCode.MSG, "高管业绩占比和不等于100");
                    }
                    if (null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100)) != 0 && reduce6.compareTo(BigDecimal.valueOf(0)) != 0) {
                        throw new SmsException(ResponseCode.MSG, "管理员业绩占比和不等于100");
                    }
                    for (Salesman salesmen : salesmens) {
                        salesmen.setOrderId(String.valueOf(courseList.getId()));
                        salesmen.setOrderNum(courseReatmentNum);
                        salesmen.setOrderType(2);
                        salesmen.setOrderDate(courseList.getDate());
                        salesmen.setState(0);
                        salesmen.setMoney(courseList.getCollectionCashAmount());
                        salesmen.setProjectId(courseAccount.getCourseProjectId());
                        salesmen.setStoreNum(baseStore1.getStoreNum());
                        salesmen.setStoreName(baseStore1.getStoreName());
                        salesmen.setStoreIdOrder(baseStore1.getId());
                        salesmen.setOperatorBy(courseList.getInputBy());
                        salesmen.setIsAddition(courseList.getIsAddition());
                        salesmen.setStaffId(salesmen.getId());
                    }
                    ssmSalesmanService.addBatch(salesmens);
                }
            } catch (Exception e) {
                log.error("SsmCourseServiceImpl.addCourse:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            //添加现付支付方式
            if (null != payLists && payLists.size() > 0 && x==0) {
                List<PayList> collect = payLists.stream().filter(item -> item.getPayMoney().compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList());
                if (collect != null && collect.size() > 0) {
                    for (PayList payList : collect) {
                        payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        payList.setDocId(courseReatmentNum);
                        payList.setType(Constant.doc_type_card_use);
                        payList.setStoreId(courseList.getStoreId());
                        payList.setPayDate(courseList.getDate());
                        payList.setIsCancel(2);
                    }
                    ssmPayService.addPayList(collect);
                }
                x++;
            }

            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseList, courseAccount);
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);

//        TransactionRecord transactionRecord = this.setTransactionRecord(courseList,courseAccount);
//        ssmTransactionRecordService.add(transactionRecord);


            //将疗程单据信息添加到评价表
            MemberCsRequest memberCsRequest = new MemberCsRequest();
            BeanUtils.copyProperties(courseList, memberCsRequest);
            memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            memberCsRequest.setDocId(courseId);
            memberCsRequest.setDocNum(courseReatmentNum);
            memberCsRequest.setDocType(Constant.doc_type_card_use);
            memberCsRequest.setDocDate(courseList.getDate());
            memberCsRequest.setTradeId(courseList.getProjctId());
            memberCsRequest.setTradeName(courseList.getProjectName());
            memberCsRequest.setTradeMoney(courseList.getAmount());
            memberCsRequest.setTradeCount(courseList.getNumberTimes());
            StringBuffer staffIds = new StringBuffer();
            StringBuffer staffNames = new StringBuffer();
            if (staffLists.size() > 0) {
                for (StaffRequest staffRequest : staffLists) {
                    staffIds = staffIds.append(staffRequest.getId()).append(",");
                    staffNames = staffNames.append(staffRequest.getStaffName()).append(",");
                }
            }
            memberCsRequest.setStaffIds(staffIds.toString());
            memberCsRequest.setStaffNames(staffNames.toString());
            ssmMemberCsService.addMemberCs(memberCsRequest);


        }
        return i;
    }

    @Override
    public PageInfo<CourseListResponse> memberPage(CourseListRequest courseListRequest) throws SmsException, ParseException {
//        Date date = DateUtils.YMParse(courseListRequest.getSelectDate());
        SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM");
        Date date = sm.parse(courseListRequest.getSelectDate());
        courseListRequest.setDate(date);
//        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
//        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())),date) < 0){
//            throw new SmsException(ResponseCode.NO_DATA);
//        }
        List<Long> lists = new ArrayList<>();
        if (courseListRequest.getSelectType() == 0) {
            lists = courseListRequest.getStoreList();
        } else {
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
            if (null == baseStore1.getParentId() && (courseListRequest.getStoreList().size() < 0 || courseListRequest.getStoreList() == null)) {
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(courseListRequest.getStoreId());
                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());
                lists = collect;
            } else {
                lists.add(courseListRequest.getStoreId());
            }

        }
        courseListRequest.setStoreList(lists);
        PageInfo<CourseList> pageInfo = dao.memberPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo.getList()) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
//            //隐藏手机号码
//            String memberPhone = CommonUtils.mobileHide(courseList.getMobilePhone());
//            courseListResponse.setMobilePhone(memberPhone);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(courseList.getCourseReatmentNum()));
            List<PayList> list = ssmPayService.select(payList);

            //查询充值卡付列表(通过账户交易记录)
            List<RechargeAccountResponse> rechargeConsumeList = this.setRechargeAccountList(courseList);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            courseListResponse.setPayLists(list);
//            if(entities!=null && entities.size()>0){
//                for (AchiCommEntity entity : entities) {
//                    if(entity.getSaleStaffId()!=null) {
//                        BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(entity.getSaleStaffId());
//                        entity.setBrandNumber(baseStaff.getBrandNumber());
//                    }
//                }
//            }
            courseListResponse.setEntities(entities);
            courseListResponse.setRechargeConsumeList(rechargeConsumeList);
            listResponses.add(courseListResponse);
        }
        for (CourseListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
            salesman.setOrderType(2);
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderNum(listRespons.getCourseReatmentNum());
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        List<CourseListResponse> k = listResponses.stream().filter(item -> item.getCourseReatmentNum().startsWith("LC")||item.getCourseReatmentNum().startsWith("CS")).collect(Collectors.toList());
        for (CourseListResponse courseListResponse : k) {
            if(courseListResponse.getInputId()!=null){
                BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(courseListResponse.getInputId());
                courseListResponse.setInputNum(baseStaff.getStaffNum());
            }

        }
        PageInfo<CourseListResponse> p = new PageInfo<>(k);
        p.setTotal(pageInfo.getTotal());
        return p;
    }
    @Override
    public CourseVo selectCourseMemberInit(CourseListRequest courseListRequest) {
//        List<CourseListResponse> collect = new ArrayList<>();
        //根据订单支付方式
        PayList payList = new PayList();
        payList.setDocId(courseListRequest.getDocId());
        List<PayList> select = ssmPayService.select(payList);
        List<CourseList> courseLists = dao.selectCourseMemberInit(courseListRequest);
        List<RechargeAccountResponse> rechargelist = new ArrayList<>();
        List<AchiCommEntity> achiCommList = new ArrayList<>();
        for (CourseList list : courseLists) {
            List<RechargeAccountResponse> rechargeAccountResponses = this.selectRechargeAccountList(list);
            CourseAccount courseAccount = new CourseAccount();
            courseAccount.setCourseNum(list.getCourseReatmentNum());
            courseAccount.setCourseProjectId(list.getProjctId());
            List<CourseAccount> select1 = ssmCourseAccountService.select(courseAccount);
            if(select1!=null && select1.size()>0){
                list.setAnotherName(select1.get(0).getAnotherName());
            }
            achiCommList = this.getAchiCommList(list);
//            if(achiCommList!=null&&achiCommList.size()>0){
//                for (AchiCommEntity achiCommEntity : achiCommList) {
//                    if(achiCommEntity.getSaleStaffId()!=null) {
//                        BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(achiCommEntity.getSaleStaffId());
//                        achiCommEntity.setBrandNumber(baseStaff.getBrandNumber());
//                    }
//                }
//            }
            rechargelist.addAll(rechargeAccountResponses);
        }
        CourseVo courseVo = new CourseVo();
        courseVo.setPayLists(select);
        courseVo.setRechargeConsumeList(rechargelist);
        courseVo.setCourseLists(courseLists);
        courseVo.setEntities(achiCommList);

        return courseVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int memberInitCancel(CourseListRequest courseListRequest) throws SmsException {
        int i = 0;
        PayList payList = new PayList();
        payList.setDocId(courseListRequest.getCourseReatmentNum());
        List<PayList> payListList = ssmPayService.select(payList);
        if(payListList!=null&&payListList.size()>0) {
            for (PayList list : payListList) {
                list.setIsCancel(3);
                ssmPayService.updateByNum(list);
            }
        }
        CourseList courseList = new CourseList();
        BeanUtils.copyProperties(courseListRequest, courseList);
        //判断该单据是否欠款
        if (courseListRequest.getDebtMoney().compareTo(BigDecimal.valueOf(0)) == 1) {
            DebtList debtList = new DebtList();
            debtList.setDocNum(courseListRequest.getCourseReatmentNum());
            debtList.setStoreId(courseListRequest.getStoreId());
            List<DebtList> select = ssmDebtService.select(debtList);
            for (DebtList list : select) {
                if (list.getState() == 1 || list.getState() == 2  ) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.MSG, "该单据存在未作废还款和取消欠款，请先作废");
                }
                if(list.getTradeId().equals(courseList.getProjctId()) && list.getTradeMoney().compareTo(courseList.getAmount())==0
                        && (list.getAccountId()==courseList.getCourseAccountId() || list.getAccountId().toString().equals(courseList.getCourseAccountId().toString()))){
                    if(list.getDebtMoney().compareTo(courseList.getDebtMoney())!=0){
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        throw new SmsException(ResponseCode.MSG,"该单据已经存在还款，不允许作废");
                    }
                }
            }
        }
        //如果使用积分支付 将积分返回
        if (courseList.getIntegral() !=null && 0 != courseList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(courseList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() + courseList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }
        //查询疗程账户
        CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(courseList.getCourseAccountId());
        if (null == courseAccount) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S, "疗程账户");
        }

        //判断当前疗程单是否是最近疗程单
        this.checkRecentCourse(courseList, courseAccount);

        //修改疗程单据状态
        courseList.setIsCancel(1);
        courseList.setCancelDate(new Date());

        //疗程账户扣减次数
        //CourseAccount afterAccount = ssmCourseAccountService.subCount(courseAccount, courseList.getNumberTimes(), 1);
        CourseAccount afterAccount = ssmCourseAccountService.subCount(courseAccount, courseList.getNumberTimes(), 1, courseList);
        //如果有使用充值卡支付 充值账户钱数增加
        if (null != courseList.getCollectionRechargeAmount()) {
            List<RechargeAccountRequest> rechargeAccountRequestList = courseListRequest.getRechargeAccountList();
            ssmRechargeAccountService.addMoney(rechargeAccountRequestList, courseList);
        }

        //设置作废人信息
        if (redisClient.hasKey(getStaffKey(courseListRequest.getStaffPhone()))) {
            StaffResponse staffResponse = redisClient.get(getStaffKey(courseListRequest.getStaffPhone()));
            courseList.setCancelId(staffResponse.getId());
            courseList.setCancelBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(courseListRequest.getStaffPhone()) + "*");
        //从redis查询 设置作废人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            courseList.setCancelId(staffResponse.getId());
            courseList.setCancelBy(staffResponse.getStaffName());
        }
        //只计算总先付卡付业绩提成
        courseList.setAchievementAmount(BigDecimalUtils.bigDecimal("0"));
        courseList.setCommissionAmount(BigDecimalUtils.bigDecimal("0"));
        courseList.setCardAchievementAmount(BigDecimalUtils.bigDecimal("0"));
        courseList.setCardCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        //单据业务员业绩提成置0
//        if (null != courseList.getSaleOneStaffId()) {
//            courseList.setSaleOneAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleOneCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != courseList.getSaleTwoStaffId()) {
//            courseList.setSaleTwoAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleTwoCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != courseList.getSaleThreeStaffId()) {
//            courseList.setSaleThreeAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleThreeCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != courseList.getSaleFourStaffId()) {
//            courseList.setSaleFourAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            courseList.setSaleFourCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }

        //欠款 删除欠款记录
        if (1 == courseList.getIsDebt()) {
            DebtListRequest debtListRequest = new DebtListRequest();
            debtListRequest.setDocId(courseList.getId());
            debtListRequest.setMemberId(courseList.getMemberId());
            debtListRequest.setStoreId(courseList.getStoreId());
            ssmDebtService.deleteDebt(debtListRequest);
        }

        try {
            i = dao.memberInitCancel(courseList);
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(courseList.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(1);
                ssmSalesmanService.updateNotNull(salesman1);
            }
        } catch (Exception e) {
            log.error("SsmCourseServiceImpl.cancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加账户交易记录
        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseList, afterAccount);
        accountTradeRecord.setOrderStatu(1);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

        //将评价单进行删除操作
        MemberCs memberCs = new MemberCs();
        memberCs.setDocId(courseList.getId());
        ssmMemberCsService.delete(memberCs);

        return i;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateMemberInitStaff(CourseListRequest courseListRequest) throws SmsException {
        StoreParament storeParament = StoreParaUtils.getStorePara(courseListRequest.getStoreId(), Constant.editOrderNum);
        int days = (int) DateUtils.getDayDiff(courseListRequest.getDate(), new Date());
        if("999".equals(storeParament.getParamentValue())) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            if(!dateFormat.format(new Date()).equals(dateFormat.format(courseListRequest.getDate()))) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "请联系管理员");
            }
        }
        if (!"0".equals(storeParament.getParamentValue())) {
            if (Integer.parseInt(storeParament.getParamentValue()) < days) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSIONS, "单据超过允许修改时间");
            }
        }

        int i = 0;
//        CourseList courseList = new CourseList();
        CourseListRequest courseListRequest1 = new CourseListRequest();
        courseListRequest1.setDocId(courseListRequest.getDocId());
        courseListRequest1.setDate(courseListRequest.getDate());
        List<CourseList> courseListss = dao.selectCourseMemberInit(courseListRequest1);
        List<PayList> payLists = courseListRequest.getPayLists();
        if(payLists!=null && payLists.size()>0){
            for (PayList payList : payLists) {
                BaseCollectionType baseCollectionType = ssmCollectionTypeService.selectByPrimaryKey(payList.getPayId());
                payList.setPayName(baseCollectionType.getCollectionTypeName());
                ssmPayService.updateByPrimaryKey(payList);
            }
        }
        for (CourseList courseList : courseListss) {
//            BeanUtils.copyProperties(courseListRequest, courseList);
            //修改疗程账户的项目别名
//            CourseAccount courseAccount = new CourseAccount();
//            courseAccount.setCourseNum(courseList.getCourseReatmentNum());
//            courseAccount.setCourseProjectId(courseList.getProjctId());
//            List<CourseAccount> select1 = ssmCourseAccountService.select(courseAccount);
//            if(select1!=null && select1.size()>0){
//                for (CourseAccount account : select1) {
//                    account.setAnotherName(courseList.getAnotherName());
//                    ssmCourseAccountService.updateByPrimaryKey(account);
//                }
//            }
            //设置业务员
            List<StaffRequest> staffLists = courseListRequest.getStaffLists();
            BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100)) != 0 && reduce3.compareTo(BigDecimal.valueOf(0)) != 0) {
                throw new SmsException(ResponseCode.MSG, "助理业绩占比和不等于100");
            }
            courseList.setSaleOneStaffId(null);
            courseList.setSaleOneStaffName(null);
            courseList.setSaleOneIdentity(null);
            courseList.setSaleOneRatio(null);
            courseList.setSaleOneNumber(null);

            courseList.setSaleTwoStaffId(null);
            courseList.setSaleTwoStaffName(null);
            courseList.setSaleTwoIdentity(null);
            courseList.setSaleTwoRatio(null);
            courseList.setSaleTwoNumber(null);

            courseList.setSaleThreeStaffId(null);
            courseList.setSaleThreeStaffName(null);
            courseList.setSaleThreeIdentity(null);
            courseList.setSaleThreeRatio(null);
            courseList.setSaleThreeNumber(null);

            courseList.setSaleFourStaffId(null);
            courseList.setSaleFourStaffName(null);
            courseList.setSaleFourIdentity(null);
            courseList.setSaleFourRatio(null);
            courseList.setSaleFourNumber(null);

            courseList.setSaleFiveStaffId(null);
            courseList.setSaleFiveStaffName(null);
            courseList.setSaleFiveIdentity(null);
            courseList.setSaleFiveRatio(null);
            courseList.setSaleFiveNumber(null);

            courseList.setSaleSixStaffId(null);
            courseList.setSaleSixStaffName(null);
            courseList.setSaleSixIdentity(null);
            courseList.setSaleSixRatio(null);
            courseList.setSaleSixNumber(null);

            courseList.setSaleSevenStaffId(null);
            courseList.setSaleSevenStaffName(null);
            courseList.setSaleSevenIdentity(null);
            courseList.setSaleSevenRatio(null);
            courseList.setSaleSevenNumber(null);

            courseList.setSaleEightStaffId(null);
            courseList.setSaleEightStaffName(null);
            courseList.setSaleEightIdentity(null);
            courseList.setSaleEightRatio(null);
            courseList.setSaleEightNumber(null);


            this.setStaffValue(staffLists, courseList);

//        //计算卡付现付业绩提成
//        List<PayList> payLists = courseListRequest.getPayLists();
//        //查询对应充值账户
//        List<RechargeAccountRequest> rechargeAccountList = courseListRequest.getRechargeAccountList();
//        courseList = this.setAchiComm(courseList,rechargeAccountList,payLists);
            //如果欠款，则修改欠款单
            if(courseList.getIsDebt()==1){
                DebtList debtList = new DebtList();
                debtList.setDocId(courseList.getId());
                List<DebtList> debtLists = ssmDebtService.select(debtList);
                for (DebtList list : debtLists) {
                    if(list.getState()==0) {
                        list.setSaleOneStaffId(null);
                        list.setSaleOneStaffName(null);
                        list.setSaleOneIdentity(null);
                        list.setSaleOneRatio(null);
                        list.setSaleOneNumber(null);

                        list.setSaleTwoStaffId(null);
                        list.setSaleTwoStaffName(null);
                        list.setSaleTwoIdentity(null);
                        list.setSaleTwoRatio(null);
                        list.setSaleTwoNumber(null);

                        list.setSaleThreeStaffId(null);
                        list.setSaleThreeStaffName(null);
                        list.setSaleThreeIdentity(null);
                        list.setSaleThreeRatio(null);
                        list.setSaleThreeNumber(null);

                        list.setSaleFourStaffId(null);
                        list.setSaleFourStaffName(null);
                        list.setSaleFourIdentity(null);
                        list.setSaleFourRatio(null);
                        list.setSaleFourNumber(null);

                        list.setSaleFiveStaffId(null);
                        list.setSaleFiveStaffName(null);
                        list.setSaleFiveIdentity(null);
                        list.setSaleFiveRatio(null);
                        list.setSaleFiveNumber(null);

                        list.setSaleSixStaffId(null);
                        list.setSaleSixStaffName(null);
                        list.setSaleSixIdentity(null);
                        list.setSaleSixRatio(null);
                        list.setSaleSixNumber(null);

                        list.setSaleSevenStaffId(null);
                        list.setSaleSevenStaffName(null);
                        list.setSaleSevenIdentity(null);
                        list.setSaleSevenRatio(null);
                        list.setSaleSevenNumber(null);

                        list.setSaleEightStaffId(null);
                        list.setSaleEightStaffName(null);
                        list.setSaleEightIdentity(null);
                        list.setSaleEightRatio(null);
                        list.setSaleEightNumber(null);
                        this.setStaffValue(staffLists, list);
                        ssmDebtService.updateNotNull(list);
                    }
                }
            }
            try {
                i = dao.updateMemberInitStaff(courseList);
                CourseListRequest courseLists = new CourseListRequest();
                courseLists.setId(courseList.getId());
                courseLists.setDate(courseListRequest.getDate());
                List<CourseList> courseLists1 = dao.selectMemberInitPages(courseLists);
                Salesman salesman = new Salesman();
                salesman.setOrderId(String.valueOf(courseList.getId()));
                List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
                Date date = courseList.getDate();
                for (Salesman salesman1 : salesmen) {
                    date = salesman1.getOrderDate();
                    ssmSalesmanService.delete(salesman1);
                }
                BaseStore baseStore = new BaseStore();
                baseStore.setId(courseListRequest.getStoreId());
                BaseStore select = ssmBaseStoreService.selectOne(baseStore);
                List<Salesman> salesmens = courseListRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType() == 1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if (null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100)) != 0 && reduce5.compareTo(BigDecimal.valueOf(0)) != 0) {
                    throw new SmsException(ResponseCode.MSG, "高管业绩占比和不等于100");
                }
                if (null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100)) != 0 && reduce6.compareTo(BigDecimal.valueOf(0)) != 0) {
                    throw new SmsException(ResponseCode.MSG, "管理员业绩占比和不等于100");
                }
                for (Salesman salesmen2 : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
//                    salesmen2.setStaffId(salesmen2.getId());
                    salesmen2.setId(salesmen2.getId() + i1);
                    salesmen2.setOrderId(String.valueOf(courseList.getId()));
                    salesmen2.setOrderNum(courseList.getCourseReatmentNum());
                    salesmen2.setOrderType(2);
                    salesmen2.setOrderDate(date);
                    salesmen2.setState(0);
                    salesmen2.setMoney(courseLists1.get(0).getCollectionCashAmount());
                    salesmen2.setProjectId(courseLists1.get(0).getProjctId());
                    salesmen2.setStoreNum(select.getStoreNum());
                    salesmen2.setStoreName(select.getStoreName());
                    salesmen2.setOperatorBy(courseList.getInputBy());
                    salesmen2.setIsAddition(courseList.getIsAddition());
                    salesmen2.setStoreIdOrder(select.getId());
                }
                ssmSalesmanService.addBatch(salesmens);
            } catch (Exception e) {
                log.error("SsmCourseServiceImpl.updateStaff:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
        }

        return i;
    }
    @Override
    public List<CourseListResponse> memberInitStaff(Long storeId, String dateStr, Date date) throws SmsException, ParseException {
        CourseListRequest courseListRequest = new CourseListRequest();
        courseListRequest.setDate(date);
        courseListRequest.setStoreId(storeId);
        courseListRequest.setDateStr(dateStr);
        courseListRequest.setIsCancel(0);
//        courseListRequest.setPageSize(500);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(courseListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())), date) < 0) {
            throw new SmsException(ResponseCode.NO_DATA);
        }

        List<CourseList> pageInfo = courseListMemberInitMapper.selectPage(courseListRequest);
        List<CourseListResponse> listResponses = new ArrayList<>();
        for (CourseList courseList : pageInfo) {
            CourseListResponse courseListResponse = new CourseListResponse();
            BeanUtils.copyProperties(courseList, courseListResponse);
            //设置业务人员列表
            List<AchiCommEntity> entities = this.getAchiCommList(courseList);
            for (AchiCommEntity entity : entities) {
                if (courseList.getCourseReatmentNum().equals(entity.getDocNum())) {
                    entity.setProjectId(courseList.getProjectNum());
                }
                entity.setDocId(courseList.getId());
            }
            courseListResponse.setEntities(entities);
            listResponses.add(courseListResponse);
        }
        return listResponses;
    }
}
