package com.ssm.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.BigDecimalUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmRechargeAccountGiveDao;
import com.ssm.manage.dao.SsmRechargeCardTransitionDao;
import com.ssm.manage.dao.SsmRechargeDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.query.RechargeCardTransitionRequest;
import com.ssm.manage.query.StaffRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.query.TurnMembershipCardRequest;
import com.ssm.manage.response.RateContribution;
import com.ssm.manage.response.RechargeCardTransitionResponse;
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.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

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

import static java.util.Comparator.comparing;

@Service
@Slf4j
public class SsmRechargeCardTransitionServiceImpl  extends BaseServiceImpl<RechargeCardTransition> implements SsmRechargeCardTransitionService {


    @Autowired
    private RedisClient<StaffResponse> redisClient;

    @Autowired
    private SsmRechargeCardTransitionDao dao;
    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;
    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmRechargeAccountGiveDao ssmRechargeAccountGiveDao;

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

    private static String staffKey = "staffKey";

    @Override
    public PageInfo<RechargeCardTransitionResponse> selectPage(RechargeCardTransitionRequest turnMembershipCardRequest) {
        PageInfo<RechargeCardTransitionResponse> pageInfo = new PageInfo<>();
        List<RechargeCardTransitionResponse> rechargeCardTransitionResponses = new ArrayList<>();
        Example example = new Example(RechargeCardTransition.class);
        Example.Criteria criteria = example.createCriteria();

        BaseStores baseStores = new BaseStores();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(turnMembershipCardRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null == pagesorganization.getParentId()){
                baseStores = pagesorganization;
            }
        }

        if(baseStores.getId().equals(turnMembershipCardRequest.getStoreId())){ //总店
            for (BaseStores pagesorganization : pagesorganizations) {
                if(null == pagesorganization.getParentId()){
                    Example examples = new Example(TurnMembershipCard.class);
                    Example.Criteria criterias = examples.createCriteria();
                    criterias.andEqualTo("storeId",pagesorganization.getId());
                    if (null != turnMembershipCardRequest.getMemberId()){
                        criterias.andLike("memberId","%" + turnMembershipCardRequest.getMemberId() + "%");
                    }
                    if (null != turnMembershipCardRequest.getMemberNum()){
                        criterias.andLike("memberNum","%" + turnMembershipCardRequest.getMemberNum() + "%");
                    }
                    if (null != turnMembershipCardRequest.getMemberName()){
                        criterias.andLike("memberName","%" + turnMembershipCardRequest.getMemberName() + "%");
                    }
                    if (null != turnMembershipCardRequest.getDocNum()){
                        criterias.andLike("docNum","%" + turnMembershipCardRequest.getDocNum() + "%");
                    }
                    if (null != turnMembershipCardRequest.getDocDate()){
                        criterias.andLike("docDate","%" + turnMembershipCardRequest.getDocDate() + "%");
                    }
                    if (null != turnMembershipCardRequest.getState()){
                        criterias.andEqualTo("state",turnMembershipCardRequest.getState());
                    }
                    List<RechargeCardTransition> rechargeCardTransitions = dao.selectByExample(examples);
                    for (RechargeCardTransition rechargeCardTransition : rechargeCardTransitions) {
                        RechargeCardTransitionResponse rechargeCardTransitionResponse = new RechargeCardTransitionResponse();
                        BeanUtils.copyProperties(rechargeCardTransition,rechargeCardTransitionResponse);
                        List<StaffRequest> staffValue = this.getStaffValue(rechargeCardTransition);
                        rechargeCardTransitionResponse.setStaffLists(staffValue);
                        rechargeCardTransitionResponses.add(rechargeCardTransitionResponse);
                    }
                }else{
                    Example examples = new Example(TurnMembershipCard.class);
                    Example.Criteria criterias = examples.createCriteria();
                    criterias.andEqualTo("storeId",pagesorganization.getId());
                    if (null != turnMembershipCardRequest.getMemberId()){
                        criterias.andLike("memberId","%" + turnMembershipCardRequest.getMemberId() + "%");
                    }
                    if (null != turnMembershipCardRequest.getMemberNum()){
                        criterias.andLike("memberNum","%" + turnMembershipCardRequest.getMemberNum() + "%");
                    }
                    if (null != turnMembershipCardRequest.getMemberName()){
                        criterias.andLike("memberName","%" + turnMembershipCardRequest.getMemberName() + "%");
                    }
                    if (null != turnMembershipCardRequest.getDocNum()){
                        criterias.andLike("docNum","%" + turnMembershipCardRequest.getDocNum() + "%");
                    }
                    if (null != turnMembershipCardRequest.getDocDate()){
                        criterias.andLike("docDate","%" + turnMembershipCardRequest.getDocDate() + "%");
                    }
                    if (null != turnMembershipCardRequest.getState()){
                        criterias.andIn("state",Arrays.asList(1,3,4));
                    }
                    List<RechargeCardTransition> rechargeCardTransitions = dao.selectByExample(examples);
                    for (RechargeCardTransition rechargeCardTransition : rechargeCardTransitions) {
                        RechargeCardTransitionResponse rechargeCardTransitionResponse = new RechargeCardTransitionResponse();
                        BeanUtils.copyProperties(rechargeCardTransition,rechargeCardTransitionResponse);
                        List<StaffRequest> staffValue = this.getStaffValue(rechargeCardTransition);
                        rechargeCardTransitionResponse.setStaffLists(staffValue);
                        rechargeCardTransitionResponses.add(rechargeCardTransitionResponse);
                    }
                }
            }

        }else{ //分店
            Example examples = new Example(TurnMembershipCard.class);
            Example.Criteria criterias = examples.createCriteria();
            criterias.andEqualTo("storeId",turnMembershipCardRequest.getStoreId());
            if (null != turnMembershipCardRequest.getMemberId()){
                criterias.andLike("memberId","%" + turnMembershipCardRequest.getMemberId() + "%");
            }
            if (null != turnMembershipCardRequest.getMemberNum()){
                criterias.andLike("memberNum","%" + turnMembershipCardRequest.getMemberNum() + "%");
            }
            if (null != turnMembershipCardRequest.getMemberName()){
                criterias.andLike("memberName","%" + turnMembershipCardRequest.getMemberName() + "%");
            }
            if (null != turnMembershipCardRequest.getDocNum()){
                criterias.andLike("docNum","%" + turnMembershipCardRequest.getDocNum() + "%");
            }
            if (null != turnMembershipCardRequest.getDocDate()){
                criterias.andLike("docDate","%" + turnMembershipCardRequest.getDocDate() + "%");
            }
            if (null != turnMembershipCardRequest.getState()){
                criterias.andEqualTo("state",turnMembershipCardRequest.getState());
            }
            List<RechargeCardTransition> rechargeCardTransitions = dao.selectByExample(examples);
            for (RechargeCardTransition rechargeCardTransition : rechargeCardTransitions) {
                RechargeCardTransitionResponse rechargeCardTransitionResponse = new RechargeCardTransitionResponse();
                BeanUtils.copyProperties(rechargeCardTransition,rechargeCardTransitionResponse);
                List<StaffRequest> staffValue = this.getStaffValue(rechargeCardTransition);
                rechargeCardTransitionResponse.setStaffLists(staffValue);
                rechargeCardTransitionResponses.add(rechargeCardTransitionResponse);
            }
        }
        pageInfo.setTotal(rechargeCardTransitionResponses.size());


        List<RechargeCardTransitionResponse> rateContributions1 = new ArrayList<>();
        int pageNum = 0;
        int pageSize = 0;
        if(turnMembershipCardRequest.getPageNum()!=1){
            pageNum=(turnMembershipCardRequest.getPageNum()*turnMembershipCardRequest.getPageSize())-11;
        }
        if(pageNum==0){
            pageSize = turnMembershipCardRequest.getPageSize();
        }else{
            pageSize = (turnMembershipCardRequest.getPageNum()*turnMembershipCardRequest.getPageSize());
        }
        if(pageSize>rechargeCardTransitionResponses.size()){
            pageSize= rechargeCardTransitionResponses.size();
        }

        rechargeCardTransitionResponses.sort(comparing(RechargeCardTransitionResponse::getDocDate).reversed());

        List<RechargeCardTransitionResponse> rateContributions2 = rechargeCardTransitionResponses.subList(pageNum, pageSize);
        pageInfo.setList(rateContributions2);
        return pageInfo;
    }

    @Override
    public PageInfo<RechargeCardTransitionResponse> selectPageNew(RechargeCardTransitionRequest turnMembershipCardRequest) {
        PageInfo<RechargeCardTransitionResponse> pageInfo = new PageInfo<>();
        List<RechargeCardTransitionResponse> rechargeCardTransitionResponses = new ArrayList<>();
        List<Long> lists = new ArrayList<>();
//        if(turnMembershipCardRequest.getSelectType()==0){
            lists=turnMembershipCardRequest.getStoreList();
//        }else{
//            BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(turnMembershipCardRequest.getStoreId());
//            if(null == baseStore1.getParentId()&&(turnMembershipCardRequest.getStoreList().size()<0||turnMembershipCardRequest.getStoreList()==null)){
//                StoreRequest storeRequest = new StoreRequest();
//                storeRequest.setId(turnMembershipCardRequest.getStoreId());
//                List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
//                List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());
//                lists=collect;
//            }else{
//                lists.add(turnMembershipCardRequest.getStoreId());
//            }
//        }

        Example examples = new Example(RechargeCardTransition.class);
        Example.Criteria criterias = examples.createCriteria();
        if(lists!=null && lists.size()>0){
            criterias.andIn("storeId",lists);
        }
        if (null != turnMembershipCardRequest.getMemberId()){
            criterias.andLike("memberId","%" + turnMembershipCardRequest.getMemberId() + "%");
        }
        if (null != turnMembershipCardRequest.getMobilePhone()){
            criterias.andLike("mobilePhone","%" + turnMembershipCardRequest.getMobilePhone() + "%");
        }
        if (null != turnMembershipCardRequest.getMemberName()){
            criterias.andLike("memberName","%" + turnMembershipCardRequest.getMemberName() + "%");
        }
        if (null != turnMembershipCardRequest.getDocNum()){
            criterias.andLike("docNum","%" + turnMembershipCardRequest.getDocNum() + "%");
        }
        if (null != turnMembershipCardRequest.getDocDate()){
            criterias.andLike("docDate","%" + turnMembershipCardRequest.getDocDate() + "%");
        }
        if (null != turnMembershipCardRequest.getState()){
            criterias.andEqualTo("state",turnMembershipCardRequest.getState());
        }
        List<RechargeCardTransition> rechargeCardTransitions = dao.selectByExample(examples);
        for (RechargeCardTransition rechargeCardTransition : rechargeCardTransitions) {
            RechargeCardTransitionResponse rechargeCardTransitionResponse = new RechargeCardTransitionResponse();
            BeanUtils.copyProperties(rechargeCardTransition,rechargeCardTransitionResponse);
            List<StaffRequest> staffValue = this.getStaffValue(rechargeCardTransition);
            rechargeCardTransitionResponse.setStaffLists(staffValue);
            rechargeCardTransitionResponses.add(rechargeCardTransitionResponse);
        }
        pageInfo.setTotal(rechargeCardTransitionResponses.size());


        List<RechargeCardTransitionResponse> rateContributions1 = new ArrayList<>();
        int pageNum = 0;
        int pageSize = 0;
        if(turnMembershipCardRequest.getPageNum()!=1){
            pageNum=(turnMembershipCardRequest.getPageNum()*turnMembershipCardRequest.getPageSize())-11;
        }
        if(pageNum==0){
            pageSize = turnMembershipCardRequest.getPageSize();
        }else{
            pageSize = (turnMembershipCardRequest.getPageNum()*turnMembershipCardRequest.getPageSize());
        }
        if(pageSize>rechargeCardTransitionResponses.size()){
            pageSize= rechargeCardTransitionResponses.size();
        }

        rechargeCardTransitionResponses.sort(comparing(RechargeCardTransitionResponse::getDocDate).reversed());

        List<RechargeCardTransitionResponse> rateContributions2 = rechargeCardTransitionResponses.subList(pageNum, pageSize);
        pageInfo.setList(rateContributions2);
        return pageInfo;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(RechargeCardTransitionRequest rechargeCardTransitionRequest, String phone) throws SmsException, Exception {
        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        //创建SimpleDateFormat对象实例并定义好转换格式
        SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd");
        String formats = sdfs.format(new Date());
        String num = this.getNum(formats, rechargeCardTransitionRequest.getStoreId());

        RechargeCardTransition rechargeCardTransition = new RechargeCardTransition();
        BeanUtils.copyProperties(rechargeCardTransitionRequest, rechargeCardTransition);
        rechargeCardTransition.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());

        List<StaffRequest> staffLists = rechargeCardTransitionRequest.getStaffLists();
        BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
            throw new SmsException(ResponseCode.MSG,"业务员业绩占比和不等于100");
        }
        this.setStaffValue(staffLists,rechargeCardTransition);
        rechargeCardTransition.setState(0);
        rechargeCardTransition.setDocNum(num);
        rechargeCardTransition.setDocDate(new Date());
        rechargeCardTransition.setInsertId(staffResponse.getId());
        rechargeCardTransition.setInsertName(staffResponse.getStaffName());
        rechargeCardTransition.setInsertDate(new Date());
        //RechargeAccountOutin rechargeAccountGiveCheck=new RechargeAccountOutin();
        if((rechargeCardTransition.getInGiftMoney().intValue()>Double.valueOf(String.valueOf(rechargeCardTransition.getGiftConsumeMoney())))
                ||(rechargeCardTransition.getInMoney().intValue()>Double.valueOf(String.valueOf(rechargeCardTransition.getCardConsumeMoney())))){
           throw new SmsException(ResponseCode.MSG,"转出金额大于账户可用金额");
        }
        return dao.insert(rechargeCardTransition);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int update(RechargeCardTransitionRequest rechargeCardTransitionRequest, String phone) throws SmsException, Exception {
        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        RechargeCardTransition rechargeCardTransition = new RechargeCardTransition();
        //2 RechargeCardTransition rechargeCardTransition = dao.selectByPrimaryKey(rechargeCardTransitionRequest.getId());
        List<StaffRequest> staffLists = rechargeCardTransitionRequest.getStaffLists();
        BigDecimal reduce3 = staffLists.stream().map(aa -> aa.getRatio()).reduce(BigDecimal.ZERO, BigDecimal::add);
        if(null != reduce3 && reduce3.compareTo(BigDecimal.valueOf(100))!=0 && reduce3.compareTo(BigDecimal.valueOf(0))!=0){
            throw new SmsException(ResponseCode.MSG,"业务员业绩占比和不等于100");
        }
        BeanUtils.copyProperties(rechargeCardTransitionRequest,rechargeCardTransition);
        this.setStaffValue(staffLists,rechargeCardTransition);
        rechargeCardTransition.setUpdateId(staffResponse.getId());
        rechargeCardTransition.setUpdateName(staffResponse.getStaffName());
        rechargeCardTransition.setUpdateDate(new Date());
        int update = dao.updateByPrimaryKey(rechargeCardTransition);
        return update;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateState(RechargeCardTransitionRequest rechargeCardTransitionRequest, String phone) throws SmsException, Exception {
        int state =0;
        StaffResponse staffResponse = new StaffResponse();
        Set<String> keys = redisClient.keys(getStaffKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        RechargeCardTransition rechargeCardTransition = dao.selectByPrimaryKey(rechargeCardTransitionRequest.getId());
        if(1 == rechargeCardTransitionRequest.getState()){//送审
            if(0 == rechargeCardTransition.getState() || 2==rechargeCardTransition.getState() ||4==rechargeCardTransition.getState()){//送审
                rechargeCardTransition.setState(rechargeCardTransitionRequest.getState());
                rechargeCardTransition.setUpdateId(staffResponse.getId());
                rechargeCardTransition.setUpdateName(staffResponse.getStaffName());
                rechargeCardTransition.setUpdateDate(new Date());
                state =  dao.updateByPrimaryKeySelective(rechargeCardTransition);
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许送审");
            }
        }else if(2 == rechargeCardTransitionRequest.getState()){ //回收
            if(1 == rechargeCardTransition.getState()){
                rechargeCardTransition.setState(rechargeCardTransitionRequest.getState());
                rechargeCardTransition.setUpdateId(staffResponse.getId());
                rechargeCardTransition.setUpdateName(staffResponse.getStaffName());
                rechargeCardTransition.setUpdateDate(new Date());
                state =  dao.updateByPrimaryKeySelective(rechargeCardTransition);
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许回收");
            }

        }
        else if(3 == rechargeCardTransitionRequest.getState()){ //审核
            if(1 == rechargeCardTransition.getState()){
                rechargeCardTransition.setState(rechargeCardTransitionRequest.getState());
                RechargeAccount rechargeAccount = new RechargeAccount();
                rechargeAccount.setId(rechargeCardTransition.getOutAccountId());
                RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccount.getId());
                if(rechargeAccount1.getCardRestMoney().compareTo(rechargeAccount1.getCardConsumeMoney())!=0){
                    throw new SmsException(ResponseCode.MSG,"转出账户存在欠款，请先还款或者取消欠款");
                }
                if(rechargeAccount1.getCardRestMoney().compareTo(rechargeCardTransition.getInMoney())==-1){
                    throw new SmsException(ResponseCode.MSG,"转出账户当前剩余金额不足");
                }
                if(rechargeAccount1.getGiftConsumeMoney().compareTo(rechargeCardTransition.getInGiftMoney())==-1){
                    throw new SmsException(ResponseCode.MSG,"转出账户当前赠送剩余金额不足");
                }
                //扣除转出账户金额
                rechargeAccount1.setCardRestMoney(rechargeAccount1.getCardRestMoney().subtract(rechargeCardTransition.getInMoney()));
                rechargeAccount1.setCardConsumeMoney(rechargeAccount1.getCardConsumeMoney().subtract(rechargeCardTransition.getInMoney()));
                rechargeAccount1.setGiftConsumeMoney(rechargeAccount1.getGiftConsumeMoney().subtract(rechargeCardTransition.getInGiftMoney()));
                rechargeAccount1.setCardGiftMoney(rechargeAccount1.getCardGiftMoney().subtract(rechargeCardTransition.getInGiftMoney()));
                //获取本单转出赠送金额
                BigDecimal giftConsumeMoneyGive=rechargeCardTransition.getInGiftMoney();
                //updateType==1为修改  asType==1为减0为加
                this.rechargeAccountGive(rechargeAccount1,rechargeCardTransition,giftConsumeMoneyGive,1,1);

                ssmRechargeAccountService.addMoney(rechargeAccount1);
                AccountTradeRecord accountTradeRecord = addAccountTradeRecords(rechargeAccount1, rechargeCardTransition);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);

                //添加充值账户，判断是否存在
                RechargeAccount rechargeAccount5 = new RechargeAccount();
                rechargeAccount5.setRechargeTypeId(rechargeCardTransition.getInRechargeTypeId());
                rechargeAccount5.setMemberId(rechargeCardTransition.getMemberId());
                RechargeAccount rechargeAccount3 = ssmRechargeAccountService.selectOne(rechargeAccount5);
                if(null == rechargeAccount3){ //不存在
                    //新建
                    StoreMemberList storeMemberList = new StoreMemberList();
                    storeMemberList.setId(rechargeCardTransition.getMemberId());
                    StoreMemberList storeMemberList1 = ssmStoreMemberService.selectByPrimaryKey(storeMemberList.getId());

                    RechargeType rechargeType = new RechargeType();
                    rechargeType.setId(rechargeCardTransition.getInRechargeTypeId());
                    RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);

                    RechargeAccount rechargeAccount2 = new RechargeAccount();
                    rechargeAccount2.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    rechargeAccount2.setMemberId(storeMemberList1.getId());
                    rechargeAccount2.setMemberName(storeMemberList1.getMemberName());
                    rechargeAccount2.setMemberName(storeMemberList1.getMemberName());
                    rechargeAccount2.setCardRestMoney(rechargeCardTransition.getInMoney());
                    rechargeAccount2.setCardConsumeMoney(rechargeCardTransition.getInMoney());
                    rechargeAccount2.setGiftConsumeMoney(rechargeCardTransition.getInGiftMoney());
                    rechargeAccount2.setCardGiftMoney(rechargeCardTransition.getInGiftMoney());
                    rechargeAccount2.setRechargeTypeId(rechargeCardTransition.getInRechargeTypeId());
                    rechargeAccount2.setRechargeTypeNum(rechargeCardTransition.getInRechargeTypeNum());
                    rechargeAccount2.setRechargeTypeName(rechargeCardTransition.getInRechargeTypeName());
                    rechargeAccount2.setType(rechargeType1.getType());
                    rechargeAccount2.setDiscount(rechargeType1.getDiscount());
                    rechargeAccount2.setDiscount(rechargeType1.getDiscount());
                    rechargeAccount2.setStoreId(rechargeAccount1.getStoreId());
                    rechargeAccount2.setStoreName(rechargeAccount1.getStoreName());
                    rechargeAccount2.setState(1);
                    if(null != rechargeAccount1.getEndTime()){
                        rechargeAccount2.setEndTime(rechargeAccount1.getEndTime());
                    }
                    rechargeAccount2.setFirstCharge(0L);
                    rechargeAccount2.setCardNum(0);
                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount2,rechargeCardTransition,giftConsumeMoneyGive,0,0);
                    int save = ssmRechargeAccountService.save(rechargeAccount2);
                    if(save==0){
                        throw new SmsException(ResponseCode.MSG,"添加转入会员卡失败");
                    }
                    AccountTradeRecord accountTradeRecord2 = this.setInAccountTradeRecord(storeMemberList1, rechargeAccount2, rechargeCardTransition);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord2);
                    rechargeCardTransition.setInAccountId(rechargeAccount2.getId());
                    state = dao.updateByPrimaryKeySelective(rechargeCardTransition);
                    if(state==0){
                        throw new SmsException(ResponseCode.MSG,"审核失败");
                    }
                }else{//存在

                    StoreMemberList storeMemberList = new StoreMemberList();
                    storeMemberList.setId(rechargeCardTransition.getMemberId());
                    StoreMemberList storeMemberList1 = ssmStoreMemberService.selectByPrimaryKey(storeMemberList.getId());

                    RechargeType rechargeType = new RechargeType();
                    rechargeType.setId(rechargeCardTransition.getInRechargeTypeId());
                    RechargeType rechargeType1 = ssmRechargeTypeSevice.selectOne(rechargeType);

                    rechargeAccount3.setCardRestMoney(rechargeAccount3.getCardRestMoney().add(rechargeCardTransition.getInMoney()));
                    rechargeAccount3.setCardConsumeMoney(rechargeAccount3.getCardConsumeMoney().add(rechargeCardTransition.getInMoney()));
                    rechargeAccount3.setGiftConsumeMoney(rechargeAccount3.getGiftConsumeMoney().add(rechargeCardTransition.getInGiftMoney()));
                    rechargeAccount3.setCardGiftMoney(rechargeAccount3.getCardGiftMoney().add(rechargeCardTransition.getInGiftMoney()));

                    //updateType==1为修改  asType==1为减0为加
                    this.rechargeAccountGive(rechargeAccount3,rechargeCardTransition,giftConsumeMoneyGive,1,0);

                    ssmRechargeAccountService.addMoney(rechargeAccount3);
                    AccountTradeRecord accountTradeRecord2 = this.setInAccountTradeRecord(storeMemberList1, rechargeAccount3, rechargeCardTransition);
                    ssmAccountTradeRecordService.addRecord(accountTradeRecord2);
                    rechargeCardTransition.setInAccountId(rechargeAccount3.getId());
                    state = dao.updateByPrimaryKeySelective(rechargeCardTransition);
                    if(state==0){
                        throw new SmsException(ResponseCode.MSG,"审核失败");
                    }
                }

            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许审核");
            }

        }
        else if(4 == rechargeCardTransitionRequest.getState()){ //反审核
            if(3==rechargeCardTransition.getState()){
                rechargeCardTransition.setState(rechargeCardTransitionRequest.getState());
                //检查账户是否足够返回余额
                RechargeAccount rechargeAccount = new RechargeAccount();
                rechargeAccount.setId(rechargeCardTransition.getInAccountId());
                RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccount.getId());
                RechargeAccount rechargeAccount2 = ssmRechargeAccountService.selectByPrimaryKey(rechargeCardTransition.getOutAccountId());
                if(rechargeAccount1.getCardConsumeMoney().compareTo(rechargeCardTransition.getInMoney())==-1){
                    throw new SmsException(ResponseCode.MSG,"转入的账户可用余额不足");
                }
                if(rechargeAccount1.getGiftConsumeMoney().compareTo(rechargeCardTransition.getInGiftMoney())==-1){
                    throw new SmsException(ResponseCode.MSG,"转入的账户赠送可用余额不足");
                }

                StoreMemberList storeMemberList = new StoreMemberList();
                storeMemberList.setId(rechargeCardTransition.getMemberId());
                StoreMemberList storeMemberList1 = ssmStoreMemberService.selectByPrimaryKey(storeMemberList.getId());

                rechargeAccount1.setCardRestMoney(rechargeAccount1.getCardRestMoney().subtract(rechargeCardTransition.getInMoney()));
                rechargeAccount1.setCardConsumeMoney(rechargeAccount1.getCardConsumeMoney().subtract(rechargeCardTransition.getInMoney()));
                rechargeAccount1.setGiftConsumeMoney(rechargeAccount1.getGiftConsumeMoney().subtract(rechargeCardTransition.getInGiftMoney()));
                rechargeAccount1.setCardGiftMoney(rechargeAccount1.getCardGiftMoney().subtract(rechargeCardTransition.getInGiftMoney()));

                //获取本单转出赠送金额
                BigDecimal giftConsumeMoneyGive=rechargeCardTransition.getInGiftMoney();
                //updateType==1为修改  asType==1为减    0为加
                this.rechargeAccountGive(rechargeAccount1,rechargeCardTransition,giftConsumeMoneyGive,1,1);
                ssmRechargeAccountService.addMoney(rechargeAccount1);
                AccountTradeRecord accountTradeRecord2 = this.setInAccountTradeRecord(storeMemberList1, rechargeAccount1, rechargeCardTransition);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord2);

                //返回转出的金额
                RechargeAccount rechargeAccount3 = new RechargeAccount();
                rechargeAccount3.setId(rechargeCardTransition.getOutAccountId());
                RechargeAccount rechargeAccount4 = ssmRechargeAccountService.selectByPrimaryKey(rechargeAccount3.getId());
                rechargeAccount4.setCardRestMoney(rechargeAccount4.getCardRestMoney().add(rechargeCardTransition.getInMoney()));
                rechargeAccount4.setCardConsumeMoney(rechargeAccount4.getCardConsumeMoney().add(rechargeCardTransition.getInMoney()));
                rechargeAccount4.setGiftConsumeMoney(rechargeAccount4.getGiftConsumeMoney().add(rechargeCardTransition.getInGiftMoney()));
                rechargeAccount4.setCardGiftMoney(rechargeAccount4.getCardGiftMoney().add(rechargeCardTransition.getInGiftMoney()));
                //updateType==1为修改  asType==1为减0为加
                this.rechargeAccountGive(rechargeAccount4,rechargeCardTransition,giftConsumeMoneyGive,1,0);
                ssmRechargeAccountService.addMoney(rechargeAccount4);
                AccountTradeRecord accountTradeRecord = addAccountTradeRecords(rechargeAccount4, rechargeCardTransition);
                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                state = dao.updateByPrimaryKeySelective(rechargeCardTransition);
                if(state==0){
                    throw new SmsException(ResponseCode.MSG,"审核失败");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许反审核");
            }
        }
        return state;
    }

    @Override
    public int delete(RechargeCardTransitionRequest rechargeCardTransitionRequest) throws SmsException, Exception {
        RechargeCardTransition rechargeCardTransition = dao.selectByPrimaryKey(rechargeCardTransitionRequest.getId());
        if(0!= rechargeCardTransition.getState()){
            throw new SmsException(ResponseCode.MSG,"当前单据已经不是新增状态，不允许删除");
        }
        return dao.deleteByPrimaryKey(rechargeCardTransition.getId());
    }

    /*
     * 添加转入会员转卡交易记录
     * */
    public AccountTradeRecord setInAccountTradeRecord(StoreMemberList storeMemberList,RechargeAccount rechargeAccount,RechargeCardTransition rechargeCardTransition){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(rechargeCardTransition.getStoreId());
        accountTradeRecord.setStoreName(rechargeCardTransition.getStoreName());
        accountTradeRecord.setMemberId(rechargeCardTransition.getMemberId());
        accountTradeRecord.setMemberName(rechargeCardTransition.getMemberNum());
        try {
            accountTradeRecord.setMemberPhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).trim());
        } catch (Exception e) {
            e.printStackTrace();
        }

        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        accountTradeRecord.setPrice(rechargeCardTransition.getInMoney());
        if(rechargeCardTransition.getState() == 3) {//转入审核==添加
            accountTradeRecord.setAccountType(Constant.doc_type_recharge_Transition_in);
            accountTradeRecord.setInputDate(rechargeCardTransition.getDocDate());
            accountTradeRecord.setInputBy(rechargeCardTransition.getUpdateName());
            accountTradeRecord.setAccountInMoney(rechargeCardTransition.getInMoney());
            accountTradeRecord.setGiftInMenoy(rechargeCardTransition.getInGiftMoney());
            accountTradeRecord.setOrderStatu(0);
        }else {//转入反审核==扣减
            accountTradeRecord.setAccountType(Constant.doc_type_recharge_Transition_in_cancel);
            accountTradeRecord.setInputDate(rechargeCardTransition.getDocDate());
            accountTradeRecord.setInputBy(rechargeCardTransition.getUpdateName());
            accountTradeRecord.setAccountSpendMoney(rechargeCardTransition.getInMoney());
            accountTradeRecord.setAccountGiftSpendMoney(rechargeCardTransition.getInGiftMoney());
            accountTradeRecord.setOrderStatu(2);
        }
        accountTradeRecord.setDocId(rechargeCardTransition.getId());
        accountTradeRecord.setDocNum(rechargeCardTransition.getDocNum());
        accountTradeRecord.setDocType(Constant.doc_type_recharge_Transition);
        accountTradeRecord.setTradeId(rechargeCardTransition.getInRechargeTypeId());
        accountTradeRecord.setTradeName(rechargeCardTransition.getInRechargeTypeName());
        accountTradeRecord.setTradeMoney(rechargeCardTransition.getInMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setCardMoney(rechargeCardTransition.getInMoney());
        accountTradeRecord.setCashMoney(BigDecimal.valueOf(0));
        return accountTradeRecord;
    }

    private AccountTradeRecord addAccountTradeRecords(RechargeAccount rechargeAccount,RechargeCardTransition rechargeCardTransition){
        AccountTradeRecord accountTradeRecords = new AccountTradeRecord();
        accountTradeRecords.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecords.setStoreId(rechargeCardTransition.getStoreId());
        accountTradeRecords.setStoreName(rechargeCardTransition.getStoreName());
        accountTradeRecords.setMemberId(rechargeCardTransition.getMemberId());
        accountTradeRecords.setMemberName(rechargeCardTransition.getMemberName());
        accountTradeRecords.setMemberIdentity(rechargeCardTransition.getMemberIdentityCard());
        accountTradeRecords.setMemberPhone(rechargeCardTransition.getMobilePhone());
        accountTradeRecords.setAccountId(rechargeAccount.getId());
        accountTradeRecords.setAccountName(rechargeAccount.getRechargeTypeName());
        accountTradeRecords.setDocId(rechargeCardTransition.getId());
        accountTradeRecords.setDocNum(rechargeCardTransition.getDocNum());
        if(rechargeCardTransition.getState()==3){
            accountTradeRecords.setAccountType(Constant.doc_type_recharge_Transition_out);
            accountTradeRecords.setInputBy(rechargeCardTransition.getUpdateName());
            accountTradeRecords.setAccountSpendMoney(rechargeCardTransition.getInMoney());
            accountTradeRecords.setAccountGiftSpendMoney(rechargeCardTransition.getInGiftMoney());
            accountTradeRecords.setInputDate(rechargeCardTransition.getUpdateDate());
            accountTradeRecords.setOrderStatu(0);
        }else{
            accountTradeRecords.setAccountType(Constant.doc_type_recharge_Transition_out_cancel);
            accountTradeRecords.setInputBy(rechargeCardTransition.getUpdateName());
            accountTradeRecords.setAccountInMoney(rechargeCardTransition.getInMoney());
            accountTradeRecords.setGiftInMenoy(rechargeCardTransition.getInGiftMoney());
            accountTradeRecords.setInputDate(rechargeCardTransition.getUpdateDate());
            accountTradeRecords.setOrderStatu(2);
        }
        accountTradeRecords.setDocType(Constant.doc_type_recharge_Transition);
        accountTradeRecords.setInputDate(rechargeCardTransition.getDocDate());
        accountTradeRecords.setDebtMoney(BigDecimal.valueOf(0));
        accountTradeRecords.setPrice(rechargeCardTransition.getInMoney());

        accountTradeRecords.setTradeId(rechargeCardTransition.getOutRechargeTypeId());
        accountTradeRecords.setTradeName(rechargeCardTransition.getOutRechargeTypeName());
        accountTradeRecords.setTradeMoney(rechargeCardTransition.getInMoney());
        accountTradeRecords.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecords.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecords.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecords.setCardMoney(rechargeCardTransition.getInMoney());
        accountTradeRecords.setCashMoney(BigDecimal.valueOf(0));
        return accountTradeRecords;
    }


    /*
     * 业务员赋值
     * */
    public void setStaffValue(List<StaffRequest> staffLists, RechargeCardTransition rechargeList){
        for (int i = 0; i < staffLists.size(); i++) {

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

    public List<StaffRequest> getStaffValue( RechargeCardTransition rechargeList){
        List<StaffRequest> staffLists = new ArrayList<>();
        if(null != rechargeList.getSaleOneStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleOneStaffId());
            staffRequest.setStaffName(rechargeList.getSaleOneStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleOneIdentity());
            staffRequest.setRatio(rechargeList.getSaleOneRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleOneNumber());
            staffLists.add(staffRequest);
        }
        if(null != rechargeList.getSaleTwoStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleTwoStaffId());
            staffRequest.setStaffName(rechargeList.getSaleTwoStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleTwoIdentity());
            staffRequest.setRatio(rechargeList.getSaleTwoRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleTwoNumber());
            staffLists.add(staffRequest);
        }
        if(null != rechargeList.getSaleThreeStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleThreeStaffId());
            staffRequest.setStaffName(rechargeList.getSaleThreeStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleThreeIdentity());
            staffRequest.setRatio(rechargeList.getSaleThreeRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleThreeNumber());
            staffLists.add(staffRequest);
        }
        if(null != rechargeList.getSaleFourStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleFourStaffId());
            staffRequest.setStaffName(rechargeList.getSaleFourStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleFourIdentity());
            staffRequest.setRatio(rechargeList.getSaleFourRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleFourNumber());
            staffLists.add(staffRequest);
        } if(null != rechargeList.getSaleFiveStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleFiveStaffId());
            staffRequest.setStaffName(rechargeList.getSaleFiveStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleFiveIdentity());
            staffRequest.setRatio(rechargeList.getSaleFiveRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleFiveNumber());
            staffLists.add(staffRequest);
        } if(null != rechargeList.getSaleSixStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleSixStaffId());
            staffRequest.setStaffName(rechargeList.getSaleSixStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleSixIdentity());
            staffRequest.setRatio(rechargeList.getSaleSixRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleSixNumber());
            staffLists.add(staffRequest);
        } if(null != rechargeList.getSaleSevenStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleSevenStaffId());
            staffRequest.setStaffName(rechargeList.getSaleSevenStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleSevenIdentity());
            staffRequest.setRatio(rechargeList.getSaleSevenRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleSevenNumber());
            staffLists.add(staffRequest);
        } if(null != rechargeList.getSaleEightStaffId()){
            StaffRequest staffRequest = new StaffRequest();
            staffRequest.setId(rechargeList.getSaleEightStaffId());
            staffRequest.setStaffName(rechargeList.getSaleEightStaffName());
            staffRequest.setIdentityCard(rechargeList.getSaleEightIdentity());
            staffRequest.setRatio(rechargeList.getSaleEightRatio());
            staffRequest.setBrandNumber(rechargeList.getSaleEightNumber());
            staffLists.add(staffRequest);
        }
        return staffLists;
    }

    public String getNum(String date,Long storeId){
        Example example = new Example(RechargeCardTransition.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("docNum","%" + date.replace("-","") + "%");
        criteria.andEqualTo("storeId",storeId);
        List<RechargeCardTransition> list = dao.selectByExample(example);
        String num= "CZNT";
        if(null != list){
            if(list.size()>0 ){
                if(list.size()>999){
                    num += date+(list.size()+1);
                }else  if(list.size()>99){
                    num += date+"0"+(list.size()+1);
                }else  if(list.size()>9){
                    num += date+"00"+(list.size()+1);
                }else{
                    num += date+"000"+(list.size()+1);
                }
            }else{
                num += date+"0001";
            }
        }else{
            num += date+"0001";
        }
        return num.replace("-","");
    }

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

    public void rechargeAccountGive(RechargeAccount rechargeAccount1,RechargeCardTransition rechargeCardTransition,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(rechargeCardTransition.getStoreId());
            //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));

                        //原账户赠送金额-本单充值赠送金额
                        BigDecimal reduce = List.stream().map(RechargeAccountGive::getGiftConsumeMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                        //如果扣减赠送等于账户所有赠送
                        if(reduce.compareTo(giftConsumeMoneyGive)==0){
                            for (RechargeAccountGive accountGive : List) {

                                accountGive.setGiftConsumeMoney(BigDecimal.ZERO);
                                ssmRechargeAccountGiveDao.updateByGifMoney(accountGive);
//                                ssmRechargeAccountGiveDao.updateByExampleSelective(accountGive,example);
                            }
                        }else if(reduce.compareTo(giftConsumeMoneyGive)==1){
                            //这是一个接收需要扣除的金额
                            BigDecimal sub = giftConsumeMoneyGive;
                            //进行遍历
                            for (RechargeAccountGive accountGive : List) {
                                //当前账户的前不足以支付扣除的赠送金额，则将当前账户的钱进行清零
                                if(accountGive.getGiftConsumeMoney().compareTo(sub)==-1){
                                    //赠送金额减账户余额，计算扣除当前账户还需要扣除剩余的金额
                                    sub = sub.subtract(accountGive.getGiftConsumeMoney());
                                    accountGive.setGiftConsumeMoney(BigDecimal.ZERO);
                                    ssmRechargeAccountGiveDao.updateByGifMoney(accountGive);
//                                    ssmRechargeAccountGiveDao.updateByExampleSelective(accountGive,example);
                                    //如果扣减的赠送金额小于或者等于账号的金额，则将当前账户的金额减去扣除的赠送金额
                                }else if(accountGive.getGiftConsumeMoney().compareTo(sub)==1 || accountGive.getGiftConsumeMoney().compareTo(sub)==0){
                                    sub = accountGive.getGiftConsumeMoney().subtract(sub);
                                    accountGive.setGiftConsumeMoney(sub);
                                    ssmRechargeAccountGiveDao.updateByGifMoney(accountGive);
//                                    ssmRechargeAccountGiveDao.updateByExampleSelective(accountGive,example);
                                }
                            }
                        }
                    }
                    ssmRechargeAccountGiveDao.updateByExampleSelective(rechargeAccountGive,example);
                }
            }else{//添加一个新仅门店使用的赠卡
                ssmRechargeAccountGiveDao.insert(rechargeAccountGive);
            }

        }
    }
}
