package com.ssm.manage.service.impl;

import cn.hutool.core.date.DateTime;
import com.github.pagehelper.PageInfo;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.extendEntity.StoreDaily;
import com.ssm.manage.mapper.RechargeListMapper;
import com.ssm.manage.response.*;
import com.ssm.manage.service.SsmDebtService;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmRechargeDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.query.*;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

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

@Service
@Slf4j
public class SsmRechargeServiceImpl extends BaseServiceImpl<RechargeList> implements SsmRechargeService {
    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    SsmCollectionTypeService ssmCollectionTypeService;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmPromotionProjectService ssmPromotionProjectService;

    @Autowired
    private SsmDocPromotionProjectService ssmDocPromotionProjectService;

    @Autowired
    SsmBaseStaffService ssmBaseStaffService;

    @Autowired
    private SsmMemberService ssmMemberService;
    @Autowired
    private SsmRefundRecordService ssmRefundRecordService;
    @Autowired
    private SsmTransactionRecordService ssmTransactionRecordService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    /*@Autowired
    private SsmRechargeAccountGiveService ssmRechargeAccountGiveService;*/

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmMemberCsService ssmMemberCsService;


    @Autowired
    private SsmRechargeDao dao;

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

    private static String staffKey = "staffKey";


    @Override
    public PageInfo<RechargeListResponse> selectPage(RechargeListRequest rechargeListRequest) throws ParseException, SmsException {
        Date date = DateUtils.YMParse(rechargeListRequest.getSelectDate());
        rechargeListRequest.setRechargeDate(date);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())),date) < 0){
            throw new SmsException(ResponseCode.NO_DATA);
        }
        PageInfo<RechargeList> pageInfo = dao.selectPage(rechargeListRequest);
        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo.getList()) {
            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList,rechargeListResponse);
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(rechargeList.getId()));
            List<PayList> list = ssmPayService.select(payList);
            rechargeListResponse.setPayLists(list);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            rechargeListResponse.setEntities(entities);
            listResponses.add(rechargeListResponse);
        }
        for (RechargeListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderType(1);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        PageInfo<RechargeListResponse> p =  new PageInfo<>(listResponses);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<RechargeListResponse> tstPage(RechargeListRequest rechargeListRequest) throws ParseException, SmsException {
        return null;
    }


    @Override
    public PageInfo<RechargeListResponse> selectPageNew(RechargeListRequest rechargeListRequest) throws ParseException, SmsException {
        Date date = DateUtils.YMParse(rechargeListRequest.getSelectDate());
        rechargeListRequest.setRechargeDate(date);
        List<Long> lists = new ArrayList<>();
        if(rechargeListRequest.getSelectType()==0){
            lists=rechargeListRequest.getStoreList();
        }else{
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
            if(null == baseStore1.getParentId()&&(rechargeListRequest.getStoreList().size()<0||rechargeListRequest.getStoreList()==null)){
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(rechargeListRequest.getStoreId());
                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());
                lists=collect;
            }else{
                lists.add(rechargeListRequest.getStoreId());
            }
        }
        rechargeListRequest.setStoreList(lists);
        PageInfo<RechargeList> pageInfo = dao.selectPageNew(rechargeListRequest);
        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo.getList()) {
            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList,rechargeListResponse);
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(rechargeList.getRechargeNum()));
            List<PayList> list = ssmPayService.select(payList);
            rechargeListResponse.setPayLists(list);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            rechargeListResponse.setEntities(entities);
            BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(rechargeList.getInputId());
            if(baseStaff!=null){
                rechargeListResponse.setInputNum(baseStaff.getStaffNum());
            }
            listResponses.add(rechargeListResponse);
        }
        for (RechargeListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderType(1);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        PageInfo<RechargeListResponse> p =  new PageInfo<>(listResponses);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<RechargeListResponse> pageDetail(RechargeListRequest rechargeListRequest) throws ParseException, SmsException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(rechargeListRequest.getSelectDate());
        rechargeListRequest.setRechargeDate(parse);
        PageInfo<RechargeList> pageInfo = dao.selectPage(rechargeListRequest);
        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo.getList()) {
            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList,rechargeListResponse);
//            //隐藏手机号码
//            String memberPhone = CommonUtils.mobileHide(rechargeList.getMobilePhone());
//            rechargeListResponse.setMobilePhone(memberPhone);
            PayList payList = new PayList();
            payList.setDocId(rechargeList.getRechargeNum());
            List<PayList> list = ssmPayService.select(payList);
            rechargeListResponse.setPayLists(list);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            rechargeListResponse.setEntities(entities);
            listResponses.add(rechargeListResponse);
        }
        for (RechargeListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
//            PayList payList = new PayList();
//            payList.setDocId(listRespons.getRechargeNum());
//            listRespons.setPayLists(ssmPayService.select(payList));
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderType(1);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        PageInfo<RechargeListResponse> p =  new PageInfo<>(listResponses);
        p.setTotal(pageInfo.getTotal());
        return p;
    }

    @Override
    public PageInfo<RechargeList> page(RechargeListRequest rechargeListRequest) throws SmsException, ParseException {
        Date date = DateUtils.YMParse(DateUtils.YMFormat(rechargeListRequest.getRechargeDate()));
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.YMFormat(baseStore.getFunderDate())),date) < 0){
            throw new SmsException(ResponseCode.NO_DATA);
        }
        PageInfo<RechargeList> pageInfo = dao.selectPage(rechargeListRequest);
        return pageInfo;
    }

    public List<AchiCommEntity> getAchiCommList(RechargeList rechargeList){
        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");
        if (null != rechargeList.getSaleOneStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));

            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberOne());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleOneIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleOneRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleOneRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleOneRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(),rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleOneRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleOneRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != rechargeList.getSaleTwoStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberTwo());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleTwoIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleTwoRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleTwoRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleTwoRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleTwoRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleTwoRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != rechargeList.getSaleThreeStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberThree());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleThreeIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleThreeRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        //四
        if (null != rechargeList.getSaleFourStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberFour());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleFourIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleFourRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleFourRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleFourRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }

        //五
        if (null != rechargeList.getSaleFiveStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberFive());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleFiveStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleFiveStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleFiveIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleFiveRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleFiveRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleFiveRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }

        //六
        if (null != rechargeList.getSaleSixStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberSix());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleSixStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleSixStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleSixIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleSixRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleSixRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleSixRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }

        //七
        if (null != rechargeList.getSaleSevenStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberSeven());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleSevenStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleSevenStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleSevenIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleSevenRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleSevenRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleSevenRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }

        //8
        if (null != rechargeList.getSaleEightStaffId() && rechargeList.getSaleEightStaffId()!=0){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getCollectionCashAmount());
            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getRechargeNum());
            achiCommEntity.setDocType(Constant.doc_type_recharge);
            achiCommEntity.setDocDate(rechargeList.getRechargeDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());

            achiCommEntity.setBrandNumber(rechargeList.getBrandNumberEight());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleEightStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleEightStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleEightIdentityCard());
            achiCommEntity.setSaleRatio(rechargeList.getSaleEightRatio());
            achiCommEntity.setSaleAchievementAmount(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleEightRatio(),hundredBD)));
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),BigDecimalUtils.div(rechargeList.getSaleEightRatio(),hundredBD)));

            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(achiCommEntity.getSaleAchievementAmount(), rechargeList.getTypeRatio()));
            }else {
                achiCommEntity.setSaleCommissionAmount(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()),
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }

        return entities;
    }

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

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addRecharge(RechargeListRequest rechargeListRequest) throws SmsException {
        int i = 0;
        RechargeAccount rechargeAccount1 = new RechargeAccount();
        rechargeAccount1.setMemberId(rechargeListRequest.getMemberId());
        rechargeAccount1.setStoreId(rechargeListRequest.getStoreId());
        List<RechargeAccount> select = ssmRechargeAccountService.select(rechargeAccount1);
        for (RechargeAccount rechargeAccount : select) {
            if(rechargeAccount.getRechargeTypeId()==rechargeListRequest.getRechargeTypeId()
                    || rechargeAccount.getRechargeTypeId().equals(rechargeListRequest.getRechargeTypeId())){
                if(rechargeAccount.getCardRestMoney().compareTo(rechargeAccount.getCardConsumeMoney())!=0){
                    throw new SmsException(ResponseCode.MSG,"会员在该门店存在其他充值卡欠款，请先进行还款");
                }
            }
        }
        //如果返回欠款不等于空那么就是欠款，那么就添加多一条记录，充值欠款
            if(rechargeListRequest.getDebtMoney()!=null){

            }
        RechargeList rechargeList = new RechargeList();
        BeanUtils.copyProperties(rechargeListRequest,rechargeList);
        //账户数据插入
        //查询充值卡类型
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeList.getRechargeTypeId());
        rechargeList.setDonateType(rechargeType.getDonateType());
        StoreParament storeParament = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.rec_debt);
        if (rechargeType == null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"充值类别");
        }else {
            //不允许欠款 查看欠款参数是否有值
            if ("0".equals(storeParament.getParamentValue())){
                if ( rechargeList.getIsDebt() == 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "充值");
                }
            }
        }
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(rechargeList.getStoreId());
        BaseStores baseStores1 = ssmBaseStoreService.pagesorganizations(storeRequest).stream().filter(baseStores -> null == baseStores.getParentId()).findAny().orElse(null);
        StoreParament storeParas = StoreParaUtils.getStorePara(baseStores1.getId(), Constant.maximumAmount);
        if(!"0".equals(storeParas.getParamentValue().trim())){
            if(BigDecimalUtils.compareTo(BigDecimalUtils.add(rechargeList.getCollectionAmount(), rechargeList.getDebtMoney()), BigDecimal.valueOf(Double.valueOf(storeParas.getParamentValue()))) == 1){
                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION, "实际充值金额超出充值控制上限,");
            }
        }
        //充值单数据插入
        Long rechargeId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        rechargeList.setId(rechargeId);
        //生成单据号

        rechargeList.setRechargeDate(new Date());
        //不走补单 正常开单 补单时间默认为开单时间
        if (1 == rechargeList.getIsAddition()) {
            rechargeList.setRechargeDate(rechargeList.getAdditionDate());
        }
        String storeNum=ssmBaseStoreService.selectByPrimaryKey(rechargeList.getStoreId()).getStoreNum();
        String rechargeNum = this.getDocNum(rechargeList,storeNum);
        rechargeList.setRechargeNum(rechargeNum);
        rechargeList.setIsCancel(0);
        //查询门店参数
        //充值有欠款可消费比率参数
        StoreParament para = new StoreParament();
        if ("1".equals(storeParament.getParamentValue())) {
            para = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.rec_debt_usable);
        }
        //查询是否有充值账户
        RechargeAccount rechargeAccount = new RechargeAccount();
        rechargeAccount.setRechargeTypeId(rechargeType.getId());
       // rechargeAccount.setStoreId(rechargeList.getStoreId());
        rechargeAccount.setMemberId(rechargeList.getMemberId());
//        RechargeAccount beforeAccount = ssmRechargeAccountService.selectOne(rechargeAccount);
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
        StoreRequest stores = new StoreRequest();
        stores.setId(rechargeList.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(stores);
        List<Long> storeIds = new ArrayList<>();
        Long storeID=null;
        for (BaseStores pagesorganization : pagesorganizations) {
            storeIds.add(pagesorganization.getId());
            if(null == pagesorganization.getParentId()){
                storeID=pagesorganization.getId();
            }
        }
        criteria.andEqualTo("rechargeTypeId",rechargeType.getId());
        criteria.andIn("storeId",storeIds);
        criteria.andEqualTo("memberId",rechargeList.getMemberId());
        //criteria.andEqualTo("state", 1);
        List<RechargeAccount> list = ssmRechargeAccountService.selectByExample(example);
        RechargeAccount beforeAccount = null;
        if (list.size() > 0) {
            beforeAccount = list.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();
            BeanUtils.copyProperties(rechargeList, account);
            account.setId(rechargeAccountId);
            rechargeList.setRechargeAccountId(rechargeAccountId);
            //对充值账户进行赋值
            account = ssmRechargeAccountService.setRechargeAccount(rechargeType, rechargeList, account, para);
            account.setCardNum(0);
            account.setFirstCharge(0L);
            //account.setCardRechargeMoney(rechargeType.getFirstAmount());
            ssmRechargeAccountService.addRechargeAccount(account);
            BeanUtils.copyProperties(account,rechargeAccount);
        }else {//存在账户 添加账户金额
            //判断充前金额是否和当前账户相等
            if (BigDecimalUtils.compareTo(rechargeList.getBeforeMoney(),beforeAccount.getCardRestMoney()) != 0){
                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION,"充值账户充前金额和当前账户剩余金额不相等");
            }
            //剩余金额与可消费金额不等
//            if(BigDecimalUtils.compareTo(beforeAccount.getCardRestMoney(),beforeAccount.getCardConsumeMoney()) != 0){
//                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION,"充值账户存在欠款");
//            }
            rechargeList.setRechargeAccountId(beforeAccount.getId());
            beforeAccount.setRechargeNum(rechargeNum);
            beforeAccount.setCardNum(1);
            ssmRechargeAccountService.addMoney(beforeAccount,rechargeList,rechargeType,para);
            BeanUtils.copyProperties(beforeAccount,rechargeAccount);
        }



        //员工业绩提成
        List<StaffRequest> staffLists = rechargeListRequest.getStaffLists();
        BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
            throw new SmsException(ResponseCode.MSG,"业务业绩占比和不等于100");
        }
        this.setStaffValue(staffLists,rechargeList);
        //欠款 添加欠款记录
        if (1 == rechargeList.getIsDebt()){
            DebtListRequest debtListRequest = new DebtListRequest();
            BeanUtils.copyProperties(rechargeList,debtListRequest);
            debtListRequest.setTradeId(rechargeList.getRechargeTypeId());
            debtListRequest.setTradeName(rechargeList.getRechargeTypeName());
            debtListRequest.setTradeMoney(rechargeList.getRechargeAmount());
            debtListRequest.setDocId(rechargeId);
            debtListRequest.setDocNum(rechargeNum);
            debtListRequest.setDocType(Constant.doc_type_recharge);
            debtListRequest.setAccountId(rechargeAccount.getId());
            debtListRequest.setStaffLists(staffLists);
            debtListRequest.setState(0);
            debtListRequest.setDocDate(rechargeList.getRechargeDate());
            debtListRequest.setRepayConsumeMoney(BigDecimalUtils.bigDecimal(para.getParamentValue()).divide(BigDecimalUtils.bigDecimal("100")));
            int i1 = ssmDebtService.addDebt(debtListRequest);
        }

        //设置录单人信息
        if (redisClient.hasKey(getStaffKey(rechargeListRequest.getStaffPhone()))){
            StaffResponse staffResponse = redisClient.get(getStaffKey(rechargeListRequest.getStaffPhone()));
            rechargeList.setInputId(staffResponse.getId());
            rechargeList.setInputBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(rechargeListRequest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            rechargeList.setInputId(staffResponse.getId());
            rechargeList.setInputBy(staffResponse.getStaffName());
        }
        try {
            rechargeList.setLiftType(0);
            rechargeList.setRechargeTypeNum(rechargeListRequest.getRechargeTypeNum());
            //查询门店充值的当前欠款可用比例
            List<StoreParament> storeParaments=ssmStoreParaService.list(rechargeList.getStoreId());
            for(StoreParament storeParament1:storeParaments){
                if(storeParament1.getParamentName().equals("recDebtUsable"))
                    rechargeList.setStoreRecDebtUsable(storeParament1.getParamentValue());  ;
            }
            i = dao.addRecharge(rechargeList);
            //高管业绩
            if(null != rechargeListRequest.getSalesmens()){
                List<Salesman> salesmens = rechargeListRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100))!=0 && reduce5.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"高管业绩占比和不等于100");
                }
                if(null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100))!=0 && reduce6.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"管理员业绩占比和不等于100");
                }
                for (Salesman salesmen : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
                    salesmen.setStaffId(salesmen.getId());
                    salesmen.setId(salesmen.getId()+i1);
                    salesmen.setOrderId(String.valueOf(rechargeList.getId()));
                    salesmen.setOrderNum(rechargeNum);
                    salesmen.setOrderType(1);
                    salesmen.setOrderDate(rechargeList.getRechargeDate());
                    salesmen.setState(0);
                    salesmen.setOperatorBy(rechargeList.getInputBy());
                    salesmen.setMoney(rechargeListRequest.getCollectionCashAmount());
                    salesmen.setProjectId(rechargeListRequest.getRechargeTypeId());
                    salesmen.setIsAddition(rechargeList.getIsAddition());
                }
                ssmSalesmanService.addBatch(salesmens);
            }
            RechargeType rechargeType1 = new RechargeType();
            rechargeType1.setId(rechargeList.getRechargeTypeId());
            RechargeType rechargeType2 = ssmRechargeTypeSevice.selectOne(rechargeType1);
            if(rechargeType2.getType()!=1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                refundRecord.setRechargeId(rechargeList.getId());
                refundRecord.setMemberId(rechargeList.getMemberId());
                refundRecord.setMemberName(rechargeList.getMemberName());
                refundRecord.setRechargeTypeId(rechargeList.getRechargeTypeId());
                refundRecord.setRechargeTypeName(rechargeList.getRechargeTypeName());
                refundRecord.setRechargeDate(rechargeList.getRechargeDate());
                refundRecord.setRechargeAmount(rechargeList.getRechargeAmount());
                refundRecord.setCollectionAmount(rechargeList.getCollectionAmount());
                refundRecord.setRefundDebtMoney(BigDecimal.valueOf(0));
                if(rechargeType.getDonateType()==0){
                    refundRecord.setRechargeGiftAmount(rechargeType2.getGiftMoney());
                }else{
                    BigDecimal divide = rechargeType.getGiftMoney().divide(BigDecimal.valueOf(100));
                    refundRecord.setRechargeGiftAmount(divide.multiply(rechargeList.getCollectionAmount()));
                }

                if(rechargeList.getIsDebt()==1){
                    refundRecord.setIsReceived(0);
                }else{
                    refundRecord.setIsReceived(1);
                }

                refundRecord.setAmountRefunded(BigDecimal.valueOf(0));
                refundRecord.setAmountGiftRefunded(BigDecimal.valueOf(0));
                refundRecord.setIsDeduct(0);
                int save = ssmRefundRecordService.save(refundRecord);
            }
        } catch (Exception e) {
            log.error("SsmRechargeServiceImpl.addRecharge:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.FAILED);
        }
        //如果使用积分支付将门店会员积分进行扣减
        if (0 != rechargeList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(rechargeList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() - rechargeList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }
        //支付方式插入
        List<PayList> payLists = rechargeListRequest.getPayLists();
        if (null != payLists && payLists.size() > 0) {
            for (PayList payList : payLists) {
                payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                payList.setDocId(String.valueOf(rechargeNum));
                payList.setType(Constant.doc_type_recharge);
                payList.setStoreId(rechargeListRequest.getStoreId());
                payList.setPayDate(rechargeList.getRechargeDate());
                payList.setIsCancel(0);
            }
            ssmPayService.addPayList(payLists);
        }

        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(rechargeList,rechargeAccount);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        //将充值单据信息添加到评价表
        MemberCsRequest memberCsRequest = new MemberCsRequest();
        BeanUtils.copyProperties(rechargeList, memberCsRequest);
        memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberCsRequest.setDocId(rechargeId);
        memberCsRequest.setDocNum(rechargeNum);
        memberCsRequest.setDocType(Constant.doc_type_recharge);
        memberCsRequest.setDocDate(rechargeList.getRechargeDate());
        memberCsRequest.setTradeId(rechargeList.getRechargeTypeId());
        memberCsRequest.setTradeName(rechargeList.getRechargeTypeName());
        memberCsRequest.setTradeMoney(rechargeList.getRechargeAmount());
        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;
    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addRecharges(RechargeListRequest rechargeListRequest) throws SmsException {
        int i = 0;
        RechargeList rechargeList = new RechargeList();
        BeanUtils.copyProperties(rechargeListRequest,rechargeList);
        //        //将对应平台会员数据添加到门店会员里(门店会员不存在)
//        StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(rechargeList.getMemberId());
//        if (null == storeMember){
//            MemberList member = ssmMemberService.selectByPrimaryKey(rechargeList.getMemberId());
//            MemberRequest memberRequest = new MemberRequest();
//            BeanUtils.copyProperties(memberRequest,member);
//            try {
//                ssmStoreMemberService.addStoreMember(memberRequest);
//            }catch (Exception e){
//                log.error("SsmRechargeServiceImpl.addRecharge:",e);
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
//            }
//        }

        //账户数据插入
        //查询充值卡类型
        RechargeList rechargeLists = new RechargeList();
        rechargeLists.setRechargeTypeId(rechargeListRequest.getRawCardId());
        rechargeListRequest.setRechargeTypeId(rechargeListRequest.getRawCardId());
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeLists.getRechargeTypeId());
        rechargeList.setRechargeTypeId(rechargeType.getId());
        rechargeList.setDonateType(rechargeType.getDonateType());
        RechargeType rechargeTypes = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());

        rechargeType.setFirstAmount(rechargeTypes.getFirstAmount());
        rechargeType.setRechargeMoney(rechargeTypes.getRechargeMoney());

        StoreParament storeParament = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.rec_debt);
        if (rechargeType == null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"充值类别");
        }else {
            //不允许欠款 查看欠款参数是否有值
            if ("0".equals(storeParament.getParamentValue())){
                if ( rechargeList.getIsDebt() == 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "充值");
                }
            }else {
//                //折扣卡 允许超额充值  赠送卡不允许超额支付 实际充值金额+欠款与标准金额保持一致
//                if (rechargeType.getType() == 0) {//赠送卡
//                    if (BigDecimalUtils.compareTo(BigDecimalUtils.add(rechargeList.getCollectionAmount(), rechargeList.getDebtMoney()), rechargeList.getRechargeAmount()) != 0) {
//                        throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION, "实际充值金额与标准金额不相等");
//                    }
//                }
            }
        }


        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(rechargeList.getStoreId());
        BaseStores baseStores1 = ssmBaseStoreService.pagesorganizations(storeRequest).stream().filter(baseStores -> null == baseStores.getParentId()).findAny().orElse(null);
        StoreParament storeParas = StoreParaUtils.getStorePara(baseStores1.getId(), Constant.maximumAmount);
        if(!"0".equals(storeParas.getParamentValue().trim())){
            if(BigDecimalUtils.compareTo(BigDecimalUtils.add(rechargeList.getCollectionAmount(), rechargeList.getDebtMoney()), BigDecimal.valueOf(Double.valueOf(storeParas.getParamentValue()))) == 1){
                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION, "实际充值金额超出充值控制上限,");
            }
        }

        //充值单数据插入
        Long rechargeId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        rechargeList.setId(rechargeId);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        //生成单据号
        if (1 == rechargeList.getIsAddition()) {
            rechargeList.setRechargeDate(rechargeList.getAdditionDate());
        }else {
            rechargeList.setRechargeDate(new Date());
            rechargeList.setAdditionDate(new Date());

        }
        String rechargeNum = this.getDocNum(rechargeList,baseStore.getStoreNum());
        rechargeList.setRechargeNum(rechargeNum);
        //不走补单 正常开单 补单时间默认为开单时间
        rechargeList.setIsCancel(0);

        //查询门店参数
        //充值有欠款可消费比率参数
        StoreParament para = new StoreParament();
        if ("1".equals(storeParament.getParamentValue())) {
            para = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.rec_debt_usable);
        }
        //查询是否有充值账户
        RechargeAccount rechargeAccount = new RechargeAccount();
        rechargeAccount.setRechargeTypeId(rechargeTypes.getId());
        rechargeAccount.setStoreId(rechargeList.getStoreId());
        rechargeAccount.setMemberId(rechargeList.getMemberId());
//        RechargeAccount beforeAccount = ssmRechargeAccountService.selectOne(rechargeAccount);
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("rechargeTypeId",rechargeType.getId());
        //criteria.andEqualTo("storeId",rechargeList.getStoreId());
        criteria.andEqualTo("memberId",rechargeList.getMemberId());
        criteria.andEqualTo("state", 1);
        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.allow_valid);
       /* if ("1".equals(parament.getParamentValue())) {
            criteria.andGreaterThan("endTime", new Date());
        }*/
        List<RechargeAccount> list = ssmRechargeAccountService.selectByExample(example);
        RechargeAccount beforeAccount = null;
        if (list.size() > 0) {
            if("1".equals(parament.getParamentValue())&&list.get(0).getEndTime()!=null){
                if(list.get(0).getEndTime().before(new DateTime(new Date()))){
                    beforeAccount = list.get(0);
                }
            }else{
                beforeAccount = list.get(0);
            }
        }

        //清除升级前账户金额
        RechargeAccount rechargeAccounts = new RechargeAccount();
        if(rechargeListRequest.getIds()==null){
            throw new SmsException(ResponseCode.MSG,"请选择升级转出的账号");
        }
        rechargeAccounts.setId(rechargeListRequest.getIds());
        RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectOne(rechargeAccounts);
        DebtListRequest debtListRequests = new DebtListRequest();
        debtListRequests.setMemberId(rechargeListRequest.getMemberId());
        debtListRequests.setTradeId(rechargeAccount1.getRechargeTypeId());
        List<DebtList> debtLists = ssmDebtService.selectList(debtListRequests);
        if(debtLists.size()>0) {
            throw new SmsException(ResponseCode.NOT_LIFT);
        }
        rechargeList.setLiftMoney(rechargeAccount1.getCardRestMoney());
        rechargeList.setLiftGiftMoney(rechargeAccount1.getGiftConsumeMoney());
        rechargeList.setRawRechargeTypeName(rechargeAccount1.getRechargeTypeName());

        BigDecimal cardRestMoney = rechargeAccount1.getCardRestMoney();
        BigDecimal cardConsumeMoney = rechargeAccount1.getCardConsumeMoney();
        BigDecimal giftConsumeMoney = rechargeAccount1.getGiftConsumeMoney();
        BigDecimal cardGiftMoney = rechargeAccount1.getCardGiftMoney();
        if(cardRestMoney.compareTo(cardConsumeMoney)!=0){
            throw new SmsException(ResponseCode.MSG,"升级前账户存在欠款，请先取消欠款");
        }


        rechargeAccount1.setCardRestMoney(BigDecimal.valueOf(0.00));
        rechargeAccount1.setCardConsumeMoney(BigDecimal.valueOf(0.00));
        rechargeAccount1.setGiftConsumeMoney(BigDecimal.valueOf(0.00));
        rechargeAccount1.setCardGiftMoney(BigDecimal.valueOf(0.00));
        int i2 = ssmRechargeAccountService.updateNotNull(rechargeAccount1);
        //添加升级后账户金额
        if(i2==0){
            throw new SmsException(ResponseCode.ENCRYPT_ERROR,"修改充值前账户");
        }


        //第一次充值 无充值账户
        if (null == beforeAccount) {
            Long rechargeAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
            RechargeAccount account = new RechargeAccount();
            BeanUtils.copyProperties(rechargeList, account);



            account.setId(rechargeAccountId);
            rechargeList.setRechargeAccountId(rechargeAccountId);
            //对充值账户进行赋值
            account = ssmRechargeAccountService.setRechargeAccount(rechargeType, rechargeList, account, para);
            account.setCardRestMoney(BigDecimalUtils.add(cardRestMoney,account.getCardRestMoney()));
            account.setCardConsumeMoney(BigDecimalUtils.add(cardConsumeMoney,account.getCardConsumeMoney()));
            account.setGiftConsumeMoney(BigDecimalUtils.add(giftConsumeMoney,account.getGiftConsumeMoney()));
            account.setCardGiftMoney(BigDecimalUtils.add(cardGiftMoney,account.getCardGiftMoney()));
            //account.setCardRechargeMoney(rechargeType.getFirstAmount());
            account.setCardNum(0);
            ssmRechargeAccountService.addRechargeAccount(account);
            BeanUtils.copyProperties(account,rechargeAccount);
        }else {//存在账户 添加账户金额
            //判断充前金额是否和当前账户相等
            Example examples = new Example(RechargeAccount.class);
            Example.Criteria criterias = example.createCriteria();
            criterias.andEqualTo("rechargeTypeId",rechargeListRequest.getRawRechargeTypeId());
            //criterias.andEqualTo("storeId",rechargeList.getStoreId());
            criterias.andEqualTo("memberId",rechargeList.getMemberId());
            criterias.andEqualTo("state", 1);

            /*if ("1".equals(parament.getParamentValue())) {
                criteria.andGreaterThan("endTime", new Date());
            }*/

            List<RechargeAccount> lists1 = ssmRechargeAccountService.selectByExample(example);
            List<RechargeAccount> lists=new ArrayList<>();
            if(lists1.size()>0){//筛选过期的账户
                for(RechargeAccount rechargeAccount2:lists1){
                    if("1".equals(parament.getParamentValue())&&rechargeAccount2.getEndTime()!=null){
                        if(rechargeAccount2.getEndTime().before(new DateTime(new Date()))){
                            lists.add(rechargeAccount2);
                        }
                    }else{
                        lists.add(rechargeAccount2);
                    }
                }
            }


            if (BigDecimalUtils.compareTo(rechargeList.getBeforeMoney(),cardRestMoney.add(lists.get(0).getCardRestMoney())) != 0){
                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION,"充值账户充前金额和当前账户剩余金额不相等");
            }
            //剩余金额与可消费金额不等
            if(BigDecimalUtils.compareTo(beforeAccount.getCardRestMoney(),beforeAccount.getCardConsumeMoney()) != 0){
                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION,"充值账户存在欠款");
            }
            rechargeList.setRechargeAccountId(beforeAccount.getId());
            beforeAccount.setRechargeNum(rechargeNum);
            beforeAccount.setCardRestMoney(BigDecimalUtils.add(cardRestMoney,beforeAccount.getCardRestMoney()));
            beforeAccount.setCardConsumeMoney(BigDecimalUtils.add(cardConsumeMoney,beforeAccount.getCardConsumeMoney()));
            beforeAccount.setGiftConsumeMoney(BigDecimalUtils.add(giftConsumeMoney,beforeAccount.getGiftConsumeMoney()));
            beforeAccount.setCardGiftMoney(BigDecimalUtils.add(cardGiftMoney,beforeAccount.getCardGiftMoney()));
            beforeAccount.setCardNum(0);
            ssmRechargeAccountService.addMoney(beforeAccount,rechargeList,rechargeType,para);
            BeanUtils.copyProperties(beforeAccount,rechargeAccount);
        }



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




        //欠款 添加欠款记录
        if (1 == rechargeList.getIsDebt()){
            DebtListRequest debtListRequest = new DebtListRequest();
            BeanUtils.copyProperties(rechargeList,debtListRequest);
            debtListRequest.setTradeId(rechargeList.getRechargeTypeId());
            debtListRequest.setTradeName(rechargeList.getRechargeTypeName());
            debtListRequest.setTradeMoney(rechargeList.getRechargeAmount());
            debtListRequest.setDocId(rechargeId);
            debtListRequest.setDocNum(rechargeNum);
            debtListRequest.setDocType(Constant.doc_type_recharge);
            debtListRequest.setAccountId(rechargeAccount.getId());
            debtListRequest.setStaffLists(staffLists);
            debtListRequest.setState(0);
            debtListRequest.setDocDate(rechargeList.getRechargeDate());
            debtListRequest.setRepayConsumeMoney(BigDecimalUtils.bigDecimal(para.getParamentValue()).divide(BigDecimalUtils.bigDecimal("100")));
            int i1 = ssmDebtService.addDebt(debtListRequest);
        }

        //设置录单人信息
        if (redisClient.hasKey(getStaffKey(rechargeListRequest.getStaffPhone()))){
            StaffResponse staffResponse = redisClient.get(getStaffKey(rechargeListRequest.getStaffPhone()));
            rechargeList.setInputId(staffResponse.getId());
            rechargeList.setInputBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(rechargeListRequest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            rechargeList.setInputId(staffResponse.getId());
            rechargeList.setInputBy(staffResponse.getStaffName());
        }
        try {
            rechargeList.setLiftType(rechargeListRequest.getLiftType());
            rechargeList.setRawRechargeTypeId(rechargeListRequest.getRawRechargeTypeId());
            i = dao.addRecharge(rechargeList);

            //高管业绩
            if(null != rechargeListRequest.getSalesmens()){
                List<Salesman> salesmens = rechargeListRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100))!=0 && reduce5.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"高管业绩占比和不等于100");
                }
                if(null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100))!=0 && reduce6.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"管理员业绩占比和不等于100");
                }
                for (Salesman salesmen : salesmens) {
                    salesmen.setStaffId(salesmen.getId());
                    salesmen.setOrderId(String.valueOf(rechargeList.getId()));
                    salesmen.setOrderNum(rechargeNum);
                    salesmen.setOrderType(1);
                    salesmen.setOrderDate(new Date());
                    salesmen.setMoney(rechargeListRequest.getCollectionCashAmount());
                    salesmen.setProjectId(rechargeListRequest.getRechargeTypeId());
                    salesmen.setState(rechargeList.getIsCancel());
                    salesmen.setStoreNum(baseStore.getStoreNum());
                    salesmen.setStoreName(baseStore.getStoreName());
                    salesmen.setStoreIdOrder(baseStore.getId());
                    salesmen.setStoreId(baseStore.getId());
                    salesmen.setOperatorBy(rechargeList.getInputBy());
                    salesmen.setIsAddition(rechargeList.getIsAddition());
                }
                ssmSalesmanService.addBatch(salesmens);
            }
            RechargeType rechargeType1 = new RechargeType();
            rechargeType1.setId(rechargeList.getRechargeTypeId());
            RechargeType rechargeType2 = ssmRechargeTypeSevice.selectOne(rechargeType1);
            if(rechargeType2.getType()!=1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                refundRecord.setRechargeId(rechargeList.getId());
                refundRecord.setMemberId(rechargeList.getMemberId());
                refundRecord.setMemberName(rechargeList.getMemberName());
                refundRecord.setRechargeTypeId(rechargeList.getRechargeTypeId());
                refundRecord.setRechargeTypeName(rechargeList.getRechargeTypeName());
                refundRecord.setRechargeDate(rechargeList.getRechargeDate());
                refundRecord.setRechargeAmount(rechargeList.getRechargeAmount());
                refundRecord.setCollectionAmount(rechargeList.getCollectionAmount());
                refundRecord.setRefundDebtMoney(BigDecimal.valueOf(0));
                if(rechargeType.getDonateType()==0){
                    refundRecord.setRechargeGiftAmount(rechargeType2.getGiftMoney());
                }else{
                    BigDecimal divide = rechargeType.getGiftMoney().divide(BigDecimal.valueOf(100));
                    refundRecord.setRechargeGiftAmount(divide.multiply(rechargeList.getCollectionAmount()));
                }

                if(rechargeList.getIsDebt()==1){
                    refundRecord.setIsReceived(0);
                }else{
                    refundRecord.setIsReceived(1);
                }
                refundRecord.setAmountRefunded(BigDecimal.valueOf(0));
                refundRecord.setAmountGiftRefunded(BigDecimal.valueOf(0));
                refundRecord.setIsDeduct(0);
                int save = ssmRefundRecordService.save(refundRecord);
            }

        } catch (Exception e) {
            log.error("SsmRechargeServiceImpl.addRecharge:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.FAILED);
        }
        //如果使用积分支付将门店会员积分进行扣减
        if (0 != rechargeList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(rechargeList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() - rechargeList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }
        //支付方式插入
        List<PayList> payLists = rechargeListRequest.getPayLists();
        if (null != payLists && payLists.size() > 0) {
            for (PayList payList : payLists) {
                payList.setStoreId(rechargeListRequest.getStoreId());
                payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                payList.setIsCancel(0);
//                payList.setDocId(String.valueOf(rechargeId));
                payList.setDocId(rechargeNum);
                payList.setType(Constant.doc_type_recharge);
                payList.setPayDate(new Date());
            }
            ssmPayService.addPayList(payLists);
        }

        AccountTradeRecord accountTradeRecords = new AccountTradeRecord();
        //添加转出记录
        if(true){

            accountTradeRecords.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            accountTradeRecords.setStoreId(rechargeList.getStoreId());
            accountTradeRecords.setStoreName(rechargeList.getStoreName());
            accountTradeRecords.setMemberId(rechargeList.getMemberId());
            accountTradeRecords.setMemberName(rechargeList.getMemberName());
            accountTradeRecords.setMemberIdentity(rechargeList.getMemberIdentityCard());
            accountTradeRecords.setMemberPhone(rechargeList.getMobilePhone());
            accountTradeRecords.setAccountId(rechargeAccount1.getId());
            accountTradeRecords.setAccountName(rechargeAccount1.getRechargeTypeName());
            accountTradeRecords.setDocId(rechargeList.getId());
            accountTradeRecords.setDocNum(rechargeList.getRechargeNum());
            if(rechargeListRequest.getLiftType()==1){
                accountTradeRecords.setDocType(Constant.doc_type_recharge_upgrade_out);
            }else{
                accountTradeRecords.setDocType(Constant.doc_type_recharge_demotion_out);
            }


            accountTradeRecords.setAccountType(Constant.account_type_recharge);
            accountTradeRecords.setInputDate(rechargeList.getRechargeDate());
            accountTradeRecords.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecords.setDebtMoney(rechargeList.getDebtMoney());
            accountTradeRecords.setInputBy(rechargeList.getInputBy());
            accountTradeRecords.setPrice(rechargeList.getRechargeAmount());
            accountTradeRecords.setIsAddition(rechargeList.getIsAddition());
            accountTradeRecords.setTradeId(rechargeAccount1.getRechargeTypeId());
            accountTradeRecords.setTradeName(rechargeAccount1.getRechargeTypeName());
            accountTradeRecords.setTradeMoney(cardRestMoney);
            accountTradeRecords.setAccountRestMoney(BigDecimal.valueOf(0));
            accountTradeRecords.setAccountConsumeMoney(BigDecimal.valueOf(0));
            accountTradeRecords.setAccountGiftRestMoney(BigDecimal.valueOf(0));
            accountTradeRecords.setAccountGiftConsumeMoney(BigDecimal.valueOf(0));
            accountTradeRecords.setCardMoney(cardRestMoney);
            accountTradeRecords.setCashMoney(rechargeList.getCollectionCashAmount());
            ssmAccountTradeRecordService.addRecord(accountTradeRecords);
        }

        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecords(rechargeList,rechargeAccount,cardRestMoney);
        accountTradeRecord.setAccountRestMoney(accountTradeRecord.getAccountRestMoney().add(accountTradeRecords.getAccountRestMoney()));
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

        //将充值单据信息添加到评价表
        MemberCsRequest memberCsRequest = new MemberCsRequest();
        BeanUtils.copyProperties(rechargeList, memberCsRequest);
        memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberCsRequest.setDocId(rechargeId);
        memberCsRequest.setDocNum(rechargeNum);
        memberCsRequest.setDocType(Constant.doc_type_recharge);
        memberCsRequest.setDocDate(rechargeList.getRechargeDate());
        memberCsRequest.setTradeId(rechargeList.getRechargeTypeId());
        memberCsRequest.setTradeName(rechargeList.getRechargeTypeName());
        memberCsRequest.setTradeMoney(rechargeList.getRechargeAmount());
        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;
    }

    /*
    * 业务员赋值
    * */
    public void setStaffValue(List<StaffRequest> staffLists, RechargeList rechargeList){
        //查询会员是否有积分
        StoreParament parament = StoreParaUtils.getStorePara(rechargeList.getStoreId(),Constant.member_integral);
        //有积分
        if("1".equals(parament.getParamentValue())){
            //查询积分是否计入业绩提成门店参数
            StoreParament storeParament = StoreParaUtils.getStorePara(rechargeList.getStoreId(),Constant.integral);
            //积分付计入业绩和提成 计算总业绩提成
            if ("0".equals(storeParament.getParamentValue())) {
                rechargeList.setSaleAchievement(rechargeList.getCollectionAmount());
                //提成标准是按比例提成
                if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
                    rechargeList.setSaleCommission(BigDecimalUtils.multiply(rechargeList.getCollectionAmount(), rechargeList.getTypeRatio()));
                } else {
                    rechargeList.setSaleCommission(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(), rechargeList.getRechargeAmount()), rechargeList.getTypeRatio()));
                }
            }
        }
        //无积分 或者不计算业绩提成
        rechargeList.setSaleAchievement(rechargeList.getCollectionCashAmount());
        if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) != 1) {
            rechargeList.setSaleCommission(BigDecimalUtils.multiply(rechargeList.getCollectionCashAmount(), rechargeList.getTypeRatio()));
        } else {
            rechargeList.setSaleCommission(BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionCashAmount(), rechargeList.getRechargeAmount()), rechargeList.getTypeRatio()));
        }

        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0){
                rechargeList.setSaleOneStaffId(staffRequest.getId());
                rechargeList.setSaleOneStaffName(staffRequest.getStaffName());
                rechargeList.setSaleOneIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleOneRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberOne(staffRequest.getBrandNumber());
                //单个业务员业绩提成不在单个计算
//                if("0".equals(storeParament.getParamentValue())){
//                    rechargeList.setSaleOneAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(), rechargeList.getCollectionAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(),BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleOneCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionAmount(), rechargeList.getSaleOneRatio()));
//                    }else {
//                        rechargeList.setSaleOneCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }else {
//                    rechargeList.setSaleOneAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(),rechargeList.getCollectionCashAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(),BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleOneCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionCashAmount(), rechargeList.getSaleOneRatio()));
//                    }else {
//                        rechargeList.setSaleOneCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }


            }else if (i == 1){
                rechargeList.setSaleTwoStaffId(staffRequest.getId());
                rechargeList.setSaleTwoStaffName(staffRequest.getStaffName());
                rechargeList.setSaleTwoIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleTwoRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberTwo(staffRequest.getBrandNumber());
//                if ("0".equals(storeParament.getParamentValue())) {
//                    rechargeList.setSaleTwoAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(), rechargeList.getCollectionAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleTwoCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionAmount(), rechargeList.getSaleTwoRatio()));
//                    } else {
//                        rechargeList.setSaleTwoCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }else {
//                    rechargeList.setSaleTwoAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(), rechargeList.getCollectionCashAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleTwoCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionCashAmount(), rechargeList.getSaleTwoRatio()));
//                    } else {
//                        rechargeList.setSaleTwoCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }
            }else if (i == 2){
                rechargeList.setSaleThreeStaffId(staffRequest.getId());
                rechargeList.setSaleThreeStaffName(staffRequest.getStaffName());
                rechargeList.setSaleThreeIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleThreeRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberThree(staffRequest.getBrandNumber());
//                if ("0".equals(storeParament.getParamentValue())) {
//                    rechargeList.setSaleThreeAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(), rechargeList.getCollectionAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleThreeCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionAmount(), rechargeList.getSaleThreeRatio()));
//                    } else {
//                        rechargeList.setSaleThreeCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }else {
//                    rechargeList.setSaleThreeAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(), rechargeList.getCollectionCashAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleThreeCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionCashAmount(), rechargeList.getSaleThreeRatio()));
//                    } else {
//                        rechargeList.setSaleThreeCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }
            }else if (i == 3){
                rechargeList.setSaleFourStaffId(staffRequest.getId());
                rechargeList.setSaleFourStaffName(staffRequest.getStaffName());
                rechargeList.setSaleFourIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleFourRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberFour(staffRequest.getBrandNumber());
//                if ("0".equals(storeParament.getParamentValue())) {
//                    rechargeList.setSaleFourAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(), rechargeList.getCollectionAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleFourCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionAmount(), rechargeList.getSaleFourRatio()));
//                    } else {
//                        rechargeList.setSaleFourCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }else {
//                    rechargeList.setSaleFourAchievementAmount(Constant.getAchievementAmount(staffRequest.getRatio(), rechargeList.getCollectionCashAmount()));
//                    if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == -1) {
//                        rechargeList.setSaleFourCommissionAmount(Constant.getCommissionAmount(rechargeList.getTypeRatio(), rechargeList.getCollectionCashAmount(), rechargeList.getSaleFourRatio()));
//                    } else {
//                        rechargeList.setSaleFourCommissionAmount(rechargeList.getTypeRatio());
//                    }
//                }
            }


            else if (i == 4){
                rechargeList.setSaleFiveStaffId(staffRequest.getId());
                rechargeList.setSaleFiveStaffName(staffRequest.getStaffName());
                rechargeList.setSaleFiveIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleFiveRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberFive(staffRequest.getBrandNumber());
            }


            else if (i == 5){
                rechargeList.setSaleSixStaffId(staffRequest.getId());
                rechargeList.setSaleSixStaffName(staffRequest.getStaffName());
                rechargeList.setSaleFourIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleSixRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberSix(staffRequest.getBrandNumber());
            }


            else if (i == 6){
                rechargeList.setSaleSevenStaffId(staffRequest.getId());
                rechargeList.setSaleSevenStaffName(staffRequest.getStaffName());
                rechargeList.setSaleSevenIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleSevenRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberSeven(staffRequest.getBrandNumber());
            }


            else if (i == 7){
                rechargeList.setSaleEightStaffId(staffRequest.getId());
                rechargeList.setSaleEightStaffName(staffRequest.getStaffName());
                rechargeList.setSaleEightIdentityCard(staffRequest.getIdentityCard());
                rechargeList.setSaleEightRatio(staffRequest.getRatio());
                rechargeList.setBrandNumberEight(staffRequest.getBrandNumber());
            }
        }
    }

    /*
    * 生成充值单号 年月日+编码 20200823
    * */
    public String getDocNum(RechargeList rechargeList,String storeNum){
        //查询数据库充值单编码最新的一个
        String ymdDate = DateUtils.YMDFormat(rechargeList.getRechargeDate());
        RechargeListRequest rechargeListRequest = new RechargeListRequest();
        rechargeListRequest.setRechargeDate(rechargeList.getRechargeDate());
        String rechargeNum = "CZ";
        rechargeListRequest.setSelectDate(rechargeNum+storeNum.trim()+ymdDate);
        rechargeListRequest.setStoreId(rechargeList.getStoreId());
        List<RechargeList> rechargeLists = dao.getDocNum(rechargeListRequest);
        String num;
        int mm = 0;
        if (rechargeLists != null && rechargeLists.size() > 0) {
            RechargeList recharge = rechargeLists.get(0);
            int a=storeNum.trim().length();
            mm = Integer.parseInt(recharge.getRechargeNum().substring(10+a)) + 1;
            if (mm < 10){
                num = "00" + mm;
            }else if (mm < 100){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }
            rechargeNum += storeNum.trim() + ymdDate + num;

        }else {
            num = "001" ;
            rechargeNum += storeNum.trim() + ymdDate + num;
        }
        return rechargeNum;
    }

    /*
     * 账户交易记录属性赋值 充值
     * */
    public AccountTradeRecord setAccountTradeRecord(CourseAccount rechargeList,DocPromotionProject rechargeAccount,RechargeList list){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(rechargeList.getStoreId());
        accountTradeRecord.setStoreName(rechargeList.getStoreName());
        accountTradeRecord.setMemberId(rechargeList.getMemberId());
        accountTradeRecord.setMemberName(rechargeList.getMemberName());
        accountTradeRecord.setMemberPhone(rechargeAccount.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeList.getId());
        accountTradeRecord.setAccountName(rechargeList.getCourseProjectName());
        accountTradeRecord.setPrice(rechargeList.getPrice());
        if(list.getIsAddition()==1){
            accountTradeRecord.setAdditionDate(list.getAdditionDate());
        }
        if(list.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(list.getRechargeDate());
            accountTradeRecord.setInputBy(list.getInputBy());
            accountTradeRecord.setAccountInMoney(list.getCollectionAmount());
            if(list.getIsDebt()==1){
                accountTradeRecord.setGiftInMenoy(BigDecimal.valueOf(0));
            }else{
                accountTradeRecord.setGiftInMenoy(list.getGiftAfterMoney().subtract(list.getGiftBeforeMoney()));
            }
        }else {
            accountTradeRecord.setOrderStatu(1);
            accountTradeRecord.setAccountType(Constant.account_type_recharge_cancel);
            accountTradeRecord.setInputDate(list.getCancelDate());
            accountTradeRecord.setInputBy(list.getCancelBy());
            accountTradeRecord.setAccountSpendMoney(list.getCollectionAmount());
            if(list.getIsDebt()==1){
                accountTradeRecord.setAccountGiftSpendMoney(BigDecimal.valueOf(0));
            }else{
                accountTradeRecord.setAccountGiftSpendMoney(list.getGiftAfterMoney().subtract(list.getGiftBeforeMoney()));
            }
        }
        accountTradeRecord.setDocId(list.getId());
        accountTradeRecord.setDocNum(list.getRechargeNum());
        accountTradeRecord.setDocType(Constant.doc_type_recharge_course);
        accountTradeRecord.setDebtMoney(rechargeList.getDebtMoney());

        accountTradeRecord.setIsAddition(list.getIsAddition());
        accountTradeRecord.setTradeId(rechargeList.getCourseProjectId());
        accountTradeRecord.setPrice(rechargeList.getPrice());
        accountTradeRecord.setTradeName(rechargeList.getCourseProjectName());
        accountTradeRecord.setTradeMoney(rechargeList.getPrice());
        accountTradeRecord.setAccountRestMoney(rechargeList.getCourseRestPrice());
        accountTradeRecord.setAccountConsumeMoney(rechargeList.getCourseConsumePrice());
        accountTradeRecord.setAccountRestCount(rechargeList.getCourseRestCount());
        accountTradeRecord.setAccountConsumeCount(rechargeList.getCourseConsumeCount());
        accountTradeRecord.setCardMoney(BigDecimal.valueOf(0));
        accountTradeRecord.setCashMoney(list.getCollectionCashAmount());
        return accountTradeRecord;
    }


    /*
    * 账户交易记录属性赋值 充值
    * */
    public AccountTradeRecord setAccountTradeRecord(RechargeList rechargeList,RechargeAccount rechargeAccount){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(rechargeList.getStoreId());
        accountTradeRecord.setStoreName(rechargeList.getStoreName());
        accountTradeRecord.setMemberId(rechargeList.getMemberId());
        accountTradeRecord.setMemberName(rechargeList.getMemberName());
        accountTradeRecord.setMemberIdentity(rechargeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(rechargeList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setPrice(rechargeList.getRechargeAmount());
        if(rechargeList.getIsAddition()==1){
            accountTradeRecord.setAdditionDate(rechargeList.getAdditionDate());
        }
        if(rechargeList.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(rechargeList.getRechargeDate());
            accountTradeRecord.setInputBy(rechargeList.getInputBy());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            if(rechargeList.getIsDebt()==1){
                accountTradeRecord.setGiftInMenoy(BigDecimal.valueOf(0));
            }else{
                accountTradeRecord.setGiftInMenoy(rechargeList.getGiftAfterMoney().subtract(rechargeList.getGiftBeforeMoney()));
            }
        }else {
            accountTradeRecord.setOrderStatu(1);
            accountTradeRecord.setAccountType(Constant.account_type_recharge_cancel);
            accountTradeRecord.setInputDate(rechargeList.getCancelDate());
            accountTradeRecord.setInputBy(rechargeList.getCancelBy());
            accountTradeRecord.setAccountSpendMoney(rechargeList.getCollectionAmount());
            if(rechargeList.getIsDebt()==1){
                accountTradeRecord.setAccountGiftSpendMoney(BigDecimal.valueOf(0));
            }else{
                accountTradeRecord.setAccountGiftSpendMoney(rechargeList.getGiftAfterMoney().subtract(rechargeList.getGiftBeforeMoney()));
            }
        }
        accountTradeRecord.setDocId(rechargeList.getId());
        accountTradeRecord.setDocNum(rechargeList.getRechargeNum());
        accountTradeRecord.setDocType(Constant.doc_type_recharge);
        accountTradeRecord.setDebtMoney(rechargeList.getDebtMoney());

        accountTradeRecord.setIsAddition(rechargeList.getIsAddition());
        accountTradeRecord.setTradeId(rechargeList.getRechargeTypeId());
        accountTradeRecord.setPrice(rechargeList.getRechargeAmount());
        accountTradeRecord.setTradeName(rechargeList.getRechargeTypeName());
        accountTradeRecord.setTradeMoney(rechargeList.getCollectionCashAmount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCashMoney(rechargeList.getCollectionCashAmount());
        accountTradeRecord.setCardMoney(BigDecimal.valueOf(0));
        if(null ==rechargeList.getLiftMoney()){
            accountTradeRecord.setCardMoney(BigDecimal.valueOf(0));
        }else{
            accountTradeRecord.setCardMoney(rechargeList.getLiftMoney());
        }

        accountTradeRecord.setCashMoney(rechargeList.getCollectionCashAmount());
        return accountTradeRecord;
    }

    /*
     * 账户交易记录属性赋值 充值
     * */
    public TransactionRecord setTransactionRecord(RechargeList rechargeList,RechargeAccount rechargeAccount){
        TransactionRecord accountTradeRecord = new TransactionRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(rechargeList.getStoreId());
        accountTradeRecord.setStoreName(rechargeList.getStoreName());
        accountTradeRecord.setMemberId(rechargeList.getMemberId());
        accountTradeRecord.setMemberName(rechargeList.getMemberName());
        accountTradeRecord.setMemberIdentity(rechargeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(rechargeList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        RechargeType rechargeTypes = new RechargeType();
        rechargeTypes.setId(rechargeAccount.getRechargeTypeId());
        rechargeTypes = ssmRechargeTypeSevice.selectOne(rechargeTypes);
        accountTradeRecord.setAccountNum(rechargeTypes.getRechargeTypeNum());
        if(rechargeList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_recharge);
            accountTradeRecord.setDocDate(rechargeList.getRechargeDate());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setDate(new Date());
            accountTradeRecord.setType(3);
            accountTradeRecord.setDocState(0);
            accountTradeRecord.setOperationBy(rechargeList.getInputBy());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setAccountInGiftMoney(rechargeList.getLiftGiftMoney().add(rechargeList.getGiftAfterMoney().subtract(rechargeList.getGiftBeforeMoney())));

        }else {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_cancel);
            accountTradeRecord.setDocDate(rechargeList.getCancelDate());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setDate(new Date());
            accountTradeRecord.setType(4);
            accountTradeRecord.setDocState(1);
            accountTradeRecord.setOperationBy(rechargeList.getCancelBy());
            accountTradeRecord.setCardMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setAccountGiftSpendMoney(rechargeList.getLiftGiftMoney().add(rechargeList.getGiftAfterMoney().subtract(rechargeList.getGiftBeforeMoney())));
        }
        accountTradeRecord.setDocId(rechargeList.getId());
        accountTradeRecord.setDocNum(rechargeList.getRechargeNum());


        RechargeType rechargeType = new RechargeType();
        rechargeType.setId(rechargeList.getRechargeTypeId());
        rechargeType = ssmRechargeTypeSevice.selectOne(rechargeType);
        accountTradeRecord.setDocProjectId(rechargeList.getRechargeTypeId());
        accountTradeRecord.setDocProjectName(rechargeList.getRechargeTypeName());
        accountTradeRecord.setDocProjectNum(rechargeType.getRechargeTypeNum());
        accountTradeRecord.setTradingMoney(rechargeList.getCollectionCashAmount());
        accountTradeRecord.setDebtMoney(rechargeList.getDebtMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCashMoney(rechargeList.getCollectionCashAmount());
        return accountTradeRecord;
    }

    /*
     * 账户交易记录属性赋值 充值
     * */
    public AccountTradeRecord setAccountTradeRecords(RechargeList rechargeList,RechargeAccount rechargeAccount,BigDecimal cardRestMoney){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(rechargeList.getStoreId());
        accountTradeRecord.setStoreName(rechargeList.getStoreName());
        accountTradeRecord.setMemberId(rechargeList.getMemberId());
        accountTradeRecord.setMemberName(rechargeList.getMemberName());
        accountTradeRecord.setMemberIdentity(rechargeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(rechargeList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(rechargeList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_recharge);
            accountTradeRecord.setInputDate(rechargeList.getRechargeDate());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setInputBy(rechargeList.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_cancel);
            accountTradeRecord.setInputDate(rechargeList.getCancelDate());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setInputBy(rechargeList.getCancelBy());
        }
        accountTradeRecord.setPrice(rechargeList.getRechargeAmount());
        accountTradeRecord.setDebtMoney(rechargeList.getDebtMoney());
        accountTradeRecord.setDocId(rechargeList.getId());
        accountTradeRecord.setDocNum(rechargeList.getRechargeNum());
        //accountTradeRecord.setDocType(Constant.doc_type_recharge);
        if(rechargeList.getLiftType()==1){
            accountTradeRecord.setDocType(Constant.doc_type_recharge_upgrade_in);
        }else{
            accountTradeRecord.setDocType(Constant.doc_type_recharge_demotion_in);
        }
        accountTradeRecord.setIsAddition(rechargeList.getIsAddition());
        accountTradeRecord.setTradeId(rechargeList.getRechargeTypeId());
        accountTradeRecord.setTradeName(rechargeList.getRechargeTypeName());
        accountTradeRecord.setTradeMoney(rechargeList.getCollectionCashAmount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setAccountSpendMoney(rechargeList.getCollectionCashAmount());
        accountTradeRecord.setCardMoney(cardRestMoney);
        accountTradeRecord.setCashMoney(rechargeList.getCollectionCashAmount());
        return accountTradeRecord;
    }


    public TransactionRecord setAccountTradeRecordss(RechargeList rechargeList,RechargeAccount rechargeAccount){
        TransactionRecord accountTradeRecord = new TransactionRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(rechargeList.getStoreId());
        accountTradeRecord.setStoreName(rechargeList.getStoreName());
        accountTradeRecord.setMemberId(rechargeList.getMemberId());
        accountTradeRecord.setMemberName(rechargeList.getMemberName());
        accountTradeRecord.setMemberIdentity(rechargeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(rechargeList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        RechargeType rechargeType = new RechargeType();
        rechargeType.setId(rechargeAccount.getRechargeTypeId());
        RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
        accountTradeRecord.setAccountNum(rechargeType1.getRechargeTypeNum());
        if(rechargeList.getIsCancel() == 0) {
            if(rechargeList.getLiftType()==1){
                accountTradeRecord.setType(4);
            }else{
                accountTradeRecord.setType(6);
            }

            accountTradeRecord.setDocState(0);
            accountTradeRecord.setDocDate(rechargeList.getRechargeDate());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setAccountInGiftMoney(rechargeList.getLiftGiftMoney().add(rechargeList.getGiftAfterMoney().subtract(rechargeList.getGiftBeforeMoney())));
        }else {
            if(rechargeList.getLiftType()==1){
                accountTradeRecord.setType(8);
            }else{
                accountTradeRecord.setType(10);
            }
            accountTradeRecord.setDocState(1);
            accountTradeRecord.setAccountType(Constant.account_type_recharge_cancel);
            accountTradeRecord.setDocDate(rechargeList.getCancelDate());
            accountTradeRecord.setAccountInMoney(rechargeList.getCollectionAmount());
            accountTradeRecord.setAccountInGiftMoney(rechargeList.getLiftGiftMoney().add(rechargeList.getGiftAfterMoney().subtract(rechargeList.getGiftBeforeMoney())));
        }

        accountTradeRecord.setDate(new Date());
        accountTradeRecord.setDocId(rechargeList.getId());
        accountTradeRecord.setDocNum(rechargeList.getRechargeNum());
        //accountTradeRecord.setDocType(Constant.doc_type_recharge);
        accountTradeRecord.setDocProjectId(rechargeList.getRechargeTypeId());
        accountTradeRecord.setDocProjectName(rechargeList.getRechargeTypeName());
        accountTradeRecord.setTradingMoney(rechargeList.getRechargeAmount());
        accountTradeRecord.setCashMoney(rechargeList.getCollectionCashAmount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        //accountTradeRecord.setAccountSpendMoney(rechargeList.getCollectionCashAmount());
        return accountTradeRecord;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int cancel(RechargeListRequest rechargeListRequest) throws SmsException {
        //查询作废后剩余金额是否大于0
        StoreParament storeParament = StoreParaUtils.getStorePara(rechargeListRequest.getStoreId(), Constant.service_ticke);
        int days = (int) DateUtils.getDayDiff(rechargeListRequest.getRechargeDate(), new Date());
        if(!"0".equals(storeParament.getParamentValue())) {
            if (Integer.parseInt(storeParament.getParamentValue()) < days) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据超过允许作废时间");
            }
        }
        RechargeList rechargeList = new RechargeList();
        BeanUtils.copyProperties(rechargeListRequest,rechargeList);
        PayList payList = new PayList();
        payList.setDocId(rechargeListRequest.getRechargeNum());

        List<PayList> payListList = ssmPayService.select(payList);
        if(payListList!=null&&payListList.size()>0) {
            for (PayList list : payListList) {
                list.setIsCancel(1);
                ssmPayService.updateByNum(list);
            }
        }
        if(rechargeList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
            DebtList debtList = new DebtList();
            debtList.setDocId(rechargeList.getId());
            debtList.setStoreId(rechargeList.getStoreId());
            List<DebtList> select = ssmDebtService.select(debtList);
            for (DebtList list : select) {
                if(list.getState()==1 ||list.getState()==2){
                    throw new SmsException(ResponseCode.MSG,"该单据存在未作废还款和取消欠款，请先作废");
                }else{
                    if(rechargeList.getDebtMoney().compareTo(list.getDebtMoney())!=0){
                        throw new SmsException(ResponseCode.MSG,"该单据存在未作废还款和取消欠款，请先作废");
                    }
                }
            }
        }
        //如果使用积分支付 将积分返回
        if (0 != rechargeList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(rechargeList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() + rechargeList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());
        if (null == rechargeType){
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"充值类别");
        }

        RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeListRequest.getRechargeAccountId());
        if (null == rechargeAccount){
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"充值账户");
        }
        //判断当前充值单是否是最近充值单(傻逼要求)
        //this.checkRecentRec(rechargeList,rechargeAccount);
        //账户扣减金额
        RechargeAccount account = ssmRechargeAccountService.subMoney(rechargeAccount, rechargeList, rechargeType);
        //单据作废状态修改
        rechargeList.setIsCancel(1);
        rechargeList.setCancelDate(new Date());
        //设置作废人信息
        if (redisClient.hasKey(getStaffKey(rechargeListRequest.getStaffPhone()))){
            StaffResponse staffResponse = redisClient.get(getStaffKey(rechargeListRequest.getStaffPhone()));
            rechargeList.setCancelId(staffResponse.getId());
            rechargeList.setCancelBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(rechargeListRequest.getStaffPhone()) + "*");
        //从redis查询 设置作废人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            rechargeList.setCancelId(staffResponse.getId());
            rechargeList.setCancelBy(staffResponse.getStaffName());
        }
        //只计算总业绩提成
        rechargeList.setSaleAchievement(BigDecimalUtils.bigDecimal("0"));
        rechargeList.setSaleCommission(BigDecimalUtils.bigDecimal("0"));
//        //单据业务员业绩提成置0
//        if (null != rechargeList.getSaleOneStaffId()) {
//            rechargeList.setSaleOneAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            rechargeList.setSaleOneCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != rechargeList.getSaleTwoStaffId()) {
//            rechargeList.setSaleTwoAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            rechargeList.setSaleTwoCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != rechargeList.getSaleThreeStaffId()) {
//            rechargeList.setSaleThreeAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            rechargeList.setSaleThreeCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }
//        if (null != rechargeList.getSaleFourStaffId()) {
//            rechargeList.setSaleFourAchievementAmount(BigDecimalUtils.bigDecimal("0"));
//            rechargeList.setSaleFourCommissionAmount(BigDecimalUtils.bigDecimal("0"));
//        }

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

        int i = dao.cancel(rechargeList);
        Salesman salesman = new Salesman();
        salesman.setOrderId(String.valueOf(rechargeList.getId()));
        List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
        for (Salesman salesman1 : salesmen) {
            salesman1.setState(1);
            ssmSalesmanService.updateNotNull(salesman1);
        }

        if(rechargeType.getType()!=1){
            //删除充值退款记录表
            RefundRecord refundRecord = new RefundRecord();
            refundRecord.setRechargeId(rechargeList.getId());
            ssmRefundRecordService.delete(refundRecord);
        }


        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(rechargeList, rechargeAccount);
        accountTradeRecord.setOrderStatu(1);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

//        if(rechargeList.getLiftType()!=0){
//            TransactionRecord transactionRecord = this.setTransactionRecord(rechargeList, rechargeAccount);
//            if(rechargeList.getLiftType()==1){
//                transactionRecord.setType(8);
//            }else{
//                transactionRecord.setType(10);
//            }
//            ssmTransactionRecordService.add(transactionRecord);
//        }else{
//            TransactionRecord transactionRecord = this.setTransactionRecord(rechargeList, rechargeAccount);
//            ssmTransactionRecordService.add(transactionRecord);
//        }


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

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int cancelPromotionCourse(RechargeListRequest rechargeListRequest) throws SmsException {
        RechargeList rechargeList = new RechargeList();
        BeanUtils.copyProperties(rechargeListRequest,rechargeList);
        PayList payList = new PayList();
        payList.setDocId(rechargeListRequest.getRechargeNum());

        List<PayList> payListList = ssmPayService.select(payList);
        if(payListList!=null&&payListList.size()>0) {
            for (PayList list : payListList) {
                list.setIsCancel(1);
                ssmPayService.updateByNum(list);
            }
        }
        if(rechargeList.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
            DebtList debtList = new DebtList();
            debtList.setDocId(rechargeList.getId());
            debtList.setStoreId(rechargeList.getStoreId());
            List<DebtList> select = ssmDebtService.select(debtList);
            for (DebtList list : select) {
                if(list.getState()==1 ||list.getState()==2){
                    throw new SmsException(ResponseCode.MSG,"该单据存在未作废还款和取消欠款，请先作废");
                }else{
                    if(rechargeList.getDebtMoney().compareTo(list.getDebtMoney())!=0){
                        throw new SmsException(ResponseCode.MSG,"该单据存在未作废还款和取消欠款，请先作废");
                    }
                }
            }
        }
        //如果使用积分支付 将积分返回
        if (0 != rechargeList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(rechargeList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() + rechargeList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeListRequest.getRechargeTypeId());
        if (null == rechargeType){
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"充值类别");
        }

        RechargeAccount rechargeAccount = ssmRechargeAccountService.selectByPrimaryKey(rechargeListRequest.getRechargeAccountId());
        if (null == rechargeAccount){
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"充值账户");
        }
        //判断当前充值单是否是最近充值单(傻逼要求)
//        this.checkRecentRec(rechargeList,rechargeAccount);
        //账户扣减金额
        RechargeAccount account = ssmRechargeAccountService.subMoney(rechargeAccount, rechargeList, rechargeType);
        //单据作废状态修改
        rechargeList.setIsCancel(1);
        rechargeList.setCancelDate(new Date());
        //设置作废人信息
        if (redisClient.hasKey(getStaffKey(rechargeListRequest.getStaffPhone()))){
            StaffResponse staffResponse = redisClient.get(getStaffKey(rechargeListRequest.getStaffPhone()));
            rechargeList.setCancelId(staffResponse.getId());
            rechargeList.setCancelBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(rechargeListRequest.getStaffPhone()) + "*");
        //从redis查询 设置作废人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            rechargeList.setCancelId(staffResponse.getId());
            rechargeList.setCancelBy(staffResponse.getStaffName());
        }
        //只计算总业绩提成
        rechargeList.setSaleAchievement(BigDecimalUtils.bigDecimal("0"));
        rechargeList.setSaleCommission(BigDecimalUtils.bigDecimal("0"));

        //欠款 删除欠款记录
        if (1 == rechargeList.getIsDebt()){
            DebtListRequest debtListRequest = new DebtListRequest();
            debtListRequest.setDocId(rechargeList.getId());
            debtListRequest.setMemberId(rechargeList.getMemberId());
            debtListRequest.setStoreId(rechargeList.getStoreId());
            ssmDebtService.deleteDebt(debtListRequest);
        }
        //查询当前的充值卡是不是促销类型，有没有送疗程
        if(0 == rechargeList.getIsDebt() ){
            if(rechargeType.getType()==2){
                //查询有没有赠送的疗程
                PromotionProject promotionProject = new PromotionProject();
                promotionProject.setPromotionId(rechargeType.getId());
                List<PromotionProject> select = ssmPromotionProjectService.select(promotionProject);
                if(select!=null && select.size()>0){
                    //查询会员账户
                    for (PromotionProject project : select) {
                        CourseAccount courseAccount = new CourseAccount();
                        courseAccount.setCourseNum(rechargeList.getRechargeNum());
                        courseAccount.setMemberId(rechargeList.getMemberId());
                        courseAccount.setCourseProjectId(project.getProjectId());
                        courseAccount.setStoreId(rechargeList.getStoreId());
                        courseAccount = ssmCourseAccountService.selectOne(courseAccount);

                        if(project.getTimes()!=courseAccount.getCourseRestCount() || project.getTimes()!=courseAccount.getCourseConsumeCount()){
                            throw new SmsException(ResponseCode.MSG,"赠送的疗程已经消费，无法作废！");
                        }
                        courseAccount.setCourseRestCount(0);
                        courseAccount.setCourseConsumeCount(0);
                        courseAccount.setCourseRestPrice(BigDecimal.ZERO);
                        courseAccount.setCourseConsumePrice(BigDecimal.ZERO);
                        courseAccount.setCourseProjectMoney(BigDecimal.ZERO);
                        courseAccount.setCourseStandardMoney(BigDecimal.ZERO);
                        ssmCourseAccountService.updateByPrimaryKey(courseAccount);
                    }
                }
            }
        }


        int i = dao.cancel(rechargeList);
        Salesman salesman = new Salesman();
        salesman.setOrderId(String.valueOf(rechargeList.getId()));
        List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
        for (Salesman salesman1 : salesmen) {
            salesman1.setState(1);
            ssmSalesmanService.updateNotNull(salesman1);
        }
        if(rechargeType.getType()!=1){
            //删除充值退款记录表
            RefundRecord refundRecord = new RefundRecord();
            refundRecord.setRechargeId(rechargeList.getId());
            ssmRefundRecordService.delete(refundRecord);
        }


        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(rechargeList, rechargeAccount);
        accountTradeRecord.setOrderStatu(1);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

//        if(rechargeList.getLiftType()!=0){
//            TransactionRecord transactionRecord = this.setTransactionRecord(rechargeList, rechargeAccount);
//            if(rechargeList.getLiftType()==1){
//                transactionRecord.setType(8);
//            }else{
//                transactionRecord.setType(10);
//            }
//            ssmTransactionRecordService.add(transactionRecord);
//        }else{
//            TransactionRecord transactionRecord = this.setTransactionRecord(rechargeList, rechargeAccount);
//            ssmTransactionRecordService.add(transactionRecord);
//        }


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

    public void checkRecentRec(RechargeList rechargeList, RechargeAccount rechargeAccount) throws SmsException {
        //判断充值后金额和账户剩余金额是否相等
        if(BigDecimalUtils.compareTo(rechargeList.getAfterMoney(), rechargeAccount.getCardRestMoney())!=0){
            throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION,"单据充值后金额和账户剩余金额不相等");
        }
//        if(BigDecimalUtils.compareTo(rechargeList.getGiftAfterMoney(), rechargeAccount.getCardGiftMoney())!=0){
//            throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION,"单据充值后赠品金额和账户剩余赠品金额不相等");
//        }
        //判断作废单是否是最近的单(仅允许作废最后做的充值单)
        RechargeListRequest rechargeListRequest = new RechargeListRequest();
        rechargeListRequest.setStoreId(rechargeList.getStoreId());
        rechargeListRequest.setMemberId(rechargeList.getMemberId());
        rechargeListRequest.setRechargeDate(rechargeList.getRechargeDate());
        rechargeListRequest.setRechargeAccountId(rechargeAccount.getId());
        RechargeList recharge = dao.getRecDoc(rechargeListRequest).get(0);
        //获取最近的充值单号
        String maxRecNum = recharge.getRechargeNum();
        if(!rechargeList.getRechargeNum().equals(maxRecNum)){
            throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION,"账户已有新充值");
        }
        //判断时间是否超过允许作废时间
        StoreParament storeParament = StoreParaUtils.getStorePara(rechargeList.getStoreId(),Constant.service_ticke);
        Long days =  DateUtils.getDayDiff(recharge.getRechargeDate(),new Date());
        if(!"0".equals(storeParament.getParamentValue())) {
            if (days.longValue() > Long.parseLong(storeParament.getParamentValue())) {
                throw new SmsException(ResponseCode.CANCEL_NOT_PERMISSION, "单据超过允许作废时间");
            }
        }
    }

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

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

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateStaff(RechargeListRequest rechargeListRequest) throws SmsException {
        List<PayList> payLists = rechargeListRequest.getPayLists();
        if(payLists!=null && payLists.size()>0){
            for (PayList payList : payLists) {
                BaseCollectionType baseCollectionType = ssmCollectionTypeService.selectByPrimaryKey(payList.getPayId());
                payList.setPayName(baseCollectionType.getCollectionTypeName());
                ssmPayService.updateByPrimaryKey(payList);
            }
        }
        int i = 0;
        RechargeList rechargeList = new RechargeList();
        BeanUtils.copyProperties(rechargeListRequest,rechargeList);

        StoreParament storeParament = StoreParaUtils.getStorePara(rechargeListRequest.getStoreId(), Constant.editOrderNum);
        int days = (int) DateUtils.getDayDiff(rechargeListRequest.getRechargeDate(), new Date());
        if("999".equals(storeParament.getParamentValue())) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
            if(!dateFormat.format(new Date()).equals(dateFormat.format(rechargeListRequest.getRechargeDate()))) {
                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<StaffRequest> staffLists = rechargeListRequest.getStaffLists();
        BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
            throw new SmsException(ResponseCode.MSG,"业务员业绩占比和不等于100");
        }
        this.setStaffValue(staffLists,rechargeList);
        BaseStore baseStore = new BaseStore();
        baseStore.setId(rechargeListRequest.getStoreId());
        BaseStore baseStore1 = ssmBaseStoreService.selectOne(baseStore);
            DebtList debtList = new DebtList();
            debtList.setDocId(rechargeList.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(rechargeList);
            RechargeList selectById = dao.selectById(rechargeList);
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(rechargeList.getId()));
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            Date date = rechargeList.getRechargeDate();
            for (Salesman salesman1 : salesmen) {
                date = salesman1.getOrderDate();
                ssmSalesmanService.delete(salesman1);
            }
            List<Salesman> salesmens = rechargeListRequest.getSalesmens();
            BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
            if(null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100))!=0 && reduce5.compareTo(BigDecimal.valueOf(0))!=0){
                throw new SmsException(ResponseCode.MSG,"高管业绩占比和不等于100");
            }
            if(null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100))!=0 && reduce6.compareTo(BigDecimal.valueOf(0))!=0){
                throw new SmsException(ResponseCode.MSG,"管理员业绩占比和不等于100");
            }
            for (Salesman salesmen2 : salesmens) {
                Random r = new Random(3);
                int i1 = r.nextInt();
                salesmen2.setStaffId(salesmen2.getId());
                salesmen2.setId(salesmen2.getId()+i1);
                salesmen2.setOrderId(String.valueOf(selectById.getId()));
                salesmen2.setOrderNum(selectById.getRechargeNum());
                salesmen2.setOrderType(1);
                salesmen2.setOrderDate(date);
                salesmen2.setState(0);
                salesmen2.setProjectId(selectById.getRechargeTypeId());
                salesmen2.setMoney(rechargeListRequest.getCollectionCashAmount());
                salesmen2.setProjectId(rechargeListRequest.getRechargeTypeId());
                salesmen2.setStoreNum(baseStore1.getStoreNum());
                salesmen2.setStoreName(baseStore1.getStoreName());
                salesmen2.setStoreIdOrder(baseStore1.getId());
                salesmen2.setOperatorBy(selectById.getInputBy());
                salesmen2.setIsAddition(selectById.getIsAddition());
            }
            ssmSalesmanService.addBatch(salesmens);
        } catch (Exception e) {
            log.error("SsmRechargeServiceImpl.updateStaff:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.FAILED);
        }
        return i;
    }

    @Autowired
    private RechargeListMapper mapper;
    @Override
    public List<RechargeListResponse> selectList(Long storeId, String dateStr, Date date) throws ParseException, SmsException {
        RechargeListRequest rechargeListRequest = new RechargeListRequest();
        rechargeListRequest.setDateStr(dateStr);
        rechargeListRequest.setRechargeDate(date);
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setIsCancel(0);
//        rechargeListRequest.setPageSize(500);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.ymFormat(baseStore.getFunderDate())), date) < 0){
            throw new SmsException(ResponseCode.NO_DATA);
        }
        List<RechargeList> pageInfo = mapper.selectPage(rechargeListRequest);
        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo) {
            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList, rechargeListResponse);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            for (AchiCommEntity entity : entities) {
                if(rechargeList.getRechargeNum().equals(entity.getDocNum())){
                    entity.setProjectId(rechargeList.getRechargeTypeNum());
                }
                entity.setDocId(rechargeList.getId());
            }
            rechargeListResponse.setEntities(entities);
            listResponses.add(rechargeListResponse);
        }
        return listResponses;
    }

    @Override
    public List<RechargeListResponse> selectListchia(Long storeId, Date date) throws ParseException, SmsException {
        RechargeListRequest rechargeListRequest = new RechargeListRequest();
        rechargeListRequest.setRechargeDate(date);
        rechargeListRequest.setStoreId(storeId);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String format1 = format.format(date);
        rechargeListRequest.setDateStr(format1);
        PageInfo<RechargeList> pageInfo = dao.selectPage(rechargeListRequest);
        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo.getList()) {
            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList, rechargeListResponse);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            for (AchiCommEntity entity : entities) {
                if(rechargeList.getRechargeNum().equals(entity.getDocNum())){
                    entity.setProjectId(rechargeList.getRechargeTypeNum());
                }
            }
            rechargeListResponse.setEntities(entities);
            listResponses.add(rechargeListResponse);
        }
        return listResponses;
    }

    @Autowired
    private RechargeListMapper rechargeListMapper;
    @Override
    public List<RechargeListResponse> selectListAbnormal(Long storeId, String dateStr, Date date) throws ParseException, SmsException {
        RechargeListRequest rechargeListRequest = new RechargeListRequest();
        rechargeListRequest.setDateStr(dateStr);
        rechargeListRequest.setRechargeDate(date);
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setIsCancel(0);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.ymFormat(baseStore.getFunderDate())), date) < 0){
            throw new SmsException(ResponseCode.NO_DATA);
        }
        List<RechargeList> pageInfo = rechargeListMapper.selectPage(rechargeListRequest);
        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo) {
            //总业绩
            BigDecimal totalPerformance = BigDecimal.valueOf(0);

            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList, rechargeListResponse);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            for (AchiCommEntity entity : entities) {
                if(rechargeList.getRechargeNum().equals(entity.getDocNum())){
                    entity.setProjectId(rechargeList.getRechargeTypeNum());
                }
                totalPerformance=totalPerformance.add(entity.getCardAchi().add(entity.getCashAchi()));
            }
            //总业绩大于0
            if(totalPerformance.compareTo(rechargeList.getCollectionAmount())==-1){
                rechargeListResponse.setEntities(entities);
                rechargeListResponse.setErrorMessage("员工没拿完业绩，请检查是否填写员工或者漏填员工，无误则检查项目是否有业绩提成");
                listResponses.add(rechargeListResponse);
            }
            if(totalPerformance.compareTo(rechargeList.getCollectionAmount())==1){
                rechargeListResponse.setEntities(entities);
                rechargeListResponse.setErrorMessage("业绩超出单据金额，请检查已填员工的项目的业绩提成是否正确");
                listResponses.add(rechargeListResponse);
            }
            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){
                rechargeListResponse.setEntities(entities);
                rechargeListResponse.setErrorMessage("存在占比为零的员工存在");
                if(!listResponses.contains(rechargeListResponse)){
                    listResponses.add(rechargeListResponse);
                }
            }
        }
        return listResponses;
    }

    @Override
    public List<RechargeListResponse> selectLists(Long storeId, String startDate, String endDate, Date date) throws ParseException, SmsException {
        RechargeListRequest rechargeListRequest = new RechargeListRequest();
        rechargeListRequest.setStartTime(com.alibaba.excel.util.DateUtils.parseDate(startDate));
        rechargeListRequest.setEndTime(com.alibaba.excel.util.DateUtils.parseDate(endDate));
        rechargeListRequest.setRechargeDate(date);
        rechargeListRequest.setStoreId(storeId);
        rechargeListRequest.setIsCancel(0);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
        if (DateUtils.compare(DateUtils.YMParse(DateUtils.ymFormat(baseStore.getFunderDate())), date) < 0){
            throw new SmsException(ResponseCode.NO_DATA);
        }
        PageInfo<RechargeList> pageInfo = dao.selectPages(rechargeListRequest);
        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo.getList()) {
            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList, rechargeListResponse);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            rechargeListResponse.setEntities(entities);
            listResponses.add(rechargeListResponse);
        }
        return listResponses;
    }

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

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

    public List<RechargeList> selectListSalem(RechargeList rechargeList){
        return dao.selectListSalem(rechargeList);
    }

    @Override
    public int updateRatio(RechargeList rechargeList){
        return dao.updateRatio(rechargeList);
    }

    @Override
    public StoreDaily grouponTuan(StoreDailyRequest storeDailyRequest) {
        return dao.grouponTuan(storeDailyRequest);
    }
    @Override
    public StoreDaily grouponTuanNew(StoreDailyRequest storeDailyRequest) {
        return mapper.grouponTuanNew(storeDailyRequest);
    }

    @Override
    public List<BaseGrouponCardResponse> grouponTuan1(StoreDailyRequest storeDailyRequest) {
        PageInfo<BaseGrouponCard> pageInfo=dao.grouponTuan1(storeDailyRequest);
        List<BaseGrouponCardResponse> list=new ArrayList<>();
        for (BaseGrouponCard baseGrouponCard : pageInfo.getList()) {
            BaseGrouponCardResponse baseGrouponCardResponse=new BaseGrouponCardResponse();
            List<AchiCommEntity> entities = this.getAchiCommLists1(baseGrouponCard);
           /* for (AchiCommEntity entity : entities) {
                if(baseGrouponCard.getDocNum().equals(entity.getDocNum())){
                    entity.setProjectId(baseGrouponCard.getRechargeTypeNum());
                }
                entity.setDocId(baseGrouponCard.getId());
            }*/
            baseGrouponCardResponse.setStaffLists(entities);
            list.add(baseGrouponCardResponse);
        }
        return list;
    }

    @Override
    public RechargeList selectAchiEntities(RechargeList rechargeList) {

        return dao.selectAchiEntities(rechargeList);
    }

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

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

    @Override
    public List<RechargeList> selectList(RechargeListRequest rechargeListRequest) {
        return mapper.selectList(rechargeListRequest);
    }

    @Override
    public PageInfo<RechargeListResponse> rechargeGifList(RechargeListRequest rechargeListRequest) throws ParseException {
        Date date = DateUtils.YMParse(rechargeListRequest.getSelectDate());
        rechargeListRequest.setRechargeDate(date);

        List<Long> lists = new ArrayList<>();
        if(rechargeListRequest.getSelectType()==0){
            lists=rechargeListRequest.getStoreList();
        }else{
            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(rechargeListRequest.getStoreId());
            if(null == baseStore1.getParentId()&&(rechargeListRequest.getStoreList().size()<0||rechargeListRequest.getStoreList()==null)){
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(rechargeListRequest.getStoreId());
                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());
                lists=collect;
            }else{
                lists.add(rechargeListRequest.getStoreId());
            }
        }
        rechargeListRequest.setStoreList(lists);
        PageInfo<RechargeList> pageInfo = dao.rechargeGifList(rechargeListRequest);

        List<RechargeListResponse> listResponses = new ArrayList<>();
        for (RechargeList rechargeList : pageInfo.getList()) {
            RechargeListResponse rechargeListResponse = new RechargeListResponse();
            BeanUtils.copyProperties(rechargeList,rechargeListResponse);
            PayList payList = new PayList();
            payList.setDocId(String.valueOf(rechargeList.getRechargeNum()));
            List<PayList> list = ssmPayService.select(payList);
            rechargeListResponse.setPayLists(list);
            List<AchiCommEntity> entities = this.getAchiCommList(rechargeList);
            rechargeListResponse.setEntities(entities);
            BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(rechargeList.getInputId());
            rechargeListResponse.setInputNum(baseStaff.getStaffNum());
            rechargeListResponse.setRechargeGiftMoney(rechargeListResponse.getGiftAfterMoney().subtract(rechargeListResponse.getGiftBeforeMoney()));
            listResponses.add(rechargeListResponse);
        }
        for (RechargeListResponse listRespons : listResponses) {
            Salesman salesman = new Salesman();
            salesman.setOrderId(String.valueOf(listRespons.getId()));
            salesman.setOrderType(1);
            List<Salesman> salesmen = ssmSalesmanService.selectList(salesman);
            listRespons.setSalesmens(salesmen);
        }
        PageInfo<RechargeListResponse> p =  new PageInfo<>(listResponses);
        p.setTotal(pageInfo.getTotal());
        return p;
    }


    public List<AchiCommEntity> getAchiCommLists1(BaseGrouponCard rechargeList){
        List<AchiCommEntity> entities = new ArrayList<>();
        BigDecimal CountMoney = rechargeList.getRechargeMoney().multiply(BigDecimal.valueOf(rechargeList.getQuantity()));
        BigDecimal hundredBD = com.ssm.manage.utils.BigDecimalUtils.bigDecimal("100");
        if (null != rechargeList.getSaleOneStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(rechargeList.getRechargeMoney().multiply(BigDecimal.valueOf(rechargeList.getQuantity())));
//            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
//            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));

            achiCommEntity.setDocNum(rechargeList.getDocNum());
            achiCommEntity.setDocType(Constant.account_type_recharge_groupon);
            achiCommEntity.setDocDate(rechargeList.getDocDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getSaleOneNumber());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(rechargeList.getSaleOneRatio());
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(CountMoney,BigDecimalUtils.div(rechargeList.getSaleOneRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == 1) {
                achiCommEntity.setCashComm(rechargeList.getTypeRatio().multiply(BigDecimalUtils.div(rechargeList.getSaleOneRatio(),hundredBD)));
            }else {
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(CountMoney,
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleOneRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != rechargeList.getSaleTwoStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(CountMoney);
//            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
//            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getDocNum());
            achiCommEntity.setDocType(Constant.account_type_recharge_groupon);
            achiCommEntity.setDocDate(rechargeList.getDocDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getSaleTwoNumber());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(rechargeList.getSaleTwoRatio());
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(CountMoney,BigDecimalUtils.div(rechargeList.getSaleTwoRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == 1) {
                achiCommEntity.setCashComm(rechargeList.getTypeRatio().multiply(BigDecimalUtils.div(rechargeList.getSaleTwoRatio(),hundredBD)));
            }else {
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(CountMoney,
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleTwoRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != rechargeList.getSaleThreeStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(CountMoney);
//            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
//            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getDocNum());
            achiCommEntity.setDocType(Constant.account_type_recharge_groupon);
            achiCommEntity.setDocDate(rechargeList.getDocDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getSaleThreeNumber());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(rechargeList.getSaleThreeRatio());
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(CountMoney,BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == 1) {
                achiCommEntity.setCashComm(rechargeList.getTypeRatio().multiply(BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD)));
            }else {
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(CountMoney,
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleThreeRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        if (null != rechargeList.getSaleFourStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setMoney(CountMoney);
//            achiCommEntity.setMemberNum(String.valueOf(rechargeList.getMemberId()));
//            achiCommEntity.setMemberName(rechargeList.getMemberName());
            achiCommEntity.setProjectId(String.valueOf(rechargeList.getRechargeTypeId()));
            achiCommEntity.setDocNum(rechargeList.getDocNum());
            achiCommEntity.setDocType(Constant.account_type_recharge_groupon);
            achiCommEntity.setDocDate(rechargeList.getDocDate());
            achiCommEntity.setTradeName(rechargeList.getRechargeTypeName());
            achiCommEntity.setBrandNumber(rechargeList.getSaleFourNumber());
            achiCommEntity.setSaleStaffId(rechargeList.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(rechargeList.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(rechargeList.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(rechargeList.getSaleFourRatio());
            achiCommEntity.setCashAchi(BigDecimalUtils.multiply(CountMoney,BigDecimalUtils.div(rechargeList.getSaleFourRatio(),hundredBD)));
            if (BigDecimalUtils.compareTo(rechargeList.getTypeRatio(), BigDecimalUtils.bigDecimal("1")) == 1) {
                achiCommEntity.setCashComm(rechargeList.getTypeRatio().multiply(BigDecimalUtils.div(rechargeList.getSaleFourRatio(),hundredBD)));
            }else {
                achiCommEntity.setCashComm(BigDecimalUtils.multiply(CountMoney,
                        BigDecimalUtils.multiply(rechargeList.getTypeRatio(), BigDecimalUtils.div(rechargeList.getSaleFourRatio(),hundredBD))));
            }
            if(null == achiCommEntity.getCashAchi()){
                achiCommEntity.setCashAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardAchi() ){
                achiCommEntity.setCardAchi(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCashComm()){
                achiCommEntity.setCashComm(BigDecimal.valueOf(0));
            }
            if(null == achiCommEntity.getCardComm()){
                achiCommEntity.setCardComm(BigDecimal.valueOf(0));
            }
            achiCommEntity.setTotalPerformance(BigDecimalUtils.add(achiCommEntity.getCashAchi(),achiCommEntity.getCardAchi()));
            achiCommEntity.setTotalCommission(BigDecimalUtils.add(achiCommEntity.getCashComm(),achiCommEntity.getCardComm()));

            entities.add(achiCommEntity);
        }
        return entities;
    }
    @Transactional(rollbackFor=Exception.class)
    @Override
    public int addPromotionRecharge(RechargeListRequest rechargeListRequest) throws SmsException {
        int i = 0;
        RechargeAccount rechargeAccount1 = new RechargeAccount();
        rechargeAccount1.setMemberId(rechargeListRequest.getMemberId());
        rechargeAccount1.setStoreId(rechargeListRequest.getStoreId());
        List<RechargeAccount> select = ssmRechargeAccountService.select(rechargeAccount1);
        for (RechargeAccount rechargeAccount : select) {
            if(rechargeAccount.getRechargeTypeId()==rechargeListRequest.getRechargeTypeId()
                    || rechargeAccount.getRechargeTypeId().equals(rechargeListRequest.getRechargeTypeId())){
                if(rechargeAccount.getCardRestMoney().compareTo(rechargeAccount.getCardConsumeMoney())!=0){
                    throw new SmsException(ResponseCode.MSG,"会员该充值卡在该门店存在欠款，请先进行还款");
                }
            }
        }
        //如果返回欠款不等于空那么就是欠款，那么就添加多一条记录，充值欠款
        if(rechargeListRequest.getDebtMoney()!=null){

        }
        RechargeList rechargeList = new RechargeList();
        BeanUtils.copyProperties(rechargeListRequest,rechargeList);
        //账户数据插入
        //查询充值卡类型
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeList.getRechargeTypeId());
        rechargeList.setDonateType(rechargeType.getDonateType());
        StoreParament storeParament = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.rec_debt);
        if (rechargeType == null){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"充值类别");
        }else {
            //不允许欠款 查看欠款参数是否有值
            if ("0".equals(storeParament.getParamentValue())){
                if ( rechargeList.getIsDebt() == 1) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.DEBT_NOT_PERMISSION, "充值");
                }
            }
        }
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(rechargeList.getStoreId());
        BaseStores baseStores1 = ssmBaseStoreService.pagesorganizations(storeRequest).stream().filter(baseStores -> null == baseStores.getParentId()).findAny().orElse(null);
        StoreParament storeParas = StoreParaUtils.getStorePara(baseStores1.getId(), Constant.maximumAmount);
        if(!"0".equals(storeParas.getParamentValue().trim())){
            if(BigDecimalUtils.compareTo(BigDecimalUtils.add(rechargeList.getCollectionAmount(), rechargeList.getDebtMoney()), BigDecimal.valueOf(Double.valueOf(storeParas.getParamentValue()))) == 1){
                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION, "实际充值金额超出充值控制上限,");
            }
        }
        //充值单数据插入
        Long rechargeId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
        rechargeList.setId(rechargeId);
        //生成单据号

        rechargeList.setRechargeDate(new Date());
        //不走补单 正常开单 补单时间默认为开单时间
        if (1 == rechargeList.getIsAddition()) {
            rechargeList.setRechargeDate(rechargeList.getAdditionDate());
        }
        String storeNum=ssmBaseStoreService.selectByPrimaryKey(rechargeList.getStoreId()).getStoreNum();
        String rechargeNum = this.getDocNum(rechargeList,storeNum);
        rechargeList.setRechargeNum(rechargeNum);
        rechargeList.setIsCancel(0);
        //查询门店参数
        //充值有欠款可消费比率参数
        StoreParament para = new StoreParament();
        if ("1".equals(storeParament.getParamentValue())) {
            para = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.rec_debt_usable);
        }
        //查询是否有充值账户
        RechargeAccount rechargeAccount = new RechargeAccount();
        rechargeAccount.setRechargeTypeId(rechargeType.getId());
        // rechargeAccount.setStoreId(rechargeList.getStoreId());
        rechargeAccount.setMemberId(rechargeList.getMemberId());
//        RechargeAccount beforeAccount = ssmRechargeAccountService.selectOne(rechargeAccount);
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
        StoreRequest stores = new StoreRequest();
        stores.setId(rechargeList.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(stores);
        List<Long> storeIds = new ArrayList<>();
        Long storeID=null;
        for (BaseStores pagesorganization : pagesorganizations) {
            storeIds.add(pagesorganization.getId());
            if(null == pagesorganization.getParentId()){
                storeID=pagesorganization.getId();
            }
        }
        criteria.andEqualTo("rechargeTypeId",rechargeType.getId());
        criteria.andIn("storeId",storeIds);
        criteria.andEqualTo("memberId",rechargeList.getMemberId());
        //criteria.andEqualTo("state", 1);
        List<RechargeAccount> list = ssmRechargeAccountService.selectByExample(example);
        RechargeAccount beforeAccount = null;
        if (list.size() > 0) {
            beforeAccount = list.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();
            BeanUtils.copyProperties(rechargeList, account);
            account.setId(rechargeAccountId);
            rechargeList.setRechargeAccountId(rechargeAccountId);
            //对充值账户进行赋值
            account = ssmRechargeAccountService.setRechargeAccount(rechargeType, rechargeList, account, para);
            account.setCardNum(0);
            account.setFirstCharge(0L);
            //account.setCardRechargeMoney(rechargeType.getFirstAmount());
            ssmRechargeAccountService.addRechargeAccount(account);
            BeanUtils.copyProperties(account,rechargeAccount);
        }else {//存在账户 添加账户金额
            //判断充前金额是否和当前账户相等
            if (BigDecimalUtils.compareTo(rechargeList.getBeforeMoney(),beforeAccount.getCardRestMoney()) != 0){
                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION,"充值账户充前金额和当前账户剩余金额不相等");
            }
            //剩余金额与可消费金额不等
//            if(BigDecimalUtils.compareTo(beforeAccount.getCardRestMoney(),beforeAccount.getCardConsumeMoney()) != 0){
//                throw new SmsException(ResponseCode.RECHARGE_NOT_PERMISSION,"充值账户存在欠款");
//            }
            rechargeList.setRechargeAccountId(beforeAccount.getId());
            beforeAccount.setRechargeNum(rechargeNum);
            beforeAccount.setCardNum(1);
            ssmRechargeAccountService.addMoney(beforeAccount,rechargeList,rechargeType,para);
            BeanUtils.copyProperties(beforeAccount,rechargeAccount);
        }

//        todo 无欠款并且是活动卡类别
        if(rechargeList.getIsDebt()==0 && rechargeType.getType()==2){
            //查询有没有赠送的疗程
            PromotionProject promotionProject = new PromotionProject();
            promotionProject.setPromotionId(rechargeType.getId());
            List<PromotionProject> promotionProjects = ssmPromotionProjectService.select(promotionProject);
            //判断是否有赠送的疗程
            if(promotionProjects!=null && promotionProjects.size()>0){
                for (PromotionProject project : promotionProjects) {
                    //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                    Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                    CourseAccount courseAccount = new CourseAccount();
                    BeanUtils.copyProperties(rechargeList, courseAccount);
                    courseAccount.setId(courseAccountId);
                    if (project.getType() == 0) {
                        courseAccount.setCourseType("1");
                    } else {
                        courseAccount.setCourseType("2");
                    }
                    courseAccount.setCourseNum(rechargeNum);

                    //对疗程账户进行赋值
                    courseAccount = ssmCourseAccountService.addCourseAccountByPromotionRecharge(courseAccount, project, project.getTimes());

                    //添加促销活动项目明细
                    DocPromotionProject docPromotionProject = new DocPromotionProject();
                    BeanUtils.copyProperties(project,docPromotionProject);
                    docPromotionProject.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    docPromotionProject.setMemberId(rechargeList.getMemberId());
                    docPromotionProject.setMemberName(rechargeList.getMemberName());
                    docPromotionProject.setMemberIdentityCard(rechargeList.getMemberIdentityCard());
                    docPromotionProject.setMobilePhone(rechargeList.getMobilePhone());
                    docPromotionProject.setDocNum(rechargeList.getRechargeNum());
                    docPromotionProject.setDocDate(rechargeList.getRechargeDate());
                    docPromotionProject.setCourseAccountId(courseAccountId);
                    docPromotionProject.setTimes(project.getTimes());
                    ssmDocPromotionProjectService.saveNotNull(docPromotionProject);
                    //添加账户交易记录
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseAccount, docPromotionProject,rechargeList);
                    accountTradeRecord.setInputBy(rechargeList.getInputBy());
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                }
            }
        }



        //员工业绩提成
        List<StaffRequest> staffLists = rechargeListRequest.getStaffLists();
        BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
            throw new SmsException(ResponseCode.MSG,"业务业绩占比和不等于100");
        }
        this.setStaffValue(staffLists,rechargeList);
        //欠款 添加欠款记录
        if (1 == rechargeList.getIsDebt()){
            DebtListRequest debtListRequest = new DebtListRequest();
            BeanUtils.copyProperties(rechargeList,debtListRequest);
            debtListRequest.setTradeId(rechargeList.getRechargeTypeId());
            debtListRequest.setTradeName(rechargeList.getRechargeTypeName());
            debtListRequest.setTradeMoney(rechargeList.getRechargeAmount());
            debtListRequest.setDocId(rechargeId);
            debtListRequest.setDocNum(rechargeNum);
            debtListRequest.setDocType(Constant.doc_type_recharge);
            debtListRequest.setAccountId(rechargeAccount.getId());
            debtListRequest.setStaffLists(staffLists);
            debtListRequest.setState(0);
            debtListRequest.setDocDate(rechargeList.getRechargeDate());
            debtListRequest.setRepayConsumeMoney(BigDecimalUtils.bigDecimal(para.getParamentValue()).divide(BigDecimalUtils.bigDecimal("100")));
            int i1 = ssmDebtService.addDebt(debtListRequest);
        }

        //设置录单人信息
        if (redisClient.hasKey(getStaffKey(rechargeListRequest.getStaffPhone()))){
            StaffResponse staffResponse = redisClient.get(getStaffKey(rechargeListRequest.getStaffPhone()));
            rechargeList.setInputId(staffResponse.getId());
            rechargeList.setInputBy(staffResponse.getStaffName());
        }
        Set<String> keys = redisClient.keys(getStaffKey(rechargeListRequest.getStaffPhone()) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            StaffResponse staffResponse = redisClient.get(key);
            rechargeList.setInputId(staffResponse.getId());
            rechargeList.setInputBy(staffResponse.getStaffName());
        }
        try {
            rechargeList.setLiftType(0);
            rechargeList.setRechargeTypeNum(rechargeListRequest.getRechargeTypeNum());
            //查询门店充值的当前欠款可用比例
            List<StoreParament> storeParaments=ssmStoreParaService.list(rechargeList.getStoreId());
            for(StoreParament storeParament1:storeParaments){
                if(storeParament1.getParamentName().equals("recDebtUsable"))
                    rechargeList.setStoreRecDebtUsable(storeParament1.getParamentValue());  ;
            }
            i = dao.addRecharge(rechargeList);
            //高管业绩
            if(null != rechargeListRequest.getSalesmens()){
                List<Salesman> salesmens = rechargeListRequest.getSalesmens();
                BigDecimal reduce5 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==0).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal reduce6 = salesmens.stream().filter(salesman1 -> salesman1.getStaffType()==1).map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(null != reduce5 && reduce5.compareTo(BigDecimal.valueOf(100))!=0 && reduce5.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"高管业绩占比和不等于100");
                }
                if(null != reduce6 && reduce6.compareTo(BigDecimal.valueOf(100))!=0 && reduce6.compareTo(BigDecimal.valueOf(0))!=0){
                    throw new SmsException(ResponseCode.MSG,"管理员业绩占比和不等于100");
                }
                for (Salesman salesmen : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
                    salesmen.setStaffId(salesmen.getId());
                    salesmen.setId(salesmen.getId()+i1);
                    salesmen.setOrderId(String.valueOf(rechargeList.getId()));
                    salesmen.setOrderNum(rechargeNum);
                    salesmen.setOrderType(1);
                    salesmen.setOrderDate(rechargeList.getRechargeDate());
                    salesmen.setState(0);
                    salesmen.setOperatorBy(rechargeList.getInputBy());
                    salesmen.setMoney(rechargeListRequest.getCollectionCashAmount());
                    salesmen.setProjectId(rechargeListRequest.getRechargeTypeId());
                    salesmen.setIsAddition(rechargeList.getIsAddition());
                }
                ssmSalesmanService.addBatch(salesmens);
            }
            RechargeType rechargeType1 = new RechargeType();
            rechargeType1.setId(rechargeList.getRechargeTypeId());
            RechargeType rechargeType2 = ssmRechargeTypeSevice.selectOne(rechargeType1);
            if(rechargeType2.getType()!=1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                refundRecord.setRechargeId(rechargeList.getId());
                refundRecord.setMemberId(rechargeList.getMemberId());
                refundRecord.setMemberName(rechargeList.getMemberName());
                refundRecord.setRechargeTypeId(rechargeList.getRechargeTypeId());
                refundRecord.setRechargeTypeName(rechargeList.getRechargeTypeName());
                refundRecord.setRechargeDate(rechargeList.getRechargeDate());
                refundRecord.setRechargeAmount(rechargeList.getRechargeAmount());
                refundRecord.setCollectionAmount(rechargeList.getCollectionAmount());
                refundRecord.setRefundDebtMoney(BigDecimal.valueOf(0));
                if(rechargeType.getDonateType()==0){
                    refundRecord.setRechargeGiftAmount(rechargeType2.getGiftMoney());
                }else{
                    BigDecimal divide = rechargeType.getGiftMoney().divide(BigDecimal.valueOf(100));
                    refundRecord.setRechargeGiftAmount(divide.multiply(rechargeList.getCollectionAmount()));
                }

                if(rechargeList.getIsDebt()==1){
                    refundRecord.setIsReceived(0);
                }else{
                    refundRecord.setIsReceived(1);
                }

                refundRecord.setAmountRefunded(BigDecimal.valueOf(0));
                refundRecord.setAmountGiftRefunded(BigDecimal.valueOf(0));
                refundRecord.setIsDeduct(0);
                int save = ssmRefundRecordService.save(refundRecord);
            }
        } catch (Exception e) {
            log.error("SsmRechargeServiceImpl.addRecharge:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.FAILED);
        }
        //如果使用积分支付将门店会员积分进行扣减
        if (0 != rechargeList.getIntegral()) {
            StoreMemberList storeMember = ssmStoreMemberService.selectByPrimaryKey(rechargeList.getMemberId());
            storeMember.setIntegral(storeMember.getIntegral() - rechargeList.getIntegral());
            ssmStoreMemberService.updateByPrimaryKey(storeMember);
        }
        //支付方式插入
        List<PayList> payLists = rechargeListRequest.getPayLists();
        if (null != payLists && payLists.size() > 0) {
            for (PayList payList : payLists) {
                payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                payList.setDocId(String.valueOf(rechargeNum));
                payList.setType(Constant.doc_type_recharge);
                payList.setStoreId(rechargeListRequest.getStoreId());
                payList.setPayDate(rechargeList.getRechargeDate());
                payList.setIsCancel(0);
            }
            ssmPayService.addPayList(payLists);
        }

        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(rechargeList,rechargeAccount);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
        //将充值单据信息添加到评价表
        MemberCsRequest memberCsRequest = new MemberCsRequest();
        BeanUtils.copyProperties(rechargeList, memberCsRequest);
        memberCsRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        memberCsRequest.setDocId(rechargeId);
        memberCsRequest.setDocNum(rechargeNum);
        memberCsRequest.setDocType(Constant.doc_type_recharge);
        memberCsRequest.setDocDate(rechargeList.getRechargeDate());
        memberCsRequest.setTradeId(rechargeList.getRechargeTypeId());
        memberCsRequest.setTradeName(rechargeList.getRechargeTypeName());
        memberCsRequest.setTradeMoney(rechargeList.getRechargeAmount());
        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;
    }

}
