package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmCourseAccountDao;
import com.ssm.manage.dao.SsmDocPromotionDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.extendEntity.StoreDaily;
import com.ssm.manage.mapper.DocPromotionMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.*;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmDocPromotionServiceImpl extends BaseServiceImpl<DocPromotion> implements SsmDocPromotionService {
    @Autowired
    private SsmPromotionService ssmPromotionService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmCollectionTypeService ssmCollectionTypeService;

    @Autowired
    private SsmRechargeAccountGiveService ssmRechargeAccountGiveService;

    @Autowired
    private PromotionRechargeListService promotionRechargeListService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmDebtService ssmDebtService;
    @Autowired
    private SsmCancelDebtListService ssmCancelDebtListService;

    @Autowired
    private SsmPromotionProjectService ssmPromotionProjectService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmDocPromotionProjectService ssmDocPromotionProjectService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmMemberCsService ssmMemberCsService;

    @Autowired
    private SsmDocPromotionDao dao;

    @Autowired
    private SsmCourseAccountDao ssmCourseAccountDao;

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

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

    @Override
    public PageInfo<DocPromotionResponse> selectPage(DocPromotionRequest docPromotionRequest) {
        PageInfo<DocPromotion> pageInfo = dao.selectPage(docPromotionRequest);
        List<DocPromotionResponse> list = new ArrayList<>();
        for (DocPromotion docPromotion : pageInfo.getList()) {
            DocPromotionResponse docPromotionResponse = new DocPromotionResponse();
            BeanUtils.copyProperties(docPromotion, docPromotionResponse);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(docPromotion.getId()));
            List<PayList> payLists = ssmPayService.select(payList);
            //查询充值卡付列表(通过账户交易记录)
            List<RechargeAccountResponse> rechargeConsumeList = this.setRechargeAccountList(docPromotion);
            List<AchiCommEntity> entities = this.getAchiCommList(docPromotion);
            //设置业务员
            docPromotionResponse.setEntities(entities);
            docPromotionResponse.setPayLists(payLists);
            docPromotionResponse.setRechargeConsumeList(rechargeConsumeList);
            list.add(docPromotionResponse);
        }
        PageInfo<DocPromotionResponse> p = new PageInfo<>(list);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<DocPromotionResponse> selectPageNew(DocPromotionRequest docPromotionRequest) {

        PageInfo<DocPromotion> pageInfo =  dao.selectPageNew(docPromotionRequest);
        List<DocPromotionResponse> list = new ArrayList<>();
        for (DocPromotion docPromotion : pageInfo.getList()) {
            DocPromotionResponse docPromotionResponse = new DocPromotionResponse();
            BeanUtils.copyProperties(docPromotion, docPromotionResponse);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(docPromotion.getId()));
            List<PayList> payLists = ssmPayService.select(payList);
            //查询充值卡付列表(通过账户交易记录)
            List<RechargeAccountResponse> rechargeConsumeList = this.setRechargeAccountList(docPromotion);
            List<AchiCommEntity> entities = this.getAchiCommList(docPromotion);
            //设置业务员
            docPromotionResponse.setEntities(entities);
            docPromotionResponse.setPayLists(payLists);
            docPromotionResponse.setRechargeConsumeList(rechargeConsumeList);
            list.add(docPromotionResponse);
        }
        PageInfo<DocPromotionResponse> p = new PageInfo<>(list);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<DocPromotionResponse> pageDetail(DocPromotionRequest docPromotionRequest) {
        PageInfo<DocPromotion> pageInfo = dao.selectPage(docPromotionRequest);
        List<DocPromotionResponse> list = new ArrayList<>();
        for (DocPromotion docPromotion : pageInfo.getList()) {
            DocPromotionResponse docPromotionResponse = new DocPromotionResponse();
            BeanUtils.copyProperties(docPromotion, docPromotionResponse);
            //查询现付列表
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(docPromotion.getId()));
            List<PayList> payLists = ssmPayService.select(payList);
            //查询充值卡付列表(通过账户交易记录)
            List<RechargeAccountResponse> rechargeConsumeList = this.setRechargeAccountList(docPromotion);
            List<AchiCommEntity> entities = this.getAchiCommList(docPromotion);
            //设置业务员
            docPromotionResponse.setEntities(entities);
            docPromotionResponse.setPayLists(payLists);
            docPromotionResponse.setRechargeConsumeList(rechargeConsumeList);
            list.add(docPromotionResponse);
        }
        PageInfo<DocPromotionResponse> p = new PageInfo<>(list);
        p.setTotal(pageInfo.getTotal());
        return p;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addDoc(DocPromotionRequest docPromotionRequest) throws SmsException {
        int i = 0;
        Long cid = 0l;
        List<Long> cids = new ArrayList<>();
        DocPromotion docPromotion = new DocPromotion();
        BeanUtils.copyProperties(docPromotionRequest, docPromotion);
        PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotionRequest.getPromotionId());
        List<RechargeAccountRequest> rechargeAccountList = docPromotionRequest.getRechargeAccountList();
        StoreParament debtPara = new StoreParament();
        if(0 == docPromotionRequest.getIsDebt()){
            //允许充值卡付
            //查询对应充值账户

            if (1 == promotionList.getCardBuy()){
                BigDecimal discountMoneyTotal = BigDecimalUtils.bigDecimal("0");
                if (null != rechargeAccountList && rechargeAccountList.size() > 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, "账户可消费金额小于卡付金额");
                        }
                    }
                }
                //折扣卡允许折扣 赠送卡允许使用赠送金额
                if (1 == promotionList.getCardLimit()) {
                    BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
                    for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                        //计算卡付金额抵扣金额
                        BigDecimal discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                        discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                    }
                    //总支付金额 = 总卡付金额抵扣金额 + 总现付
                    BigDecimal amount = BigDecimalUtils.add(discountMoneyTotal, docPromotion.getCollectionCashAmount(), 2);
                    if (BigDecimalUtils.compareTo(docPromotion.getAmount(), amount) != 0) {
                        throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                    }
                } else {//不折扣
                    //校验金额
                    //总支付金额 = 总卡付金额抵扣金额 + 总现付
                    if (BigDecimalUtils.compareTo(docPromotionRequest.getAmount(), BigDecimalUtils.add(docPromotionRequest.getCollectionCashAmount(), docPromotionRequest.getCollectionRechargeAmount())) != 0){
                        throw new SmsException(ResponseCode.PROMOTION_NOT_PERMISSION,"总支付金额和成交金额不相等");
                    }
                }
            }else {
                //不允许充值卡支付 只校验现付金额
                if (BigDecimalUtils.compareTo(docPromotionRequest.getAmount(), docPromotionRequest.getCollectionCashAmount()) != 0){
                    throw new SmsException(ResponseCode.PROMOTION_NOT_PERMISSION,"总支付金额和成交金额不相等");
                }
            }
        }else{
            //判断是否允许欠款
//            StoreParament parament = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(),Constant.promotion);
            StoreParament parament = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(),Constant.allow_debt);
            if ("0".equals(parament.getParamentValue())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "疗程促销");
            }else {
//                StoreParament debtRatio = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(), Constant.promotionRatio);
                StoreParament debtRatio = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(), Constant.debt_ratio);

                //实际收款
                BigDecimal cashMoney = docPromotionRequest.getCollectionCashAmount().add(docPromotionRequest.getCollectionRechargeAmount());
                BigDecimal courseReatmentAmount = cashMoney;
                BigDecimal multiply = docPromotionRequest.getPrice();
                //最少支付金额
                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(docPromotionRequest.getStoreId(),Constant.promotionUsable);
                debtPara = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(),Constant.debt_usable);
            }
        }

        //设置主键Id
        Long docId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        docPromotion.setId(docId);
        Date docDate = new Date();
        docPromotion.setDocDate(docDate);
        //设置单据号

        String storeNUmm=ssmBaseStoreService.selectByPrimaryKey(docPromotionRequest.getStoreId()).getStoreNum();
        String docNum = this.getDocNum(docPromotionRequest,storeNUmm);
        docPromotion.setDocNum(docNum);
        //计算卡付现付业绩提成
        List<PayList> payLists = docPromotionRequest.getPayLists();
        docPromotion = this.setAchiComm(docPromotion,rechargeAccountList,payLists);
        //设置业务员
        List<StaffRequest> staffLists = docPromotionRequest.getStaffLists();
        this.setStaffValue(staffLists,docPromotion);
        docPromotion.setInputDate(new Date());


        //设置录单人信息
        if (redisClient.hasKey(getKey(docPromotionRequest.getStaffPhone()))) {
            docPromotion.setInputId(redisClient.get(getKey(docPromotionRequest.getStaffPhone())).getId());
            docPromotion.setInputBy(redisClient.get(getKey(docPromotionRequest.getStaffPhone())).getStaffName());

        }
        Set<String> keys = redisClient.keys(getKey(docPromotionRequest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            docPromotion.setInputId(staffResponse.getId());
            docPromotion.setInputBy(staffResponse.getStaffName());
        }
        docPromotion.setIsCancel(0);
        BigDecimal totalMoney = BigDecimal.valueOf(0);
                PromotionListRequest promotionListRequest = new PromotionListRequest();
        promotionListRequest.setId(promotionList.getId());
        List<PromotionProject> list = ssmPromotionProjectService.selectList(promotionListRequest);
//        String[] strings = null;
//        if(!"".equals(docPromotionRequest.getProjectArray()) && null != docPromotionRequest.getProjectArray()){
//            strings = docPromotion.getProjectArray().split(",");
//            for (PromotionProject promotionProject : list) {
//                for (String string : strings) {
//                    Long aLong = Long.valueOf(string);
//                    if(promotionProject.getId().equals(aLong)){
//                        =totalMoney.add(promotionProject.getProjectTotalMoney());
//                    }
//                }
//            }
//        }

//        if(null !=docPromotion.getProjectCount() && 0<=docPromotion.getProjectCount()) {
        if(null !=docPromotionRequest.getPromotionProjects() && 0<docPromotionRequest.getPromotionProjects().size()) {
            BigDecimal totalProjectMoney = docPromotionRequest.getPromotionProjects().stream().filter(promotionProject -> 0 ==promotionProject.getType()).map(PromotionProject::getProjectTotalMoney).reduce(BigDecimal.ZERO,BigDecimal::add);

            //计算金额
            //固定价要按比例平摊金额
            if(docPromotion.getMoneyType()==0){
                for (PromotionProject promotionProject : docPromotionRequest.getPromotionProjects()) {
                    BigDecimal divide = promotionProject.getProjectTotalMoney().multiply(docPromotionRequest.getAmount()).divide(totalProjectMoney, 2, BigDecimal.ROUND_HALF_UP);
                    promotionProject.setProjectTotalMoney(divide.setScale(2,BigDecimal.ROUND_HALF_UP));
                    promotionProject.setPriceMember(divide.divide(BigDecimal.valueOf(promotionProject.getTimes()*docPromotion.getCount()),2,BigDecimal.ROUND_HALF_UP));
                }
            }

            totalMoney= docPromotionRequest.getAmount();
            for (PromotionProject promotionProject : docPromotionRequest.getPromotionProjects()) {
                //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                cid = courseAccountId;
                cids.add(cid);
                CourseAccount courseAccount = new CourseAccount();
                BeanUtils.copyProperties(docPromotion, courseAccount);
                courseAccount.setId(courseAccountId);
                if (promotionProject.getType() == 0) {
                    courseAccount.setCourseType("1");
                } else {
                    courseAccount.setCourseType("2");
                }
                courseAccount.setCourseNum(docNum);

                //对疗程账户进行赋值
                if(0 == docPromotionRequest.getIsDebt()){
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount());
                }else{ //有欠款
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount(),docPromotion,totalMoney);
                }



                //添加促销活动项目明细
                DocPromotionProject docPromotionProject = new DocPromotionProject();
                BeanUtils.copyProperties(promotionProject,docPromotionProject);
                docPromotionProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                docPromotionProject.setMemberId(docPromotionRequest.getMemberId());
                docPromotionProject.setMemberName(docPromotionRequest.getMemberName());
                docPromotionProject.setMemberIdentityCard(docPromotionRequest.getMemberIdentityCard());
                docPromotionProject.setCard(docPromotionRequest.getCard());
                docPromotionProject.setMobilePhone(docPromotionRequest.getMobilePhone());
                docPromotionProject.setDocNum(docNum);
                docPromotionProject.setDocDate(docDate);
                docPromotionProject.setCourseAccountId(courseAccountId);
                docPromotionProject.setTimes(promotionProject.getTimes() * docPromotion.getCount());
                ssmDocPromotionProjectService.saveNotNull(docPromotionProject);
                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,courseAccount, docPromotionProject);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }else {
            totalMoney = list.stream().filter(promotionProject -> 0 ==promotionProject.getType()).map(PromotionProject::getProjectTotalMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
            for (PromotionProject promotionProject : list) {
                promotionProject.setPriceMember(promotionProject.getProjectTotalMoney().divide(BigDecimal.valueOf(promotionProject.getTimes()),2,BigDecimal.ROUND_HALF_UP));
                //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                cid = courseAccountId;
                cids.add(cid);
                CourseAccount courseAccount = new CourseAccount();
                BeanUtils.copyProperties(docPromotion, courseAccount);
                courseAccount.setId(courseAccountId);
                if (promotionProject.getType() == 0) {
                    courseAccount.setCourseType("1");
                } else {
                    courseAccount.setCourseType("2");
                }
                courseAccount.setCourseNum(docNum);

                //对疗程账户进行赋值
                if(0 == docPromotionRequest.getIsDebt()){
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount());
                }else{ //有欠款
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount(),docPromotion,totalMoney);
                }

                //添加促销活动项目明细
                DocPromotionProject docPromotionProject = new DocPromotionProject();
                BeanUtils.copyProperties(promotionProject,docPromotionProject);
                docPromotionProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                docPromotionProject.setMemberId(docPromotionRequest.getMemberId());
                docPromotionProject.setMemberName(docPromotionRequest.getMemberName());
                docPromotionProject.setMemberIdentityCard(docPromotionRequest.getMemberIdentityCard());
                docPromotionProject.setCard(docPromotionRequest.getCard());
                docPromotionProject.setMobilePhone(docPromotionRequest.getMobilePhone());
                docPromotionProject.setDocNum(docNum);
                docPromotionProject.setDocDate(docDate);
                docPromotionProject.setCourseAccountId(courseAccountId);
                docPromotionProject.setTimes(promotionProject.getTimes() * docPromotion.getCount());
                ssmDocPromotionProjectService.saveNotNull(docPromotionProject);
                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,courseAccount, docPromotionProject);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }

        //如果使用充值卡支付 对使用的充值账户金额扣减
        if (BigDecimalUtils.compareTo(docPromotion.getCollectionRechargeAmount(),BigDecimalUtils.bigDecimal("0")) == 1) {
            //计算扣减金额 并添加账户交易记录
            ssmRechargeAccountService.subMoney(rechargeAccountList, docPromotion);
        }
        //欠款 添加欠款记录
        if (1 == docPromotionRequest.getIsDebt()){
            DebtListRequest debtListRequest = new DebtListRequest();
            BeanUtils.copyProperties(docPromotion,debtListRequest);
            debtListRequest.setTradeId(docPromotion.getPromotionId());
            debtListRequest.setTradeName(docPromotion.getPromotionName());
            debtListRequest.setTradeMoney(docPromotion.getPrice());
            debtListRequest.setDocId(docPromotion.getId());
            debtListRequest.setDocNum(docPromotion.getDocNum());
            debtListRequest.setDocType(Constant.promotion_card_use);
//            debtListRequest.setAccountId(courseAccountId);
            debtListRequest.setStaffLists(staffLists);
            debtListRequest.setState(0);
            debtListRequest.setDocDate(docPromotion.getDocDate());
            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);
        }
        try {
            i = dao.saveNotNull(docPromotion);

            Long docPromotionId = docPromotion.getId();
            for (Long aLong : cids) {
                CourseAccount courseAccount = new CourseAccount();
                courseAccount.setId(aLong);
                courseAccount.setPromotionDocId(docPromotionId);
                ssmCourseAccountDao.updateByPrimaryKeySelective(courseAccount);
            }


            HttpSession session = docPromotionRequest.getSession();
            //添加高管的当前单据门店信息
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(Long.valueOf(String.valueOf(session.getAttribute("storeId"))));
            BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
            //高管业绩
            List<Salesman> salesmens = docPromotionRequest.getSalesmens();
            for (Salesman salesmen : salesmens) {
                salesmen.setOrderId(String.valueOf(docPromotion.getId()));
                salesmen.setOrderNum(docPromotion.getDocNum());
                salesmen.setOrderType(8);
                salesmen.setOrderDate(new Date());
                salesmen.setState(0);
                salesmen.setOperatorBy(docPromotion.getInputBy());
                salesmen.setMoney(docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount()));
                salesmen.setProjectId(docPromotion.getPromotionId());
                salesmen.setStoreNum(baseStore1.getStoreNum());
                salesmen.setStoreName(baseStore1.getStoreName());
                salesmen.setStoreIdOrder(baseStore1.getId());
            }
            ssmSalesmanService.addBatch(salesmens);
        }catch (Exception e){
            log.error("SsmDocPromotionServiceImpl.addDoc:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加现付支付方式
        if (null != payLists && payLists.size() > 0) {
            for (PayList payList : payLists) {
                payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                payList.setDocId(String.valueOf(docId));
                payList.setType(Constant.doc_type_promotion);
                payList.setStoreId(docPromotionRequest.getStoreId());
                payList.setIsCancel(0);
            }
            ssmPayService.addPayList(payLists);
        }
        //将促销单据信息添加到评价表
        MemberCsRequest memberCsRequest = new MemberCsRequest();
        BeanUtils.copyProperties(docPromotion, memberCsRequest);
        memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberCsRequest.setDocId(docPromotion.getId());
        memberCsRequest.setDocNum(docNum);
        memberCsRequest.setDocType(Constant.doc_type_promotion);
        memberCsRequest.setDocDate(docPromotion.getDocDate());
        memberCsRequest.setTradeId(docPromotion.getPromotionId());
        memberCsRequest.setTradeName(docPromotion.getPromotionName());
        memberCsRequest.setTradeMoney(docPromotion.getPrice());
        memberCsRequest.setTradeCount(docPromotion.getCount());
        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 addPromotionRechargeList(DocPromotionRequest docPromotionRequest) throws SmsException {
        int i = 0;
        Long cid = 0l;
        List<Long> cids = new ArrayList<>();
        DocPromotion docPromotion = new DocPromotion();
        BeanUtils.copyProperties(docPromotionRequest, docPromotion);
        PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotionRequest.getPromotionId());
        List<RechargeAccountRequest> rechargeAccountList = docPromotionRequest.getRechargeAccountList();
        StoreParament debtPara = new StoreParament();
        if(0 == docPromotionRequest.getIsDebt()){
            //允许充值卡付
            //查询对应充值账户

            if (1 == promotionList.getCardBuy()){
                BigDecimal discountMoneyTotal = BigDecimalUtils.bigDecimal("0");
                if (null != rechargeAccountList && rechargeAccountList.size() > 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, "账户可消费金额小于卡付金额");
                        }
                    }
                }
                //折扣卡允许折扣 赠送卡允许使用赠送金额
                if (1 == promotionList.getCardLimit()) {
                    BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
                    for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
                        //计算卡付金额抵扣金额
                        BigDecimal discountMoney = BigDecimalUtils.div(rechargeAccountRequest.getSpendMoney(), BigDecimalUtils.div(rechargeAccountRequest.getDiscount(), hundredBd));
                        discountMoneyTotal = BigDecimalUtils.add(discountMoneyTotal, discountMoney);
                    }
                    //总支付金额 = 总卡付金额抵扣金额 + 总现付
                    BigDecimal amount = BigDecimalUtils.add(discountMoneyTotal, docPromotion.getCollectionCashAmount(), 2);
                    if (BigDecimalUtils.compareTo(docPromotion.getAmount(), amount) != 0) {
                        throw new SmsException(ResponseCode.COURSE_NOT_PERMISSION, "总支付金额和成交金额不相等");
                    }
                } else {//不折扣
                    //校验金额
                    //总支付金额 = 总卡付金额抵扣金额 + 总现付
                    if (BigDecimalUtils.compareTo(docPromotionRequest.getAmount(), BigDecimalUtils.add(docPromotionRequest.getCollectionCashAmount(), docPromotionRequest.getCollectionRechargeAmount())) != 0){
                        throw new SmsException(ResponseCode.PROMOTION_NOT_PERMISSION,"总支付金额和成交金额不相等");
                    }
                }
            }else {
                //不允许充值卡支付 只校验现付金额
                if (BigDecimalUtils.compareTo(docPromotionRequest.getAmount(), docPromotionRequest.getCollectionCashAmount()) != 0){
                    throw new SmsException(ResponseCode.PROMOTION_NOT_PERMISSION,"总支付金额和成交金额不相等");
                }
            }
        }
        else{
            //判断是否允许欠款
//            StoreParament parament = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(),Constant.promotion);
            StoreParament parament = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(),Constant.allow_debt);
            if ("0".equals(parament.getParamentValue())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "疗程促销");
            }else {
//                StoreParament debtRatio = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(), Constant.promotionRatio);
                StoreParament debtRatio = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(), Constant.debt_ratio);

                //实际收款
                BigDecimal cashMoney = docPromotionRequest.getCollectionCashAmount().add(docPromotionRequest.getCollectionRechargeAmount());
                BigDecimal courseReatmentAmount = cashMoney;
                BigDecimal multiply = docPromotionRequest.getPrice();
                //最少支付金额
                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(docPromotionRequest.getStoreId(),Constant.promotionUsable);
                debtPara = StoreParaUtils.getStorePara(docPromotionRequest.getStoreId(),Constant.debt_usable);
            }
        }

        //设置主键Id
        Long docId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        docPromotion.setId(docId);
        Date docDate = new Date();
        docPromotion.setDocDate(docDate);
        //设置单据号

        String storeNUmm=ssmBaseStoreService.selectByPrimaryKey(docPromotionRequest.getStoreId()).getStoreNum();
        String docNum = this.getDocNum(docPromotionRequest,storeNUmm);
        docPromotion.setDocNum(docNum);
        //计算卡付现付业绩提成
        List<PayList> payLists = docPromotionRequest.getPayLists();
        docPromotion = this.setAchiComm(docPromotion,rechargeAccountList,payLists);
        //设置业务员
        List<StaffRequest> staffLists = docPromotionRequest.getStaffLists();
        this.setStaffValue(staffLists,docPromotion);
        docPromotion.setInputDate(new Date());


        //设置录单人信息
        if (redisClient.hasKey(getKey(docPromotionRequest.getStaffPhone()))) {
            docPromotion.setInputId(redisClient.get(getKey(docPromotionRequest.getStaffPhone())).getId());
            docPromotion.setInputBy(redisClient.get(getKey(docPromotionRequest.getStaffPhone())).getStaffName());

        }
        Set<String> keys = redisClient.keys(getKey(docPromotionRequest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            docPromotion.setInputId(staffResponse.getId());
            docPromotion.setInputBy(staffResponse.getStaffName());
        }
        docPromotion.setIsCancel(0);
        BigDecimal totalMoney = BigDecimal.valueOf(0);
        PromotionListRequest promotionListRequest = new PromotionListRequest();
        promotionListRequest.setId(promotionList.getId());
        List<PromotionProject> list = ssmPromotionProjectService.selectList(promotionListRequest);

        List<PromotionRechargeList> promotionRechargeLists = promotionRechargeListService.selectList(promotionListRequest);
//        String[] strings = null;
//        if(!"".equals(docPromotionRequest.getProjectArray()) && null != docPromotionRequest.getProjectArray()){
//            strings = docPromotion.getProjectArray().split(",");
//            for (PromotionProject promotionProject : list) {
//                for (String string : strings) {
//                    Long aLong = Long.valueOf(string);
//                    if(promotionProject.getId().equals(aLong)){
//                        =totalMoney.add(promotionProject.getProjectTotalMoney());
//                    }
//                }
//            }
//        }

//        if(null !=docPromotion.getProjectCount() && 0<=docPromotion.getProjectCount()) {
        if(null !=docPromotionRequest.getPromotionProjects() && 0<docPromotionRequest.getPromotionProjects().size()) {
            BigDecimal totalProjectMoney = docPromotionRequest.getPromotionProjects().stream().filter(promotionProject -> 0 ==promotionProject.getType()).map(PromotionProject::getProjectTotalMoney).reduce(BigDecimal.ZERO,BigDecimal::add);

            //计算金额
            //固定价要按比例平摊金额
            if(docPromotion.getMoneyType()==0){
                for (PromotionProject promotionProject : docPromotionRequest.getPromotionProjects()) {
                    BigDecimal divide = promotionProject.getProjectTotalMoney().multiply(docPromotionRequest.getAmount()).divide(totalProjectMoney, 2, BigDecimal.ROUND_HALF_UP);
                    promotionProject.setProjectTotalMoney(divide.setScale(2,BigDecimal.ROUND_HALF_UP));
                    promotionProject.setPriceMember(divide.divide(BigDecimal.valueOf(promotionProject.getTimes()*docPromotion.getCount()),2,BigDecimal.ROUND_HALF_UP));
                }
            }

            totalMoney= docPromotionRequest.getAmount();
            for (PromotionProject promotionProject : docPromotionRequest.getPromotionProjects()) {
                //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                cid = courseAccountId;
                cids.add(cid);
                CourseAccount courseAccount = new CourseAccount();
                BeanUtils.copyProperties(docPromotion, courseAccount);
                courseAccount.setId(courseAccountId);
                if (promotionProject.getType() == 0) {
                    courseAccount.setCourseType("1");
                } else {
                    courseAccount.setCourseType("2");
                }
                courseAccount.setCourseNum(docNum);

                //对疗程账户进行赋值
                if(0 == docPromotionRequest.getIsDebt()){
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount());
                }else{ //有欠款
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount(),docPromotion,totalMoney);
                }



                //添加促销活动项目明细
                DocPromotionProject docPromotionProject = new DocPromotionProject();
                BeanUtils.copyProperties(promotionProject,docPromotionProject);
                docPromotionProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                docPromotionProject.setMemberId(docPromotionRequest.getMemberId());
                docPromotionProject.setMemberName(docPromotionRequest.getMemberName());
                docPromotionProject.setMemberIdentityCard(docPromotionRequest.getMemberIdentityCard());
                docPromotionProject.setCard(docPromotionRequest.getCard());
                docPromotionProject.setMobilePhone(docPromotionRequest.getMobilePhone());
                docPromotionProject.setDocNum(docNum);
                docPromotionProject.setDocDate(docDate);
                docPromotionProject.setCourseAccountId(courseAccountId);
                docPromotionProject.setTimes(promotionProject.getTimes() * docPromotion.getCount());
                ssmDocPromotionProjectService.saveNotNull(docPromotionProject);
                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,courseAccount, docPromotionProject);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }
        else {
            totalMoney = list.stream().filter(promotionProject -> 0 == promotionProject.getType()).map(PromotionProject::getProjectTotalMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
            for (PromotionProject promotionProject : list) {
                promotionProject.setPriceMember(promotionProject.getProjectTotalMoney().divide(BigDecimal.valueOf(promotionProject.getTimes()), 2, BigDecimal.ROUND_HALF_UP));
                //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                cid = courseAccountId;
                cids.add(cid);
                CourseAccount courseAccount = new CourseAccount();
                BeanUtils.copyProperties(docPromotion, courseAccount);
                courseAccount.setId(courseAccountId);
                if (promotionProject.getType() == 0) {
                    courseAccount.setCourseType("1");
                } else {
                    courseAccount.setCourseType("2");
                }
                courseAccount.setCourseNum(docNum);

                //对疗程账户进行赋值
                if (0 == docPromotionRequest.getIsDebt()) {
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount());
                } else { //有欠款
                    courseAccount = ssmCourseAccountService.addCourseAccount(courseAccount, promotionProject, docPromotion.getCount(), docPromotion, totalMoney);
                }

                //添加促销活动项目明细
                DocPromotionProject docPromotionProject = new DocPromotionProject();
                BeanUtils.copyProperties(promotionProject, docPromotionProject);
                docPromotionProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                docPromotionProject.setMemberId(docPromotionRequest.getMemberId());
                docPromotionProject.setMemberName(docPromotionRequest.getMemberName());
                docPromotionProject.setMemberIdentityCard(docPromotionRequest.getMemberIdentityCard());
                docPromotionProject.setCard(docPromotionRequest.getCard());
                docPromotionProject.setMobilePhone(docPromotionRequest.getMobilePhone());
                docPromotionProject.setDocNum(docNum);
                docPromotionProject.setDocDate(docDate);
                docPromotionProject.setCourseAccountId(courseAccountId);
                docPromotionProject.setTimes(promotionProject.getTimes() * docPromotion.getCount());
                ssmDocPromotionProjectService.saveNotNull(docPromotionProject);
                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion, courseAccount, docPromotionProject);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
            // todo 如果有充值卡且没有欠款则直接将卡插入到会员账号中
            if (0 == docPromotionRequest.getIsDebt()) {
                PromotionListRequest promotionListRequest1 = new PromotionListRequest();
                promotionListRequest1.setId(promotionList.getId());
                List<PromotionRechargeList> promotionRechargeListList = promotionRechargeListService.selectList(promotionListRequest1);
                if (promotionRechargeListList != null && promotionRechargeListList.size() > 0) {
                    for (PromotionRechargeList promotionRechargeList : promotionRechargeListList) {
                        //判断是否有这个充值卡账号
                        Example example = new Example(RechargeAccount.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("rechargeTypeId", promotionRechargeList.getRechargeId());
                        criteria.andEqualTo("memberId", docPromotion.getMemberId());
                        List<RechargeAccount> rechargeAccounts = ssmRechargeAccountService.selectByExample(example);
                        RechargeAccount beforeAccount = null;
                        if (rechargeAccounts.size() > 0) {
                            beforeAccount = rechargeAccounts.get(0);
                            if (beforeAccount.getState() == 0) {
                                beforeAccount.setState(1);
//                                    ssmRechargeAccountService.updateByPrimaryKey(beforeAccount);
                            }
                        }

//                            第一次充值 无充值账户
                        if (null == beforeAccount) {


                            Long rechargeAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                            RechargeAccount account = new RechargeAccount();
                            account.setId(rechargeAccountId);
                            //对充值账户进行赋值
                            account.setMemberId(docPromotion.getMemberId());
                            account.setMemberName(docPromotion.getMemberName());
                            account.setCardRechargeMoney(promotionRechargeList.getRechargeMoney());
                            account.setCardRestMoney(BigDecimal.ZERO);
                            account.setRechargeTypeId(promotionRechargeList.getRechargeId());
                            account.setRechargeTypeName(promotionRechargeList.getRechargeName());
                            account.setRechargeTypeNum(promotionRechargeList.getRechargeNum());
                            RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(promotionRechargeList.getRechargeId());
                            account.setType(rechargeType.getType());
                            account.setDiscount(new BigDecimal(promotionRechargeList.getRechargeDiscount().toString()));
                            account.setCardGiftMoney(promotionRechargeList.getRechargeMoney());
                            account.setStoreId(docPromotion.getStoreId());
                            account.setStoreName(docPromotion.getStoreName());
                            account.setCardConsumeMoney(BigDecimal.ZERO);
                            account.setGiftConsumeMoney(promotionRechargeList.getRechargeMoney());
                            account.setState(1);
                            account.setCardNum(0);
                            account.setFirstCharge(0L);
                            //account.setCardRechargeMoney(rechargeType.getFirstAmount());
                            ssmRechargeAccountService.addRechargeAccount(account);
                            //判断是否仅本门店使用,如果是给充值赠送明细加一条记录
                            if (promotionRechargeList.getRechargeMoneyType() == 1) {
                                RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
                                rechargeAccountGive.setAccountId(account.getId());
                                rechargeAccountGive.setMemberId(account.getMemberId());
                                rechargeAccountGive.setMemberName(account.getMemberName());
                                rechargeAccountGive.setRechargeNum(docNum);
                                rechargeAccountGive.setStoreId(account.getStoreId());
                                rechargeAccountGive.setStoreName(docPromotion.getStoreName());
                                rechargeAccountGive.setGiftConsumeMoney(promotionRechargeList.getRechargeMoney());
                                rechargeAccountGive.setRechargeDate(docDate);
                                rechargeAccountGive.setRechargeTypeId(promotionRechargeList.getRechargeId());
                                rechargeAccountGive.setRechargeTypeName(promotionRechargeList.getRechargeName());
                                ssmRechargeAccountGiveService.save(rechargeAccountGive);
                            }
                            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion, promotionRechargeList, account);
                            ssmAccountTradeRecordService.addRecord(accountTradeRecord);


                        } else {//存在账户 添加账户金额
                            //判断充前金额是否和当前账户相等
                            beforeAccount.setCardGiftMoney(beforeAccount.getCardGiftMoney().add(promotionRechargeList.getRechargeMoney()));
                            beforeAccount.setGiftConsumeMoney(beforeAccount.getGiftConsumeMoney().add(promotionRechargeList.getRechargeMoney()));
                            beforeAccount.setCardNum(1);
                            ssmRechargeAccountService.updateByPrimaryKey(beforeAccount);
                            //判断是否仅本门店使用,如果是给充值赠送明细加一条记录
                            if (promotionRechargeList.getRechargeMoneyType() == 1) {
                                //查询有没有当前门店的赠送金额
                                RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
                                rechargeAccountGive.setAccountId(beforeAccount.getId());
                                List<RechargeAccountGive> select = ssmRechargeAccountGiveService.select(rechargeAccountGive);
                                Long storeId = docPromotion.getStoreId();
                                if (select != null && select.size() > 0) {
                                    List<RechargeAccountGive> collect = select.stream().filter(item -> item.getStoreId() == storeId || item.getStoreId().toString().equals(storeId.toString())).collect(Collectors.toList());
                                    if (collect != null && collect.size() > 0) {
                                        rechargeAccountGive = collect.get(0);
                                        rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().add(promotionRechargeList.getRechargeMoney()));
                                        ssmRechargeAccountGiveService.updateByGifMoney(rechargeAccountGive);
                                    } else {
                                        rechargeAccountGive = new RechargeAccountGive();
                                        rechargeAccountGive.setAccountId(beforeAccount.getId());
                                        rechargeAccountGive.setMemberId(beforeAccount.getMemberId());
                                        rechargeAccountGive.setMemberName(beforeAccount.getMemberName());
                                        rechargeAccountGive.setRechargeNum(docNum);
                                        rechargeAccountGive.setStoreId(docPromotion.getStoreId());
                                        rechargeAccountGive.setStoreName(docPromotion.getStoreName());
                                        rechargeAccountGive.setGiftConsumeMoney(promotionRechargeList.getRechargeMoney());
                                        rechargeAccountGive.setRechargeDate(docDate);
                                        rechargeAccountGive.setRechargeTypeId(promotionRechargeList.getRechargeId());
                                        rechargeAccountGive.setRechargeTypeName(promotionRechargeList.getRechargeName());
                                        ssmRechargeAccountGiveService.save(rechargeAccountGive);
                                    }
                                }

                            }
                            AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion, promotionRechargeList, beforeAccount);
                            ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                        }

                    }
                }
            }
        }

        //如果使用充值卡支付 对使用的充值账户金额扣减
        if (BigDecimalUtils.compareTo(docPromotion.getCollectionRechargeAmount(),BigDecimalUtils.bigDecimal("0")) == 1) {
            //计算扣减金额 并添加账户交易记录
            ssmRechargeAccountService.subMoney(rechargeAccountList, docPromotion);
        }
        //欠款 添加欠款记录
        if (1 == docPromotionRequest.getIsDebt()){
            DebtListRequest debtListRequest = new DebtListRequest();
            BeanUtils.copyProperties(docPromotion,debtListRequest);
            debtListRequest.setTradeId(docPromotion.getPromotionId());
            debtListRequest.setTradeName(docPromotion.getPromotionName());
            debtListRequest.setTradeMoney(docPromotion.getPrice());
            debtListRequest.setDocId(docPromotion.getId());
            debtListRequest.setDocNum(docPromotion.getDocNum());
            debtListRequest.setDocType(Constant.promotion_card_use);
//            debtListRequest.setAccountId(courseAccountId);
            debtListRequest.setStaffLists(staffLists);
            debtListRequest.setState(0);
            debtListRequest.setDocDate(docPromotion.getDocDate());
            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);
        }
        try {
            i = dao.saveNotNull(docPromotion);

            Long docPromotionId = docPromotion.getId();
            for (Long aLong : cids) {
                CourseAccount courseAccount = new CourseAccount();
                courseAccount.setId(aLong);
                courseAccount.setPromotionDocId(docPromotionId);
                ssmCourseAccountDao.updateByPrimaryKeySelective(courseAccount);
            }


            HttpSession session = docPromotionRequest.getSession();
            //添加高管的当前单据门店信息
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(Long.valueOf(String.valueOf(session.getAttribute("storeId"))));
            BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);
            //高管业绩
            List<Salesman> salesmens = docPromotionRequest.getSalesmens();
            for (Salesman salesmen : salesmens) {
                salesmen.setOrderId(String.valueOf(docPromotion.getId()));
                salesmen.setOrderNum(docPromotion.getDocNum());
                salesmen.setOrderType(8);
                salesmen.setOrderDate(new Date());
                salesmen.setState(0);
                salesmen.setOperatorBy(docPromotion.getInputBy());
                salesmen.setMoney(docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount()));
                salesmen.setProjectId(docPromotion.getPromotionId());
                salesmen.setStoreNum(baseStore1.getStoreNum());
                salesmen.setStoreName(baseStore1.getStoreName());
                salesmen.setStoreIdOrder(baseStore1.getId());
            }
            ssmSalesmanService.addBatch(salesmens);
        }catch (Exception e){
            log.error("SsmDocPromotionServiceImpl.addDoc:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //添加现付支付方式
        if (null != payLists && payLists.size() > 0) {
            for (PayList payList : payLists) {
                payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                payList.setDocId(String.valueOf(docId));
                payList.setType(Constant.doc_type_promotion);
                payList.setStoreId(docPromotionRequest.getStoreId());
                payList.setIsCancel(0);
            }
            ssmPayService.addPayList(payLists);
        }
        //将促销单据信息添加到评价表
        MemberCsRequest memberCsRequest = new MemberCsRequest();
        BeanUtils.copyProperties(docPromotion, memberCsRequest);
        memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberCsRequest.setDocId(docPromotion.getId());
        memberCsRequest.setDocNum(docNum);
        memberCsRequest.setDocType(Constant.doc_type_promotion);
        memberCsRequest.setDocDate(docPromotion.getDocDate());
        memberCsRequest.setTradeId(docPromotion.getPromotionId());
        memberCsRequest.setTradeName(docPromotion.getPromotionName());
        memberCsRequest.setTradeMoney(docPromotion.getPrice());
        memberCsRequest.setTradeCount(docPromotion.getCount());
        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 cancel(DocPromotionRequest docPromotionRequest) throws SmsException {
        int i = 0;
        DocPromotion docPromotion = dao.selectByPrimaryKey(docPromotionRequest.getId());
        PayList payList = new PayList();
        payList.setDocId(String.valueOf(docPromotionRequest.getId()));
        List<PayList> payListList = ssmPayService.select(payList);
        if(payListList!=null&&payListList.size()>0) {
            for (PayList list : payListList) {
                list.setIsCancel(1);
                ssmPayService.updateByNum(list);
            }
        }
        if(docPromotion.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
            DebtList debtList = new DebtList();
            debtList.setDocId(docPromotion.getId());
            debtList.setStoreId(docPromotion.getStoreId());
            List<DebtList> select = ssmDebtService.select(debtList);
            for (DebtList list : select) {
                if(list.getState()==1 ||list.getState()==2){
                    throw new SmsException(ResponseCode.MSG,"该单据存在未作废还款和取消欠款，请先作废");
                }
            }
        }
        //判断时间是否超过允许作废时间
        StoreParament storeParament = StoreParaUtils.getStorePara(docPromotion.getStoreId(),Constant.service_ticke);
        Long days =  DateUtils.getDayDiff(docPromotion.getDocDate(),new Date());
        if(!"0".equals(storeParament.getParamentValue())) {
            if (days.longValue() > Long.parseLong(storeParament.getParamentValue())) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据超过允许作废时间");
            }
        }
        Boolean cancelDebt=false;
        if(docPromotion.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1) {
            cancelDebt=true;
            DebtList debtList = new DebtList();
            debtList.setDocId(docPromotion.getId());
            debtList.setStoreId(docPromotion.getStoreId());
            DebtList select = ssmDebtService.selectOne(debtList);
            if(select.getState()==1){
                throw new SmsException(ResponseCode.MSG,"单据欠款存在还款，请先作废还款");
            }

            CancelDebtList cancelDebtList = new CancelDebtList();
            cancelDebtList.setDebtId(select.getId());
            cancelDebtList.setState(3);
            List<CancelDebtList> select2 = ssmCancelDebtListService.select(cancelDebtList);
            if(select2.size()>0){
                throw new SmsException(ResponseCode.MSG,"单据欠款存在取消欠款，请先作废取消欠款");
            }

            //判断是否已经还款
            RepayTradeList repayTradeList = new RepayTradeList();
            repayTradeList.setDocId(select.getId());
            List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList);
            for (RepayTradeList tradeList : select1) {
                RepayList repayList = new RepayList();
                repayList.setRepayNum(tradeList.getRepayNum());
                repayList.setStoreId(tradeList.getStoreId());
                repayList.setIsCancel(0);
                List<RepayList> select3 = ssmRepayService.select(repayList);
                if (select3.size()>0) {
                    throw new SmsException(ResponseCode.MSG,"单据欠款存在还款，请先作废还款");
                }
            }

            int i1 = ssmDebtService.deleteByPrimaryKey(select.getId());
            if(i1==0){
                throw new SmsException(ResponseCode.MSG,"清除欠款单失败");
            }

        }

        //修改疗程单据状态
        docPromotion.setIsCancel(1);
        docPromotion.setCancelDate(new Date());
        //设置作废人信息
        if (redisClient.hasKey(getKey(docPromotionRequest.getStaffPhone()))){
            StaffResponse staffResponse = redisClient.get(getKey(docPromotionRequest.getStaffPhone()));
            docPromotion.setCancelId(staffResponse.getId());
            docPromotion.setCancelBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getKey(docPromotionRequest.getStaffPhone()) + "*");
        //从redis查询 设置作废人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            docPromotion.setCancelId(staffResponse.getId());
            docPromotion.setCancelBy(staffResponse.getStaffName());
        }
        //疗程账户扣减次数
        DocPromotionProject docPromotionProject = new DocPromotionProject();
        docPromotionProject.setDocNum(docPromotion.getDocNum());
//        docPromotionProject.setStoreId(docPromotion.getStoreId());
        List<DocPromotionProject> list = ssmDocPromotionProjectService.select(docPromotionProject);

        BigDecimal totalMoney = list.stream().filter(promotionProject -> 0 ==promotionProject.getType()).map(DocPromotionProject::getProjectTotalMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        for (DocPromotionProject project : list) {
            if(project.getType()==1){
//                if(!cancelDebt){
                    //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                    CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(project.getCourseAccountId());
                    Integer subCount = project.getTimes();
                    if(project.getPriceMember().compareTo(BigDecimal.ZERO)==0){

                    project.setPriceMember(new BigDecimal("1"));
                    }
                    BigDecimal courseRestPrice1 = courseAccount.getCourseRestPrice();

                    BigDecimal add = docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount());

                    BigDecimal courseRestPrice = add.multiply(project.getProjectTotalMoney().divide(totalMoney, 2, BigDecimal.ROUND_HALF_UP));

                //                    int i2 = (courseAccount.getCourseConsumePrice().divide(project.getPriceMember().compareTo(BigDecimal.ZERO)==0?new BigDecimal("1"):project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();
//
//                    int i1 = (courseRestPrice.divide(project.getPriceMember().compareTo(BigDecimal.ZERO)==0?new BigDecimal("1"):project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();
                int i2 =0;
                if(courseAccount.getCourseConsumeCount() - project.getTimes() >= 0){
                    i2 = courseAccount.getCourseConsumeCount() - project.getTimes();
                }
                courseAccount = ssmCourseAccountService.subCount(courseAccount, project.getTimes(), 1,i2);
                //添加账户交易记录
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,courseAccount, docPromotionProject,courseRestPrice1);
                    accountTradeRecord.setOrderStatu(1);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
//                }
            }else{

                //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(project.getCourseAccountId());
                Integer subCount = project.getTimes();
                BigDecimal courseRestPrice1 = courseAccount.getCourseRestPrice();
                BigDecimal add = docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount());

                BigDecimal courseRestPrice = add.multiply(project.getProjectTotalMoney().divide(totalMoney, 2, BigDecimal.ROUND_HALF_UP));

                int i2 = (courseAccount.getCourseConsumePrice().divide(project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();

                int i1 = (courseRestPrice.divide(project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();

                courseAccount = ssmCourseAccountService.subCount(courseAccount, i1, 1,i2);
                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,courseAccount, docPromotionProject,courseRestPrice1);
                accountTradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }
        //如果使用充值卡支付 对使用的充值账户金额添加
        if (BigDecimalUtils.compareTo(docPromotion.getCollectionRechargeAmount(),BigDecimalUtils.bigDecimal("0")) == 1) {
            //计算添加金额 并添加账户交易记录
            ssmRechargeAccountService.addMoney(docPromotionRequest.getRechargeAccountList(), docPromotion);
        }
        try {
            i = dao.updateByPrimaryKeySelective(docPromotion);
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(docPromotion.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(1);
                ssmSalesmanService.updateNotNull(salesman1);
            }
        }catch (Exception e){
            log.error("SsmDocPromotionServiceImpl.cancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //将评价单进行删除操作
        MemberCs memberCs = new MemberCs();
        memberCs.setDocId(docPromotion.getId());
        ssmMemberCsService.delete(memberCs);
        return i;
    }

    /*
     * 业务员赋值
     * */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int cancelPromotionRecharge(DocPromotionRequest docPromotionRequest) throws SmsException {
        int i = 0;
        DocPromotion docPromotion = dao.selectByPrimaryKey(docPromotionRequest.getId());
        PayList payList = new PayList();
        payList.setDocId(String.valueOf(docPromotionRequest.getId()));
        List<PayList> payListList = ssmPayService.select(payList);
        if(payListList!=null&&payListList.size()>0) {
            for (PayList list : payListList) {
                list.setIsCancel(1);
                ssmPayService.updateByNum(list);
            }
        }
        if(docPromotion.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
            DebtList debtList = new DebtList();
            debtList.setDocId(docPromotion.getId());
            debtList.setStoreId(docPromotion.getStoreId());
            List<DebtList> select = ssmDebtService.select(debtList);
            for (DebtList list : select) {
                if(list.getState()==1 ||list.getState()==2){
                    throw new SmsException(ResponseCode.MSG,"该单据存在未作废还款和取消欠款，请先作废");
                }
            }
        }
        //判断时间是否超过允许作废时间
        StoreParament storeParament = StoreParaUtils.getStorePara(docPromotion.getStoreId(),Constant.service_ticke);
        Long days =  DateUtils.getDayDiff(docPromotion.getDocDate(),new Date());
        if(!"0".equals(storeParament.getParamentValue())) {
            if (days.longValue() > Long.parseLong(storeParament.getParamentValue())) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据超过允许作废时间");
            }
        }
        Boolean cancelDebt=false;
        if(docPromotion.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1) {
            cancelDebt=true;
            DebtList debtList = new DebtList();
            debtList.setDocId(docPromotion.getId());
            debtList.setStoreId(docPromotion.getStoreId());
            DebtList select = ssmDebtService.selectOne(debtList);
            if(select.getState()==1){
                throw new SmsException(ResponseCode.MSG,"单据欠款存在还款，请先作废还款");
            }

            CancelDebtList cancelDebtList = new CancelDebtList();
            cancelDebtList.setDebtId(select.getId());
            cancelDebtList.setState(3);
            List<CancelDebtList> select2 = ssmCancelDebtListService.select(cancelDebtList);
            if(select2.size()>0){
                throw new SmsException(ResponseCode.MSG,"单据欠款存在取消欠款，请先作废取消欠款");
            }

            //判断是否已经还款
            RepayTradeList repayTradeList = new RepayTradeList();
            repayTradeList.setDocId(select.getId());
            List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList);
            for (RepayTradeList tradeList : select1) {
                RepayList repayList = new RepayList();
                repayList.setRepayNum(tradeList.getRepayNum());
                repayList.setStoreId(tradeList.getStoreId());
                repayList.setIsCancel(0);
                List<RepayList> select3 = ssmRepayService.select(repayList);
                if (select3.size()>0) {
                    throw new SmsException(ResponseCode.MSG,"单据欠款存在还款，请先作废还款");
                }
            }

            int i1 = ssmDebtService.deleteByPrimaryKey(select.getId());
            if(i1==0){
                throw new SmsException(ResponseCode.MSG,"清除欠款单失败");
            }

        }

        //修改疗程单据状态
        docPromotion.setIsCancel(1);
        docPromotion.setCancelDate(new Date());
        //设置作废人信息
        if (redisClient.hasKey(getKey(docPromotionRequest.getStaffPhone()))){
            StaffResponse staffResponse = redisClient.get(getKey(docPromotionRequest.getStaffPhone()));
            docPromotion.setCancelId(staffResponse.getId());
            docPromotion.setCancelBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getKey(docPromotionRequest.getStaffPhone()) + "*");
        //从redis查询 设置作废人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            docPromotion.setCancelId(staffResponse.getId());
            docPromotion.setCancelBy(staffResponse.getStaffName());
        }
        //先判断是否欠款，如果有欠款的就不需要作废充值卡账号
        if(docPromotion.getDebtMoney().compareTo(BigDecimal.valueOf(0))!=1){
            //查询促销项目进行判断促销项目是什么类型
            PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion.getPromotionId());
            //如果是买就送
            if(promotionList.getType()==1){
                //查询充值列表，判断是否有送充值卡
                PromotionListRequest promotionListRequest = new PromotionListRequest();
                promotionListRequest.setId(promotionList.getId());
                List<PromotionRechargeList> promotionRechargeListList = promotionRechargeListService.selectList(promotionListRequest);
                //根据充值卡类别和会员id查询充值卡账户并且进行扣钱
                if(promotionRechargeListList!=null && promotionRechargeListList.size()>0){
                    for (PromotionRechargeList promotionRechargeList : promotionRechargeListList) {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setMemberId(docPromotion.getMemberId());
                        rechargeAccount.setRechargeTypeId(promotionRechargeList.getRechargeId());
                        //查询一个充值账户进行扣减金额
                        rechargeAccount = ssmRechargeAccountService.selectByMemberIdAndRechargeTypeIdAndMoney(rechargeAccount);
                        if(rechargeAccount.getCardGiftMoney().compareTo(promotionRechargeList.getRechargeMoney())==-1
                                || rechargeAccount.getGiftConsumeMoney().compareTo(promotionRechargeList.getRechargeMoney())==-1){
                            throw new SmsException(ResponseCode.MSG,"赠送的充值卡金额不足，无法作废");
                        }
                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().subtract(promotionRechargeList.getRechargeMoney()));
                        rechargeAccount.setGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney().subtract(promotionRechargeList.getRechargeMoney()));
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,promotionRechargeList,rechargeAccount);
                        ssmRechargeAccountService.updateByPrimaryKey(rechargeAccount);
                        //如果是仅本门店使用的，还要对赠送明细进行金额扣减
                        if(promotionRechargeList.getRechargeMoneyType()==1){
                            RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
                            rechargeAccountGive.setAccountId(rechargeAccount.getId());
                            List<RechargeAccountGive> select = ssmRechargeAccountGiveService.select(rechargeAccountGive);
                            List<RechargeAccountGive> collect = select.stream().filter(item -> item.getStoreId() == docPromotion.getStoreId() || item.getStoreId().toString().equals(docPromotion.getStoreId().toString())).collect(Collectors.toList());
                            rechargeAccountGive = collect.get(0);
                            if(rechargeAccountGive.getGiftConsumeMoney().compareTo(promotionRechargeList.getRechargeMoney())==-1){
                                throw new SmsException(ResponseCode.MSG,"赠送的充值卡金额不足，无法作废");
                            }
                            rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().subtract(promotionRechargeList.getRechargeMoney()));
                            ssmRechargeAccountGiveService.updateByGifMoney(rechargeAccountGive);
                        }
                        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

                    }
                }
            }
        }



        //疗程账户扣减次数
        DocPromotionProject docPromotionProject = new DocPromotionProject();
        docPromotionProject.setDocNum(docPromotion.getDocNum());
//        docPromotionProject.setStoreId(docPromotion.getStoreId());
        List<DocPromotionProject> list = ssmDocPromotionProjectService.select(docPromotionProject);

        BigDecimal totalMoney = list.stream().filter(promotionProject -> 0 ==promotionProject.getType()).map(DocPromotionProject::getProjectTotalMoney).reduce(BigDecimal.ZERO,BigDecimal::add);
        for (DocPromotionProject project : list) {
            if(project.getType()==1){
//                if(!cancelDebt){
                //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(project.getCourseAccountId());
                Integer subCount = project.getTimes();
                BigDecimal courseRestPrice1 = courseAccount.getCourseRestPrice();

                BigDecimal add = docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount());

                BigDecimal courseRestPrice = add.multiply(project.getProjectTotalMoney().divide(totalMoney, 2, BigDecimal.ROUND_HALF_UP));

//                    int i2 = (courseAccount.getCourseConsumePrice().divide(project.getPriceMember().compareTo(BigDecimal.ZERO)==0?new BigDecimal("1"):project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();
//
//                    int i1 = (courseRestPrice.divide(project.getPriceMember().compareTo(BigDecimal.ZERO)==0?new BigDecimal("1"):project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();
                int i2 =0;
                if(courseAccount.getCourseConsumeCount() - project.getTimes() >= 0){
                    i2 = courseAccount.getCourseConsumeCount() - project.getTimes();
                }
                courseAccount = ssmCourseAccountService.subCount(courseAccount, project.getTimes(), 1,i2);
                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,courseAccount, docPromotionProject,courseRestPrice1);
                accountTradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
//                }
            }else{

                //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                CourseAccount courseAccount = ssmCourseAccountService.selectByPrimaryKey(project.getCourseAccountId());
                Integer subCount = project.getTimes();
                BigDecimal courseRestPrice1 = courseAccount.getCourseRestPrice();
                BigDecimal add = docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount());

                BigDecimal courseRestPrice = add.multiply(project.getProjectTotalMoney().divide(totalMoney, 2, BigDecimal.ROUND_HALF_UP));

                int i2 = (courseAccount.getCourseConsumePrice().divide(project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();

                int i1 = (courseRestPrice.divide(project.getPriceMember(), 2, BigDecimal.ROUND_HALF_UP)).intValue();

                courseAccount = ssmCourseAccountService.subCount(courseAccount, i1, 1,i2);
                //添加账户交易记录
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion,courseAccount, docPromotionProject,courseRestPrice1);
                accountTradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }
        //如果使用充值卡支付 对使用的充值账户金额添加
        if (BigDecimalUtils.compareTo(docPromotion.getCollectionRechargeAmount(),BigDecimalUtils.bigDecimal("0")) == 1) {
            //计算添加金额 并添加账户交易记录
            ssmRechargeAccountService.addMoney(docPromotionRequest.getRechargeAccountList(), docPromotion);
        }
        try {
            i = dao.updateByPrimaryKeySelective(docPromotion);
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(docPromotion.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen) {
                salesman1.setState(1);
                ssmSalesmanService.updateNotNull(salesman1);
            }
        }catch (Exception e){
            log.error("SsmDocPromotionServiceImpl.cancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        //将评价单进行删除操作
        MemberCs memberCs = new MemberCs();
        memberCs.setDocId(docPromotion.getId());
        ssmMemberCsService.delete(memberCs);
        return i;
    }
    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
    public int updateStaff(DocPromotionRequest docPromotionRequest) throws SmsException {
        int i = 0;
        DocPromotion docPromotion = new DocPromotion();
        BeanUtils.copyProperties(docPromotionRequest, docPromotion);
        StoreParament storeParament = StoreParaUtils.getStorePara(docPromotion.getStoreId(), Constant.editOrderNum);
        int days = (int) DateUtils.getDayDiff(docPromotion.getDocDate(), new Date());
        if("999".equals(storeParament.getParamentValue())) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            if(!dateFormat.format(new Date()).equals(dateFormat.format(docPromotion.getDocDate()))) {
                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, "单据超过允许修改时间");
            }
        }
        List<PayList> payLists = docPromotionRequest.getPayLists();
        if(payLists!=null && payLists.size()>0){
            for (PayList payList : payLists) {
                BaseCollectionType baseCollectionType = ssmCollectionTypeService.selectByPrimaryKey(payList.getPayId());
                payList.setPayName(baseCollectionType.getCollectionTypeName());
                payList.setIsCancel(0);
                ssmPayService.updateByPrimaryKey(payList);
            }
        }
        //设置业务员
        List<StaffRequest> staffLists = docPromotionRequest.getStaffLists();
        this.setStaffValue(staffLists,docPromotion);
            DebtList debtList = new DebtList();
            debtList.setDocId(docPromotion.getId());
            List<DebtList> debtLists = ssmDebtService.select(debtList);
            if(debtLists!=null &&debtLists.size()>0){
            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(docPromotion);
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(docPromotion.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            Date date = new Date();
            for (Salesman salesman1 : salesmen) {
                date = salesman1.getOrderDate();
                ssmSalesmanService.delete(salesman1);
            }
            DocPromotion docPromotion1 = dao.selectOne(docPromotion);
            HttpSession session = docPromotionRequest.getSession();
            BaseStore baseStore = new BaseStore();
            baseStore.setId(docPromotionRequest.getStoreId());
            BaseStore baseStore1 = ssmBaseStoreService.selectOne(baseStore);
            List<Salesman> salesmens = docPromotionRequest.getSalesmens();
//            DocPromotionProject docPromotionProject = new DocPromotionProject();
//            docPromotionProject.setPromotionNum(docPromotion.getPromotionNum());
//            List<DocPromotionProject> select = ssmDocPromotionProjectService.select(docPromotionProject);
//            for (DocPromotionProject promotionProject : select) {
//
//            }
            for (Salesman salesmen2 : salesmens) {
                Random r = new Random(3);
                int i1 = r.nextInt();
                salesmen2.setId(salesmen2.getId()+i1);
                salesmen2.setOrderId(String.valueOf(docPromotion.getId()));
                salesmen2.setOrderNum(docPromotion1.getDocNum());
                salesmen2.setOrderType(8);
                salesmen2.setOrderDate(date);
                salesmen2.setState(0);
                salesmen2.setMoney(docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount()));
//                salesmen2.setProjectId(Long.valueOf(docPromotion.getPromotionNum()));
                salesmen2.setStoreNum(baseStore1.getStoreNum());
                salesmen2.setStoreName(baseStore1.getStoreName());
                salesmen2.setStoreIdOrder(baseStore1.getId());
            }
            ssmSalesmanService.addBatch(salesmens);
        } catch (Exception e) {
            log.error("SsmDocPromotionServiceImpl.updateStaff:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    public List<DocPromotionResponse> selectList(Long storeId, String dateStr) {
        Example example = new Example(DocPromotion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId", storeId);
        criteria.andEqualTo("isCancel", 0);
        criteria.andLike("docDate", dateStr + "%");
        List<DocPromotion> list = dao.selectByExample(example);
        List<DocPromotionResponse> responses = new ArrayList<>();
        for (DocPromotion docPromotion : list) {
            DocPromotionResponse docPromotionResponse = new DocPromotionResponse();
            BeanUtils.copyProperties(docPromotion, docPromotionResponse);
            //设置业务员
            List<AchiCommEntity> entities = this.getAchiCommList(docPromotion);
            for (AchiCommEntity entity : entities) {
                entity.setDocId(docPromotion.getId());
                if(null != entity.getProjectId()){
//                    BaseProject baseProject = new BaseProject();
//                    baseProject.setId(Long.valueOf(entity.getProjectId()));
//                    BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
                    entity.setProjectId("促销项目");
                }
            }
            docPromotionResponse.setEntities(entities);
            responses.add(docPromotionResponse);
        }
        return responses;
    }

    @Override
    public List<DocPromotion> selectFKJ(DocPromotionRequest docPromotionRequest) {
        return dao.selectFKJ(docPromotionRequest);
    }
    @Override
    public List<DocPromotion> selectFKJByDate(DocPromotionRequest docPromotionRequest) {
        return mapper.selectFKJByDate(docPromotionRequest);
    }

    @Override
    public List<DocPromotionResponse> selectListAbnormal(Long storeId, String dateStr) {
        Example example = new Example(DocPromotion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId", storeId);
        criteria.andEqualTo("isCancel", 0);
        criteria.andLike("docDate", dateStr + "%");
        List<DocPromotion> list = dao.selectByExample(example);
        List<DocPromotionResponse> responses = new ArrayList<>();
        for (DocPromotion docPromotion : list) {
            //总业绩
            BigDecimal totalPerformance = BigDecimal.valueOf(0);
            DocPromotionResponse docPromotionResponse = new DocPromotionResponse();
            BeanUtils.copyProperties(docPromotion, docPromotionResponse);
            //设置业务员
            List<AchiCommEntity> entities = this.getAchiCommList(docPromotion);
            for (AchiCommEntity entity : entities) {
                totalPerformance=totalPerformance.add(entity.getCashAchi().add(entity.getCardAchi()));
            }
            if(totalPerformance.subtract(docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount())).abs().compareTo(new BigDecimal("0.05")) == 1 ){
                docPromotionResponse.setEntities(entities);
                docPromotionResponse.setErrorMessage("请检查是否填写员工或者漏填员工，无误则检查项目是否有业绩提成");
                responses.add(docPromotionResponse);
            }
            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){
                docPromotionResponse.setEntities(entities);
                docPromotionResponse.setErrorMessage("存在占比为零的员工存在");
                if(!responses.contains(docPromotionResponse)){
                    responses.add(docPromotionResponse);
                }
            }

        }
        return responses;
    }


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

    @Override
    public List<PromotionDayVo> selectByDay(List<Long> storeIds, Date startTime, Date endTime) {


        return dao.selectByDay(storeIds,startTime,endTime);
    }
    @Autowired
    private DocPromotionMapper mapper;

    @Override
    public List<DocPromotion> selectList(DocPromotionRequest docPromotionRequest) {
        return mapper.selectList(docPromotionRequest);
    }

    @Override
    public List<DocPromotion> selectListByStartTimeAndEndTime(Long id, Date startTime, Date endTime) {
        return mapper.selectListByStartTimeAndEndTime(id,startTime,endTime);
    }

    @Override
    public List<DocPromotionResponse> selectLists(Long storeId, String startDate,String endDte) {
        Example example = new Example(DocPromotion.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("storeId", storeId);
        criteria.andEqualTo("isCancel", 0);
//        criteria.andLike("docDate", dateStr + "%");
        criteria.andBetween("docDate", startDate,endDte);
        List<DocPromotion> list = dao.selectByExample(example);
        List<DocPromotionResponse> responses = new ArrayList<>();
        for (DocPromotion docPromotion : list) {
            DocPromotionResponse docPromotionResponse = new DocPromotionResponse();
            BeanUtils.copyProperties(docPromotion, docPromotionResponse);
            //设置业务员
            List<AchiCommEntity> entities = this.getAchiCommList(docPromotion);
            docPromotionResponse.setEntities(entities);
            responses.add(docPromotionResponse);
        }
        return responses;
    }

    /*
     * 账户交易记录属性赋值 促销活动
     * */
    public AccountTradeRecord setAccountTradeRecord(DocPromotion docPromotion,CourseAccount courseAccount, DocPromotionProject docPromotionProject){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(docPromotion.getStoreId());
        accountTradeRecord.setStoreName(docPromotion.getStoreName());
        accountTradeRecord.setMemberId(docPromotion.getMemberId());
        accountTradeRecord.setMemberName(docPromotion.getMemberName());
        accountTradeRecord.setMemberIdentity(docPromotion.getManageIdentity());
        accountTradeRecord.setMemberPhone(docPromotion.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
        accountTradeRecord.setPrice(docPromotion.getPrice());
        if(docPromotion.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_project);
            accountTradeRecord.setInputDate(docPromotion.getDocDate());
            accountTradeRecord.setInputBy(docPromotion.getInputBy());
            accountTradeRecord.setOrderStatu(0);
            if ("1".equals(courseAccount.getCourseType())){
                accountTradeRecord.setAccountInMoney(docPromotionProject.getProjectTotalMoney());
            }else {
                accountTradeRecord.setAccountInMoney(BigDecimalUtils.bigDecimal("0"));
            }
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
        }else {
            accountTradeRecord.setInputBy(docPromotion.getCancelBy());
            accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
            accountTradeRecord.setInputDate(docPromotion.getCancelDate());
            if ("1".equals(courseAccount.getCourseType())){
                accountTradeRecord.setAccountInMoney(docPromotionProject.getProjectTotalMoney());
            }else {
                accountTradeRecord.setAccountSpendMoney(BigDecimalUtils.bigDecimal("0"));
            }
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
            accountTradeRecord.setOrderStatu(1);
        }
        accountTradeRecord.setDocId(docPromotion.getId());
        accountTradeRecord.setDocNum(docPromotion.getDocNum());
        accountTradeRecord.setDocType(Constant.dabao_promotion);
        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.setCashMoney(docPromotion.getCollectionCashAmount());
        accountTradeRecord.setCardMoney(docPromotion.getCollectionRechargeAmount());
        return accountTradeRecord;
    }

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

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


        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCashMoney(docPromotion.getCollectionCashAmount());
        accountTradeRecord.setCardMoney(docPromotion.getCollectionRechargeAmount());
        return accountTradeRecord;
    }
    /*
     * 账户交易记录属性赋值 促销活动
     * */
    public AccountTradeRecord setAccountTradeRecord(DocPromotion docPromotion,CourseAccount courseAccount, DocPromotionProject docPromotionProject,BigDecimal courseRestPrice1){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(docPromotion.getStoreId());
        accountTradeRecord.setStoreName(docPromotion.getStoreName());
        accountTradeRecord.setMemberId(docPromotion.getMemberId());
        accountTradeRecord.setMemberName(docPromotion.getMemberName());
        accountTradeRecord.setMemberIdentity(docPromotion.getManageIdentity());
        accountTradeRecord.setMemberPhone(docPromotion.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());
        accountTradeRecord.setPrice(docPromotion.getPrice());
        if(docPromotion.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_project);
            accountTradeRecord.setInputDate(docPromotion.getDocDate());
            accountTradeRecord.setInputBy(docPromotion.getInputBy());
            accountTradeRecord.setOrderStatu(0);
            if ("1".equals(courseAccount.getCourseType())){
                accountTradeRecord.setAccountInMoney(courseAccount.getCourseRestPrice());
            }else {
                accountTradeRecord.setAccountInMoney(BigDecimalUtils.bigDecimal("0"));
            }
            accountTradeRecord.setAccountInCount(courseAccount.getCourseCount());
        }else {
            accountTradeRecord.setInputBy(docPromotion.getCancelBy());
            accountTradeRecord.setAccountType(Constant.account_type_project_cancel);
            accountTradeRecord.setInputDate(docPromotion.getCancelDate());
            accountTradeRecord.setAccountSpendMoney(courseRestPrice1);
            accountTradeRecord.setAccountSpendCount(courseAccount.getCourseCount());
            accountTradeRecord.setOrderStatu(1);
        }
        accountTradeRecord.setDocId(docPromotion.getId());
        accountTradeRecord.setDocNum(docPromotion.getDocNum());
        accountTradeRecord.setDocType(Constant.doc_type_promotion);
        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.setCashMoney(docPromotion.getCollectionCashAmount());
        accountTradeRecord.setCardMoney(docPromotion.getCollectionRechargeAmount());
        return accountTradeRecord;
    }

    public String getDocNum(DocPromotionRequest docPromotionRequest,String StoreNUm) {
        //查询数据库门店编码最新的一个
        String ymdDate = DateUtils.YMDFormat(new Date());
        Example example = new Example(DocPromotion.class);
        Example.Criteria criteria = example.createCriteria();
        //按门店编码降序排列
        example.setOrderByClause("doc_num desc");
        //通过时间模糊查询
        criteria.andLike("docNum", "%" +ymdDate + "%");
        criteria.andEqualTo("storeId", docPromotionRequest.getStoreId());
        List<DocPromotion> lists = dao.selectByExample(example);
        String docNum;
        String num;
        int mm = 0;
        if (lists != null && lists.size() > 0) {
            DocPromotion promotion = lists.get(0);
            int a=StoreNUm.length();
            mm = Integer.parseInt(promotion.getDocNum().substring(8+a)) + 1;
            if (mm < 10) {
                num = "00" + mm;
            } else if (mm < 100) {
                num = "0" + mm;
            } else {
                num = String.valueOf(mm);
            }
            docNum = StoreNUm + ymdDate + num;
        } else {
            num = "001";
            docNum = StoreNUm + ymdDate + num;
        }
        return docNum;
    }

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

        BigDecimal  gdp=cashRechargeAchiSum.divide((docPromotion.getCollectionCashAmount().add(docPromotion.getCollectionRechargeAmount())),10,BigDecimal.ROUND_HALF_UP);
        BigDecimal  in=new BigDecimal("1");



        BigDecimal count  = BigDecimalUtils.bigDecimal(docPromotion.getCount().toString());
        //提成标准是按比例提成 计算现付业绩提成
        if (null != payLists && payLists.size() > 0) {

            //现付销售提成标准  >0 <=1比率   >1固定金额
            BigDecimal commRatio = docPromotion.getSalesCommission();
            //业绩为现付支付金额
            docPromotion.setAchievementAmount(docPromotion.getCollectionCashAmount().multiply(in.subtract(gdp)));
            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                docPromotion.setCommissionAmount(BigDecimalUtils.multiply(commRatio, docPromotion.getCollectionCashAmount().multiply(in.subtract(gdp))));
            } else {
                //提成 * （现付金额/成交金额）* 套数
                docPromotion.setCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(commRatio, BigDecimalUtils.div(docPromotion.getCollectionCashAmount().multiply(in.subtract(gdp)), docPromotion.getAmount())), count));
            }
        }
        if (null != rechargeAccountRequestList && rechargeAccountRequestList.size() > 0) {
            //卡付销售提成标准  >0 <=1比率   >1固定金额
            BigDecimal commRatio = docPromotion.getCardSalesCommission();
            //卡付业绩为卡付金额
            docPromotion.setCardAchievementAmount(docPromotion.getCollectionRechargeAmount().multiply(in.subtract(gdp)));
            if (BigDecimalUtils.compareTo(commRatio, BigDecimalUtils.bigDecimal("1")) != 1) {
                docPromotion.setCardCommissionAmount(BigDecimalUtils.multiply(commRatio, docPromotion.getCardAchievementAmount()));
            } else {
                //提成 * （现付金额/成交金额）* 套数
                docPromotion.setCardCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.multiply(commRatio, BigDecimalUtils.div(docPromotion.getCollectionRechargeAmount().multiply(in.subtract(gdp)), docPromotion.getAmount())), count));
            }
        }

        return docPromotion;
    }


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

        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0){
                docPromotion.setSaleOneStaffId(staffRequest.getId());
                docPromotion.setSaleOneStaffName(staffRequest.getStaffName());
                docPromotion.setSaleOneIdentity(staffRequest.getIdentityCard());
                docPromotion.setSaleOneRatio(staffRequest.getRatio());
                docPromotion.setSaleOneNumber(staffRequest.getBrandNumber());
            }else if (i == 1){
                docPromotion.setSaleTwoStaffId(staffRequest.getId());
                docPromotion.setSaleTwoStaffName(staffRequest.getStaffName());
                docPromotion.setSaleTwoIdentity(staffRequest.getIdentityCard());
                docPromotion.setSaleTwoRatio(staffRequest.getRatio());
                docPromotion.setSaleTwoNumber(staffRequest.getBrandNumber());
            }else if (i == 2){
                docPromotion.setSaleThreeStaffId(staffRequest.getId());
                docPromotion.setSaleThreeStaffName(staffRequest.getStaffName());
                docPromotion.setSaleThreeIdentity(staffRequest.getIdentityCard());
                docPromotion.setSaleThreeRatio(staffRequest.getRatio());
                docPromotion.setSaleThreeNumber(staffRequest.getBrandNumber());
            }else if(i==3){
                docPromotion.setSaleFourStaffId(staffRequest.getId());
                docPromotion.setSaleFourStaffName(staffRequest.getStaffName());
                docPromotion.setSaleFourIdentity(staffRequest.getIdentityCard());
                docPromotion.setSaleFourRatio(staffRequest.getRatio());
                docPromotion.setSaleFourNumber(staffRequest.getBrandNumber());

            }
        }
    }

    /*
     * 业务员列表设置返回值
     * */
    public List<AchiCommEntity> getAchiCommList(DocPromotion courseList){

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


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

    public String getKey(String phone) {
        String key = "";
        if (StringUtils.isNotBlank(phone)) {
            key = Constant.staffKey + phone;
        }
        return key;
    }


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

    /*
     * 充值卡付列表设置返回值
     * */
    public List<RechargeAccountResponse> setRechargeAccountList(DocPromotion docPromotion){
        List<RechargeAccountResponse> list = new ArrayList<>();
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setDocType(Constant.doc_type_promotion);
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume);
        accountTradeRecordRequest.setDocId(docPromotion.getId());
        accountTradeRecordRequest.setInputDate(docPromotion.getDocDate());
        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.setSpendMoney(accountTradeRecord.getAccountSpendMoney());
            list.add(rechargeAccountResponse);
        }
        return list;
    }
}
