package com.ssm.manage.service.impl;

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

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

import static java.util.Comparator.comparing;

@Service
@Slf4j
public class SsmRechargeAccountServiceImpl extends BaseServiceImpl<RechargeAccount> implements SsmRechargeAccountService {
    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmPromotionProjectService ssmPromotionProjectService;

    @Autowired
    private SsmDocPromotionService ssmDocPromotionService;
    @Autowired
    private SsmDocPromotionProjectService ssmDocPromotionProjectService;
    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmRechargeAccountGiveService ssmRechargeAccountGiveService;

    @Autowired
    private SsmRepayTradeService ssmRepayTradeService;
    @Autowired
    private SsmRepayService ssmRepayService;
    @Autowired
    private SsmRepayAccountListService ssmRepayAccountListService;
    @Autowired
    private SsmRechargeService ssmRechargeService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmDebtService ssmDebtService;
    @Autowired
    private SsmRefundRecordService ssmRefundRecordService;

    @Autowired
    private SsmCashAccountSrevice ssmCashAccountSrevice;
    @Autowired
    private SsmRefundRechargeDetailService ssmRefundRechargeDetailService;

    @Autowired
    private SsmProjectService ssmProjectService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmPromotionService ssmPromotionService;

    @Autowired
    private SsmCancelDebtListService ssmCancelDebtListService;

    @Autowired
    private SsmRechargeAccountDao dao;

    @Autowired
    private SsmRechargeAccountGiveDao ssmRechargeAccountGiveDao;

    @Autowired
    private RedisClient<StaffResponse> redisClient;

    private static String staffKey = "staffKey";

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

    @Override
    public List<RechargeAccount> selectList(RechargeAccountRequest rechargeAccountRequest) {
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != rechargeAccountRequest.getStoreId()) {
            criteria.andEqualTo("storeId", rechargeAccountRequest.getStoreId());
        }
        if (null != rechargeAccountRequest.getStoreIds()){
            criteria.andIn("storeId", Arrays.asList(rechargeAccountRequest.getStoreIds()));
        }
        criteria.andEqualTo("memberId",rechargeAccountRequest.getMemberId());
        criteria.andGreaterThanOrEqualTo("cardConsumeMoney",BigDecimalUtils.bigDecimal("1"));
        criteria.andEqualTo("state", 1);
        if (StringUtils.isNotBlank(rechargeAccountRequest.getRechargeTypeName())){
            criteria.andLike("rechargeTypeName", "%" + rechargeAccountRequest.getRechargeTypeName() + "%");
        }
        List<RechargeAccount> list = dao.selectByExample(example);
        List<RechargeAccount> resultList = new ArrayList<>();
        List<RechargeAccount> rechargeAccountList = new ArrayList<>();
        //+
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (RechargeAccount rechargeAccount : list) {
            String rechargeNum = rechargeAccount.getRechargeNum();
            if(rechargeNum!=null && rechargeNum.length()>0 && rechargeNum.startsWith("CZ")){
                String substring = rechargeNum.substring(rechargeNum.length() - 11, rechargeNum.length() - 3);
                StrBuilder strBuilder = new StrBuilder(substring);
                Date parse;
                StrBuilder insert = strBuilder.insert(6, "-").insert(4, "-");
                try {
                    parse = dateFormat.parse(String.valueOf(insert));
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                RechargeList rechargeList = new RechargeList();
                rechargeList.setRechargeNum(rechargeNum);
                rechargeList.setRechargeDate(parse);
                RechargeList rechargeList1 = ssmRechargeService.selectAchiEntities(rechargeList);

                List<AchiCommEntity> achiCommList = this.getAchiCommList(rechargeList1);
                if(rechargeList1.getDebtMoney().compareTo(BigDecimal.valueOf(0))==1){
                    RepayTradeList repayTradeList = new RepayTradeList();
                    repayTradeList.setDocNum(rechargeList1.getRechargeNum());
                    List<RepayTradeList> repayTradeLists = ssmRepayTradeService.selectList(repayTradeList);
                    if(repayTradeLists!=null && repayTradeLists.size()>0) {
                        for (RepayTradeList tradeList : repayTradeLists) {
                            if (tradeList.getTradeId().equals(rechargeList1.getRechargeTypeId())) {
                                achiCommList.addAll(this.getAchiCommList(tradeList));
                            }
                        }
                    }
                }
                BigDecimal reduce = achiCommList.stream().map(AchiCommEntity::getSaleAchievementAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                if(reduce.compareTo(BigDecimal.ZERO)==0){
                    reduce = new BigDecimal("1");
                }
                for (AchiCommEntity achiCommEntity : achiCommList) {

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

        Map<Long, List<RechargeAccount>> map = list.stream().collect(Collectors.groupingBy(RechargeAccount::getStoreId));

        if(list.size()>0){
            Long StoreId=null;
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(list.get(0).getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    StoreId=pagesorganization.getId();
                }
            }
            StoreParament storePara = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
            //充值账户所属门店存在使用有效期参数
            if (null != list && list.size() > 0 && "1".equals(storePara.getParamentValue())){
                //过滤a账户结束时间大于当前时间
                //rechargeAccountList = list.stream().filter(rechargeAccount -> null != rechargeAccount.getEndTime() && DateUtils.compare(new Date(), rechargeAccount.getEndTime()) > 0).collect(Collectors.toList());
                for (RechargeAccount rechargeAccount : list) {
                    RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
                    //判断是否促销卡，是否是限制门店使用
                    if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                        RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                        BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                        rechargeAccountGive.setAccountId(rechargeAccount.getId());
                        rechargeAccountGive.setStoreId(rechargeAccountRequest.getNowStoreId());
                        Example example1 = new Example(RechargeAccountGive.class);
                        Example.Criteria criteria1 = example1.createCriteria();
                        criteria1.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                        criteria1.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                        //查询原账户的赠送金额
                        List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example1);
                        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
                        for(RechargeAccountGive rechargeAccountGive1:List){
                            if(rechargeAccountGive1.getStoreId().hashCode()!=rechargeAccountRequest.getNowStoreId().hashCode())
                                giftConsumeMoneyGive=giftConsumeMoneyGive.add(rechargeAccountGive1.getGiftConsumeMoney());
                        }
                        //原账户赠送可用金额-不是本门店赠送金额=本门店可用的赠送金额
                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().subtract(giftConsumeMoneyGive));
                        rechargeAccount.setGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney().subtract(giftConsumeMoneyGive));
                    }


                    if(null == rechargeType.getUnifiedDue()){
                        if(null == rechargeAccount.getEndTime()){
                            rechargeAccountList.add(rechargeAccount);
                        }else{
                            if(new Date().before(rechargeAccount.getEndTime())){
                                rechargeAccountList.add(rechargeAccount);
                            }
                        }
                    }else{
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        try {
                            if(new Date().before(format.parse(rechargeType.getUnifiedDue()))){
                                if(null == rechargeAccount.getEndTime()){
                                    rechargeAccountList.add(rechargeAccount);
                                }else{
                                    if(new Date().before(rechargeAccount.getEndTime())){
                                        rechargeAccountList.add(rechargeAccount);
                                    }
                                }
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                    }

                }
            }else{
                rechargeAccountList=list;
            }
            resultList.addAll(rechargeAccountList);
            for (RechargeAccount rechargeAccount : resultList) {
                RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
                rechargeAccountGive.setAccountId(rechargeAccount.getId());
                List<RechargeAccountGive> select = ssmRechargeAccountGiveDao.select(rechargeAccountGive);
                List<RechargeAccountGive> collect = select.stream().filter(item -> item.getGiftConsumeMoney().compareTo(BigDecimal.valueOf(0)) ==1).collect(Collectors.toList());
                rechargeAccount.setRechargeAccountGiveList(collect);
            }
            return resultList;
        }else{
            return resultList;
        }

        //是否使用有效期
//        List<StoreParament> paraments = StoreParaUtils.getStorePara(Constant.allow_valid);
//        for (StoreParament parament : paraments) {
//            if(null != parament.getStoreId()){
//                rechargeAccountList = map.get(parament.getStoreId());
//
//                Long StoreId=null;
//                StoreRequest storeRequest = new StoreRequest();
//                storeRequest.setId(parament.getStoreId());
//                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
//                for (BaseStores pagesorganization : pagesorganizations) {
//                    if(null == pagesorganization.getParentId()){
//                        StoreId=pagesorganization.getId();
//                    }
//                }
//                StoreParament paramentz = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
////充值账户所属门店存在使用有效期参数
//                if (null != rechargeAccountList && rechargeAccountList.size() > 0 && "1".equals(paramentz.getParamentValue())){
//                    //过滤a账户结束时间大于当前时间
//                    rechargeAccountList = rechargeAccountList.stream().filter(rechargeAccount -> DateUtils.compare(new Date(), rechargeAccount.getEndTime()) > 0).collect(Collectors.toList());
//                }
//                if (null != rechargeAccountList){
//                    resultList.addAll(rechargeAccountList);
//                }else {
//                    continue;
//                }
//            }
//        }


    }

    public List<AchiCommEntity> getAchiCommList(RepayTradeList repayTradeList){
//        repayTradeList.setRepayMoney(repayTradeList.getRepayMoney().negate());
//        repayTradeList.setPayMoney(repayTradeList.getPayMoney().negate());
//        repayTradeList.setAchievementAmount(repayTradeList.getAchievementAmount().negate());
//        repayTradeList.setCommissionAmount(repayTradeList.getCommissionAmount().negate());
//        repayTradeList.setCardAchievementAmount(repayTradeList.getCardAchievementAmount().negate());
//        repayTradeList.setCardCommissionAmount(repayTradeList.getCardCommissionAmount().negate());
        //疗程欠款单，充值开卡添加提成
        BigDecimal coursDebteRecharge = BigDecimal.valueOf(0);
        BigDecimal coursDebteRechargechia = BigDecimal.valueOf(0);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                entities.add(achiCommEntity);
            }
        }

        return entities;
    }

    public List<AchiCommEntity> getAchiCommList(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 List<RechargeAccount> cashSelectListByStore(RechargeAccountRequest rechargeAccountRequest) throws SmsException {
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
        /*if (null != rechargeAccountRequest.getStoreId()) {
            criteria.andEqualTo("storeId", rechargeAccountRequest.getStoreId());
        }*/
        if (null != rechargeAccountRequest.getStoreIds()){
            criteria.andIn("storeId", Arrays.asList(rechargeAccountRequest.getStoreIds()));
        }
        if (null != rechargeAccountRequest.getStoreIdl()){
            criteria.andIn("storeId", rechargeAccountRequest.getStoreIdl());
        }
        if (null != rechargeAccountRequest.getRechargeTypeId()){
            criteria.andEqualTo("rechargeTypeId", rechargeAccountRequest.getRechargeTypeId());
        }
        criteria.andEqualTo("memberId",rechargeAccountRequest.getMemberId());
        //criteria.andGreaterThanOrEqualTo("cardRestMoney",BigDecimalUtils.bigDecimal("1"));
        criteria.andEqualTo("state", 1);
        if (StringUtils.isNotBlank(rechargeAccountRequest.getRechargeTypeName())){
            criteria.andLike("rechargeTypeName", "%" + rechargeAccountRequest.getRechargeTypeName() + "%");
        }

        Example.Criteria c = example.createCriteria();
//        c.andGreaterThan("cardRestMoney",BigDecimalUtils.bigDecimal("0")).orGreaterThan("giftConsumeMoney", BigDecimalUtils.bigDecimal("0"));
        example.and(c);
        List<RechargeAccount> list = dao.selectByExample(example);
        RechargeAccountGive rechargeAccountGive1 = new RechargeAccountGive();
        rechargeAccountGive1.setMemberId(rechargeAccountRequest.getMemberId());
//        rechargeAccountGive1.setStoreId(rechargeAccountRequest.getStoreId());
        List<RechargeAccountGive> select = ssmRechargeAccountGiveService.select(rechargeAccountGive1);

        if(select!=null&&select.size()>0){
            for (RechargeAccountGive rechargeAccountGive : select) {
                for (int i = 0; i < list.size(); i++) {
                    if(list.get(i).getId() ==rechargeAccountGive.getAccountId() ||   list.get(i).getId().toString().equals(rechargeAccountGive.getAccountId().toString())){
                        list.get(i).setGiftConsumeMoney(BigDecimal.valueOf(0));
                        list.get(i).setCardGiftMoney(BigDecimal.valueOf(0));

                    }
                }
            }
            for (RechargeAccountGive rechargeAccountGive : select) {
                for (int i = 0; i < list.size(); i++) {
                    if((list.get(i).getId().toString().equals(rechargeAccountGive.getAccountId().toString()) && rechargeAccountGive.getStoreId().toString().equals(rechargeAccountRequest.getStoreId().toString()))
                    || list.get(i).getId() == rechargeAccountGive.getAccountId() && rechargeAccountGive.getStoreId() == rechargeAccountRequest.getStoreId()){
                        list.get(i).setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney());
                        list.get(i).setCardGiftMoney(rechargeAccountGive.getGiftConsumeMoney());
//                        list.get(i).setGiftConsumeMoney(list.get(i).getGiftConsumeMoney().add(rechargeAccountGive.getGiftConsumeMoney()));
//                        list.get(i).setCardGiftMoney(list.get(i).getCardGiftMoney().add(rechargeAccountGive.getGiftConsumeMoney()));

                    }
                }
            }
        }
        List<RechargeAccount> resultList = new ArrayList<>();
        List<RechargeAccount> resultLists = new ArrayList<>();
//        List<RechargeAccount> rechargeAccountList = new ArrayList<>();
//        Map<Long, List<RechargeAccount>> map = list.stream().collect(Collectors.groupingBy(RechargeAccount::getStoreId));

        Long mdID=null;

        //是否使用有效期
        for (RechargeAccount rechargeAccount : list) {
            if(null == mdID){
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(rechargeAccount.getStoreId());
                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                long asLong = pagesorganizations.stream().filter(baseStores -> null == baseStores.getParentId()).mapToLong(BaseStores::getId).findAny().getAsLong();
                mdID=asLong;
            }
            StoreParament paraments = StoreParaUtils.getStorePara(mdID,Constant.allow_valid);
            if( "1".equals(paraments.getParamentValue())){
                RechargeType rechargeType = new RechargeType();
                rechargeType.setId(rechargeAccount.getRechargeTypeId());
                RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                try {
                    if(rechargeType1.getUnifiedDue()!=null) {
                        Date d = simpleDateFormat.parse(rechargeType1.getUnifiedDue());
                        if (!d.before(new Date())) {
                            if (null == rechargeAccount.getEndTime()) {
                                resultList.add(rechargeAccount);
                                continue;
                            } else {
//                    if(DateUtils.compare(, rechargeAccount.getEndTime()) > 0){
                                if (new Date().before(rechargeAccount.getEndTime())) {
                                } else {
                                    continue;
                                }
                            }
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                try {
                    if(null == rechargeType1.getUnifiedDue()){
                        resultList.add(rechargeAccount);
                    }else{
                        Date parse = simpleDateFormat.parse(rechargeType1.getUnifiedDue());
                        if(!parse.before(new Date())){
                            resultList.add(rechargeAccount);
                        }
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else{
                resultList.add(rechargeAccount);
            }
        }

        int a=0;
        for (RechargeAccount parament : resultList) {
            RechargeType rechargeType = new RechargeType();
            rechargeType.setId(parament.getRechargeTypeId());
            RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
            parament.setRechargeTypeNum(rechargeType1.getRechargeTypeNum());
            //判断是否是促销卡
//            if(rechargeType1.getType()==2){
//                //查询是否有设置过仅限门店使用的赠卡
//                Example example1 = new Example(RechargeAccountGive.class);
//                Example.Criteria criteria1 = example1.createCriteria();
//                criteria1.andEqualTo("accountId",parament.getId());
//                criteria1.andEqualTo("memberId",parament.getMemberId());
//                //查询原账户的赠送金额
//                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example1);
//
//                BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
//                for(RechargeAccountGive rechargeAccountGive:List){
//                    if(rechargeAccountGive.getStoreId().hashCode()!=rechargeAccountRequest.getStoreId().hashCode())
//                        giftConsumeMoneyGive=giftConsumeMoneyGive.add(rechargeAccountGive.getGiftConsumeMoney());
//                }
//
////                if(rechargeAccountRequest.getSelectType()==null||rechargeAccountRequest.getSelectType()!=1){
////                    //原账户赠送可用金额-不是本门店赠送金额=本门店可用的赠送金额
////                    parament.setCardGiftMoney(parament.getCardGiftMoney().subtract(giftConsumeMoneyGive));
////                    parament.setGiftConsumeMoney(parament.getGiftConsumeMoney().subtract(giftConsumeMoneyGive));
////                }
//            }
            resultLists.add(parament);

            a++;
        }
        List<RechargeAccount> collect = resultLists.stream()
                .filter(item -> (item.getCardRestMoney().
                        add(item.getCardGiftMoney())).compareTo(new BigDecimal("0")) ==1 ).collect(Collectors.toList());
        return collect;
    }
    @Override
    public List<RechargeAccount> cashSelectList(RechargeAccountRequest rechargeAccountRequest) throws SmsException {
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
        /*if (null != rechargeAccountRequest.getStoreId()) {
            criteria.andEqualTo("storeId", rechargeAccountRequest.getStoreId());
        }*/
        if (null != rechargeAccountRequest.getStoreIds()){
            criteria.andIn("storeId", Arrays.asList(rechargeAccountRequest.getStoreIds()));
        }
        if (null != rechargeAccountRequest.getStoreIdl()){
            criteria.andIn("storeId", rechargeAccountRequest.getStoreIdl());
        }
        if (null != rechargeAccountRequest.getRechargeTypeId()){
            criteria.andEqualTo("rechargeTypeId", rechargeAccountRequest.getRechargeTypeId());
        }
        criteria.andEqualTo("memberId",rechargeAccountRequest.getMemberId());
        //criteria.andGreaterThanOrEqualTo("cardRestMoney",BigDecimalUtils.bigDecimal("1"));
        criteria.andEqualTo("state", 1);
        if (StringUtils.isNotBlank(rechargeAccountRequest.getRechargeTypeName())){
            criteria.andLike("rechargeTypeName", "%" + rechargeAccountRequest.getRechargeTypeName() + "%");
        }

        Example.Criteria c = example.createCriteria();
//        c.andGreaterThan("cardRestMoney",BigDecimalUtils.bigDecimal("0")).orGreaterThan("giftConsumeMoney", BigDecimalUtils.bigDecimal("0"));
        example.and(c);
        List<RechargeAccount> list = dao.selectByExample(example);
        List<RechargeAccount> resultList = new ArrayList<>();
        List<RechargeAccount> resultLists = new ArrayList<>();
//        List<RechargeAccount> rechargeAccountList = new ArrayList<>();
//        Map<Long, List<RechargeAccount>> map = list.stream().collect(Collectors.groupingBy(RechargeAccount::getStoreId));

        Long mdID=null;

        //是否使用有效期
        for (RechargeAccount rechargeAccount : list) {
            if(null == mdID){
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(rechargeAccount.getStoreId());
                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                long asLong = pagesorganizations.stream().filter(baseStores -> null == baseStores.getParentId()).mapToLong(BaseStores::getId).findAny().getAsLong();
                mdID=asLong;
            }
            StoreParament paraments = StoreParaUtils.getStorePara(mdID,Constant.allow_valid);
            if( "1".equals(paraments.getParamentValue())){
                RechargeType rechargeType = new RechargeType();
                rechargeType.setId(rechargeAccount.getRechargeTypeId());
                RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

                try {
                    if(rechargeType1.getUnifiedDue()!=null) {
                        Date d = simpleDateFormat.parse(rechargeType1.getUnifiedDue());
                        if (!d.before(new Date())) {
                            if (null == rechargeAccount.getEndTime()) {
                                resultList.add(rechargeAccount);
                                continue;
                            } else {
//                    if(DateUtils.compare(, rechargeAccount.getEndTime()) > 0){
                                if (new Date().before(rechargeAccount.getEndTime())) {
                                } else {
                                    continue;
                                }
                            }
                        }
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }

                try {
                    if(null == rechargeType1.getUnifiedDue()){
                        resultList.add(rechargeAccount);
                    }else{
                        Date parse = simpleDateFormat.parse(rechargeType1.getUnifiedDue());
                        if(!parse.before(new Date())){
                            resultList.add(rechargeAccount);
                        }
                    }

                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }else{
                resultList.add(rechargeAccount);
            }
        }

        int a=0;
//        for (RechargeAccount parament : resultList) {
//            RechargeType rechargeType = new RechargeType();
//            rechargeType.setId(parament.getRechargeTypeId());
//            RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
//            parament.setRechargeTypeNum(rechargeType1.getRechargeTypeNum());
//            //判断是否是促销卡
//            if(rechargeType1.getType()==2){
//                //查询是否有设置过仅限门店使用的赠卡
//                Example example1 = new Example(RechargeAccountGive.class);
//                Example.Criteria criteria1 = example1.createCriteria();
//                criteria1.andEqualTo("accountId",parament.getId());
//                criteria1.andEqualTo("memberId",parament.getMemberId());
//                //查询原账户的赠送金额
//                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example1);
//
//                BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
//                for(RechargeAccountGive rechargeAccountGive:List){
//                    if(rechargeAccountGive.getStoreId().hashCode()!=rechargeAccountRequest.getStoreId().hashCode())
//                        giftConsumeMoneyGive=giftConsumeMoneyGive.add(rechargeAccountGive.getGiftConsumeMoney());
//                }
//
//                if(rechargeAccountRequest.getSelectType()==null||rechargeAccountRequest.getSelectType()!=1){
//                    //原账户赠送可用金额-不是本门店赠送金额=本门店可用的赠送金额
//                    parament.setCardGiftMoney(parament.getCardGiftMoney().subtract(giftConsumeMoneyGive));
//                    parament.setGiftConsumeMoney(parament.getGiftConsumeMoney().subtract(giftConsumeMoneyGive));
//                }
//            }
//            resultLists.add(parament);
//
//            a++;
//        }
        List<RechargeAccount> collect = resultList.stream()
                .filter(item -> item.getCardRestMoney().
                        add(item.getCardGiftMoney()).compareTo(new BigDecimal("0")) > 0).collect(Collectors.toList());
        for (RechargeAccount rechargeAccount : collect) {
            RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
            rechargeAccountGive.setAccountId(rechargeAccount.getId());
            List<RechargeAccountGive> select = ssmRechargeAccountGiveDao.select(rechargeAccountGive);
            List<RechargeAccountGive> collect1 = select.stream().filter(item -> item.getGiftConsumeMoney().compareTo(BigDecimal.valueOf(0)) > 0).collect(Collectors.toList());
            rechargeAccount.setRechargeAccountGiveList(collect1);
        }
        return collect;
    }


    @Override
    public List<RechargeAccount> cashSelectListall(RechargeAccountRequest rechargeAccountRequest) throws SmsException {
        List<RechargeAccount> lists = new ArrayList<>();

        //总店
        BaseStores stores=new BaseStores();
        List<Long> storeIdList= new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(rechargeAccountRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null ==pagesorganization.getParentId()){
                stores=pagesorganization;
            }
            storeIdList.add(pagesorganization.getId());
        }
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
//        if (null != rechargeAccountRequest.getStoreId()) {
//            criteria.andEqualTo("storeId", rechargeAccountRequest.getStoreId());
//        }
        criteria.andIn("storeId", storeIdList);
        if (null != rechargeAccountRequest.getRechargeTypeId()){
            criteria.andEqualTo("rechargeTypeId", rechargeAccountRequest.getRechargeTypeId());
        }
        criteria.andEqualTo("memberId",rechargeAccountRequest.getMemberId());
        if (StringUtils.isNotBlank(rechargeAccountRequest.getRechargeTypeName())){
            criteria.andLike("rechargeTypeName", "%" + rechargeAccountRequest.getRechargeTypeName() + "%");
        }
        List<RechargeAccount> list = dao.selectByExample(example);
        for (RechargeAccount parament : list) {
            RechargeType rechargeType = new RechargeType();
            rechargeType.setId(parament.getRechargeTypeId());
            RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
            parament.setRechargeTypeNum(rechargeType1.getRechargeTypeNum());
        }
        Long mdID = null;
        //判断是否设置了有效期
        List<RechargeAccount> list2 = new ArrayList<>();
        for (RechargeAccount rechargeAccount : list) {
            if(null == mdID){
                StoreRequest storeRequests = new StoreRequest();
                storeRequests.setId(rechargeAccount.getStoreId());
                List<BaseStores> pagesorganizations1 = ssmBaseStoreService.pagesorganizations(storeRequests);
                long asLong = pagesorganizations1.stream().filter(baseStores -> null == baseStores.getParentId()).mapToLong(BaseStores::getId).findAny().getAsLong();
                mdID=asLong;
            }
            StoreParament paramentz = StoreParaUtils.getStorePara(mdID, Constant.allow_valid);
            if ("1".equals(paramentz.getParamentValue())){
                RechargeType rechargeType = new RechargeType();
                rechargeType.setId(rechargeAccount.getRechargeTypeId());
                RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date=null;

                if(null == rechargeType1.getUnifiedDue()){
                    if(null !=rechargeAccount.getEndTime()){
                        if(rechargeAccount.getEndTime().before(new Date()) || (rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1&&rechargeAccount.getGiftConsumeMoney().compareTo(BigDecimal.valueOf(0))!=1)){
                            list2.add(rechargeAccount);
                        }
                    }else{
                        if(rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1&&rechargeAccount.getGiftConsumeMoney().compareTo(BigDecimal.valueOf(0))!=1){
                            list2.add(rechargeAccount);
                        }
                    }
                }else{
                    try {
                        date = format.parse(rechargeType1.getUnifiedDue());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if(null !=rechargeAccount.getEndTime()){
                        if(rechargeAccount.getEndTime().before(new Date())|| date.before(new Date()) || (rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1&&rechargeAccount.getGiftConsumeMoney().compareTo(BigDecimal.valueOf(0))!=1)){
                            list2.add(rechargeAccount);
                        }
                    }else{
                        if((rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1&&rechargeAccount.getGiftConsumeMoney().compareTo(BigDecimal.valueOf(0))!=1)||date.before(new Date())){
                            list2.add(rechargeAccount);
                        }
                    }
                }
            }else{
                if(rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1&&rechargeAccount.getGiftConsumeMoney().compareTo(BigDecimal.valueOf(0))!=1){
                    list2.add(rechargeAccount);
                }
            }
        }
        return list2;
    }


    @Override
    public List<RechargeAccount> delay(RechargeAccountRequest rechargeAccountRequest) throws SmsException {
        List<RechargeAccount> lists = new ArrayList<>();

        //总店
        BaseStores stores=new BaseStores();
        List<Long> storeIdList= new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(rechargeAccountRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null ==pagesorganization.getParentId()){
                stores=pagesorganization;
            }
            storeIdList.add(pagesorganization.getId());
        }
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
//        if (null != rechargeAccountRequest.getStoreId()) {
//            criteria.andEqualTo("storeId", rechargeAccountRequest.getStoreId());
//        }
        criteria.andIn("storeId", storeIdList);
        if (null != rechargeAccountRequest.getRechargeTypeId()){
            criteria.andEqualTo("rechargeTypeId", rechargeAccountRequest.getRechargeTypeId());
        }
        criteria.andEqualTo("memberId",rechargeAccountRequest.getMemberId());
        if (StringUtils.isNotBlank(rechargeAccountRequest.getRechargeTypeName())){
            criteria.andLike("rechargeTypeName", "%" + rechargeAccountRequest.getRechargeTypeName() + "%");
        }
        List<RechargeAccount> list = dao.selectByExample(example);
        for (RechargeAccount parament : list) {
            RechargeType rechargeType = new RechargeType();
            rechargeType.setId(parament.getRechargeTypeId());
            RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
            parament.setRechargeTypeNum(rechargeType1.getRechargeTypeNum());
        }
        Long mdID = null;
        //判断是否设置了有效期
        List<RechargeAccount> list2 = new ArrayList<>();
        for (RechargeAccount rechargeAccount : list) {
            if(null == mdID){
                StoreRequest storeRequests = new StoreRequest();
                storeRequests.setId(rechargeAccount.getStoreId());
                List<BaseStores> pagesorganizations1 = ssmBaseStoreService.pagesorganizations(storeRequests);
                long asLong = pagesorganizations1.stream().filter(baseStores -> null == baseStores.getParentId()).mapToLong(BaseStores::getId).findAny().getAsLong();
                mdID=asLong;
            }
            StoreParament paramentz = StoreParaUtils.getStorePara(mdID, Constant.allow_valid);
            if ("1".equals(paramentz.getParamentValue())){
                RechargeType rechargeType = new RechargeType();
                rechargeType.setId(rechargeAccount.getRechargeTypeId());
                RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date=null;

                if(null == rechargeType1.getUnifiedDue()){
                    if(null !=rechargeAccount.getEndTime()){
                        //|| rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1
                        if(rechargeAccount.getEndTime().before(new Date()) ){
                            list2.add(rechargeAccount);
                        }
                    }else{
                        //if(rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1){
                            //list2.add(rechargeAccount);
                       //}
                    }
                }else{
                    try {
                        date = format.parse(rechargeType1.getUnifiedDue());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if(null !=rechargeAccount.getEndTime()){
                        //|| rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1
                        if(rechargeAccount.getEndTime().before(new Date())|| date.before(new Date()) ){
                            list2.add(rechargeAccount);
                        }
                    }else{
                        //if(rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1){
                            //list2.add(rechargeAccount);
                        //}
                    }
                }
            }else{
                //if(rechargeAccount.getCardRestMoney().compareTo(BigDecimal.valueOf(0))!=1){
                    //list2.add(rechargeAccount);
                //}
            }
        }
        return list2;
    }


    @Override
    public List<RechargeAccount> newcashSelectList(RechargeAccountRequest rechargeAccountRequest) {
        Example example = new Example(RechargeAccount.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != rechargeAccountRequest.getStoreId()) {
            criteria.andEqualTo("storeId", rechargeAccountRequest.getStoreId());
        }
        if (null != rechargeAccountRequest.getStoreIdl()){
            criteria.andIn("storeId",rechargeAccountRequest.getStoreIdl());
        }
        if (null != rechargeAccountRequest.getRechargeTypeId()){
            criteria.andEqualTo("rechargeTypeId", rechargeAccountRequest.getRechargeTypeId());
        }
        criteria.andEqualTo("memberId",rechargeAccountRequest.getMemberId());
        criteria.andGreaterThanOrEqualTo("cardConsumeMoney",BigDecimalUtils.bigDecimal("1"));
        criteria.andEqualTo("state", 1);
        if (StringUtils.isNotBlank(rechargeAccountRequest.getRechargeTypeName())){
            criteria.andLike("rechargeTypeName", "%" + rechargeAccountRequest.getRechargeTypeName() + "%");
        }
        Example.Criteria c = example.createCriteria();
        c.andGreaterThan("cardConsumeMoney",BigDecimalUtils.bigDecimal("1")).orGreaterThan("giftConsumeMoney", BigDecimalUtils.bigDecimal("0"));
        example.and(c);
        List<RechargeAccount> list = dao.selectByExample(example);
        List<RechargeAccount> resultList = new ArrayList<>();
        List<RechargeAccount> rechargeAccountList = new ArrayList<>();
        Map<Long, List<RechargeAccount>> map = list.stream().collect(Collectors.groupingBy(RechargeAccount::getStoreId));
        //是否使用有效期
        List<StoreParament> paraments = StoreParaUtils.getPara(Constant.allow_valid);
        for (StoreParament parament : paraments) {
            rechargeAccountList = map.get(parament.getStoreId());
            Long StoreId=null;
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(parament.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    StoreId=pagesorganization.getId();
                }
            }
            if(StoreId==null){
                StoreId = parament.getStoreId();
            }
            StoreParament paramentz = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
            //充值账户所属门店存在使用有效期参数
            if (null != rechargeAccountList && rechargeAccountList.size() > 0 && "1".equals(paramentz.getParamentValue())){
                //过滤
                rechargeAccountList = rechargeAccountList.stream().filter(rechargeAccount ->null == rechargeAccount.getEndTime() || new Date().before(rechargeAccount.getEndTime())).collect(Collectors.toList());
            }
            if (null != rechargeAccountList){
                resultList.addAll(rechargeAccountList);
            }else {
                continue;
            }
        }
        return resultList;
    }



    @Override
    public RechargeAccount selectOne(RechargeAccountRequest rechargeAccountRequest) {
        RechargeAccount rechargeAccount = new RechargeAccount();
        //rechargeAccount.setStoreId(rechargeAccountRequest.getStoreId());
        rechargeAccount.setMemberId(rechargeAccountRequest.getMemberId());
        rechargeAccount.setRechargeTypeId(rechargeAccountRequest.getRechargeTypeId());
        rechargeAccount.setState(1);
        rechargeAccount = dao.selectOne(rechargeAccount);
        if (null != rechargeAccount) { 
            //是否使用有效期
            Long StoreId=null;
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(rechargeAccountRequest.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    StoreId=pagesorganization.getId();
                }
            }
            StoreParament parament = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);

            if ("1".equals(parament.getParamentValue())) {
                if (null != rechargeAccount.getEndTime()) {
                    //对比时间
                    if (new Date().after(rechargeAccount.getEndTime())) {
                        //到期将账户彻底锁定
                        this.updateState(rechargeAccount.getId(), 0);
                        return null;
                    }
                }else {
                    //到期时间为null 即开始不限制有效期 后面修改门店参数添加有限期 此时直接续充 更新账户有效期
                    return rechargeAccount;
                }
            }
        }
        return rechargeAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addRechargeAccount(RechargeAccount rechargeAccount) throws SmsException {
        int i = 0;
        try {
            i = dao.saveNotNull(rechargeAccount);

        }catch (Exception e){
            log.error("SsmRechargeAccountServiceImpl.addRechargeAccount:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayRechargeAccount(RepayAccountListRequest repayAccountListRequest,RepayTradeRequest repayTradeRequest,RepayList repayList) throws SmsException {
        int i = 0;
        RechargeAccount rechargeAccount1 = new RechargeAccount();
        rechargeAccount1.setId(repayAccountListRequest.getAccountId());
        RechargeAccount rechargeAccount2 = dao.selectByPrimaryKey(rechargeAccount1.getId());
        if(rechargeAccount2.getCardConsumeMoney().compareTo(repayAccountListRequest.getPayMoney())==-1){
            throw new SmsException(ResponseCode.MSG,"充值卡可用金额不足");
        }
        rechargeAccount2.setCardRestMoney(rechargeAccount2.getCardRestMoney().subtract(repayAccountListRequest.getPayMoney()));
        rechargeAccount2.setCardConsumeMoney(rechargeAccount2.getCardConsumeMoney().subtract(repayAccountListRequest.getPayMoney()));
        i = dao.updateByPrimaryKeySelective(rechargeAccount2);
        if(i==0){
            throw new SmsException(ResponseCode.MSG,"扣除卡剩余金额异常");
        }
        AccountTradeRecord tradeRecord = this.setAccountTradeRecord(rechargeAccount2, repayAccountListRequest, repayTradeRequest,repayList);
        tradeRecord.setOrderStatu(0);
        ssmAccountTradeRecordService.addRecord(tradeRecord);
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int cancelRepayRechargeAccount(RepayAccountListRequest repayAccountListRequest,RepayTradeRequest repayTradeRequest,RepayList repayList) throws SmsException {
        int i = 0;
        RechargeAccount rechargeAccount1 = new RechargeAccount();
        rechargeAccount1.setId(repayAccountListRequest.getAccountId());
        RechargeAccount rechargeAccount2 = dao.selectByPrimaryKey(rechargeAccount1.getId());
        rechargeAccount2.setCardRestMoney(rechargeAccount2.getCardRestMoney().add(repayAccountListRequest.getPayMoney()));
        rechargeAccount2.setCardConsumeMoney(rechargeAccount2.getCardConsumeMoney().add(repayAccountListRequest.getPayMoney()));
        i = dao.updateByPrimaryKeySelective(rechargeAccount2);
        if(i==0){
            throw new SmsException(ResponseCode.MSG,"返回卡剩余金额异常");
        }
        AccountTradeRecord tradeRecord = this.setAccountTradeRecord(rechargeAccount2, repayAccountListRequest, repayTradeRequest,repayList);
        tradeRecord.setOrderStatu(1);
        ssmAccountTradeRecordService.addRecord(tradeRecord);
        return i;
    }

    public AccountTradeRecord setAccountTradeRecord(RechargeAccount rechargeAccount,RepayAccountListRequest repayAccountListRequest,RepayTradeRequest repayTradeRequest,RepayList repayList){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeRequest.getStoreName());
        accountTradeRecord.setMemberId(repayTradeRequest.getMemberId());
        accountTradeRecord.setMemberName(repayTradeRequest.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeRequest.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeRequest.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(repayList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.recharge_pay_Repay);
            accountTradeRecord.setAccountSpendMoney(repayAccountListRequest.getPayMoney());
            accountTradeRecord.setAccountGiftSpendMoney(BigDecimal.valueOf(0));
            accountTradeRecord.setInputDate(new Date());
            accountTradeRecord.setInputBy(repayList.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.recharge_pay_Repay_cancel);
            accountTradeRecord.setAccountInMoney(repayAccountListRequest.getPayMoney());
            accountTradeRecord.setInputDate(repayList.getCancelDate());
            accountTradeRecord.setInputBy(repayList.getCancelBy());
            accountTradeRecord.setAccountGiftSpendMoney(BigDecimal.valueOf(0));
        }
        accountTradeRecord.setDocId(repayList.getId());
        accountTradeRecord.setDocNum(repayList.getRepayNum());
        accountTradeRecord.setDocType(Constant.doc_type_repay);
        accountTradeRecord.setTradeId(repayTradeRequest.getTradeId());
        accountTradeRecord.setTradeName(repayTradeRequest.getTradeName());
        accountTradeRecord.setTradeMoney(repayTradeRequest.getDebtMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setDebtMoney(BigDecimal.valueOf(0));
        accountTradeRecord.setPrice(repayTradeRequest.getDebtMoney());

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

    @Override
    public RechargeAccount setRechargeAccount(RechargeType rechargeType, RechargeList rechargeList, RechargeAccount rechargeAccount, StoreParament storeParament) {
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");

//        //赠送金额可用利率 = 实际充值金额/标准充值金额*充值金额可用比率
//        BigDecimal giftConsumeRito = BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(),rechargeType.getRechargeMoney()),consumeRito);
        BigDecimal consumeMoney = BigDecimalUtils.bigDecimal("0");
        BigDecimal cardGiftConsumeMoney = BigDecimalUtils.bigDecimal("0");
        BigDecimal cardMoney = BigDecimalUtils.bigDecimal("0");
        BigDecimal cardGiftMoney = BigDecimalUtils.bigDecimal("0");
        //有欠款 赠送金额为0
        if (rechargeList.getIsDebt() == 1) {
            //充值金额可用比率 = 门店参数/100
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
            consumeMoney = BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),consumeRito);
            cardMoney = rechargeList.getCollectionAmount();
//            if (rechargeType.getType() == 0) {
//                cardGiftConsumeMoney = BigDecimalUtils.multiply(rechargeType.getGiftMoney(), giftConsumeRito);
//            }
        }else {
            if (rechargeType.getType() == 0) {//赠送卡
                consumeMoney = rechargeList.getCollectionAmount();
                cardMoney = rechargeList.getCollectionAmount();
                if(rechargeType.getDonateType()==0){
                    cardGiftConsumeMoney = rechargeType.getGiftMoney();
                    cardGiftMoney = rechargeType.getGiftMoney();
                }else{
                    BigDecimal CZconsumeRito = BigDecimalUtils.div(rechargeType.getGiftMoney(),hundredBd);
                    cardGiftConsumeMoney = cardMoney.multiply(CZconsumeRito);
                    cardGiftMoney = cardMoney.multiply(CZconsumeRito);
                }

            } else  if (rechargeType.getType() == 1){//折扣卡
                consumeMoney = rechargeList.getCollectionAmount();
                cardMoney = rechargeList.getCollectionAmount();
            }else  if (rechargeType.getType() == 2) {//活动卡
                consumeMoney = rechargeList.getCollectionAmount();
                cardMoney = rechargeList.getCollectionAmount();
                if(rechargeType.getDonateType()==0){
                    cardGiftConsumeMoney = rechargeType.getGiftMoney();
                    cardGiftMoney = rechargeType.getGiftMoney();
                }else{
                    BigDecimal CZconsumeRito = BigDecimalUtils.div(rechargeType.getGiftMoney(),hundredBd);
                    cardGiftConsumeMoney = cardMoney.multiply(CZconsumeRito);
                    cardGiftMoney = cardMoney.multiply(CZconsumeRito);
                }

            }
        }
//        if (rechargeType.getType() == 0) {
//            //查询赠送卡使用类别参数
//            StoreParament storeParament1 = this.getStorePara(rechargeList.getStoreId(),"useRecharge");
//            //赠送卡金额和充值金额统一使用(无赠送金额) 其他两种方式有赠送金额
//            if ("0".equals(storeParament1.getParamentValue())){
//                rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
//                rechargeAccount.setCardGiftMoney(rechargeType.getGiftMoney());
//            }else {
//                rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
//                rechargeAccount.setCardGiftMoney(rechargeType.getGiftMoney());
//            }
//            rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
//            rechargeAccount.setCardGiftMoney(rechargeType.getGiftMoney());
//            rechargeAccount.setCardConsumeMoney(consumeMoney);
//            rechargeAccount.setGiftConsumeMoney(cardGiftConsumeMoney);
//        }else {//赠送金额置0
//            rechargeAccount.setCardGiftMoney(BigDecimalUtils.bigDecimal("0"));
//            rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.bigDecimal("0"));
//            rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
//            rechargeAccount.setCardConsumeMoney(consumeMoney);
//        }
        rechargeAccount.setCardRestMoney(cardMoney);
        rechargeAccount.setCardGiftMoney(cardGiftMoney);
        rechargeAccount.setCardConsumeMoney(consumeMoney);
        rechargeAccount.setGiftConsumeMoney(cardGiftConsumeMoney);
        rechargeAccount.setDiscount(rechargeType.getDiscount());
        rechargeAccount.setDiscountFreeAmount(rechargeType.getDiscountFreeAmount());
        rechargeAccount.setCardRechargeMoney(rechargeType.getRechargeMoney());
//        rechargeAccount.setRechargeBl(rechargeAccount.getCardRestMoney().divide(rechargeAccount.getCardRestMoney().add(rechargeAccount.getCardGiftMoney())));
//        rechargeAccount.setFreeOf(rechargeAccount.getCardGiftMoney().divide(rechargeAccount.getCardRestMoney().add(rechargeAccount.getCardGiftMoney())));
        //是否使用有效期
        Long StoreId=null;
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(rechargeList.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                StoreId=pagesorganization.getId();
            }
        }
        StoreParament parament = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            if (rechargeList.getIsAddition() == 1){
                date = rechargeList.getAdditionDate();
            }


            if(null != rechargeType.getValidTime()&&0!=rechargeType.getValidTime()){
                Calendar c = Calendar.getInstance();
                c.setTime(date);
                c.set(Calendar.MONTH, c.get(Calendar.MONTH) + rechargeType.getValidTime());
                Date time = c.getTime();
                rechargeAccount.setEndTime(time);
            }else{
                rechargeAccount.setEndTime(null);
            }

        }else{
            rechargeAccount.setEndTime(null);
        }
        rechargeAccount.setType(rechargeType.getType());
        rechargeAccount.setState(1);

        //判断是否促销卡，是否是限制门店使用
        if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
            RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
            BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
            rechargeAccountGive.setAccountId(rechargeAccount.getId());
            rechargeAccountGive.setRechargeDate(rechargeList.getRechargeDate());
            ssmRechargeAccountGiveDao.insert(rechargeAccountGive);
        }
        return rechargeAccount;
    }

//    /**
//     * 首充
//     * @param rechargeType
//     * @param rechargeList
//     * @param rechargeAccount
//     * @param storeParament
//     * @return
//     */
//    @Override
//    public RechargeAccount setRechargeAccountyunxi(RechargeType rechargeType, RechargeList rechargeList, RechargeAccount rechargeAccount, StoreParament storeParament) {
//        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
//
////        //赠送金额可用利率 = 实际充值金额/标准充值金额*充值金额可用比率
////        BigDecimal giftConsumeRito = BigDecimalUtils.multiply(BigDecimalUtils.div(rechargeList.getCollectionAmount(),rechargeType.getRechargeMoney()),consumeRito);
//        BigDecimal consumeMoney = BigDecimalUtils.bigDecimal("0");
//        BigDecimal cardGiftConsumeMoney = BigDecimalUtils.bigDecimal("0");
//        BigDecimal cardMoney = BigDecimalUtils.bigDecimal("0");
//        BigDecimal cardGiftMoney = BigDecimalUtils.bigDecimal("0");
//        //有欠款 赠送金额为0
//        if (rechargeList.getIsDebt() == 1) {
//            //充值金额可用比率 = 门店参数/100
//            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
//            consumeMoney = BigDecimalUtils.multiply(rechargeList.getCollectionAmount(),consumeRito);
//            cardMoney = rechargeList.getCollectionAmount();
////            if (rechargeType.getType() == 0) {
////                cardGiftConsumeMoney = BigDecimalUtils.multiply(rechargeType.getGiftMoney(), giftConsumeRito);
////            }
//        }else {
//            if (rechargeType.getType() == 0) {//赠送卡
//                consumeMoney = rechargeList.getCollectionAmount();
//                cardMoney = rechargeList.getCollectionAmount();
//                cardGiftConsumeMoney = rechargeType.getGiftMoney();
//                cardGiftMoney = rechargeType.getGiftMoney();
//            } else {//折扣卡
//                consumeMoney = rechargeList.getCollectionAmount();
//                cardMoney = rechargeList.getCollectionAmount();
//            }
//        }
////        if (rechargeType.getType() == 0) {
////            //查询赠送卡使用类别参数
////            StoreParament storeParament1 = this.getStorePara(rechargeList.getStoreId(),"useRecharge");
////            //赠送卡金额和充值金额统一使用(无赠送金额) 其他两种方式有赠送金额
////            if ("0".equals(storeParament1.getParamentValue())){
////                rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
////                rechargeAccount.setCardGiftMoney(rechargeType.getGiftMoney());
////            }else {
////                rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
////                rechargeAccount.setCardGiftMoney(rechargeType.getGiftMoney());
////            }
////            rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
////            rechargeAccount.setCardGiftMoney(rechargeType.getGiftMoney());
////            rechargeAccount.setCardConsumeMoney(consumeMoney);
////            rechargeAccount.setGiftConsumeMoney(cardGiftConsumeMoney);
////        }else {//赠送金额置0
////            rechargeAccount.setCardGiftMoney(BigDecimalUtils.bigDecimal("0"));
////            rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.bigDecimal("0"));
////            rechargeAccount.setCardRestMoney(rechargeList.getCollectionAmount());
////            rechargeAccount.setCardConsumeMoney(consumeMoney);
////        }
//        rechargeAccount.setCardRestMoney(cardMoney);
//        rechargeAccount.setCardGiftMoney(cardGiftMoney);
//        rechargeAccount.setCardConsumeMoney(consumeMoney);
//        rechargeAccount.setGiftConsumeMoney(cardGiftConsumeMoney);
//        rechargeAccount.setDiscount(rechargeType.getDiscount());
//        rechargeAccount.setCardRechargeMoney(rechargeType.getRechargeMoney());
//        //是否使用有效期
//        StoreParament parament = StoreParaUtils.getStorePara(rechargeList.getStoreId(), Constant.allow_valid);
//        if ("1".equals(parament.getParamentValue())) {
//            Date date = new Date();
//            if (rechargeList.getIsAddition() == 1){
//                date = rechargeList.getAdditionDate();
//            }
//            rechargeAccount.setEndTime(DateUtils.diffMonth(date, rechargeType.getValidTime()));
//        }
//        rechargeAccount.setType(rechargeType.getType());
//        rechargeAccount.setState(1);
//        return rechargeAccount;
//    }

    @Override
    public RechargeAccount addMoney(RechargeAccount rechargeAccount, RechargeList rechargeList, RechargeType rechargeType, StoreParament storeParament) throws SmsException {
        BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
        BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
        BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
        BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        BigDecimal addMoneyBd = rechargeList.getCollectionAmount();
        BigDecimal addGiftMoneyBd = rechargeType.getGiftMoney();
        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");


        //存在欠款
        if (rechargeList.getIsDebt() == 1){
            //充值金额可用比率 = 门店参数/100
            BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
            cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney, BigDecimalUtils.multiply(addMoneyBd, consumeRito));
            cardRestMoney = BigDecimalUtils.add(cardRestMoney, addMoneyBd);
        }else {
            cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney, addMoneyBd);
            cardRestMoney = BigDecimalUtils.add(cardRestMoney,addMoneyBd);
            if (rechargeType.getType() == 0) {
                if(rechargeType.getDonateType()==0){
                    giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, addGiftMoneyBd);
                    cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, addGiftMoneyBd);
                }else{
                    BigDecimal CZconsumeRito = BigDecimalUtils.div(addGiftMoneyBd,hundredBd);
                    giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, CZconsumeRito.multiply(addMoneyBd));
                    cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, CZconsumeRito.multiply(addMoneyBd));
                }

            }
            if (rechargeType.getType() == 2) {
                if(rechargeType.getDonateType()==0){
                    giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, addGiftMoneyBd);
                    cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, addGiftMoneyBd);
                    giftConsumeMoneyGive=addGiftMoneyBd;
                }else{
                    BigDecimal CZconsumeRito = BigDecimalUtils.div(addGiftMoneyBd,hundredBd);
                    giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, CZconsumeRito.multiply(addMoneyBd));
                    cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, CZconsumeRito.multiply(addMoneyBd));
                    giftConsumeMoneyGive=CZconsumeRito.multiply(addMoneyBd);
                }

            }
        }
        rechargeAccount.setCardRestMoney(cardRestMoney);
        rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
        rechargeAccount.setCardGiftMoney(cardGiftMoney);
        rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
        rechargeAccount.setDiscountFreeAmount(rechargeType.getDiscountFreeAmount());
        rechargeAccount.setCardRechargeMoney(rechargeType.getRechargeMoney());
//        rechargeAccount.setRechargeBl(rechargeAccount.getCardRestMoney().divide(rechargeAccount.getCardRestMoney().add(rechargeAccount.getCardGiftMoney())));
//        rechargeAccount.setFreeOf(rechargeAccount.getCardGiftMoney().divide(rechargeAccount.getCardRestMoney().add(rechargeAccount.getCardGiftMoney())));

        Long StoreId=null;
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(rechargeList.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                StoreId=pagesorganization.getId();
            }
        }
        //是否使用有效期
        StoreParament parament = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
        if ("1".equals(parament.getParamentValue())) {
            Date date = new Date();
            //账户到期选择充值类别的时候会将账户锁定 不在使用 会重新充值一个新账户 所以续充账户不会以到期时间为开始时间计算到期时间
//            if (rechargeList.getIsAddition() == 1){
//                if (DateUtils.compare(rechargeList.getAdditionDate(), rechargeAccount.getEndTime()) >= 0){
//                    date = rechargeList.getAdditionDate();
//                }else {
//                    date = rechargeAccount.getEndTime();
//                }
//            }else {
//                if (DateUtils.compare(rechargeList.getRechargeDate(), rechargeAccount.getEndTime()) >= 0){
//                    date = rechargeAccount.getEndTime();
//                }else {
//                    date = rechargeList.getRechargeDate();
//                }
//            }
            if(rechargeList.getIsAddition() ==1){
                date = rechargeList.getAdditionDate();
            }else {
                date = rechargeList.getRechargeDate();
            }

            if(null != rechargeType.getValidTime()){
                Calendar c = Calendar.getInstance();
                c.setTime(date);
                c.set(Calendar.MONTH, c.get(Calendar.MONTH) + rechargeType.getValidTime());
                Date time = c.getTime();

                //Date endTime = DateUtils.diffMonth(date, rechargeType.getValidTime());
                //原账户结束时间比现在计算的结束时间大 结束时间以原账户结束时间赋值  <=计算的结束时间 结束时间以计算的结束时间进行赋值
                if(null != rechargeAccount.getEndTime()&&0!=rechargeType.getValidTime()){
                    if (DateUtils.compare(time,rechargeAccount.getEndTime()) <= 0){
                        rechargeAccount.setEndTime(time);
                    }
                }else{
                    rechargeAccount.setEndTime(null);
                }
            }else{
                rechargeAccount.setEndTime(null);
            }


        }
        //判断是否促销卡，是否是限制门店使用
        if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
            RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
            BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
            rechargeAccountGive.setAccountId(rechargeAccount.getId());
            rechargeAccountGive.setStoreId(rechargeList.getStoreId());
            rechargeAccountGive.setStoreName(rechargeList.getStoreName());
            rechargeAccountGive.setRechargeDate(rechargeList.getRechargeDate());
            Example example = new Example(RechargeAccountGive.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
            criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
            criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
            //查询原账户的赠送金额
            List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
            if(List.size()==0){
                rechargeAccountGive.setGiftConsumeMoney(giftConsumeMoneyGive);
                ssmRechargeAccountGiveDao.insert(rechargeAccountGive);
            }else{
                rechargeAccountGive=List.get(0);
                //原账户赠送金额+本单充值赠送金额
                rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().add(giftConsumeMoneyGive));
                ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
            }
        }
       this.addMoney(rechargeAccount);
        return rechargeAccount;
    }

    @Transactional(rollbackFor=Exception.class)
    public RechargeAccount addMoney(RechargeAccount rechargeAccount) throws SmsException {
        try {
            dao.updateByPrimaryKey(rechargeAccount);
        }catch (Exception e){
            log.error("SsmRechargeAccountServiceImpl.addMoney:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return rechargeAccount;
    }

    @Transactional(rollbackFor=Exception.class)
    public RechargeAccount addMoneyGrouponCard(RechargeAccount rechargeAccount) throws SmsException {
        try {
            dao.updateByPrimaryKey(rechargeAccount);
        }catch (Exception e){
            log.error("SsmRechargeAccountServiceImpl.addMoney:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return rechargeAccount;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public RechargeAccount subMoney(RechargeAccount rechargeAccount, RechargeList rechargeList,RechargeType rechargeType) throws SmsException {
        BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
        BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();

        BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
        BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
        BigDecimal cardConsumeMoney1 = rechargeAccount.getCardConsumeMoney();
        BigDecimal giftConsumeMoney1 = rechargeAccount.getGiftConsumeMoney();

        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        if(rechargeList.getLiftType()==0){//正常充值
            //剩余金额和赠品剩余金额拿(账户当前金额-作废单据实际支付金额)
            rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(), rechargeList.getCollectionAmount()));


            //存在欠款
            if (rechargeList.getIsDebt() == 1){

                DebtList refundDebtList = new DebtList();
                refundDebtList.setDocId(rechargeList.getId());
                DebtList debtList = ssmDebtService.selectOne(refundDebtList);
                if(debtList.getState() == 1 ){
                    throw new SmsException(ResponseCode.MSG,"该单据已经还款，请先作废还款");
                }

                //充值有欠款可消费比率参数
                StoreParament storeParament = StoreParaUtils.getStorePara(rechargeType.getStoreId(),Constant.rec_debt_usable);
                //充值金额可用比率 = 订单存的可用比例/100
                BigDecimal consumeRito=BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
                if(rechargeList.getStoreRecDebtUsable()!=null){
                     consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(rechargeList.getStoreRecDebtUsable()),hundredBd);
                }
                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,BigDecimalUtils.multiply(consumeRito,rechargeList.getCollectionAmount()));
            }else {


                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,rechargeList.getCollectionAmount());
                if (rechargeAccount.getType() == 0 || rechargeAccount.getType() == 2 ){
                    if(rechargeType.getDonateType()==0){
                        giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, rechargeType.getGiftMoney());
                        giftConsumeMoneyGive=rechargeType.getGiftMoney();
                    }else{
                        BigDecimal div = BigDecimalUtils.div(rechargeType.getGiftMoney(), hundredBd);
                        giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, rechargeList.getCollectionAmount().multiply(div));
                        giftConsumeMoneyGive=rechargeList.getCollectionAmount().multiply(div);

                    }
                }

                //账户当前赠送卡赠送金额-本条作废单据的赠送金额
                rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(), giftConsumeMoneyGive));
            }
            rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccount.setCardNum(rechargeAccount.getCardNum()-1);

            //是否使用有效期
            Long StoreId=null;
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(rechargeList.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    StoreId=pagesorganization.getId();
                }
            }
            StoreParament parament = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
            if ("1".equals(parament.getParamentValue())) {
                //rechargeAccount.setEndTime(DateUtils.diffMonth(rechargeAccount.getEndTime(), -rechargeType.getValidTime()));
            }
            rechargeAccount.getCardRestMoney();
            this.volidAccount(rechargeAccount);
            this.subMoney(rechargeAccount);
            //判断是否促销卡，是否是限制门店使用
            if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                rechargeAccountGive.setAccountId(rechargeAccount.getId());
                rechargeAccountGive.setStoreId(rechargeList.getStoreId());
                rechargeAccountGive.setStoreName(rechargeList.getStoreName());
                rechargeAccountGive.setRechargeDate(rechargeList.getRechargeDate());
                Example example = new Example(RechargeAccountGive.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                //查询原账户的赠送金额
                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                if(List.size()>0){
                    rechargeAccountGive=List.get(0);
                    //原账户赠送金额-本单充值赠送金额
                    giftConsumeMoneyGive=BigDecimalUtils.subtract(rechargeAccountGive.getGiftConsumeMoney(), giftConsumeMoneyGive);
                    rechargeAccountGive.setGiftConsumeMoney(giftConsumeMoneyGive);
                    ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                }
            }

            return rechargeAccount;
        }else{//升降级充值
            //剩余金额和赠品剩余金额直接使用单据记录中充值前金额
            //升级前账户金额
            BigDecimal beforeMoney = rechargeList.getBeforeMoney();
            BigDecimal giftBeforeMoney = rechargeList.getGiftBeforeMoney();
            BigDecimal liftMoney = rechargeList.getLiftMoney();
            BigDecimal liftGiftMoney = rechargeList.getLiftGiftMoney();
            //存在欠款
            if (rechargeList.getIsDebt() == 1){

                DebtList refundDebtList = new DebtList();
                refundDebtList.setDocId(rechargeList.getId());
                DebtList debtList = ssmDebtService.selectOne(refundDebtList);
                if(debtList.getState() == 1 ){
                    throw new SmsException(ResponseCode.MSG,"该单据已经还款，请先作废还款");
                }

                //充值有欠款可消费比率参数
                StoreParament storeParament = StoreParaUtils.getStorePara(rechargeType.getStoreId(),Constant.rec_debt_usable);
                //充值金额可用比率 = 订单存的可用比例/100
                BigDecimal consumeRito=BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
                if(rechargeList.getStoreRecDebtUsable()!=null){
                    consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(rechargeList.getStoreRecDebtUsable()),hundredBd);
                }
                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,BigDecimalUtils.add(BigDecimalUtils.multiply(consumeRito,rechargeList.getCollectionAmount()),rechargeList.getLiftMoney()));

            }else {
                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,BigDecimalUtils.add(rechargeList.getCollectionAmount(),rechargeList.getLiftMoney()));
                if (rechargeAccount.getType() == 0 || rechargeAccount.getType() == 2){
                    if(rechargeType.getDonateType()==0){
                        giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, BigDecimalUtils.add(rechargeType.getGiftMoney(),rechargeList.getLiftGiftMoney()));
                        cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney, BigDecimalUtils.add(rechargeType.getGiftMoney(),rechargeList.getLiftGiftMoney()));
                    }else{
                        BigDecimal div = BigDecimalUtils.div(rechargeType.getGiftMoney(), hundredBd);
                        giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney,BigDecimalUtils.add(rechargeList.getCollectionAmount().multiply(div) ,rechargeList.getLiftGiftMoney()));
                        cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney,BigDecimalUtils.add(rechargeList.getCollectionAmount().multiply(div) ,rechargeList.getLiftGiftMoney()));
                    }
                }
            }

//        RechargeAccount beforeAccount = ssmRechargeAccountService.selectOne(rechargeAccount);
            Example example = new Example(RechargeAccount.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("rechargeTypeId",rechargeList.getRawRechargeTypeId());
            //criteria.andEqualTo("storeId",rechargeList.getStoreId());
            criteria.andEqualTo("memberId",rechargeList.getMemberId());
            criteria.andEqualTo("state", 1);
            //是否使用有效期
            Long StoreId=null;
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(rechargeList.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    StoreId=pagesorganization.getId();
                }
            }
//            StoreParament parament = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
//            if ("1".equals(parament.getParamentValue())) {
//                criteria.andGreaterThan("endTime", new Date());
//            }
            List<RechargeAccount> list = dao.selectByExample(example);
            RechargeAccount beforeAccount = list.get(0);

            beforeAccount.setCardRestMoney(beforeAccount.getCardRestMoney().add(liftMoney));
            beforeAccount.setCardConsumeMoney(beforeAccount.getGiftConsumeMoney().add(liftMoney));
            beforeAccount.setCardGiftMoney(beforeAccount.getCardGiftMoney().add(liftGiftMoney));
            beforeAccount.setGiftConsumeMoney(beforeAccount.getGiftConsumeMoney().add(liftGiftMoney));


            //转出卡
            this.subMoney(beforeAccount);

            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.setDocId(rechargeList.getId());
            accountTradeRecord.setDocNum(rechargeList.getRechargeNum());
            if(rechargeList.getLiftType()==1){
                accountTradeRecord.setDocType(Constant.doc_type_recharge_upgrade_out_clance);
            }else{
                accountTradeRecord.setDocType(Constant.doc_type_recharge_demotion_out_clance);
            }
            accountTradeRecord.setIsAddition(rechargeList.getIsAddition());
            accountTradeRecord.setDebtMoney(rechargeList.getDebtMoney());
            accountTradeRecord.setPrice(rechargeList.getRechargeAmount());
            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(liftMoney);
            accountTradeRecord.setCashMoney(rechargeList.getCollectionCashAmount());
            accountTradeRecord.setInputDate(rechargeList.getRechargeDate());
            ssmAccountTradeRecordService.addRecord(accountTradeRecord);

//            rechargeAccount.setCardRestMoney(BigDecimal.valueOf(0));
//            rechargeAccount.setCardGiftMoney(BigDecimal.valueOf(0));
//            rechargeAccount.setCardConsumeMoney(BigDecimal.valueOf(0));
//            rechargeAccount.setGiftConsumeMoney(BigDecimal.valueOf(0));

            //升级卡
//            rechargeAccount.setCardRestMoney(rechargeList.getBeforeMoney().subtract(beforeAccount.getCardRestMoney()));
//            rechargeAccount.setCardConsumeMoney(rechargeList.getBeforeMoney().subtract(beforeAccount.getCardConsumeMoney()));
//            rechargeAccount.setCardGiftMoney(rechargeList.getGiftBeforeMoney().subtract(beforeAccount.getGiftConsumeMoney()));
//            rechargeAccount.setGiftConsumeMoney(rechargeList.getGiftBeforeMoney().subtract(beforeAccount.getGiftConsumeMoney()));
//            rechargeAccount.setRechargeTypeId(rechargeList.getRechargeTypeId());

            rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(rechargeList.getCollectionCashAmount().add(liftMoney)));
            rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney.subtract(liftGiftMoney));
            rechargeAccount.setCardGiftMoney(cardGiftMoney.subtract(liftGiftMoney));
            rechargeAccount.setCardNum(rechargeAccount.getCardNum()-1);
            this.volidAccount(rechargeAccount);
            this.subMoney(rechargeAccount);
            return rechargeAccount;
        }

    }

    @Transactional(rollbackFor=Exception.class)
    @Override
    public RechargeAccount subMoney(RechargeAccount rechargeAccount) throws SmsException {
        try {
            dao.updateByPrimaryKeySelective(rechargeAccount);
        }catch (Exception e){
            log.error("SsmRechargeAccountServiceImpl.subMoney:",e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        return rechargeAccount;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addMoney(List<RechargeAccountRequest> rechargeAccountList, CourseList courseList) throws SmsException {
        int i = 0;

        //查询账户交易记录
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume);
        accountTradeRecordRequest.setInputDate(courseList.getDate());
        accountTradeRecordRequest.setDocId(courseList.getId());
        accountTradeRecordRequest.setStoreId(courseList.getStoreId());
        List<AccountTradeRecord> recordList = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
        for (AccountTradeRecord accountTradeRecord : recordList) {
            RechargeAccount rechargeAccount = dao.selectByPrimaryKey(accountTradeRecord.getAccountId());
            BigDecimal spendMoney  = accountTradeRecord.getAccountSpendMoney();
            BigDecimal giftSpendMoney = accountTradeRecord.getAccountGiftSpendMoney();
            BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
            BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
            BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
            BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();

            if (0 == rechargeAccount.getType()){//赠送卡
                //充值金额与赠送金额按比例使用 或者 先使用充值金额,再使用赠送金额 (存在赠品金额计算)
                cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, giftSpendMoney);
                giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, giftSpendMoney);
                cardRestMoney = BigDecimalUtils.add(cardRestMoney, BigDecimalUtils.subtract(spendMoney, giftSpendMoney));
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney, BigDecimalUtils.subtract(spendMoney, giftSpendMoney));

            }else {//折扣卡
                cardRestMoney = BigDecimalUtils.add(cardRestMoney,spendMoney);
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney,spendMoney);
            }
            rechargeAccount.setCardRestMoney(cardRestMoney);
            rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccount.setLastConsumeTime(new Date());
            try {
                rechargeAccount.setFirstCharge(rechargeAccount.getFirstCharge()-1);
                i = dao.updateByPrimaryKeySelective(rechargeAccount);
            } catch (Exception e) {
                log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0){
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(courseList, rechargeAccount, spendMoney, giftSpendMoney);
                tradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(tradeRecord);

            }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int subMoney(List<RechargeAccountRequest> rechargeAccountList, CourseList courseList) throws SmsException {
        int i = 0;
        //查询门店充值账户使用参数
        StoreParament storeParament = StoreParaUtils.getStorePara(courseList.getStoreId(),Constant.use_recharge);
        //查询充值卡购买疗程是否允许使用赠送金额 是否允许折扣
        StoreParament parament = StoreParaUtils.getStorePara(courseList.getStoreId(),Constant.buycourse);
        BigDecimal subMoney = BigDecimalUtils.bigDecimal("0");
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
            if (rechargeAccountRequest.getSpendMoney()!=null &&rechargeAccountRequest.getSpendMoney().compareTo(BigDecimal.ZERO) == 1) {
                RechargeAccount rechargeAccount = new RechargeAccount();
                RechargeAccount rechargeAccounts = dao.selectByPrimaryKey(rechargeAccountRequest.getId());
                rechargeAccountRequest.setCardRestMoney(rechargeAccounts.getCardRestMoney());
                rechargeAccountRequest.setCardConsumeMoney(rechargeAccounts.getCardConsumeMoney());
                rechargeAccountRequest.setGiftConsumeMoney(rechargeAccounts.getGiftConsumeMoney());
                rechargeAccountRequest.setCardGiftMoney(rechargeAccounts.getCardGiftMoney());
                BeanUtils.copyProperties(rechargeAccountRequest, rechargeAccount);

                subMoney = rechargeAccountRequest.getSpendMoney();
                BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
                BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
                BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
                BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();
                BigDecimal giftSpendMoney = BigDecimalUtils.bigDecimal("0");
                if (0 == rechargeAccount.getType() || 2 == rechargeAccount.getType()) {//赠送卡
                    //不允许使用赠送金额
                    if ("0".equals(parament.getParamentValue())) {
                        cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, subMoney);
                        cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney, subMoney);
                    } else {
                        if ("1".equals(storeParament.getParamentValue())) {//充值金额与赠送金额按比例使用
                            //赠品扣减金额 = 扣减金额 * 赠送金额与充值金额比例
                            BigDecimal giftSubMoney = BigDecimalUtils.multiply(subMoney, BigDecimalUtils.div(cardGiftMoney, cardRestMoney));
                            //正常充值扣减金额
                            BigDecimal cardSubMoney = BigDecimalUtils.subtract(subMoney, giftSubMoney);
                            //赠品扣减后剩余金额
                            BigDecimal giftLeftMoney = BigDecimalUtils.subtract(giftConsumeMoney, giftSubMoney);
                            //赠品扣减后剩余金额 < 0 正常充值金额继续扣减
                            if (BigDecimalUtils.compareTo(giftLeftMoney, BigDecimalUtils.bigDecimal("0")) < 0) {
                                cardRestMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardRestMoney, cardSubMoney), giftLeftMoney);//剩余金额 = 剩余金额-正常充值扣减金额-赠品扣减后剩余金额(-负+正)
                                cardConsumeMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardConsumeMoney, cardSubMoney), giftLeftMoney);//可消费金额 = 可消费金额-正常充值扣减金额-赠品扣减后剩余金额
                                cardGiftMoney = BigDecimalUtils.bigDecimal("0");
                                giftConsumeMoney = BigDecimalUtils.bigDecimal("0");
                                giftSpendMoney = rechargeAccount.getGiftConsumeMoney();
                            } else {
                                cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, cardSubMoney);
                                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney, cardSubMoney);
                                cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney, giftSubMoney);
                                giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, giftSubMoney);
                                giftSpendMoney = giftSubMoney;
                            }

                        } else {
//                    //先使用赠送金额,再使用充值金额
//                    //支付金额 >= 赠送可消费金额
//                    if (BigDecimalUtils.compareTo(subMoney,giftConsumeMoney) >= 0){
//                       BigDecimal leftMoney = BigDecimalUtils.subtract(subMoney,giftConsumeMoney);
//                       cardRestMoney = BigDecimalUtils.subtract(cardRestMoney,leftMoney);
//                       cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,leftMoney);
//                       cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney,giftConsumeMoney);
//                       giftConsumeMoney = BigDecimalUtils.bigDecimal("0");
//                       giftSpendMoney = rechargeAccount.getGiftConsumeMoney();
//                    }else {
//                        cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney,subMoney);
//                        giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney,subMoney);
//                        giftSpendMoney = subMoney;
//                    }
                            //先试用实充金额 在使用赠送金额
                            //支付金额 >= 实充金额
                            if (BigDecimalUtils.compareTo(subMoney, cardConsumeMoney) >= 0) {
                                BigDecimal leftMoney = BigDecimalUtils.subtract(subMoney, cardConsumeMoney);
                                cardRestMoney = BigDecimalUtils.bigDecimal("0");
                                cardConsumeMoney = BigDecimalUtils.bigDecimal("0");
                                cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney, leftMoney);
                                giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, leftMoney);
                                giftSpendMoney = leftMoney;
                            } else {
                                cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, subMoney);
                                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney, subMoney);
                            }
                        }
                    }
                } else {//折扣卡
                    cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, subMoney);
                    cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney, subMoney);
                }

                rechargeAccount.setCardRestMoney(cardRestMoney);
                rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
                rechargeAccount.setCardGiftMoney(cardGiftMoney);
                rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
                rechargeAccount.setLastConsumeTime(courseList.getDate());
                this.volidAccount(rechargeAccount);
//            list.add(rechargeAccount);
                try {
                    if (null == rechargeAccounts.getFirstCharge()) {
                        rechargeAccount.setFirstCharge(1l);
                    } else {
                        rechargeAccount.setFirstCharge(rechargeAccounts.getFirstCharge() + 1);
                    }
                    i = dao.updateByPrimaryKeySelective(rechargeAccount);
                } catch (Exception e) {
                    log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
                if (i > 0) {
                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseList, rechargeAccount, subMoney, giftSpendMoney);
                    ssmAccountTradeRecordService.addRecord1(accountTradeRecord);

//                    TransactionRecord transactionRecord = this.setTransactionRecord(courseList, rechargeAccount, subMoney, giftSpendMoney);
//                    ssmTransactionRecordService.add(transactionRecord);
                }
            }
        }
        return i;
    }



    public AccountTradeRecord setAccountTradeRecord(CourseList courseList, RechargeAccount rechargeAccount,BigDecimal spendMoney, BigDecimal giftSpendMoney){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(courseList.getStoreId());
        accountTradeRecord.setStoreName(courseList.getStoreName());
        accountTradeRecord.setMemberId(courseList.getMemberId());
        accountTradeRecord.setMemberName(courseList.getMemberName());
        accountTradeRecord.setMemberIdentity(courseList.getMemberIdentity());
        accountTradeRecord.setMemberPhone(courseList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(courseList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume);
            accountTradeRecord.setAccountSpendMoney(spendMoney);
            accountTradeRecord.setAccountGiftSpendMoney(giftSpendMoney);
            accountTradeRecord.setInputDate(courseList.getDate());
            accountTradeRecord.setInputBy(courseList.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume_cancel);
            accountTradeRecord.setAccountInMoney(spendMoney);
            accountTradeRecord.setInputDate(courseList.getCancelDate());
            accountTradeRecord.setInputBy(courseList.getCancelBy());
            accountTradeRecord.setAccountGiftSpendMoney(giftSpendMoney);
        }
        accountTradeRecord.setDocId(courseList.getId());
        accountTradeRecord.setDocNum(courseList.getCourseReatmentNum());
        accountTradeRecord.setDocType(Constant.doc_type_card_use);
        accountTradeRecord.setTradeId(courseList.getProjctId());
        accountTradeRecord.setTradeName(courseList.getProjectName());
        accountTradeRecord.setTradeMoney(courseList.getAmount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setDebtMoney(courseList.getDebtMoney());
        accountTradeRecord.setPrice(courseList.getSalesPrice());

        accountTradeRecord.setCardMoney(courseList.getCollectionRechargeAmount());
        accountTradeRecord.setCashMoney(courseList.getCollectionCashAmount());
        return accountTradeRecord;
    }

    public TransactionRecord setTransactionRecord(CourseList courseList, RechargeAccount rechargeAccount,BigDecimal spendMoney, BigDecimal giftSpendMoney){
        TransactionRecord accountTradeRecord = new TransactionRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(courseList.getStoreId());
        accountTradeRecord.setStoreName(courseList.getStoreName());
        accountTradeRecord.setMemberId(courseList.getMemberId());
        accountTradeRecord.setMemberName(courseList.getMemberName());
        accountTradeRecord.setMemberIdentity(courseList.getMemberIdentity());
        accountTradeRecord.setMemberPhone(courseList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(courseList.getIsCancel() == 0) {
            accountTradeRecord.setType(13);
            accountTradeRecord.setDocState(0);
            accountTradeRecord.setCardMoney(spendMoney);
            accountTradeRecord.setAccountGiftSpendMoney(giftSpendMoney);
            accountTradeRecord.setDocDate(courseList.getDate());
            accountTradeRecord.setOperationBy(courseList.getInputBy());
        }else {
            accountTradeRecord.setType(15);
            accountTradeRecord.setDocState(1);
            accountTradeRecord.setAccountInMoney(courseList.getCollectionRechargeAmount());
            accountTradeRecord.setAccountInGiftMoney(giftSpendMoney);
            accountTradeRecord.setDocDate(courseList.getCancelDate());
            accountTradeRecord.setOperationBy(courseList.getCancelBy());
        }
        accountTradeRecord.setDate(new Date());
        accountTradeRecord.setDocId(courseList.getId());
        accountTradeRecord.setDocNum(courseList.getCourseReatmentNum());

        accountTradeRecord.setDocProjectId(courseList.getProjctId());
        accountTradeRecord.setDocProjectName(courseList.getProjectName());
        BaseProject baseProject = new BaseProject();
        baseProject.setId(courseList.getProjctId());
        BaseProject baseProject1 = ssmProjectService.selectOne(baseProject);
        accountTradeRecord.setDocProjectNum(baseProject1.getProjectNum());
        accountTradeRecord.setTradingMoney(courseList.getAmount());
        accountTradeRecord.setDebtMoney(courseList.getDebtMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCashMoney(courseList.getCollectionCashAmount());
        return accountTradeRecord;
    }


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

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addMoney(List<RechargeAccountRequest> rechargeAccountList, CashList cashList) throws SmsException {
        int i = 0;
        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");

        //查询账户交易记录
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume);
        accountTradeRecordRequest.setInputDate(cashList.getCashDate());
        accountTradeRecordRequest.setDocId(cashList.getId());
        accountTradeRecordRequest.setStoreId(cashList.getStoreId());
        List<AccountTradeRecord> recordList = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
        for (AccountTradeRecord accountTradeRecord : recordList) {
            RechargeAccount rechargeAccount = dao.selectByPrimaryKey(accountTradeRecord.getAccountId());
            BigDecimal spendMoney  = accountTradeRecord.getAccountSpendMoney();
            BigDecimal giftSpendMoney = accountTradeRecord.getAccountGiftSpendMoney();
            BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
            BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
            BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
            BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();

            if (0 == rechargeAccount.getType()||2 == rechargeAccount.getType()){//赠送卡
                //充值金额与赠送金额按比例使用 或者 先使用充值金额,再使用赠送金额 (存在赠品金额计算)
                cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, giftSpendMoney);
                giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, giftSpendMoney);
                cardRestMoney = BigDecimalUtils.add(cardRestMoney, spendMoney);
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney, spendMoney);
                giftConsumeMoneyGive=giftSpendMoney;

            }else {//折扣卡
                cardRestMoney = BigDecimalUtils.add(cardRestMoney,spendMoney);
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney,spendMoney);
            }
            rechargeAccount.setCardRestMoney(cardRestMoney);
            rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccount.setLastConsumeTime(new Date());
            try {
                if(null == rechargeAccount.getFirstCharge()){
                    rechargeAccount.setFirstCharge(0L);
                }else{
                    rechargeAccount.setFirstCharge(rechargeAccount.getFirstCharge()-1);
                }

                i = dao.updateByPrimaryKeySelective(rechargeAccount);
                RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
                //判断是否促销卡，是否是限制门店使用
                if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                    RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                    BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                    rechargeAccountGive.setAccountId(rechargeAccount.getId());
                    rechargeAccountGive.setStoreId(cashList.getStoreId());
                    Example example = new Example(RechargeAccountGive.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                    criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                    criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                    //查询原账户的赠送金额
                    List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                    if(List.size()==1) {
                        rechargeAccountGive = List.get(0);
                        //原账户赠送金额-本单充值赠送使用金额
                        rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().add(giftConsumeMoneyGive));
                        ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive, example);
                    }
                }

            } catch (Exception e) {
                log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0){
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(cashList, rechargeAccount,spendMoney, giftSpendMoney);
                tradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(tradeRecord);

//                TransactionRecord transactionRecord = this.setTransactionRecord(cashList, rechargeAccount, spendMoney, giftSpendMoney);
//                ssmTransactionRecordService.add(transactionRecord);
            }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int addMoney(List<RechargeAccountRequest> rechargeAccountList, ServiceOrders cashList) throws SmsException {
        int i = 0;

        //查询账户交易记录
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume_room);
        accountTradeRecordRequest.setInputDate(cashList.getDocDate());
        accountTradeRecordRequest.setDocId(cashList.getId());
        accountTradeRecordRequest.setStoreId(cashList.getStoreId());
        List<AccountTradeRecord> recordList = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
        for (AccountTradeRecord accountTradeRecord : recordList) {
            RechargeAccount rechargeAccount = dao.selectByPrimaryKey(accountTradeRecord.getAccountId());
            BigDecimal spendMoney  = accountTradeRecord.getAccountSpendMoney();
            BigDecimal giftSpendMoney = accountTradeRecord.getAccountGiftSpendMoney();
            BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
            BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
            BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
            BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();

            if (0 == rechargeAccount.getType()||2 == rechargeAccount.getType()){//赠送卡
                //充值金额与赠送金额按比例使用 或者 先使用充值金额,再使用赠送金额 (存在赠品金额计算)
                cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, giftSpendMoney);
                giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, giftSpendMoney);
                cardRestMoney = BigDecimalUtils.add(cardRestMoney, spendMoney);
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney, spendMoney);

            }else {//折扣卡
                cardRestMoney = BigDecimalUtils.add(cardRestMoney,spendMoney);
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney,spendMoney);
            }
            rechargeAccount.setCardRestMoney(cardRestMoney);
            rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccount.setLastConsumeTime(new Date());
            try {
                rechargeAccount.setFirstCharge(rechargeAccount.getFirstCharge()-1);
                i = dao.updateByPrimaryKeySelective(rechargeAccount);
            } catch (Exception e) {
                log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0){
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(cashList, rechargeAccount,spendMoney, giftSpendMoney);
                tradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(tradeRecord);

//                TransactionRecord transactionRecord = this.setTransactionRecord(cashList, rechargeAccount, spendMoney, giftSpendMoney);
//                ssmTransactionRecordService.add(transactionRecord);
            }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<AccountTradeRecord> subMoney(List<RechargeAccountRequest> rechargeAccountList, CashList cashList, List<AccountTradeRecord> list) throws SmsException {
        int i = 0;
        //查询门店充值账户使用参数
        StoreParament storeParament = StoreParaUtils.getStorePara(cashList.getStoreId(), Constant.use_recharge);
        BigDecimal subMoney = BigDecimalUtils.bigDecimal("0");
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
            RechargeAccount rechargeAccount = new RechargeAccount();
            RechargeAccount rechargeAccounts = dao.selectByPrimaryKey(rechargeAccountRequest.getId());
            BeanUtils.copyProperties(rechargeAccountRequest,rechargeAccount);
//            if(rechargeAccounts.getCardRestMoney().compareTo(rechargeAccount.getCardRestMoney())!=0){
//                throw new SmsException(ResponseCode.MSG,"扣款前金额与账户剩余金额不一致");
//            }

            RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
            //卡扣款记录
            CashAccountList cashAccountList = new CashAccountList();

            subMoney = rechargeAccountRequest.getSpendMoney();
            BigDecimal giftSpendMoney1 = rechargeAccountRequest.getGiftSpendMoney();
            BigDecimal cardRestMoney = rechargeAccounts.getCardRestMoney(); //账户剩余金额
            BigDecimal cardConsumeMoney = rechargeAccounts.getCardConsumeMoney();//账户可用金额
            BigDecimal cardGiftMoney = rechargeAccounts.getCardGiftMoney(); //赠送卡赠送金额
            BigDecimal giftConsumeMoney = rechargeAccounts.getGiftConsumeMoney(); //赠送卡可用金额
            BigDecimal giftSpendMoney =  giftSpendMoney1;
            if (0 == rechargeAccounts.getType()){//赠送卡
                cardRestMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardRestMoney(), rechargeAccountRequest.getSpendMoney());
                cardConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardConsumeMoney(), rechargeAccountRequest.getSpendMoney());
                cardGiftMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardGiftMoney(), rechargeAccountRequest.getGiftSpendMoney());
                giftConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getGiftConsumeMoney(), rechargeAccountRequest.getGiftSpendMoney());
            }else if (1 == rechargeAccounts.getType()){//折扣卡
                cardRestMoney = BigDecimalUtils.subtract(cardRestMoney,subMoney);
                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,subMoney);
                cardGiftMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardGiftMoney(), rechargeAccountRequest.getGiftSpendMoney());
                giftConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getGiftConsumeMoney(), rechargeAccountRequest.getGiftSpendMoney());
                giftConsumeMoneyGive=rechargeAccountRequest.getGiftSpendMoney();
            }else if (2 == rechargeAccounts.getType()){//促销卡
                cardRestMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardRestMoney(), rechargeAccountRequest.getSpendMoney());
                cardConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardConsumeMoney(), rechargeAccountRequest.getSpendMoney());
                cardGiftMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardGiftMoney(), rechargeAccountRequest.getGiftSpendMoney());
                giftConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getGiftConsumeMoney(), rechargeAccountRequest.getGiftSpendMoney());
                giftConsumeMoneyGive=rechargeAccountRequest.getGiftSpendMoney();
            }
            rechargeAccounts.setCardRestMoney(cardRestMoney);
            rechargeAccounts.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccounts.setCardGiftMoney(cardGiftMoney);
            rechargeAccounts.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccounts.setLastConsumeTime(cashList.getCashDate());
            this.volidAccount(rechargeAccounts);
            //设置卡扣款信息
            cashAccountList.setCardPayMoney(subMoney);
            cashAccountList.setGiftPayMoney(giftSpendMoney);
            cashAccountList.setRecAccountId(rechargeAccounts.getId());
            BeanUtils.copyProperties(rechargeAccounts, cashAccountList);
            ssmCashAccountSrevice.add(cashAccountList, cashList);
//            list.add(rechargeAccount);
            try {
                if(null == rechargeAccounts.getFirstCharge()){
                    rechargeAccount.setFirstCharge(1L);
                }else{
                    rechargeAccount.setFirstCharge(rechargeAccounts.getFirstCharge()+1);
                }
                i = dao.updateByPrimaryKeySelective(rechargeAccounts);
                //判断是否促销卡，是否是限制门店使用
                if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                    RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                    BeanUtils.copyProperties(rechargeAccounts,rechargeAccountGive);
                    rechargeAccountGive.setAccountId(rechargeAccount.getId());
                    rechargeAccountGive.setStoreId(cashList.getStoreId());
                    Example example = new Example(RechargeAccountGive.class);
                    Example.Criteria criteria = example.createCriteria();
                    criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                    criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                    criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                    //查询原账户的赠送金额
                    List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                    if(List.size()==1) {
                        rechargeAccountGive = List.get(0);
                        //赠送使用金额>账户赠送可用金额
                        if(BigDecimalUtils.compareTo(giftConsumeMoneyGive,rechargeAccountGive.getGiftConsumeMoney())==1){
                            rechargeAccountGive.setGiftConsumeMoney(new BigDecimal("0"));
                        }else{
                            //原账户赠送金额-本单充值赠送使用金额
                            rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().subtract(giftConsumeMoneyGive));
                        }
                        ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive, example);
                    }
                }

            } catch (Exception e) {
                log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0){
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(cashList, rechargeAccounts, subMoney, giftSpendMoney);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                list.add(accountTradeRecord);

//                TransactionRecord transactionRecord = this.setTransactionRecord(cashList, rechargeAccount, subMoney, giftSpendMoney);
//                ssmTransactionRecordService.add(transactionRecord);
            }

        }
        return list;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public List<AccountTradeRecord> subMoney(List<RechargeAccountRequest> rechargeAccountList, ServiceOrders serviceOrders, List<AccountTradeRecord> list) throws SmsException {
        int i = 0;
        //查询门店充值账户使用参数
        StoreParament storeParament = StoreParaUtils.getStorePara(serviceOrders.getStoreId(), Constant.use_recharge);
        BigDecimal subMoney = BigDecimalUtils.bigDecimal("0");
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
            RechargeAccount rechargeAccount = new RechargeAccount();
            RechargeAccount rechargeAccounts = dao.selectByPrimaryKey(rechargeAccountRequest.getId());
            BeanUtils.copyProperties(rechargeAccountRequest,rechargeAccount);
            RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
            //卡扣款记录
            CashAccountList cashAccountList = new CashAccountList();

            subMoney = rechargeAccountRequest.getSpendMoney();
            BigDecimal giftSpendMoney1 = rechargeAccountRequest.getGiftSpendMoney();
            BigDecimal cardRestMoney = rechargeAccounts.getCardRestMoney(); //账户剩余金额
            BigDecimal cardConsumeMoney = rechargeAccounts.getCardConsumeMoney();//账户可用金额
            BigDecimal cardGiftMoney = rechargeAccounts.getCardGiftMoney(); //赠送卡赠送金额
            BigDecimal giftConsumeMoney = rechargeAccounts.getGiftConsumeMoney(); //赠送卡可用金额
            BigDecimal giftSpendMoney =  giftSpendMoney1;
            if (0 == rechargeAccounts.getType()){//赠送卡
                cardRestMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardRestMoney(), rechargeAccountRequest.getSpendMoney());
                cardConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardConsumeMoney(), rechargeAccountRequest.getSpendMoney());
                cardGiftMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardGiftMoney(), rechargeAccountRequest.getGiftSpendMoney());
                giftConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getGiftConsumeMoney(), rechargeAccountRequest.getGiftSpendMoney());
            }else if (1 == rechargeAccounts.getType()){//折扣卡
                cardRestMoney = BigDecimalUtils.subtract(cardRestMoney,subMoney);
                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,subMoney);
            }else if (2 == rechargeAccounts.getType()){//促销卡
                cardRestMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardRestMoney(), rechargeAccountRequest.getSpendMoney());
                cardConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardConsumeMoney(), rechargeAccountRequest.getSpendMoney());
                cardGiftMoney = BigDecimalUtils.subtract(rechargeAccounts.getCardGiftMoney(), rechargeAccountRequest.getGiftSpendMoney());
                giftConsumeMoney = BigDecimalUtils.subtract(rechargeAccounts.getGiftConsumeMoney(), rechargeAccountRequest.getGiftSpendMoney());
            }
            rechargeAccounts.setCardRestMoney(cardRestMoney);
            rechargeAccounts.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccounts.setCardGiftMoney(cardGiftMoney);
            rechargeAccounts.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccounts.setLastConsumeTime(serviceOrders.getDocDate());
            this.volidAccount(rechargeAccounts);
            //设置卡扣款信息
            cashAccountList.setCardPayMoney(subMoney);
            cashAccountList.setGiftPayMoney(giftSpendMoney);
            cashAccountList.setRecAccountId(rechargeAccounts.getId());
            BeanUtils.copyProperties(rechargeAccounts, cashAccountList);
            ssmCashAccountSrevice.add(cashAccountList, serviceOrders);
//            list.add(rechargeAccount);
            try {
                if(null == rechargeAccounts.getFirstCharge()){
                    rechargeAccounts.setFirstCharge(1L);
                }else{
                    rechargeAccounts.setFirstCharge(rechargeAccounts.getFirstCharge()+1);
                }
                i = dao.updateByPrimaryKeySelective(rechargeAccounts);
            } catch (Exception e) {
                log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0){
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(serviceOrders, rechargeAccounts, subMoney, giftSpendMoney);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                list.add(accountTradeRecord);
            }
        }
        return list;
    }

    //新的交易记录
    public TransactionRecord setTransactionRecord(CashList cashList, RechargeAccount rechargeAccount, BigDecimal spendMoney,BigDecimal giftSpendMoney){
        TransactionRecord accountTradeRecord = new TransactionRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(cashList.getStoreId());
        accountTradeRecord.setStoreName(cashList.getStoreName());
        accountTradeRecord.setMemberId(cashList.getMemberId());
        accountTradeRecord.setMemberName(cashList.getMemberName());
        accountTradeRecord.setMemberIdentity(cashList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(cashList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        RechargeType rechargeType = new RechargeType();
        rechargeType.setId(rechargeAccount.getRechargeTypeId());
        rechargeType = ssmRechargeTypeSevice.selectOne(rechargeType);
        accountTradeRecord.setAccountNum(rechargeType.getRechargeTypeNum());
        if(cashList.getIsCancel() == 0) {
            accountTradeRecord.setType(0);
            accountTradeRecord.setDocDate(cashList.getCashDate());
            accountTradeRecord.setDate(new Date());
            accountTradeRecord.setOperationBy(cashList.getInputBy());
            accountTradeRecord.setDocState(0);
        }else {
            accountTradeRecord.setType(1);
            accountTradeRecord.setAccountInMoney(spendMoney);
            accountTradeRecord.setDocDate(cashList.getCancelDate());
            accountTradeRecord.setDate(new Date());
            accountTradeRecord.setOperationBy(cashList.getCancelBy());
            accountTradeRecord.setDocState(1);
        }
        accountTradeRecord.setCardMoney(spendMoney);
        accountTradeRecord.setCashMoney(cashList.getCollectionCashAmount());
        accountTradeRecord.setAccountGiftSpendMoney(giftSpendMoney);
        accountTradeRecord.setDocId(cashList.getId());
        accountTradeRecord.setDocNum(cashList.getCashNum());
        BaseProject baseProject = new BaseProject();
        baseProject.setId(cashList.getProjectId());
        baseProject = ssmProjectService.selectOne(baseProject);

        accountTradeRecord.setDocProjectId(cashList.getProjectId());
        accountTradeRecord.setDocProjectName(cashList.getProjectName());
        accountTradeRecord.setDocProjectNum(baseProject.getProjectNum());
        accountTradeRecord.setTradingMoney(cashList.getAmount());
        accountTradeRecord.setPrice(cashList.getTransactionPrice());
        accountTradeRecord.setQuantity(cashList.getNumberTimes());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        return accountTradeRecord;
    }

    public AccountTradeRecord setAccountTradeRecord(CashList cashList, RechargeAccount rechargeAccount, BigDecimal spendMoney,BigDecimal giftSpendMoney){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(cashList.getStoreId());
        accountTradeRecord.setStoreName(cashList.getStoreName());
        accountTradeRecord.setMemberId(cashList.getMemberId());
        accountTradeRecord.setMemberName(cashList.getMemberName());
        accountTradeRecord.setMemberIdentity(cashList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(cashList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(cashList.getIsCancel() == 0) {
            accountTradeRecord.setAccountSpendMoney(spendMoney);
            accountTradeRecord.setAccountGiftSpendMoney(giftSpendMoney);
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume);
            accountTradeRecord.setInputDate(cashList.getCashDate());
            accountTradeRecord.setInputBy(cashList.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume_cancel);
            accountTradeRecord.setAccountInMoney(spendMoney);
            accountTradeRecord.setGiftInMenoy(giftSpendMoney);
            accountTradeRecord.setInputDate(cashList.getCancelDate());
            accountTradeRecord.setInputBy(cashList.getCancelBy());
        }
        accountTradeRecord.setIsAddition(cashList.getIsAddition());
        accountTradeRecord.setPrice(cashList.getTransactionPrice());
        accountTradeRecord.setDocId(cashList.getId());
        accountTradeRecord.setDocNum(cashList.getCashNum());
        accountTradeRecord.setDocType(Constant.doc_type_store_cash);
        accountTradeRecord.setTradeId(cashList.getProjectId());
        accountTradeRecord.setTradeName(cashList.getProjectName());
        accountTradeRecord.setTradeMoney(cashList.getAmount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCardMoney(cashList.getCollectionRechargeAmount());
        accountTradeRecord.setCashMoney(cashList.getCollectionCashAmount());
        return accountTradeRecord;
    }

    public AccountTradeRecord setAccountTradeRecord(ServiceOrders serviceOrders, RechargeAccount rechargeAccount, BigDecimal spendMoney,BigDecimal giftSpendMoney){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(serviceOrders.getStoreId());
        accountTradeRecord.setStoreName(serviceOrders.getStoreName());
        accountTradeRecord.setMemberId(serviceOrders.getMemberId());
        accountTradeRecord.setMemberName(serviceOrders.getMemberName());
        accountTradeRecord.setMemberIdentity(serviceOrders.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(serviceOrders.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(serviceOrders.getState() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume_room);
            accountTradeRecord.setInputDate(serviceOrders.getDocDate());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume_room_cancel);
            accountTradeRecord.setAccountInMoney(spendMoney);
            accountTradeRecord.setInputDate(new Date());
        }
        accountTradeRecord.setAccountSpendMoney(spendMoney);
        accountTradeRecord.setAccountGiftSpendMoney(giftSpendMoney);
        accountTradeRecord.setDocId(serviceOrders.getId());
        accountTradeRecord.setDocNum(serviceOrders.getSettlementNum());
        accountTradeRecord.setDocType(Constant.doc_type_store_cash_room);
        accountTradeRecord.setTradeId(serviceOrders.getProjectId());
        accountTradeRecord.setTradeName(serviceOrders.getProjectName());
        accountTradeRecord.setTradeMoney(serviceOrders.getAmount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCardMoney(serviceOrders.getCollectionRechargeAmount());
        accountTradeRecord.setCashMoney(serviceOrders.getCollectionCashAmount());
        return accountTradeRecord;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repay(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        // 更新可用金额 剩余金额
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
        StoreParament storeParament = StoreParaUtils.getStorePara(repayList.getStoreId(),Constant.rec_debt_usable);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
        BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
        BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
        BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
        BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();
        //还款 剩余金额 = 原剩余金额 + 还款金额
        cardRestMoney = BigDecimalUtils.add(cardRestMoney, repayTradeList.getPayMoney());
        //剩余可用金额 = 剩余金额 * 欠款时可用比率(存在欠款时)  剩余可用金额 = 剩余金额(不存在欠款时)
        if (debtList.getState() == 1) {
            cardConsumeMoney = cardRestMoney;
        }else {
            cardConsumeMoney = BigDecimalUtils.multiply(BigDecimalUtils.add(cardRestMoney, repayTradeList.getPayMoney()),consumeRito);
        }
        //存在欠款时赠送卡没有赠送金额 还款将原本赠送金额补上
        if ((rechargeAccount.getType() == 0||rechargeAccount.getType() == 2) && debtList.getState() == 1){
            cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, rechargeType.getGiftMoney());
            giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, rechargeType.getGiftMoney());
        }
        rechargeAccount.setCardRestMoney(cardRestMoney);
        rechargeAccount.setCardConsumeMoney(cardConsumeMoney);

        RechargeList rechargeList = new RechargeList();
        rechargeList.setId(debtList.getDocId());
        rechargeList.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeList).get(0);
        if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
        }
        try {
            i = dao.updateByPrimaryKeySelective(rechargeAccount);

            if(i>0){
                if(rechargeType.getType() != 1){
                    RefundRecord refundRecord = new RefundRecord();
                    refundRecord.setRechargeId(rechargeLists.getId());
                    refundRecord.setRechargeTypeId(rechargeLists.getRechargeTypeId());
                    RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
                    refundRecord1.setRefundDebtMoney(repayTradeList.getPayMoney());
                    refundRecord1.setRefundDebtMoney(repayTradeList.getPayMoney());
                    if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
                        refundRecord1.setIsReceived(1);
                    }
                    ssmRefundRecordService.updateNotNull(refundRecord1);
                }

            }
        } catch (Exception e) {
            log.error("SsmRechargeAccountServiceImpl.repay:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0){
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, rechargeAccount, repayList);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            //更新欠款单信息
            ssmDebtService.updateNotNull(debtList);
        }
        return i;
    }

    /**
     * 暂时先用着，后期再进行修改把
     * @param repayTradeList
     * @param repayList
     * @param debtList
     * @return
     * @throws SmsException
     */
    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayNew(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i=0;
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        repayTradeList.setBeforeRestMoney(rechargeAccount.getCardRestMoney());
        repayTradeList.setBeforeConsumeMoney(rechargeAccount.getCardConsumeMoney());
        repayTradeList.setBeforeGiftRestMoney(rechargeAccount.getCardGiftMoney());
        repayTradeList.setBeforeGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        //赠送金额
        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(),Constant.rec_debt_usable);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
        rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().add(repayTradeList.getPayMoney()));
        if (debtList.getState() == 1) {
            rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardRestMoney());
        }else {
            rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().add(repayTradeList.getPayMoney().multiply(consumeRito)));
        }
        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> cancelDebtList1 = ssmCancelDebtListService.select(cancelDebtList);

        RechargeList rechargeList = new RechargeList();
        rechargeList.setId(debtList.getDocId());
        rechargeList.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeList).get(0);
        if(cancelDebtList1.size()<=0){
            if ((rechargeAccount.getType() == 0||rechargeAccount.getType() == 2) && debtList.getState() == 1){
                if(rechargeLists.getDonateType()==0){
                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), rechargeType.getGiftMoney()));
                    rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().add(rechargeType.getGiftMoney()));

                    giftConsumeMoneyGive=rechargeType.getGiftMoney();
                }else{
                    BigDecimal CZconsumeRito = BigDecimalUtils.div(rechargeType.getGiftMoney(),hundredBd);
                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
                    rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().add( rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));

                    giftConsumeMoneyGive=rechargeLists.getRechargeAmount().multiply(CZconsumeRito);
                }

            }
        }

        try {
            i = dao.updateByPrimaryKeySelective(rechargeAccount);

            //判断是否促销卡，是否是限制门店使用
            if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                rechargeAccountGive.setAccountId(rechargeAccount.getId());
                if(repayTradeList.getBelongingStoreId()!=null){
                    rechargeAccountGive.setStoreId(repayTradeList.getBelongingStoreId());
                    rechargeAccountGive.setStoreName(repayTradeList.getBelongingStoreName());
                }else{
                    rechargeAccountGive.setStoreId(repayTradeList.getStoreId());
                    rechargeAccountGive.setStoreName(repayTradeList.getStoreName());
                }
                rechargeAccountGive.setRechargeDate(rechargeList.getRechargeDate());
                Example example = new Example(RechargeAccountGive.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                //查询原账户的赠送金额
                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                if(List.size()==0){
                    rechargeAccountGive.setGiftConsumeMoney(giftConsumeMoneyGive);
                    ssmRechargeAccountGiveDao.insert(rechargeAccountGive);
                }else{
                    rechargeAccountGive=List.get(0);
                    //原账户赠送金额+本单充值赠送金额
                    rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().add(giftConsumeMoneyGive));
                    ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                }
            }





            repayTradeList.setBackRestMoney(rechargeAccount.getCardRestMoney());
            repayTradeList.setBackConsumeMoney(rechargeAccount.getCardConsumeMoney());
            repayTradeList.setBackGiftRestMoney(rechargeAccount.getCardGiftMoney());
            repayTradeList.setBackGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
            if(i>0){
                if(rechargeType.getType() != 1){
                    RefundRecord refundRecord = new RefundRecord();
                    refundRecord.setRechargeId(rechargeLists.getId());
                    refundRecord.setRechargeTypeId(rechargeLists.getRechargeTypeId());
                    RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
                    refundRecord1.setRefundDebtMoney(repayTradeList.getPayMoney());
                    if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
                        refundRecord1.setIsReceived(1);
                    }
                    ssmRefundRecordService.updateNotNull(refundRecord1);
                }

            }
        } catch (Exception e) {
            log.error("SsmRechargeAccountServiceImpl.repay:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0){
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, rechargeAccount, repayList);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            //更新欠款单信息
            ssmDebtService.updateNotNull(debtList);
        }
        return i;


    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repayNewPromotionRecharge(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i=0;
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        repayTradeList.setBeforeRestMoney(rechargeAccount.getCardRestMoney());
        repayTradeList.setBeforeConsumeMoney(rechargeAccount.getCardConsumeMoney());
        repayTradeList.setBeforeGiftRestMoney(rechargeAccount.getCardGiftMoney());
        repayTradeList.setBeforeGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        //赠送金额
        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(),Constant.rec_debt_usable);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
        rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().add(repayTradeList.getPayMoney()));
        if (debtList.getState() == 1) {
            rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardRestMoney());
        }else {
            rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().add(repayTradeList.getPayMoney().multiply(consumeRito)));
        }
        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> cancelDebtList1 = ssmCancelDebtListService.select(cancelDebtList);

        RechargeList rechargeList = new RechargeList();
        rechargeList.setId(debtList.getDocId());
        rechargeList.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeList).get(0);
        if(cancelDebtList1==null || cancelDebtList1.size()<=0){
            if ((rechargeAccount.getType() == 0||rechargeAccount.getType() == 2) && debtList.getState() == 1){
                if(rechargeLists.getDonateType()==0){
                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), rechargeType.getGiftMoney()));
                    rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().add(rechargeType.getGiftMoney()));

                    giftConsumeMoneyGive=rechargeType.getGiftMoney();
                }else{
                    BigDecimal CZconsumeRito = BigDecimalUtils.div(rechargeType.getGiftMoney(),hundredBd);
                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
                    rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().add( rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));

                    giftConsumeMoneyGive=rechargeLists.getRechargeAmount().multiply(CZconsumeRito);
                }

            }
        }

        try {
            i = dao.updateByPrimaryKeySelective(rechargeAccount);

            //判断是否促销卡，是否是限制门店使用
            if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                rechargeAccountGive.setAccountId(rechargeAccount.getId());
                if(repayTradeList.getBelongingStoreId()!=null){
                    rechargeAccountGive.setStoreId(repayTradeList.getBelongingStoreId());
                    rechargeAccountGive.setStoreName(repayTradeList.getBelongingStoreName());
                }else{
                    rechargeAccountGive.setStoreId(repayTradeList.getStoreId());
                    rechargeAccountGive.setStoreName(repayTradeList.getStoreName());
                }
                rechargeAccountGive.setRechargeDate(rechargeList.getRechargeDate());
                Example example = new Example(RechargeAccountGive.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                //查询原账户的赠送金额
                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                if(List.size()==0){
                    rechargeAccountGive.setGiftConsumeMoney(giftConsumeMoneyGive);
                    ssmRechargeAccountGiveDao.insert(rechargeAccountGive);
                }else{
                    rechargeAccountGive=List.get(0);
                    //原账户赠送金额+本单充值赠送金额
                    rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().add(giftConsumeMoneyGive));
                    ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                }
            }

            //判断是否全额还款,是否是活动卡
            //判断没有进行取消欠款过
            if(debtList.getState()==1 && rechargeAccount.getType() == 2 && (cancelDebtList1==null || cancelDebtList1.size()<=0)){
                //查询有没有赠送疗程
                PromotionProject promotionProject = new PromotionProject();
                promotionProject.setPromotionId(rechargeType.getId());
                List<PromotionProject> promotionProjectList = ssmPromotionProjectService.select(promotionProject);
                if(promotionProjectList!=null && promotionProjectList.size()>0){
                    //复制创建新的疗程账户
                    for (PromotionProject project : promotionProjectList) {
                        //添加疗程账户 (疗程账户没有续充概念 购买一次就是一个新疗程账户)
                        Long courseAccountId = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                        CourseAccount courseAccount = new CourseAccount();
                        BeanUtils.copyProperties(rechargeLists, courseAccount);
                        courseAccount.setId(courseAccountId);
                        if (project.getType() == 0) {
                            courseAccount.setCourseType("1");
                        } else {
                            courseAccount.setCourseType("2");
                        }
                        courseAccount.setCourseNum(rechargeAccount.getRechargeNum());

                        //对疗程账户进行赋值
                        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(rechargeLists.getMemberId());
                        docPromotionProject.setMemberName(rechargeLists.getMemberName());
                        docPromotionProject.setMemberIdentityCard(rechargeLists.getMemberIdentityCard());
                        docPromotionProject.setMobilePhone(rechargeLists.getMobilePhone());
                        docPromotionProject.setDocNum(rechargeLists.getRechargeNum());
                        docPromotionProject.setDocDate(rechargeLists.getRechargeDate());
                        docPromotionProject.setCourseAccountId(courseAccountId);
                        docPromotionProject.setTimes(project.getTimes());
                        ssmDocPromotionProjectService.saveNotNull(docPromotionProject);
                        //添加账户交易记录
                        AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(courseAccount, docPromotionProject,rechargeLists);
                        accountTradeRecord.setInputBy(rechargeLists.getInputBy());
                        ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                    }
                }


            }





            repayTradeList.setBackRestMoney(rechargeAccount.getCardRestMoney());
            repayTradeList.setBackConsumeMoney(rechargeAccount.getCardConsumeMoney());
            repayTradeList.setBackGiftRestMoney(rechargeAccount.getCardGiftMoney());
            repayTradeList.setBackGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
            if(i>0){
                if(rechargeType.getType() != 1){
                    RefundRecord refundRecord = new RefundRecord();
                    refundRecord.setRechargeId(rechargeLists.getId());
                    refundRecord.setRechargeTypeId(rechargeLists.getRechargeTypeId());
                    RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
                    refundRecord1.setRefundDebtMoney(repayTradeList.getPayMoney());
                    if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
                        refundRecord1.setIsReceived(1);
                    }
                    ssmRefundRecordService.updateNotNull(refundRecord1);
                }

            }
        } catch (Exception e) {
            log.error("SsmRechargeAccountServiceImpl.repay:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0){
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, rechargeAccount, repayList);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            //更新欠款单信息
            ssmDebtService.updateNotNull(debtList);
        }
        return i;


    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int repay(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList,BigDecimal CardPayMone) throws SmsException {
        int i = 0;
        // 更新可用金额 剩余金额
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
        StoreParament storeParament = StoreParaUtils.getStorePara(repayList.getStoreId(),Constant.rec_debt_usable);
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
        BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
        BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
        BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
        BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();
        //还款 剩余金额 = 原剩余金额 + 还款金额
        cardRestMoney = BigDecimalUtils.add(cardRestMoney, repayTradeList.getPayMoney().add(CardPayMone));
        //剩余可用金额 = 剩余金额 * 欠款时可用比率(存在欠款时)  剩余可用金额 = 剩余金额(不存在欠款时)
        if (debtList.getState() == 1) {
            cardConsumeMoney = cardRestMoney;
        }else {
            cardConsumeMoney = BigDecimalUtils.multiply(BigDecimalUtils.add(cardRestMoney, repayTradeList.getPayMoney().add(CardPayMone)),consumeRito);
        }
        //存在欠款时赠送卡没有赠送金额 还款将原本赠送金额补上
        if ((rechargeAccount.getType() == 0||rechargeAccount.getType() == 2) && debtList.getState() == 1){
            cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, rechargeType.getGiftMoney());
            giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, rechargeType.getGiftMoney());
        }
        rechargeAccount.setCardRestMoney(cardRestMoney);
        rechargeAccount.setCardConsumeMoney(cardConsumeMoney);

        RechargeList rechargeList = new RechargeList();
        rechargeList.setId(debtList.getDocId());
        rechargeList.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeList).get(0);
        if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney().add(CardPayMone)))==0){
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
        }
        try {
            i = dao.updateByPrimaryKeySelective(rechargeAccount);

            if(i>0){
                if(rechargeType.getType() != 1){
                    RefundRecord refundRecord = new RefundRecord();
                    refundRecord.setRechargeId(rechargeLists.getId());
                    refundRecord.setRechargeTypeId(rechargeLists.getRechargeTypeId());
                    RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
                    refundRecord1.setRefundDebtMoney(repayTradeList.getPayMoney());
                    refundRecord1.setRefundDebtMoney(repayTradeList.getPayMoney());
                    if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney().add(CardPayMone)))==0){
                        refundRecord1.setIsReceived(1);
                    }
                    ssmRefundRecordService.updateNotNull(refundRecord1);
                }

            }
        } catch (Exception e) {
            log.error("SsmRechargeAccountServiceImpl.repay:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0){
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, rechargeAccount, repayList);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            //更新欠款单信息
            ssmDebtService.updateNotNull(debtList);
        }
        return i;
    }


    @Override
    public int repayCancel(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;

        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //充值有欠款可消费比率参数
        StoreParament storeParament = StoreParaUtils.getStorePara(repayTradeList.getStoreId(),Constant.debt_usable);
        //充值金额可用比率 = 门店参数/100
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
        // 更新可用金额 剩余金额
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
        BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
        BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
        BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
        BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();
        //还款作废 剩余金额 = 现剩余金额 - 还款金额   剩余可用金额 = 现剩余可用金额 - 标准充值金额 + 当次充值可用金额
        cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, repayTradeList.getPayMoney());
        BigDecimal consumeMoney = null;
        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        List<CancelDebtList> cancelDebtList1 = ssmCancelDebtListService.select(cancelDebtList);
        BigDecimal money=BigDecimal.valueOf(0);
        for (CancelDebtList list : cancelDebtList1) {
            if(list.getState()==3){
                money=money.add(list.getCancelMoney());
            }
        }

        //查询充值单
        RechargeList rechargeList = new RechargeList();
        rechargeList.setId(debtList.getDocId());
        rechargeList.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeList).get(0);
        if(money.compareTo(BigDecimal.valueOf(0))==0){
            if(rechargeAccount.getCardNum()==0){
                consumeMoney = BigDecimalUtils.multiply(BigDecimalUtils.subtract(rechargeLists.getRechargeAmount(),debtList.getDebtMoney()), consumeRito);
//                consumeMoney = BigDecimalUtils.multiply(BigDecimalUtils.subtract(rechargeLists.getRechargeAmount(), repayTradeList.getPayMoney()), consumeRito);
                cardConsumeMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardConsumeMoney,rechargeLists.getRechargeAmount()),consumeMoney);
            }else{
                consumeMoney = BigDecimalUtils.multiply(BigDecimalUtils.subtract(rechargeLists.getRechargeAmount(), repayTradeList.getPayMoney()), consumeRito);
                cardConsumeMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardConsumeMoney, rechargeLists.getRechargeAmount()),consumeMoney);
            }
        }else{
            if(rechargeAccount.getCardNum()==0){
                consumeMoney = BigDecimalUtils.multiply(BigDecimalUtils.subtract(BigDecimalUtils.subtract(rechargeLists.getRechargeAmount(),money), repayTradeList.getPayMoney()), consumeRito);
                cardConsumeMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardConsumeMoney, BigDecimalUtils.subtract(rechargeLists.getRechargeAmount(),money)),consumeMoney);
            }else{
                consumeMoney = BigDecimalUtils.multiply(BigDecimalUtils.subtract(BigDecimalUtils.subtract(rechargeLists.getRechargeAmount(),money), repayTradeList.getPayMoney()), consumeRito);
                cardConsumeMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardConsumeMoney, BigDecimalUtils.subtract(rechargeLists.getRechargeAmount(),money)),consumeMoney);
            }
        }

        //还款作废 回到欠款状态 当次赠送卡赠送金额和赠送可用金额为0 赠送金额 = 现赠送金额 - 当次赠送金额
        if (rechargeAccount.getType() == 0 && debtList.getState() == 0){
            cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney, rechargeType.getGiftMoney());
            giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, rechargeType.getGiftMoney());
        }
        rechargeAccount.setCardRestMoney(cardRestMoney);
        rechargeAccount.setCardConsumeMoney(cardConsumeMoney);

        RechargeList rechargeListC = new RechargeList();
        rechargeListC.setId(debtList.getDocId());
        rechargeListC.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeListsC = ssmRechargeService.selectListSalem(rechargeListC).get(0);
        if(rechargeListsC.getRechargeAmount().compareTo(rechargeListsC.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
        }

        this.volidAccount(rechargeAccount);
        try {
            i = dao.updateByPrimaryKeySelective(rechargeAccount);
            if(rechargeType.getType() != 1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setRechargeId(rechargeListsC.getId());
                RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
                refundRecord1.setRefundDebtMoney(refundRecord1.getRefundDebtMoney().subtract(repayTradeList.getRepayMoney()));
                if(rechargeListsC.getRechargeAmount().compareTo(rechargeListsC.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
                    refundRecord1.setIsReceived(0);
                }
                int i1 = ssmRefundRecordService.updateNotNull(refundRecord1);
            }
        } catch (Exception e) {
            log.error("SsmRechargeAccountServiceImpl.repayCancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0){
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, rechargeAccount, repayList);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            //更新欠款单信息
            ssmDebtService.updateNotNull(debtList);
        }
        return i;
    }

    @Override
    public int repayCancelNew(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //充值有欠款可消费比率参数
        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(),Constant.rec_debt_usable);
        //充值金额可用比率 = 门店参数/100
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());

        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        if(repayTradeList.getBackRestMoney().compareTo(rechargeAccount.getCardRestMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后剩余金额与当前剩余金额不相等");
        }
        if(repayTradeList.getBackConsumeMoney().compareTo(rechargeAccount.getCardConsumeMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后可用金额与当前可用金额不相等");
        }
        if(repayTradeList.getBackGiftRestMoney().compareTo(rechargeAccount.getCardGiftMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后赠送剩余金额与当前赠送剩余金额不相等");
        }
        if(repayTradeList.getBackGiftConsumeMoney().compareTo(rechargeAccount.getGiftConsumeMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后赠送可用金额与当前赠送可用金额不相等");
        }
        //todo
        RechargeAccountGive rechargeAccountGive1 = new RechargeAccountGive();
        rechargeAccountGive1.setStoreId(repayTradeList.getStoreId());
        rechargeAccountGive1.setMemberId(repayTradeList.getMemberId());
        rechargeAccountGive1.setAccountId(repayTradeList.getAccountId());
        RechargeAccountGive rechargeAccountGive2 = ssmRechargeAccountGiveService.selectOne(rechargeAccountGive1);
        if(rechargeAccountGive2!=null && rechargeAccountGive2.getGiftConsumeMoney().compareTo(rechargeAccount.getGiftConsumeMoney())==-1){
            throw new SmsException(ResponseCode.MSG,"该充值卡存在转门店行为，不允许作废");
        }


        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
        RechargeList rechargeListC = new RechargeList();
        rechargeListC.setId(debtList.getDocId());
        rechargeListC.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeListC).get(0);
        //当前单据应充值金额
        BigDecimal rechargeAmount = rechargeLists.getRechargeAmount();
        //判断是否存在取消欠款
        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> select = ssmCancelDebtListService.select(cancelDebtList);

        //当前欠款单总金额
        BigDecimal repayTotalMoney = BigDecimal.valueOf(0);
        RepayTradeList repayTradeList2 = new RepayTradeList();
        repayTradeList2.setId(repayTradeList.getId());
        RepayTradeList repayTradeList3 = ssmRepayTradeService.selectByPrimaryKey(repayTradeList2.getId());
        RepayAccountList repayAccountLists = new RepayAccountList();
        repayAccountLists.setRepayTradeId(repayTradeList3.getId());
        List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountLists);
        for (RepayAccountList accountList : select3) {
            repayTotalMoney=repayTotalMoney.add(accountList.getPayMoney());
        }
        repayTotalMoney=repayTotalMoney.add(repayTradeList3.getPayMoney());

        //总还款金额
        BigDecimal totalMoney = BigDecimal.valueOf(0);
        //取消过欠款
        if(select.size()>0){
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(rechargeLists.getId());
            repayTradeList1.setMemberId(rechargeLists.getMemberId());
            repayTradeList1.setDocType("card_recharge");
            List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
            for (RepayTradeList tradeList : select1) {
                RepayList repayList1 = new RepayList();
                repayList1.setRepayNum(tradeList.getRepayNum());
                repayList1.setStoreId(tradeList.getStoreId());
                RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                if(repayList2.getIsCancel()==0){
                    totalMoney=totalMoney.add(tradeList.getPayMoney());
                    RepayAccountList repayAccountList = new RepayAccountList();
                    repayAccountList.setRepayTradeId(tradeList.getId());
                    List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                    for (RepayAccountList accountList : select2) {
                        totalMoney=totalMoney.add(accountList.getPayMoney());
                    }
                }
            }
            if(rechargeAmount.compareTo(rechargeLists.getCollectionCashAmount().add(totalMoney))==0){ //已经全额还款
                BigDecimal subtract = rechargeAmount.subtract(repayTotalMoney);
                BigDecimal multiply = subtract.multiply(consumeRito);
                BigDecimal subtract1 = rechargeAmount.subtract(multiply);
                //当前单据的充值剩余金额应为
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(subtract1));
            }else{//还存在欠款
                BigDecimal multiply = repayTotalMoney.multiply(consumeRito);
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(multiply));
            }

        }else{ //没有取消欠款
            //判断是否已经全额还款
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(rechargeLists.getId());
            repayTradeList1.setMemberId(rechargeLists.getMemberId());
            repayTradeList1.setDocType("card_recharge");
            List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
            for (RepayTradeList tradeList : select1) {
                RepayList repayList1 = new RepayList();
                repayList1.setRepayNum(tradeList.getRepayNum());
                repayList1.setStoreId(tradeList.getStoreId());
                RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                if(repayList2.getIsCancel()==0){
                    totalMoney=totalMoney.add(tradeList.getPayMoney());
                    RepayAccountList repayAccountList = new RepayAccountList();
                    repayAccountList.setRepayTradeId(tradeList.getId());
                    List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                    for (RepayAccountList accountList : select2) {
                        totalMoney=totalMoney.add(accountList.getPayMoney());
                    }
                }
            }
            if(rechargeAmount.compareTo(rechargeLists.getCollectionCashAmount().add(totalMoney))==0){ //已经全额还款
                BigDecimal subtract = rechargeAmount.subtract(repayTotalMoney);
                BigDecimal multiply = subtract.multiply(consumeRito);
                BigDecimal subtract1 = rechargeAmount.subtract(multiply);
                //当前单据的充值剩余金额应为
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(subtract1));
                if(rechargeType.getType()==0||rechargeType.getType()==2){
                    if(rechargeLists.getDonateType()==0){
                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().subtract(rechargeType.getGiftMoney()));
                        rechargeAccount.setGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney().subtract(rechargeType.getGiftMoney()));
                        giftConsumeMoneyGive=rechargeType.getGiftMoney();
                    }else{
                        BigDecimal CZconsumeRito = BigDecimalUtils.div(rechargeType.getGiftMoney(),hundredBd);
                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().subtract(rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
                        rechargeAccount.setGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney().subtract(rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
                        giftConsumeMoneyGive=rechargeLists.getRechargeAmount().multiply(CZconsumeRito);
//                        rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
//                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().add( rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));

                    }

                }
            }else{//还存在欠款
                BigDecimal multiply = repayTotalMoney.multiply(consumeRito);
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(multiply));
            }

        }
        //this.volidAccount(rechargeAccount);
        try {
            rechargeAccount.setCardRestMoney(repayTradeList.getBeforeRestMoney());
            rechargeAccount.setCardConsumeMoney(repayTradeList.getBeforeConsumeMoney());
            rechargeAccount.setCardGiftMoney(repayTradeList.getBeforeGiftRestMoney());
            rechargeAccount.setGiftConsumeMoney(repayTradeList.getBeforeGiftConsumeMoney());
            i = dao.updateByPrimaryKeySelective(rechargeAccount);


            //判断是否促销卡，是否是限制门店使用
            if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                rechargeAccountGive.setAccountId(rechargeAccount.getId());
                rechargeAccountGive.setStoreId(repayTradeList.getStoreId());
                rechargeAccountGive.setStoreName(repayTradeList.getStoreName());
                Example example = new Example(RechargeAccountGive.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                //查询原账户的赠送金额
                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                if(List.size()>0){
                    rechargeAccountGive=List.get(0);
                    //原账户赠送金额-本单作废赠送金额
                    rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().subtract(giftConsumeMoneyGive));
                    ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                }
            }

            if(rechargeType.getType() != 1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setRechargeId(rechargeLists.getId());
                RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
                refundRecord1.setRefundDebtMoney(refundRecord1.getRefundDebtMoney().subtract(repayTradeList.getRepayMoney()));
                if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
                    refundRecord1.setIsReceived(0);
                }
                int i1 = ssmRefundRecordService.updateNotNull(refundRecord1);
            }
        } catch (Exception e) {
            log.error("SsmRechargeAccountServiceImpl.repayCancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0){
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, rechargeAccount, repayList);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            //更新欠款单信息
            ssmDebtService.updateNotNull(debtList);
        }
        return i;
    }
    @Override
    public int repayCancelNewPromotionRecharge(RepayTradeList repayTradeList, RepayList repayList, DebtList debtList) throws SmsException {
        int i = 0;
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        //充值有欠款可消费比率参数
        StoreParament storeParament = StoreParaUtils.getStorePara(debtList.getStoreId(),Constant.rec_debt_usable);
        //充值金额可用比率 = 门店参数/100
        BigDecimal consumeRito = BigDecimalUtils.div(BigDecimalUtils.bigDecimal(storeParament.getParamentValue()),hundredBd);
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(repayTradeList.getAccountId());

        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        if(repayTradeList.getBackRestMoney().compareTo(rechargeAccount.getCardRestMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后剩余金额与当前剩余金额不相等");
        }
        if(repayTradeList.getBackConsumeMoney().compareTo(rechargeAccount.getCardConsumeMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后可用金额与当前可用金额不相等");
        }
        if(repayTradeList.getBackGiftRestMoney().compareTo(rechargeAccount.getCardGiftMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后赠送剩余金额与当前赠送剩余金额不相等");
        }
        if(repayTradeList.getBackGiftConsumeMoney().compareTo(rechargeAccount.getGiftConsumeMoney())!=0){
            throw new SmsException(ResponseCode.MSG,"该还款单关联卡包还款后赠送可用金额与当前赠送可用金额不相等");
        }
        //todo
        RechargeAccountGive rechargeAccountGive1 = new RechargeAccountGive();
        rechargeAccountGive1.setStoreId(repayTradeList.getStoreId());
        rechargeAccountGive1.setMemberId(repayTradeList.getMemberId());
        rechargeAccountGive1.setAccountId(repayTradeList.getAccountId());
        RechargeAccountGive rechargeAccountGive2 = ssmRechargeAccountGiveService.selectOne(rechargeAccountGive1);
        if(rechargeAccountGive2!=null && rechargeAccountGive2.getGiftConsumeMoney().compareTo(rechargeAccount.getGiftConsumeMoney())==-1){
            throw new SmsException(ResponseCode.MSG,"该充值卡存在转门店行为，不允许作废");
        }


        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount.getRechargeTypeId());
        RechargeList rechargeListC = new RechargeList();
        rechargeListC.setId(debtList.getDocId());
        rechargeListC.setRechargeDate(debtList.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeListC).get(0);
        //当前单据应充值金额
        BigDecimal rechargeAmount = rechargeLists.getRechargeAmount();
        //判断是否存在取消欠款
        CancelDebtList cancelDebtList = new CancelDebtList();
        cancelDebtList.setDebtId(debtList.getId());
        cancelDebtList.setState(3);
        List<CancelDebtList> select = ssmCancelDebtListService.select(cancelDebtList);

        //当前欠款单总金额
        BigDecimal repayTotalMoney = BigDecimal.valueOf(0);
        RepayTradeList repayTradeList2 = new RepayTradeList();
        repayTradeList2.setId(repayTradeList.getId());
        RepayTradeList repayTradeList3 = ssmRepayTradeService.selectByPrimaryKey(repayTradeList2.getId());
        RepayAccountList repayAccountLists = new RepayAccountList();
        repayAccountLists.setRepayTradeId(repayTradeList3.getId());
        List<RepayAccountList> select3 = ssmRepayAccountListService.select(repayAccountLists);
        for (RepayAccountList accountList : select3) {
            repayTotalMoney=repayTotalMoney.add(accountList.getPayMoney());
        }
        repayTotalMoney=repayTotalMoney.add(repayTradeList3.getPayMoney());

        //总还款金额
        BigDecimal totalMoney = BigDecimal.valueOf(0);
        //取消过欠款
        if(select.size()>0){
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(rechargeLists.getId());
            repayTradeList1.setMemberId(rechargeLists.getMemberId());
            repayTradeList1.setDocType("card_recharge");
            List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
            for (RepayTradeList tradeList : select1) {
                RepayList repayList1 = new RepayList();
                repayList1.setRepayNum(tradeList.getRepayNum());
                repayList1.setStoreId(tradeList.getStoreId());
                RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                if(repayList2.getIsCancel()==0){
                    totalMoney=totalMoney.add(tradeList.getPayMoney());
                    RepayAccountList repayAccountList = new RepayAccountList();
                    repayAccountList.setRepayTradeId(tradeList.getId());
                    List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                    for (RepayAccountList accountList : select2) {
                        totalMoney=totalMoney.add(accountList.getPayMoney());
                    }
                }
            }
            if(rechargeAmount.compareTo(rechargeLists.getCollectionCashAmount().add(totalMoney))==0){ //已经全额还款
                BigDecimal subtract = rechargeAmount.subtract(repayTotalMoney);
                BigDecimal multiply = subtract.multiply(consumeRito);
                BigDecimal subtract1 = rechargeAmount.subtract(multiply);
                //当前单据的充值剩余金额应为
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(subtract1));
            }else{//还存在欠款
                BigDecimal multiply = repayTotalMoney.multiply(consumeRito);
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(multiply));
            }

        }else{ //没有取消欠款
            //判断是否已经全额还款
            RepayTradeList repayTradeList1 = new RepayTradeList();
            repayTradeList1.setDocId(rechargeLists.getId());
            repayTradeList1.setMemberId(rechargeLists.getMemberId());
            repayTradeList1.setDocType("card_recharge");
            List<RepayTradeList> select1 = ssmRepayTradeService.select(repayTradeList1);
            for (RepayTradeList tradeList : select1) {
                RepayList repayList1 = new RepayList();
                repayList1.setRepayNum(tradeList.getRepayNum());
                repayList1.setStoreId(tradeList.getStoreId());
                RepayList repayList2 = ssmRepayService.selectOne(repayList1);
                if(repayList2.getIsCancel()==0){
                    totalMoney=totalMoney.add(tradeList.getPayMoney());
                    RepayAccountList repayAccountList = new RepayAccountList();
                    repayAccountList.setRepayTradeId(tradeList.getId());
                    List<RepayAccountList> select2 = ssmRepayAccountListService.select(repayAccountList);
                    for (RepayAccountList accountList : select2) {
                        totalMoney=totalMoney.add(accountList.getPayMoney());
                    }
                }
            }
            if(rechargeAmount.compareTo(rechargeLists.getCollectionCashAmount().add(totalMoney))==0){ //已经全额还款
                BigDecimal subtract = rechargeAmount.subtract(repayTotalMoney);
                BigDecimal multiply = subtract.multiply(consumeRito);
                BigDecimal subtract1 = rechargeAmount.subtract(multiply);
                //当前单据的充值剩余金额应为
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(subtract1));
                if(rechargeType.getType()==0||rechargeType.getType()==2){
                    if(rechargeLists.getDonateType()==0){
                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().subtract(rechargeType.getGiftMoney()));
                        rechargeAccount.setGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney().subtract(rechargeType.getGiftMoney()));
                        giftConsumeMoneyGive=rechargeType.getGiftMoney();
                    }else{
                        BigDecimal CZconsumeRito = BigDecimalUtils.div(rechargeType.getGiftMoney(),hundredBd);
                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().subtract(rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
                        rechargeAccount.setGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney().subtract(rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
                        giftConsumeMoneyGive=rechargeLists.getRechargeAmount().multiply(CZconsumeRito);
//                        rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));
//                        rechargeAccount.setCardGiftMoney(rechargeAccount.getCardGiftMoney().add( rechargeLists.getRechargeAmount().multiply(CZconsumeRito)));

                    }
                    //查询有没有赠送的疗程
                    PromotionProject promotionProject = new PromotionProject();
                    promotionProject.setPromotionId(rechargeType.getId());
                    List<PromotionProject> promotionProjectList = ssmPromotionProjectService.select(promotionProject);
                    if(promotionProjectList!=null && promotionProjectList.size()>0){
                        //查询会员账户
                        for (PromotionProject project : promotionProjectList) {
                            CourseAccount courseAccount = new CourseAccount();
                            courseAccount.setCourseNum(rechargeAccount.getRechargeNum());
                            courseAccount.setMemberId(rechargeAccount.getMemberId());
                            courseAccount.setCourseProjectId(project.getProjectId());
                            courseAccount.setStoreId(repayTradeList.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);
                            AccountTradeRecord tradeRecord = this.setAccountTradeRecordPomtion(repayTradeList, courseAccount, repayList, project.getTimes(),BigDecimal.ZERO);
                            ssmAccountTradeRecordService.addRecord(tradeRecord);
                        }
                    }

                }
            }else{//还存在欠款
                BigDecimal multiply = repayTotalMoney.multiply(consumeRito);
                rechargeAccount.setCardRestMoney(rechargeAccount.getCardRestMoney().subtract(repayTotalMoney));
                rechargeAccount.setCardConsumeMoney(rechargeAccount.getCardConsumeMoney().subtract(multiply));
            }

        }
        //this.volidAccount(rechargeAccount);
        try {
            rechargeAccount.setCardRestMoney(repayTradeList.getBeforeRestMoney());
            rechargeAccount.setCardConsumeMoney(repayTradeList.getBeforeConsumeMoney());
            rechargeAccount.setCardGiftMoney(repayTradeList.getBeforeGiftRestMoney());
            rechargeAccount.setGiftConsumeMoney(repayTradeList.getBeforeGiftConsumeMoney());
            i = dao.updateByPrimaryKeySelective(rechargeAccount);


            //判断是否促销卡，是否是限制门店使用
            if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                rechargeAccountGive.setAccountId(rechargeAccount.getId());
                rechargeAccountGive.setStoreId(repayTradeList.getStoreId());
                rechargeAccountGive.setStoreName(repayTradeList.getStoreName());
                Example example = new Example(RechargeAccountGive.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                //查询原账户的赠送金额
                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                if(List.size()>0){
                    rechargeAccountGive=List.get(0);
                    //原账户赠送金额-本单作废赠送金额
                    rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().subtract(giftConsumeMoneyGive));
                    ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                }
            }

            if(rechargeType.getType() != 1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setRechargeId(rechargeLists.getId());
                RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
                refundRecord1.setRefundDebtMoney(refundRecord1.getRefundDebtMoney().subtract(repayTradeList.getRepayMoney()));
                if(rechargeLists.getRechargeAmount().compareTo(rechargeLists.getCollectionAmount().add(repayTradeList.getRepayMoney()))==0){
                    refundRecord1.setIsReceived(0);
                }
                int i1 = ssmRefundRecordService.updateNotNull(refundRecord1);
            }
        } catch (Exception e) {
            log.error("SsmRechargeAccountServiceImpl.repayCancel:", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i > 0){
            AccountTradeRecord tradeRecord = this.setAccountTradeRecord(repayTradeList, rechargeAccount, repayList);
            ssmAccountTradeRecordService.addRecord(tradeRecord);
            //更新欠款单信息
            ssmDebtService.updateNotNull(debtList);
        }
        return i;
    }

    public AccountTradeRecord setAccountTradeRecord(RepayTradeList repayTradeList, RechargeAccount rechargeAccount, RepayList repayList){
        DebtList debtList = new DebtList();
        debtList.setId(repayTradeList.getDebtId());
        DebtList debtList1 = ssmDebtService.selectByPrimaryKey(debtList.getId());
        RechargeList rechargeList = new RechargeList();
        rechargeList.setId(debtList1.getDocId());
        rechargeList.setRechargeDate(debtList1.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeList).get(0);

        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayTradeList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeList.getStoreName());
        accountTradeRecord.setMemberId(repayTradeList.getMemberId());
        accountTradeRecord.setMemberName(repayTradeList.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(repayList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_rec_repay);
            accountTradeRecord.setAccountInMoney(repayTradeList.getPayMoney());
            accountTradeRecord.setGiftInMenoy(rechargeLists.getGiftAfterMoney().subtract(rechargeLists.getGiftBeforeMoney()));
            accountTradeRecord.setInputDate(repayList.getRepayDate());
            accountTradeRecord.setOrderStatu(0);
            accountTradeRecord.setInputBy(repayList.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_rec_repay_cancel);
            accountTradeRecord.setAccountSpendMoney(repayTradeList.getPayMoney());
            accountTradeRecord.setInputDate(repayList.getCancelDate());
            accountTradeRecord.setOrderStatu(1);
            accountTradeRecord.setInputBy(repayList.getCancelBy());
            accountTradeRecord.setAccountGiftSpendMoney(rechargeLists.getGiftAfterMoney().subtract(rechargeLists.getGiftBeforeMoney()));
        }
        accountTradeRecord.setDocId(repayList.getId());
        accountTradeRecord.setDocNum(repayList.getRepayNum());
        accountTradeRecord.setDocType(Constant.doc_type_repay);
        accountTradeRecord.setTradeId(repayTradeList.getTradeId());
        accountTradeRecord.setTradeName(repayTradeList.getTradeName());
        accountTradeRecord.setTradeMoney(repayTradeList.getRepayMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setPrice(repayList.getPayMoney());
        return accountTradeRecord;
    }

    public AccountTradeRecord setAccountTradeRecord(RepayTradeList repayTradeList, RechargeAccount rechargeAccount, RepayList repayList,BigDecimal cardPayMoney){
        DebtList debtList = new DebtList();
        debtList.setId(repayTradeList.getDebtId());
        DebtList debtList1 = ssmDebtService.selectByPrimaryKey(debtList.getId());
        RechargeList rechargeList = new RechargeList();
        rechargeList.setId(debtList1.getDocId());
        rechargeList.setRechargeDate(debtList1.getDocDate());
        RechargeList rechargeLists = ssmRechargeService.selectListSalem(rechargeList).get(0);

        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayTradeList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeList.getStoreName());
        accountTradeRecord.setMemberId(repayTradeList.getMemberId());
        accountTradeRecord.setMemberName(repayTradeList.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeList.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(repayList.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_rec_repay);
            accountTradeRecord.setAccountInMoney(repayTradeList.getPayMoney());
            accountTradeRecord.setGiftInMenoy(rechargeLists.getGiftAfterMoney().subtract(rechargeLists.getGiftBeforeMoney()));
            accountTradeRecord.setInputDate(repayList.getRepayDate());
            accountTradeRecord.setOrderStatu(0);
            accountTradeRecord.setInputBy(repayList.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_rec_repay_cancel);
            accountTradeRecord.setAccountSpendMoney(repayTradeList.getPayMoney().add(cardPayMoney));
            accountTradeRecord.setInputDate(repayList.getCancelDate());
            accountTradeRecord.setOrderStatu(1);
            accountTradeRecord.setInputBy(repayList.getCancelBy());
            accountTradeRecord.setAccountGiftSpendMoney(rechargeLists.getGiftAfterMoney().subtract(rechargeLists.getGiftBeforeMoney()));
        }
        accountTradeRecord.setDocId(repayList.getId());
        accountTradeRecord.setDocNum(repayList.getRepayNum());
        accountTradeRecord.setDocType(Constant.doc_type_repay);
        accountTradeRecord.setTradeId(repayTradeList.getTradeId());
        accountTradeRecord.setTradeName(repayTradeList.getTradeName());
        accountTradeRecord.setTradeMoney(repayTradeList.getRepayMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setPrice(repayList.getPayMoney().add(cardPayMoney));
        return accountTradeRecord;
    }


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

    @Override
    @Transactional(rollbackFor=Exception.class)
    public RechargeAccount subMoney(RefundRecharge refundRecharge) throws SmsException {

        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        if(refundRecharge.getRefundGiftMoney()!=null){
            giftConsumeMoneyGive=refundRecharge.getRefundGiftMoney();
        }

        //模拟充值退款门店参数
        int rechargeRefundCategory = 0;

        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(refundRecharge.getRecAccountId());
        if(BigDecimalUtils.compareTo(rechargeAccount.getCardRestMoney(),rechargeAccount.getCardConsumeMoney())!=0 &&BigDecimalUtils.compareTo(rechargeAccount.getCardRestMoney(),refundRecharge.getRecRefundMoney())!=0 && BigDecimalUtils.compareTo(rechargeAccount.getCardConsumeMoney(),refundRecharge.getRecRefundMoney())==-1 ){
            throw new SmsException(ResponseCode.MSG,"存在欠款时，取款的金额最大只能等于可用金额，或者全部退");
        }


        RechargeType rechargeType = new RechargeType();
        rechargeType.setId(rechargeAccount.getRechargeTypeId());
        rechargeType = ssmRechargeTypeSevice.selectOne(rechargeType);

        BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();

        //根据门店设置的退款方式进行核销
        if(0 == refundRecharge.getRefundType()){
            //一次性扣除赠送金额，已经使用过的赠送金额不扣除
            BigDecimal recRefundGiftMoney = BigDecimal.valueOf(0);
            if(rechargeType.getType()!=1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setMemberId(refundRecharge.getMemberId());
                refundRecord.setRechargeTypeId(refundRecharge.getRechargeTypeId());
                List<RefundRecord> select = ssmRefundRecordService.select(refundRecord);
                List<RefundRecord> refundRecords = new ArrayList<>();
                for (RefundRecord record : select) {
                    refundRecords.add(record);
                }

                refundRecords = refundRecords.stream().sorted(Comparator.comparing(RefundRecord::getRechargeDate).reversed()).collect(Collectors.toList());
                BigDecimal recRefundMoney = refundRecharge.getRecRefundMoney();
                //应扣赠送金额


                for (RefundRecord record : refundRecords) {
//                    boolean is= false;
//                    //判断是否第一次扣除
//                    if(record.getRechargeGiftAmount().compareTo(record.getAmountGiftRefunded()) == 1){
//                        if(record.getIsReceived()==1){
//                            is=true;
//                        }
//
//                    }
                    BigDecimal RefundGiftMoney=BigDecimal.valueOf(0);
                    //剩余可扣金额
                    BigDecimal subtract = record.getCollectionAmount().add(record.getRefundDebtMoney()).subtract(record.getAmountRefunded());
                    //剩余赠送未核销
                    BigDecimal subtract1 = record.getRechargeGiftAmount().subtract(record.getAmountGiftRefunded());
                    if(subtract.compareTo(recRefundMoney) != -1){
                        //本次核销的赠送金额
                        boolean isstate=false;
                        if(record.getCollectionAmount().add(record.getRefundDebtMoney()).compareTo(record.getAmountRefunded())!=0){
                            record.setAmountRefunded(record.getAmountRefunded().add(recRefundMoney));
                            isstate=true;
                        }
                        //足够扣

                        if(record.getRechargeGiftAmount().compareTo(record.getAmountGiftRefunded())==1 && record.getIsReceived()==1){

                            if(giftConsumeMoney.compareTo(subtract1)!=-1){
                                record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(subtract1));
                                RefundGiftMoney=subtract1;
                                giftConsumeMoney=giftConsumeMoney.subtract(subtract1);
                            }else{
                                record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(giftConsumeMoney));
                                RefundGiftMoney=giftConsumeMoney;
                                giftConsumeMoney=giftConsumeMoney.subtract(giftConsumeMoney);
                            }
                        }
                        int i = ssmRefundRecordService.updateNotNull(record);
                        if(i>0){
                            RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                            refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            refundRechargeDetail.setRefundRecordId(record.getId());
                            refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                            if(isstate){
                                if(null ==refundRechargeDetail.getRefundMoney()){
                                    refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                                }
                                refundRechargeDetail.setRefundMoney(refundRechargeDetail.getRefundMoney().add(recRefundMoney));
                            }else{
                                refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                            }
                            if(null ==refundRechargeDetail.getRefundGiftMoney()){
                                refundRechargeDetail.setRefundGiftMoney(BigDecimal.valueOf(0));
                            }
                            refundRechargeDetail.setRefundGiftMoney(refundRechargeDetail.getRefundGiftMoney().add(RefundGiftMoney));
                            recRefundGiftMoney=recRefundGiftMoney.add(RefundGiftMoney);
                            ssmRefundRechargeDetailService.save(refundRechargeDetail);

                        }
                        if(isstate){
                            recRefundMoney = BigDecimal.valueOf(0);
                        }
                        if(recRefundMoney.compareTo(BigDecimal.valueOf(0))!=1){
                            break;
                        }
                    }else{
                        boolean isstate=false;
                        ///不足够扣
                        if(record.getCollectionAmount().add(record.getRefundDebtMoney()).compareTo(record.getAmountRefunded())!=0){
                            record.setAmountRefunded(record.getAmountRefunded().add(subtract));
                            isstate=true;
                        }
                        if(record.getRechargeGiftAmount().compareTo(record.getAmountGiftRefunded())==1 && record.getIsReceived()==1){
                            if(giftConsumeMoney.compareTo(subtract1)!=-1){
                                record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(subtract1));
                                RefundGiftMoney=subtract1;
                                giftConsumeMoney=giftConsumeMoney.subtract(subtract1);
                            }else{
                                record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(giftConsumeMoney));
                                RefundGiftMoney=giftConsumeMoney;
                                giftConsumeMoney=giftConsumeMoney.subtract(giftConsumeMoney);
                            }
                        }
                        int i = ssmRefundRecordService.updateNotNull(record);
                        if(i>0){
                            RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                            refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            refundRechargeDetail.setRefundRecordId(record.getId());
                            refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                            if(isstate){
                                if(null ==refundRechargeDetail.getRefundMoney()){
                                    refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                                }
                                refundRechargeDetail.setRefundMoney(refundRechargeDetail.getRefundMoney().add(subtract));
                            }else{
                                refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                            }
                            if(null ==refundRechargeDetail.getRefundGiftMoney()){
                                refundRechargeDetail.setRefundGiftMoney(BigDecimal.valueOf(0));
                            }
                            refundRechargeDetail.setRefundGiftMoney(refundRechargeDetail.getRefundGiftMoney().add(RefundGiftMoney));
                            recRefundGiftMoney=recRefundGiftMoney.add(RefundGiftMoney);
                            ssmRefundRechargeDetailService.save(refundRechargeDetail);
                        }
                        if(isstate){
                            recRefundMoney = recRefundMoney.subtract(subtract);
                        }
                        if(recRefundMoney.compareTo(BigDecimal.valueOf(0))!=1){
                            break;
                        }
                    }
                }
            }
            refundRecharge.setCardGiftMoney(recRefundGiftMoney);
            refundRecharge.setGiftConsumeMoney(recRefundGiftMoney);
            refundRecharge.setRefundGiftMoney(recRefundGiftMoney);
            if(rechargeAccount.getCardRestMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                if(rechargeAccount.getCardRestMoney().compareTo(refundRecharge.getRecRefundMoney())==0){
                    //rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getCardRestMoney()));
                    rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getRecRefundMoney()));
                    rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(),refundRecharge.getCardGiftMoney()));
                    //rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getCardConsumeMoney()));

                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getGiftConsumeMoney(),refundRecharge.getGiftConsumeMoney()));
                    if(rechargeAccount.getCardConsumeMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getRecRefundMoney()));
                    }else{
                        rechargeAccount.setCardConsumeMoney(BigDecimal.valueOf(0));
                    }
                    this.volidAccount(rechargeAccount);
                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount,refundRecharge.getStoreId(),giftConsumeMoneyGive,1,1);
                    return this.subMoney(rechargeAccount);
                }else{

                    //rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getCardRestMoney()));
                    rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getRecRefundMoney()));
                    rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(),refundRecharge.getCardGiftMoney()));
                    //rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getCardConsumeMoney()));

                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getGiftConsumeMoney(),refundRecharge.getGiftConsumeMoney()));
                    if(rechargeAccount.getCardConsumeMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getRecRefundMoney()));
                    }else{
                        rechargeAccount.setCardConsumeMoney(BigDecimal.valueOf(0));
                    }
                    this.volidAccount(rechargeAccount);

                    //rechargeAccount.setCardRestMoney(BigDecimal.valueOf(-1));
                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount,refundRecharge.getStoreId(),giftConsumeMoneyGive,1,1);
                    return this.subMoney(rechargeAccount);
                }
            }else{
                rechargeAccount.setCardRestMoney(BigDecimal.valueOf(-2));
                return rechargeAccount;
            }

        }else  if(1 ==  refundRecharge.getRefundType()){
            //保证效率的标识
            int xl=0;
            int xl1=0;
            int bs=0;
            int bs1=0;

            List<RefundRechargeDetail> refundRechargeDetails = new ArrayList<>();
            //手工录入
            if(rechargeType.getType()!=1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setMemberId(refundRecharge.getMemberId());
                refundRecord.setRechargeTypeId(refundRecharge.getRechargeTypeId());
                List<RefundRecord> select = ssmRefundRecordService.select(refundRecord);
                List<RefundRecord> refundRecords = new ArrayList<>();
                for (RefundRecord record : select) {
                    if(record.getCollectionAmount().add(record.getRefundDebtMoney()).compareTo(record.getAmountRefunded())!=0 || record.getRechargeGiftAmount().compareTo(record.getAmountGiftRefunded())!=0 ){
                        refundRecords.add(record);
                    }
                }
                refundRecords = refundRecords.stream().sorted(Comparator.comparing(RefundRecord::getRechargeDate).reversed()).collect(Collectors.toList());
                //先核销退款的充值金额
                //退款的金额
                BigDecimal recRefundMoney = refundRecharge.getRecRefundMoney();
                for (RefundRecord record : refundRecords) {
                    BigDecimal subtract = record.getCollectionAmount().add(record.getRefundDebtMoney()).subtract(record.getAmountRefunded());
                    if(subtract.compareTo(recRefundMoney)!=-1){
                        xl++;
                        //足够核销
                        record.setAmountRefunded(record.getAmountRefunded().add(recRefundMoney));
                        RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                        refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        refundRechargeDetail.setRefundRecordId(record.getId());
                        refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                        if(null ==refundRechargeDetail.getRefundMoney()){
                            refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                        }
                        refundRechargeDetail.setRefundMoney(refundRechargeDetail.getRefundMoney().add(recRefundMoney));
                        refundRechargeDetails.add(refundRechargeDetail);

                        recRefundMoney=recRefundMoney.subtract(recRefundMoney);
                        if(recRefundMoney.compareTo(BigDecimal.valueOf(0))==0){
                            break;
                        }
                    }else{
                        xl++;
                        //不足够核销
                        record.setAmountRefunded(record.getAmountRefunded().add(subtract));

                        RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                        refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        refundRechargeDetail.setRefundRecordId(record.getId());
                        refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                        if(null ==refundRechargeDetail.getRefundMoney()){
                            refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                        }
                        refundRechargeDetail.setRefundMoney(refundRechargeDetail.getRefundMoney().add(subtract));
                        refundRechargeDetails.add(refundRechargeDetail);
                        recRefundMoney=recRefundMoney.subtract(subtract);
                        if(recRefundMoney.compareTo(BigDecimal.valueOf(0))==0){
                            break;
                        }
                    }

                }

                //核销赠送金额
                BigDecimal recRefundGiftMoney = refundRecharge.getRefundGiftMoney();
                for (RefundRecord record : refundRecords) {
                    if(recRefundGiftMoney.compareTo(BigDecimal.valueOf(0))==1){
                        BigDecimal subtract = record.getRechargeGiftAmount().subtract(record.getAmountGiftRefunded());
                        if(record.getIsReceived()==1 && subtract.compareTo(BigDecimal.valueOf(0))==1){
                            if(subtract.compareTo(recRefundGiftMoney)!=-1){
                                xl1++;
                                //足够
                                record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(recRefundGiftMoney));
                                List<RefundRechargeDetail> resultList = refundRechargeDetails.stream().filter(obj-> Objects.equals(obj.getRefundRecordId(), record.getId())).collect(Collectors.toList());
                                if(resultList.size()>0){
                                    RefundRechargeDetail refundRechargeDetail = resultList.get(0);
                                    if(null ==refundRechargeDetail.getRefundGiftMoney()){
                                        refundRechargeDetail.setRefundGiftMoney(BigDecimal.valueOf(0));
                                    }
                                    refundRechargeDetail.setRefundGiftMoney(refundRechargeDetail.getRefundGiftMoney().add(recRefundGiftMoney));
                                }else{
                                    RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                                    refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                                    refundRechargeDetail.setRefundRecordId(record.getId());
                                    refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                                    refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                                    if(null ==refundRechargeDetail.getRefundGiftMoney()){
                                        refundRechargeDetail.setRefundGiftMoney(BigDecimal.valueOf(0));
                                    }
                                    refundRechargeDetail.setRefundGiftMoney(refundRechargeDetail.getRefundGiftMoney().add(recRefundGiftMoney));
                                    refundRechargeDetails.add(refundRechargeDetail);
                                }
                                recRefundGiftMoney=recRefundGiftMoney.subtract(recRefundGiftMoney);
                            }else{
                                xl1++;
                                //不足够
                                record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(subtract));
                                List<RefundRechargeDetail> resultList = refundRechargeDetails.stream().filter(obj-> Objects.equals(obj.getRefundRecordId(), record.getId())).collect(Collectors.toList());
                                if(resultList.size()>0){
                                    RefundRechargeDetail refundRechargeDetail = resultList.get(0);
                                    if(null ==refundRechargeDetail.getRefundGiftMoney()){
                                        refundRechargeDetail.setRefundGiftMoney(BigDecimal.valueOf(0));
                                    }
                                    refundRechargeDetail.setRefundGiftMoney(refundRechargeDetail.getRefundGiftMoney().add(subtract));
                                }else{
                                    RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                                    refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                                    refundRechargeDetail.setRefundRecordId(record.getId());
                                    refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                                    refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                                    if(null ==refundRechargeDetail.getRefundGiftMoney()){
                                        refundRechargeDetail.setRefundGiftMoney(BigDecimal.valueOf(0));
                                    }
                                    refundRechargeDetail.setRefundGiftMoney(refundRechargeDetail.getRefundGiftMoney().add(subtract));
                                    refundRechargeDetails.add(refundRechargeDetail);
                                }
                                recRefundGiftMoney=recRefundGiftMoney.subtract(subtract);
                            }
                        }
                    }else{
                        break;
                    }
                }
                if(xl>xl1){
                    bs=xl;
                }else{
                    bs=xl1;
                }

                for (RefundRecord record : refundRecords) {

                    int i = ssmRefundRecordService.updateNotNull(record);
                    if(i==0){
                        throw new SmsException(ResponseCode.MSG,"审核核销充值记录异常");
                    }
                    bs1++;
                    if(bs==bs1){
                        break;
                    }
                }
                bs1=0;
                for (RefundRechargeDetail refundRechargeDetail : refundRechargeDetails) {
                    int save = ssmRefundRechargeDetailService.save(refundRechargeDetail);
                    if(save==0){
                        throw new SmsException(ResponseCode.MSG,"审核核销充值记录异常");
                    }
                    bs1++;
                    if(bs==bs1){
                        break;
                    }
                }
            }
            if(rechargeAccount.getCardRestMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                if(rechargeAccount.getCardRestMoney().compareTo(refundRecharge.getRecRefundMoney())==0){
                    //rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getCardRestMoney()));
                    rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getRecRefundMoney()));
                    rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(),refundRecharge.getRefundGiftMoney()));
                    //rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getCardConsumeMoney()));

                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getGiftConsumeMoney(),refundRecharge.getRefundGiftMoney()));
                    if(rechargeAccount.getCardConsumeMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getRecRefundMoney()));
                    }else{
                        rechargeAccount.setCardConsumeMoney(BigDecimal.valueOf(0));
                    }
                    this.volidAccount(rechargeAccount);
                    giftConsumeMoneyGive=refundRecharge.getRefundGiftMoney();
                    //判断是否促销卡，是否是限制门店使用
                   /* if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
                        RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
                        BeanUtils.copyProperties(rechargeAccount,rechargeAccountGive);
                        rechargeAccountGive.setAccountId(rechargeAccount.getId());
                        Example example = new Example(RechargeAccountGive.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                        criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                        criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                        //查询原账户的赠送金额
                        List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                        if(List.size()>0){
                            rechargeAccountGive=List.get(0);
                            //原账户赠送金额-本单充值赠送金额
                            giftConsumeMoneyGive=BigDecimalUtils.subtract(rechargeAccountGive.getGiftConsumeMoney(), giftConsumeMoneyGive);
                            rechargeAccountGive.setGiftConsumeMoney(giftConsumeMoneyGive);
                            ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                        }
                    }*/
                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount,refundRecharge.getStoreId(),giftConsumeMoneyGive,1,1);
                    return this.subMoney(rechargeAccount);
                }else{
                    //rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getCardRestMoney()));
                    rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getRecRefundMoney()));
                    rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(),refundRecharge.getRefundGiftMoney()));
                    //rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getCardConsumeMoney()));

                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getGiftConsumeMoney(),refundRecharge.getRefundGiftMoney()));
                    if(rechargeAccount.getCardConsumeMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getRecRefundMoney()));
                    }else{
                        rechargeAccount.setCardConsumeMoney(BigDecimal.valueOf(0));
                    }
                    this.volidAccount(rechargeAccount);

                    //rechargeAccount.setCardRestMoney(BigDecimal.valueOf(-1));
                    giftConsumeMoneyGive=refundRecharge.getRefundGiftMoney();
                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount,refundRecharge.getStoreId(),giftConsumeMoneyGive,1,1);
                    return this.subMoney(rechargeAccount);
                }
            }else{
                rechargeAccount.setCardRestMoney(BigDecimal.valueOf(-2));
                return this.subMoney(rechargeAccount);
            }
        }else  if(2 ==  refundRecharge.getRefundType()){
            //未想好
            BigDecimal giftConsumeMoney1 = rechargeAccount.getGiftConsumeMoney();

            //按比例扣除
            BigDecimal recRefundGiftMoney = BigDecimal.valueOf(0);
            if(rechargeType.getType()!=1){
                RefundRecord refundRecord = new RefundRecord();
                refundRecord.setMemberId(refundRecharge.getMemberId());
                refundRecord.setRechargeTypeId(refundRecharge.getRechargeTypeId());
                List<RefundRecord> select = ssmRefundRecordService.select(refundRecord);
                List<RefundRecord> refundRecords = new ArrayList<>();
                for (RefundRecord record : select) {
                    refundRecords.add(record);
                }

                refundRecords = refundRecords.stream().sorted(Comparator.comparing(RefundRecord::getRechargeDate).reversed()).collect(Collectors.toList());
                BigDecimal recRefundMoney = refundRecharge.getRecRefundMoney();
                //应扣赠送金额


                for (RefundRecord record : refundRecords) {
//                    boolean is= false;
//                    //判断是否第一次扣除
//                    if(record.getRechargeGiftAmount().compareTo(record.getAmountGiftRefunded()) == 1){
//                        if(record.getIsReceived()==1){
//                            is=true;
//                        }
//
//                    }
                    BigDecimal RefundGiftMoney=BigDecimal.valueOf(0);
                    //剩余可扣金额
                    BigDecimal subtract = record.getCollectionAmount().add(record.getRefundDebtMoney()).subtract(record.getAmountRefunded());
                    //剩余赠送未核销
                    BigDecimal subtract1 = BigDecimal.valueOf(0);
                    if(subtract.compareTo(recRefundMoney) != -1||subtract1.compareTo(BigDecimal.valueOf(0))==1){
                        //本次核销的赠送金额
                        boolean isstate=false;
                        if(record.getCollectionAmount().add(record.getRefundDebtMoney()).compareTo(record.getAmountRefunded())!=0){
                            record.setAmountRefunded(record.getAmountRefunded().add(recRefundMoney));
                            isstate=true;
                        }

                        //应扣
                        BigDecimal divide = recRefundMoney.divide(record.getCollectionAmount().add(record.getRefundDebtMoney()), 4, BigDecimal.ROUND_HALF_UP);

                        if(record.getRechargeGiftAmount().compareTo(record.getAmountGiftRefunded())==1 && record.getIsReceived()==1){

                            if(divide.compareTo(subtract1)!=-1){
                                if(giftConsumeMoney1.compareTo(divide)!=-1){
                                    record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(divide));
                                    RefundGiftMoney=divide;
                                    giftConsumeMoney=giftConsumeMoney.add(divide);
                                    giftConsumeMoney1=giftConsumeMoney1.subtract(divide);
                                }else{
                                    record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(giftConsumeMoney1));
                                    RefundGiftMoney=giftConsumeMoney1;
                                    giftConsumeMoney=giftConsumeMoney.add(giftConsumeMoney1);
                                    giftConsumeMoney1=giftConsumeMoney1.subtract(giftConsumeMoney1);
                                }

                            }else{
                                if(giftConsumeMoney1.compareTo(divide)!=-1){
                                    record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(divide));
                                    RefundGiftMoney=divide;
                                    giftConsumeMoney=giftConsumeMoney.subtract(divide);
                                    giftConsumeMoney1=giftConsumeMoney1.subtract(divide);
                                }else{
                                    record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(giftConsumeMoney1));
                                    RefundGiftMoney=giftConsumeMoney1;
                                    giftConsumeMoney=giftConsumeMoney.subtract(giftConsumeMoney1);
                                    giftConsumeMoney1=giftConsumeMoney1.subtract(giftConsumeMoney1);
                                }

                            }
                        }
                        int i = ssmRefundRecordService.updateNotNull(record);
                        if(i>0){
                            RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                            refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            refundRechargeDetail.setRefundRecordId(record.getId());
                            refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                            if(isstate){
                                refundRechargeDetail.setRefundMoney(recRefundMoney);
                            }else{
                                refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                            }
                            refundRechargeDetail.setRefundGiftMoney(RefundGiftMoney);
                            recRefundGiftMoney=recRefundGiftMoney.add(RefundGiftMoney);
                            ssmRefundRechargeDetailService.save(refundRechargeDetail);

                        }
                        if(isstate){
                            recRefundMoney = BigDecimal.valueOf(0);
                        }
                        if(recRefundMoney.compareTo(BigDecimal.valueOf(0))!=1){
                            break;
                        }
                    }else{
                        boolean isstate=false;
                        ///不足够扣
                        if(record.getCollectionAmount().add(record.getRefundDebtMoney()).compareTo(record.getAmountRefunded())!=0){
                            record.setAmountRefunded(record.getAmountRefunded().add(subtract));
                            isstate=true;
                        }
                        //足够扣
                        BigDecimal divide = recRefundMoney.divide(record.getCollectionAmount().add(record.getRefundDebtMoney()), 4, BigDecimal.ROUND_HALF_UP);

                        if(record.getRechargeGiftAmount().compareTo(record.getAmountGiftRefunded())==1 && record.getIsReceived()==1){
                            if(divide.compareTo(subtract1)!=-1){
                                if(giftConsumeMoney1.compareTo(divide)!=-1){
                                    record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(divide));
                                    RefundGiftMoney=divide;
                                    giftConsumeMoney=giftConsumeMoney.subtract(divide);
                                    giftConsumeMoney1=giftConsumeMoney1.subtract(divide);
                                }else{
                                    record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(giftConsumeMoney1));
                                    RefundGiftMoney=giftConsumeMoney1;
                                    giftConsumeMoney=giftConsumeMoney.subtract(giftConsumeMoney1);
                                    giftConsumeMoney1=giftConsumeMoney1.subtract(giftConsumeMoney1);

                                }

                            }else{
                                record.setAmountGiftRefunded(record.getAmountGiftRefunded().add(divide));
                                RefundGiftMoney=divide;
                                giftConsumeMoney=giftConsumeMoney.subtract(divide);
                                giftConsumeMoney1=giftConsumeMoney1.subtract(divide);
                            }
                        }
                        int i = ssmRefundRecordService.updateNotNull(record);
                        if(i>0){
                            RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
                            refundRechargeDetail.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            refundRechargeDetail.setRefundRecordId(record.getId());
                            refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
                            if(isstate){
                                refundRechargeDetail.setRefundMoney(subtract);
                            }else{
                                refundRechargeDetail.setRefundMoney(BigDecimal.valueOf(0));
                            }

                            refundRechargeDetail.setRefundGiftMoney(RefundGiftMoney);
                            recRefundGiftMoney=recRefundGiftMoney.add(RefundGiftMoney);
                            ssmRefundRechargeDetailService.save(refundRechargeDetail);
                        }
                        if(isstate){
                            recRefundMoney = recRefundMoney.subtract(subtract);
                        }
                        if(recRefundMoney.compareTo(BigDecimal.valueOf(0))!=1){
                            break;
                        }
                    }
                }
            }
            refundRecharge.setCardGiftMoney(recRefundGiftMoney);
            refundRecharge.setGiftConsumeMoney(recRefundGiftMoney);
            refundRecharge.setRefundGiftMoney(recRefundGiftMoney);
            if(rechargeAccount.getCardRestMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                if(rechargeAccount.getCardRestMoney().compareTo(refundRecharge.getRecRefundMoney())==0){
                    //rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getCardRestMoney()));
                    rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getRecRefundMoney()));
                    rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(),refundRecharge.getCardGiftMoney()));
                    //rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getCardConsumeMoney()));

                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getGiftConsumeMoney(),refundRecharge.getGiftConsumeMoney()));
                    if(rechargeAccount.getCardConsumeMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getRecRefundMoney()));
                    }else{
                        rechargeAccount.setCardConsumeMoney(BigDecimal.valueOf(0));
                    }
                    this.volidAccount(rechargeAccount);
                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount,refundRecharge.getStoreId(),giftConsumeMoneyGive,1,1);
                    return this.subMoney(rechargeAccount);
                }else{

                    //rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getCardRestMoney()));
                    rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),refundRecharge.getRecRefundMoney()));
                    rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(),refundRecharge.getCardGiftMoney()));
                    //rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getCardConsumeMoney()));

                    rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getGiftConsumeMoney(),refundRecharge.getGiftConsumeMoney()));
                    if(rechargeAccount.getCardConsumeMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
                        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),refundRecharge.getRecRefundMoney()));
                    }else{
                        rechargeAccount.setCardConsumeMoney(BigDecimal.valueOf(0));
                    }
                    this.volidAccount(rechargeAccount);

                    //rechargeAccount.setCardRestMoney(BigDecimal.valueOf(-1));
                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount,refundRecharge.getStoreId(),giftConsumeMoneyGive,1,1);
                    return this.subMoney(rechargeAccount);
                }
            }else{
                rechargeAccount.setCardRestMoney(BigDecimal.valueOf(-2));
                return rechargeAccount;
            }

        }
        return rechargeAccount;

    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public RechargeAccount addMoney(RefundRecharge refundRecharge) throws SmsException {
        RefundRechargeDetail refundRechargeDetail = new RefundRechargeDetail();
        BigDecimal giftConsumeMoneyGive=new BigDecimal("0");
        if(refundRecharge.getRefundGiftMoney()!=null){
            giftConsumeMoneyGive=refundRecharge.getRefundGiftMoney();
        }
        refundRechargeDetail.setRefundRechargeId(refundRecharge.getId());
        List<RefundRechargeDetail> select = ssmRefundRechargeDetailService.select(refundRechargeDetail);
        //反审核返回赠送金额
        BigDecimal giftMoney = BigDecimal.valueOf(0);
        for (RefundRechargeDetail rechargeDetail : select) {
            Boolean is = false;
            if(null == rechargeDetail.getRefundGiftMoney()){
                rechargeDetail.setRefundGiftMoney(BigDecimal.valueOf(0));
            }
            giftMoney=giftMoney.add(rechargeDetail.getRefundGiftMoney());

            RefundRecord refundRecord = new RefundRecord();
            refundRecord.setId(rechargeDetail.getRefundRecordId());
            RefundRecord refundRecord1 = ssmRefundRecordService.selectOne(refundRecord);
            if(rechargeDetail.getRefundGiftMoney().compareTo(BigDecimal.valueOf(0))==1){
                is=true;
                refundRecord1.setIsDeduct(0);
            }
            refundRecord1.setAmountRefunded(refundRecord1.getAmountRefunded().subtract(rechargeDetail.getRefundMoney()));
            refundRecord1.setAmountGiftRefunded(refundRecord1.getAmountGiftRefunded().subtract(rechargeDetail.getRefundGiftMoney()));
            ssmRefundRecordService.updateNotNull(refundRecord1);
            ssmRefundRechargeDetailService.deleteByPrimaryKey(rechargeDetail.getId());

        }
        refundRecharge.setCardGiftMoney(giftMoney);
        refundRecharge.setGiftConsumeMoney(giftMoney);
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(refundRecharge.getRecAccountId());
       // rechargeAccount.setCardRestMoney(BigDecimalUtils.add(rechargeAccount.getCardRestMoney(), refundRecharge.getCardRestMoney()));
        rechargeAccount.setCardRestMoney(BigDecimalUtils.add(rechargeAccount.getCardRestMoney(), refundRecharge.getRecRefundMoney()));
        rechargeAccount.setCardGiftMoney(BigDecimalUtils.add(rechargeAccount.getCardGiftMoney(), refundRecharge.getCardGiftMoney()));
        //rechargeAccount.setCardConsumeMoney(BigDecimalUtils.add(rechargeAccount.getCardConsumeMoney(), refundRecharge.getCardConsumeMoney()));
        rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), refundRecharge.getGiftConsumeMoney()));
        if(refundRecharge.getCardConsumeMoney().compareTo(refundRecharge.getRecRefundMoney())>-1){
            rechargeAccount.setCardConsumeMoney(BigDecimalUtils.add(rechargeAccount.getCardConsumeMoney(), refundRecharge.getRecRefundMoney()));
        }else{
            rechargeAccount.setCardConsumeMoney(BigDecimalUtils.add(rechargeAccount.getCardConsumeMoney(), refundRecharge.getCardConsumeMoney()));
        }
        //updateType==1为修改  asType==1为减0为加
        this.rechargeAccountGive(rechargeAccount,refundRecharge.getStoreId(),giftConsumeMoneyGive,1,0);
        return this.addMoney(rechargeAccount);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public RechargeAccount addMoney(CashAccountList cashAccountList,Long storeId) throws SmsException {
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(cashAccountList.getRecAccountId());
        rechargeAccount.setCardRestMoney(BigDecimalUtils.add(rechargeAccount.getCardRestMoney(), cashAccountList.getCardPayMoney()));
        rechargeAccount.setCardGiftMoney(BigDecimalUtils.add(rechargeAccount.getCardGiftMoney(), cashAccountList.getGiftPayMoney()));
        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.add(rechargeAccount.getCardConsumeMoney(), cashAccountList.getCardPayMoney()));
        rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount.getGiftConsumeMoney(), cashAccountList.getGiftPayMoney()));
        //获取本单转出赠送金额
        BigDecimal giftConsumeMoneyGive=cashAccountList.getGiftPayMoney();
        //updateType==1为修改  asType==1为减0为加
        if(storeId!=null)
        this.rechargeAccountGive(rechargeAccount,storeId,giftConsumeMoneyGive,1,0);
        return this.addMoney(rechargeAccount);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public RechargeAccount subMoney(CashAccountList cashAccountList,Long storeId) throws SmsException {
        RechargeAccount rechargeAccount = dao.selectByPrimaryKey(cashAccountList.getRecAccountId());
        rechargeAccount.setCardRestMoney(BigDecimalUtils.subtract(rechargeAccount.getCardRestMoney(),cashAccountList.getCardPayMoney()));
        rechargeAccount.setCardGiftMoney(BigDecimalUtils.subtract(rechargeAccount.getCardGiftMoney(),cashAccountList.getGiftPayMoney()));
        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getCardConsumeMoney(),cashAccountList.getCardPayMoney()));
        rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.subtract(rechargeAccount.getGiftConsumeMoney(),cashAccountList.getGiftPayMoney()));
        this.volidAccount(rechargeAccount);
        //获取本单转出赠送金额
        BigDecimal giftConsumeMoneyGive=cashAccountList.getGiftPayMoney();
        //updateType==1为修改  asType==1为减0为加
        if(storeId!=null)
        this.rechargeAccountGive(rechargeAccount,storeId,giftConsumeMoneyGive,1,1);
        return this.subMoney(rechargeAccount);
    }


    @Override
    public int addMoney(List<RechargeAccountRequest> rechargeAccountList, DocPromotion docPromotion) throws SmsException {
        int i = 0;
        //查询账户交易记录
        AccountTradeRecordRequest accountTradeRecordRequest = new AccountTradeRecordRequest();
        accountTradeRecordRequest.setAccountType(Constant.account_type_recharge_consume);
        accountTradeRecordRequest.setInputDate(docPromotion.getDocDate());
        accountTradeRecordRequest.setDocId(docPromotion.getId());
        accountTradeRecordRequest.setStoreId(docPromotion.getStoreId());
        List<AccountTradeRecord> recordList = ssmAccountTradeRecordService.selectList(accountTradeRecordRequest);
        for (AccountTradeRecord accountTradeRecord : recordList) {
            RechargeAccount rechargeAccount = dao.selectByPrimaryKey(accountTradeRecord.getAccountId());
            BigDecimal spendMoney  = accountTradeRecord.getAccountSpendMoney();
            BigDecimal giftSpendMoney = accountTradeRecord.getAccountGiftSpendMoney();
            BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
            BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
            BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
            BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();

            if (0 == rechargeAccount.getType()){//赠送卡
                //充值金额与赠送金额按比例使用 或者 先使用充值金额,再使用赠送金额 (存在赠品金额计算)
                cardGiftMoney = BigDecimalUtils.add(cardGiftMoney, giftSpendMoney);
                giftConsumeMoney = BigDecimalUtils.add(giftConsumeMoney, giftSpendMoney);
                cardRestMoney = BigDecimalUtils.add(cardRestMoney, BigDecimalUtils.subtract(spendMoney, giftSpendMoney));
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney, BigDecimalUtils.subtract(spendMoney, giftSpendMoney));

            }else {//折扣卡
                cardRestMoney = BigDecimalUtils.add(cardRestMoney,spendMoney);
                cardConsumeMoney = BigDecimalUtils.add(cardConsumeMoney,spendMoney);
            }
            rechargeAccount.setCardRestMoney(cardRestMoney);
            rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccount.setLastConsumeTime(new Date());
            try {
                rechargeAccount.setFirstCharge(rechargeAccount.getFirstCharge()-1);
                i = dao.updateByPrimaryKeySelective(rechargeAccount);
            } catch (Exception e) {
                log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0){
                AccountTradeRecord tradeRecord = this.setAccountTradeRecord(docPromotion, rechargeAccount, giftSpendMoney);
                tradeRecord.setOrderStatu(1);
                ssmAccountTradeRecordService.addRecord(tradeRecord);
            }
        }
        return i;
    }


    @Override
    public int subMoney(List<RechargeAccountRequest> rechargeAccountList, DocPromotion docPromotion) throws SmsException {
        int i= 0;
        //查询门店充值账户使用参数
        StoreParament storeParament = StoreParaUtils.getStorePara(docPromotion.getStoreId(), Constant.use_recharge);
        //查询促销方案
        PromotionList promotionList = ssmPromotionService.selectByPrimaryKey(docPromotion.getPromotionId());
        BigDecimal subMoney = BigDecimalUtils.bigDecimal("0");
        BigDecimal hundredBd = BigDecimalUtils.bigDecimal("100");
        for (RechargeAccountRequest rechargeAccountRequest : rechargeAccountList) {
            RechargeAccount rechargeAccount = new RechargeAccount();
            BeanUtils.copyProperties(rechargeAccountRequest,rechargeAccount);
            RechargeAccount rechargeAccounts = dao.selectByPrimaryKey(rechargeAccountRequest.getId());
            subMoney = rechargeAccountRequest.getSpendMoney();
            BigDecimal cardRestMoney = rechargeAccount.getCardRestMoney();
            BigDecimal cardConsumeMoney = rechargeAccount.getCardConsumeMoney();
            BigDecimal cardGiftMoney = rechargeAccount.getCardGiftMoney();
            BigDecimal giftConsumeMoney = rechargeAccount.getGiftConsumeMoney();
            BigDecimal giftSpendMoney =  BigDecimalUtils.bigDecimal("0");
            if (0 == rechargeAccount.getType() || 2 == rechargeAccount.getType()){//赠送卡
                //不允许使用赠送金额
                if (0 == promotionList.getCardLimit()){
                    cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, subMoney);
                    cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney, subMoney);
                }else {
                    if ("1".equals(storeParament.getParamentValue())) {//充值金额与赠送金额按比例使用
                        //赠品扣减金额 = 扣减金额 * 赠送金额与充值金额比例
                        BigDecimal giftSubMoney = BigDecimalUtils.multiply(subMoney, BigDecimalUtils.div(cardGiftMoney, cardRestMoney));
                        //正常充值扣减金额
                        BigDecimal cardSubMoney = BigDecimalUtils.subtract(subMoney, giftSubMoney);
                        //赠品扣减后剩余金额
                        BigDecimal giftLeftMoney = BigDecimalUtils.subtract(giftConsumeMoney, giftSubMoney);
                        //赠品扣减后剩余金额 < 0 正常充值金额继续扣减
                        if (BigDecimalUtils.compareTo(giftLeftMoney, BigDecimalUtils.bigDecimal("0")) < 0) {
                            cardRestMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardRestMoney, cardSubMoney), giftLeftMoney);//剩余金额 = 剩余金额-正常充值扣减金额-赠品扣减后剩余金额(-负+正)
                            cardConsumeMoney = BigDecimalUtils.add(BigDecimalUtils.subtract(cardConsumeMoney, cardSubMoney), giftLeftMoney);//可消费金额 = 可消费金额-正常充值扣减金额-赠品扣减后剩余金额
                            cardGiftMoney = BigDecimalUtils.bigDecimal("0");
                            giftConsumeMoney = BigDecimalUtils.bigDecimal("0");
                            giftSpendMoney = rechargeAccount.getCardConsumeMoney();
                        } else {
                            cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, cardSubMoney);
                            cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney, cardSubMoney);
                            cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney, giftSubMoney);
                            giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, giftSubMoney);
                            giftSpendMoney = giftSubMoney;
                        }

                    } else {
//                    //先使用赠送金额,再使用充值金额
//                    //支付金额 >= 赠送可消费金额
//                    if (BigDecimalUtils.compareTo(subMoney,giftConsumeMoney) >= 0){
//                        BigDecimal leftMoney = BigDecimalUtils.subtract(subMoney,cardConsumeMoney);
//                        cardRestMoney = BigDecimalUtils.subtract(cardRestMoney,leftMoney);
//                        cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,leftMoney);
//                        cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney,giftConsumeMoney);
//                        giftConsumeMoney = BigDecimalUtils.bigDecimal("0");
//                        giftSpendMoney = rechargeAccount.getGiftConsumeMoney();
//                    }else {
//                        cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney,subMoney);
//                        giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney,subMoney);
//                        giftSpendMoney = subMoney;
//                    }

                        //先试用实充金额 在使用赠送金额
                        //支付金额 >= 实充金额
                        if (BigDecimalUtils.compareTo(subMoney, cardConsumeMoney) >= 0) {
                            BigDecimal leftMoney = BigDecimalUtils.subtract(subMoney, cardConsumeMoney);
                            cardRestMoney = BigDecimalUtils.bigDecimal("0");
                            cardConsumeMoney = BigDecimalUtils.bigDecimal("0");
                            cardGiftMoney = BigDecimalUtils.subtract(cardGiftMoney, leftMoney);
                            giftConsumeMoney = BigDecimalUtils.subtract(giftConsumeMoney, leftMoney);
                            giftSpendMoney = leftMoney;
                        } else {
                            cardRestMoney = BigDecimalUtils.subtract(cardRestMoney, subMoney);
                            cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney, subMoney);
                        }
                    }
                }
            }else {//折扣卡
                cardRestMoney = BigDecimalUtils.subtract(cardRestMoney,subMoney);
                cardConsumeMoney = BigDecimalUtils.subtract(cardConsumeMoney,subMoney);
            }
            rechargeAccount.setCardRestMoney(cardRestMoney);
            rechargeAccount.setCardConsumeMoney(cardConsumeMoney);
            rechargeAccount.setCardGiftMoney(cardGiftMoney);
            rechargeAccount.setGiftConsumeMoney(giftConsumeMoney);
            rechargeAccount.setLastConsumeTime(docPromotion.getDocDate());
            this.volidAccount(rechargeAccount);
//            list.add(rechargeAccount);
            try {
                if(null == rechargeAccounts.getFirstCharge()){
                    rechargeAccount.setFirstCharge(1L);
                }else{
                    rechargeAccount.setFirstCharge(rechargeAccounts.getFirstCharge()+1);
                }

                i = dao.updateByPrimaryKeySelective(rechargeAccount);
            } catch (Exception e) {
                log.error("SsmRechargeAccountServiceImpl.subMoney:", e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (i > 0){
                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(docPromotion, rechargeAccount, giftSpendMoney);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
            }
        }

        return i;
    }

    public AccountTradeRecord setAccountTradeRecord(DocPromotion docPromotion, RechargeAccount rechargeAccount, BigDecimal giftSpendMoney){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(docPromotion.getStoreId());
        accountTradeRecord.setStoreName(docPromotion.getStoreName());
        accountTradeRecord.setMemberId(docPromotion.getMemberId());
        accountTradeRecord.setMemberName(docPromotion.getMemberName());
        accountTradeRecord.setMemberIdentity(docPromotion.getManageIdentity());
        accountTradeRecord.setMemberPhone(docPromotion.getMobilePhone());
        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setPrice(docPromotion.getPrice());
        if(docPromotion.getIsCancel() == 0) {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume);
            accountTradeRecord.setAccountSpendMoney(docPromotion.getCollectionRechargeAmount());
            accountTradeRecord.setAccountGiftSpendMoney(giftSpendMoney);
            accountTradeRecord.setInputDate(docPromotion.getDocDate());
            accountTradeRecord.setInputBy(docPromotion.getInputBy());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_consume_cancel);
            accountTradeRecord.setAccountInMoney(docPromotion.getCollectionRechargeAmount());
            accountTradeRecord.setInputDate(docPromotion.getCancelDate());
            accountTradeRecord.setGiftInMenoy(giftSpendMoney);
            accountTradeRecord.setInputBy(docPromotion.getCancelBy());
        }
        accountTradeRecord.setDocId(docPromotion.getId());
        accountTradeRecord.setDocNum(docPromotion.getDocNum());
        accountTradeRecord.setDocType(Constant.doc_type_promotion);
        accountTradeRecord.setTradeId(docPromotion.getPromotionId());
        accountTradeRecord.setTradeName(docPromotion.getPromotionName());
        accountTradeRecord.setTradeMoney(docPromotion.getAmount());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        return accountTradeRecord;
    }

    /*
    * 校验账户金额
    * */
    public RechargeAccount volidAccount(RechargeAccount rechargeAccount) throws SmsException{
        BigDecimal zeroBd = BigDecimalUtils.bigDecimal("0");
        if (BigDecimalUtils.compareTo(rechargeAccount.getCardRestMoney(), zeroBd) == -1){
            throw new SmsException(ResponseCode.IS_INSUFFICIENT,"充值账户剩余金额");
        }
//        if (BigDecimalUtils.compareTo(rechargeAccount.getCardGiftMoney(), zeroBd) == -1){
//            throw new SmsException(ResponseCode.IS_INSUFFICIENT,"充值账户赠品金额");
//        }
        if (BigDecimalUtils.compareTo(rechargeAccount.getCardConsumeMoney(), zeroBd) == -1){
            throw new SmsException(ResponseCode.IS_INSUFFICIENT,"充值账户可消费金额");
        }
//        if (BigDecimalUtils.compareTo(rechargeAccount.getGiftConsumeMoney(), zeroBd) == -1){
//            throw new SmsException(ResponseCode.IS_INSUFFICIENT,"充值账户赠品可消费金额");
//        }
        return rechargeAccount;
    }

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

    @Override
    public int updates(RechargeAccountRequest rechargeAccountRequest, String phone) {
        int i = 0;
        RechargeAccount rechargeAccounts = new RechargeAccount();
        rechargeAccounts.setId(rechargeAccountRequest.getIds());
        RechargeAccount rechargeAccount1 = dao.selectOne(rechargeAccounts);
        rechargeAccounts.setId(rechargeAccountRequest.getRechargeTypeId());
        RechargeAccount rechargeAccount = dao.selectOne(rechargeAccounts);

        rechargeAccount.setCardRestMoney(BigDecimalUtils.add(rechargeAccount1.getCardRestMoney(),rechargeAccount.getCardRestMoney()));
        rechargeAccount.setCardConsumeMoney(BigDecimalUtils.add(rechargeAccount1.getCardConsumeMoney(),rechargeAccount.getCardConsumeMoney()));
        rechargeAccount.setGiftConsumeMoney(BigDecimalUtils.add(rechargeAccount1.getGiftConsumeMoney(),rechargeAccount.getGiftConsumeMoney()));

        rechargeAccount1.setCardRestMoney(BigDecimal.valueOf(0.00));
        rechargeAccount1.setCardConsumeMoney(BigDecimal.valueOf(0.00));
        rechargeAccount1.setGiftConsumeMoney(BigDecimal.valueOf(0.00));
        int s = dao.updateByPrimaryKeySelective(rechargeAccount1);
        if(s>0){
            //设置录单人信息
            if (redisClient.hasKey(getStaffKey(phone))){
                StaffResponse staffResponse = redisClient.get(getStaffKey(phone));
                rechargeAccount.setUpdateId(staffResponse.getId());
                rechargeAccount.setUpdateBy(staffResponse.getStaffName());
                rechargeAccount.setUpdateTime(new Date());
            }
            //是否使用有效期
            Long StoreId=null;
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(rechargeAccountRequest.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    StoreId=pagesorganization.getId();
                }
            }
            StoreParament parament = StoreParaUtils.getStorePara(StoreId, Constant.allow_valid);
            if ("1".equals(parament.getParamentValue())) {
                i = dao.updateByPrimaryKeySelective(rechargeAccount);
            }
        }

        return i;
    }


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

    @Override
    public List<RechargeAccountResponse> memberRecharge(RechargeAccountRequest rechargeAccountRequest) {
        return dao.memberRecharge(rechargeAccountRequest);
    }

    @Override
    public List<RechargeAccount> selectByPrimaryKeyList(List<Long> rechargeAccountIdList) {

        return dao.selectByPrimaryKeyList(rechargeAccountIdList);
    }
    @Autowired
    private RechargeAccountMapper mapper;
    @Override
    public List<RechargeAccount> selectByIds(List<Long> rechargeAccountIdList) {
        return mapper.selectByPrimaryKeyList(rechargeAccountIdList);
    }

    @Override
    public RechargeAccount selectByMemberIdAndRechargeTypeIdAndMoney(RechargeAccount rechargeAccount) {
        return mapper.selectByMemberIdAndRechargeTypeIdAndMoney(rechargeAccount);
    }

    @Override
    public List<RechargeAccount> exportachi(RechargeAccountRequest rechargeAccountRequest) {
        return mapper.exportachi(rechargeAccountRequest);
    }
    @Override
    public PageInfo<RechargeAccount> exportachiByPage(RechargeAccountRequest rechargeAccountRequest) {
        PageHelper.startPage(rechargeAccountRequest.getPageNum(),rechargeAccountRequest.getPageSize());
        List<RechargeAccount> rechargeAccounts = mapper.exportachi(rechargeAccountRequest);
        PageInfo<RechargeAccount> pageInfo = new PageInfo<>(rechargeAccounts);
        return pageInfo;
    }

    public void rechargeAccountGive(RechargeAccount rechargeAccount1,Long storeId,BigDecimal giftConsumeMoneyGive,Integer updateType,Integer asType){
        RechargeType rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeAccount1.getRechargeTypeId());

        if(rechargeType.getType()==2&&rechargeType.getGiveType()==1){
            //1为修改，0为添加
            RechargeAccountGive rechargeAccountGive=new RechargeAccountGive();
            BeanUtils.copyProperties(rechargeAccount1,rechargeAccountGive);
            rechargeAccountGive.setAccountId(rechargeAccount1.getId());
            rechargeAccountGive.setStoreId(storeId);
            //type=1修改，查询仅门店使用账户赠送卡金额修改
            if(updateType==1){
                Example example = new Example(RechargeAccountGive.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("accountId",rechargeAccountGive.getAccountId());
                criteria.andEqualTo("storeId",rechargeAccountGive.getStoreId());
                criteria.andEqualTo("memberId",rechargeAccountGive.getMemberId());
                //查询原账户的赠送金额
                List<RechargeAccountGive> List=ssmRechargeAccountGiveDao.selectByExample(example);
                if(List.size()>0){
                    rechargeAccountGive=List.get(0);
                    if(asType==0){//（加）
                        //原账户赠送金额+本单充值赠送金额
                        rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().add(giftConsumeMoneyGive));
                    }else if(asType==1){//（减）
                        //原账户赠送金额-本单充值赠送金额
                        rechargeAccountGive.setGiftConsumeMoney(rechargeAccountGive.getGiftConsumeMoney().subtract(giftConsumeMoneyGive));
                    }
                    ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                }
            }else{//添加一个新仅门店使用的赠卡
                ssmRechargeAccountGiveDao.insert(rechargeAccountGive);
            }

        }
    }
    /*
     * 账户交易记录属性赋值 充值
     * */
    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()!=null && 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.recharge_pay_Repay);
            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.recharge_pay_Repay_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_repay);
        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 setAccountTradeRecordPomtion(RepayTradeList repayTradeList, CourseAccount courseAccount, RepayList repayList, int addCount,BigDecimal Money) {
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(repayTradeList.getStoreId());
        accountTradeRecord.setStoreName(repayTradeList.getStoreName());
        accountTradeRecord.setMemberId(repayTradeList.getMemberId());
        accountTradeRecord.setMemberName(repayTradeList.getMemberName());
        accountTradeRecord.setMemberIdentity(repayTradeList.getMemberIdentityCard());
        accountTradeRecord.setMemberPhone(repayTradeList.getMobilePhone());
        accountTradeRecord.setAccountId(courseAccount.getId());
        accountTradeRecord.setAccountName(courseAccount.getCourseProjectName());

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

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

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

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