package com.ssm.manage.service.impl;

import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.QuartzManage;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.core.utils.StoreParaUtils;
import com.ssm.manage.dao.SsmStoreMemberDao;
import com.ssm.manage.dao.SsmStoreParaDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.extendEntity.StoreDaily;
import com.ssm.manage.mapper.StoreMemberListUpdateMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.MemberResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.BigDecimalUtils;
import com.ssm.manage.utils.Constant;
import com.ssm.manage.utils.DateUtils;
import com.ssm.task.SsmStoreMemberStartTask;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.Roman;
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.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SsmStoreMemberServiceImpl extends BaseServiceImpl<StoreMemberList> implements SsmStoreMemberService {
    @Autowired
    private RedisClient<StaffResponse> redisClient;

    private static String staffKey = "staffKey";

    @Autowired
    private StoreMemberListUpdateMapper storeMemberListUpdateMapper;

    @Autowired
    private SsmCourseAccountService ssmCourseAccountService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;


    @Autowired
    private SsmRechargeAccountGiveService ssmRechargeAccountGiveService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private RedisClient<MemberResponse> memberRedisClient;

    @Autowired
    private RedisClient<StoreMemberList> memberListRedisClient;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmDebtService ssmDebtService;

    @Autowired
    private QuartzManage quartzManage;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmStoreMemberFileService ssmStoreMemberFileService;

    @Autowired
    private SsmStoreMemberPhoneService ssmStoreMemberPhoneService;

    @Autowired
    private SsmStoreMemberDao dao;

    @Autowired
    private SsmStoreMemberClassService ssmStoreMemberClassService;
    @Autowired
    private SsmCashService ssmCashService;
    @Autowired
    private SsmRechargeService ssmRechargeService;
    @Autowired
    private SsmCourseService ssmCourseService;

    @Autowired
    private SsmDocPromotionService ssmDocPromotionService;
    @Autowired
    private SsmCardChangeInProjectService ssmCardChangeInProjectService;
    @Autowired
    private SsmCardChangeService ssmCardChangeService;

    @Autowired
    private SsmRepayService ssmRepayService;
    @Autowired
    private SsmRepayAccountListService ssmRepayAccountListService;

    @Autowired
    private SsmRepayTradeService ssmRepayTradeService;

    @Autowired
    private SsmRefundOrderService ssmRefundOrderService;

    @Autowired
    private SsmRefundCashService ssmRefundCashService;
    @Autowired
    private SsmRefundRechargeService ssmRefundRechargeService;

    @Autowired
    private SsmRefundCourseService ssmRefundCourseService;


    @Autowired
    public SsmStoreParaDao ssmStoreParaDao;

    @Autowired
    public SsmBaseZengkaIssueService ssmBaseZengkaIssueService;

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

    @Override
    public PageInfo<StoreMemberList> selectPage(MemberRequest memberRequest) {
        if (StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
            memberRequest.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        }

        if(null != memberRequest.getStoreId()){
            List<Long> longs = new ArrayList<>();
            BaseStore baseStore=ssmBaseStoreService.selectByPrimaryKey(memberRequest.getStoreId());
            //区分会员清单是那个页面，type==0为会员清单页面，其它为充值时查询会员页面，ParentId()!=null判断是分店还是总店
            if(baseStore.getParentId()!=null&&memberRequest.getType()!=null&&memberRequest.getType()==0){
                longs.add(memberRequest.getStoreId());
            }else{
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(memberRequest.getStoreId());
                List<BaseStores> baseStores = ssmBaseStoreService.pagesorganizations(storeRequest);
                for (BaseStores baseStores1 :baseStores) {
                    longs.add(baseStores1.getId());
                }
            }


            memberRequest.setStoresId(longs);
            memberRequest.setStoreId(null);
        }

        //判断是纯数字手机号码
        if(memberRequest.getSlectPhoneName()!=null){
            boolean isnum=this.isNumeric(memberRequest.getSlectPhoneName());
            if(isnum){
                memberRequest.setSlectPhoneName(AESUtils.encrypt(memberRequest.getSlectPhoneName()));
            }
        }


        PageInfo pageInfo = dao.selectPage(memberRequest);
        List<StoreMemberList> lists = pageInfo.getList();
        lists.forEach(storeMemberList -> {
            try {
                storeMemberList.setMobilePhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).replaceAll("\u0000",""));
            } catch (Exception e) {
                log.error("SsmStoreMemberServiceImpl.selectPage:",e);
            }
        });

        return pageInfo;
    }

    @Override
    public PageInfo<StoreMemberList> selectPageassign(MemberRequest memberRequest) {
        if (StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
            memberRequest.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        }

//        if(null != memberRequest.getStoreId()){
//            List<Long> longs = new ArrayList<>();
//            StoreRequest storeRequest = new StoreRequest();
//            storeRequest.setId(memberRequest.getStoreId());
//            List<BaseStores> baseStores = ssmBaseStoreService.pagesorganizationim(storeRequest);
//            for (BaseStores baseStores1 :baseStores) {
//                longs.add(baseStores1.getId());
//            }
//            memberRequest.setStoresId(longs);
//            memberRequest.setStoreId(null);
//        }


        PageInfo pageInfo = dao.selectPageassign(memberRequest);
        List<StoreMemberList> lists = pageInfo.getList();
        lists.forEach(storeMemberList -> {
            try {
                BaseStaff baseStaff = ssmBaseStaffService.selectByPrimaryKey(storeMemberList.getStaffId());
                if(baseStaff!=null){
                    storeMemberList.setStaffNum(baseStaff.getBrandNumber());
                }
                storeMemberList.setMobilePhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).replaceAll("\u0000",""));
            } catch (Exception e) {
                log.error("SsmStoreMemberServiceImpl.selectPage:",e);
            }
        });

        return pageInfo;
    }

    @Override
    @Transactional
    public int updateStoreMember(MemberRequest memberRequest,String phone) throws SmsException {
        //手机号修改独立出来 只修改其他信息
//        if(StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
//            getStoreMember(memberRequest.getMobilePhone(), null, memberRequest.getStoreId());
//        }

        StoreMemberList storeMemberList = new StoreMemberList();
        BeanUtils.copyProperties(memberRequest,storeMemberList);
//        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getNewCashPassword()));
        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        StaffResponse staffResponse = redisClient.get(getKey(phone));
        storeMemberList.setModifyBy(staffResponse.getStaffName());
        storeMemberList.setModifyDate(new Date());

        //查询当前会员信息，将旧信息插入表中
        StoreMemberList oldMember = dao.selectByPrimaryKey(memberRequest.getId());
        StoreMemberListUpdate storeMemberListUpdate = new StoreMemberListUpdate();
        storeMemberListUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        storeMemberListUpdate.setMemberId(oldMember.getId());
        storeMemberListUpdate.setMemberNum(oldMember.getMemberNum());
        storeMemberListUpdate.setMemberName(oldMember.getMemberName());
        storeMemberListUpdate.setSex(oldMember.getSex());
        try {
            storeMemberListUpdate.setMobilePhone(AESUtils.decrypt(oldMember.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        storeMemberListUpdate.setState(oldMember.getState());
        storeMemberListUpdate.setPassword(oldMember.getPassword());
        storeMemberListUpdate.setCashPassword(oldMember.getCashPassword());
        storeMemberListUpdate.setUpdateId(staffResponse.getId());
        storeMemberListUpdate.setUpdateBy(staffResponse.getStaffName());
        storeMemberListUpdate.setUpdateDate(new Date());
        storeMemberListUpdate.setStoreId(memberRequest.getStoreId());
        storeMemberListUpdate.setStoreName(memberRequest.getStoreName());
        storeMemberListUpdateMapper.insert(storeMemberListUpdate);


        //修改支付密码查看修改人是否有权限
        if(memberRequest.getNewCashPassword()!=null){

        }

        if(storeMemberList.getMemberName()!=null){
            ssmBaseStoreService.updateName(storeMemberList.getMemberName());
            //更新充值卡包和疗程卡包
            CourseAccountRequest courseAccountRequest = new CourseAccountRequest();
            courseAccountRequest.setMemberId(storeMemberList.getId());
            List<CourseAccount> courseAccountList = ssmCourseAccountService.selectListByMemberList(courseAccountRequest);
            if(courseAccountList!=null && courseAccountList.size()>0) {
                for (CourseAccount courseAccount : courseAccountList) {
                    courseAccount.setMemberName(storeMemberList.getMemberName());
                    ssmCourseAccountService.updateByPrimaryKey(courseAccount);
                }
            }
            //更新充值卡的名字
            RechargeAccount rechargeAccount = new RechargeAccount();
            rechargeAccount.setMemberId(storeMemberList.getId());
            List<RechargeAccount> rechargeAccountList = ssmRechargeAccountService.select(rechargeAccount);
            if(rechargeAccountList!=null && rechargeAccountList.size()>0) {
                for (RechargeAccount account : rechargeAccountList) {
                    account.setMemberName(storeMemberList.getMemberName());
                    ssmRechargeAccountService.updateByPrimaryKey(account);
                }
            }
            //更新赠送金额卡包
            RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
            rechargeAccountGive.setMemberId(storeMemberList.getId());
            List<RechargeAccountGive> rechargeAccountGiveList = ssmRechargeAccountGiveService.select(rechargeAccountGive);
            if(rechargeAccountGiveList!=null && rechargeAccountGiveList.size()>0){
                RechargeAccountGive accountGive = rechargeAccountGiveList.get(0);
                    accountGive.setMemberName(storeMemberList.getMemberName());
                    ssmRechargeAccountGiveService.updateByMemberId(accountGive);
            }
            //更新欠款的会员名字
            DebtList debtList = new DebtList();
            debtList.setMemberId(storeMemberList.getId());
            List<DebtList> debtListList = ssmDebtService.select(debtList);
            if(debtListList!=null && debtListList.size()>0){
                for (DebtList list : debtListList) {
                    list.setMemberName(storeMemberList.getMemberName());
                    ssmDebtService.updateByPrimaryKey(list);
                }
            }

        }
        return dao.updateByPrimaryKeySelective(storeMemberList);
    }

    @Override
    public int updateMobile(MemberRequest memberRequest,String phone) throws SmsException {
        //手机号修改独立出来 只修改其他信息
        StaffResponse staffResponse = redisClient.get(getKey(phone));
        if(StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
            getStoreMember(memberRequest.getMobilePhone(), null, memberRequest.getStoreId());
        }
        //查询当前会员信息，将旧信息插入表中
        StoreMemberList oldMember = dao.selectByPrimaryKey(memberRequest.getId());
        StoreMemberListUpdate storeMemberListUpdate = new StoreMemberListUpdate();
        storeMemberListUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        storeMemberListUpdate.setMemberId(oldMember.getId());
        storeMemberListUpdate.setMemberNum(oldMember.getMemberNum());
        storeMemberListUpdate.setMemberName(oldMember.getMemberName());
        storeMemberListUpdate.setSex(oldMember.getSex());
        try {
            storeMemberListUpdate.setMobilePhone(AESUtils.decrypt(oldMember.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        storeMemberListUpdate.setState(oldMember.getState());
        storeMemberListUpdate.setPassword(oldMember.getPassword());
        storeMemberListUpdate.setCashPassword(oldMember.getCashPassword());
        storeMemberListUpdate.setUpdateId(staffResponse.getId());
        storeMemberListUpdate.setUpdateBy(staffResponse.getStaffName());
        storeMemberListUpdate.setUpdateDate(new Date());
        storeMemberListUpdate.setStoreId(memberRequest.getStoreId());
        storeMemberListUpdate.setStoreName(memberRequest.getStoreName());
        storeMemberListUpdateMapper.insert(storeMemberListUpdate);



        StoreMemberList storeMemberList = new StoreMemberList();
        BeanUtils.copyProperties(memberRequest,storeMemberList);
//        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getNewCashPassword()));
        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));

        storeMemberList.setModifyBy(staffResponse.getStaffName());
        storeMemberList.setModifyDate(new Date());
        //修改支付密码查看修改人是否有权限
        if(memberRequest.getNewCashPassword()!=null){

        }
        //添加交易记录，修改手机号
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(memberRequest.getStoreId());
        accountTradeRecord.setStoreName(memberRequest.getStoreName());
        accountTradeRecord.setMemberId(memberRequest.getId());
        accountTradeRecord.setMemberName(memberRequest.getMemberName());
        accountTradeRecord.setMemberPhone(memberRequest.getMobilePhone());
        accountTradeRecord.setDocNum(memberRequest.getMobilePhone());
        accountTradeRecord.setDocType(Constant.member_mobile_phone_change);
            accountTradeRecord.setInputDate(new Date());
            accountTradeRecord.setInputBy(staffResponse.getStaffName());
            accountTradeRecord.setAccountType(Constant.member_mobile_phone_change_new);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord);

        //添加交易记录，修改手机号
        AccountTradeRecord accountTradeRecord2 = new AccountTradeRecord();
        accountTradeRecord2.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord2.setStoreId(memberRequest.getStoreId());
        accountTradeRecord2.setStoreName(memberRequest.getStoreName());
        accountTradeRecord2.setMemberId(memberRequest.getId());
        accountTradeRecord2.setMemberName(memberRequest.getMemberName());
        accountTradeRecord2.setMemberPhone(memberRequest.getOldMobilePhone());
        accountTradeRecord2.setDocNum(memberRequest.getOldMobilePhone());
        accountTradeRecord2.setDocType(Constant.member_mobile_phone_change);
        accountTradeRecord2.setInputDate(new Date());
        accountTradeRecord2.setInputBy(staffResponse.getStaffName());
        accountTradeRecord2.setAccountType(Constant.member_mobile_phone_change_old);
        ssmAccountTradeRecordService.addRecord(accountTradeRecord2);

        if(storeMemberList.getMemberName()!=null){
            ssmBaseStoreService.updateName(storeMemberList.getMemberName());
            //更新充值卡包和疗程卡包
            CourseAccountRequest courseAccountRequest = new CourseAccountRequest();
            courseAccountRequest.setMemberId(storeMemberList.getId());
            List<CourseAccount> courseAccountList = ssmCourseAccountService.selectListByMemberList(courseAccountRequest);
            if(courseAccountList!=null && courseAccountList.size()>0) {
                for (CourseAccount courseAccount : courseAccountList) {
                    courseAccount.setMemberName(storeMemberList.getMemberName());
                    ssmCourseAccountService.updateByPrimaryKey(courseAccount);
                }
            }
            //更新充值卡的名字
            RechargeAccount rechargeAccount = new RechargeAccount();
            rechargeAccount.setMemberId(storeMemberList.getId());
            List<RechargeAccount> rechargeAccountList = ssmRechargeAccountService.select(rechargeAccount);
            if(rechargeAccountList!=null && rechargeAccountList.size()>0) {
                for (RechargeAccount account : rechargeAccountList) {
                    account.setMemberName(storeMemberList.getMemberName());
                    ssmRechargeAccountService.updateByPrimaryKey(account);
                }
            }
            //更新赠送金额卡包
            RechargeAccountGive rechargeAccountGive = new RechargeAccountGive();
            rechargeAccountGive.setMemberId(storeMemberList.getId());
            List<RechargeAccountGive> rechargeAccountGiveList = ssmRechargeAccountGiveService.select(rechargeAccountGive);
            if(rechargeAccountGiveList!=null && rechargeAccountGiveList.size()>0){
                RechargeAccountGive accountGive = rechargeAccountGiveList.get(0);
                accountGive.setMemberName(storeMemberList.getMemberName());
                ssmRechargeAccountGiveService.updateByMemberId(accountGive);
            }
            //更新欠款的会员名字
            DebtList debtList = new DebtList();
            debtList.setMemberId(storeMemberList.getId());
            List<DebtList> debtListList = ssmDebtService.select(debtList);
            if(debtListList!=null && debtListList.size()>0){
                for (DebtList list : debtListList) {
                    list.setMemberName(storeMemberList.getMemberName());
                    ssmDebtService.updateByPrimaryKey(list);
                }
            }

        }
        return dao.updateByPrimaryKeySelective(storeMemberList);
    }
    @Override
    @Transactional
    public int upcashPassword(MemberRequest memberRequest) throws SmsException {

        int i=0;
        if(memberRequest.getCashPasswordnew1()!=null&&memberRequest.getCashPasswordnew2()!=null&&!memberRequest.getCashPasswordnew1().trim().equals("")&&!memberRequest.getCashPasswordnew2().trim().equals("")){
            if(memberRequest.getCashPasswordnew1().trim()==memberRequest.getCashPasswordnew2().trim()||memberRequest.getCashPasswordnew1().trim().equals(memberRequest.getCashPasswordnew2().trim())){
                StoreMemberList storeMemberList = new StoreMemberList();
                storeMemberList.setId(memberRequest.getId());
                storeMemberList.setStoreId(memberRequest.getStoreId());
                storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getCashPassword()));
                int b=dao.updateByPrimaryKeySelective(storeMemberList);
                if(b>0){
                    StaffResponse staffResponse = redisClient.get(getKey(memberRequest.getOldPhone()));

                    //查询当前会员信息，将旧信息插入表中
                    StoreMemberList oldMember = dao.selectByPrimaryKey(memberRequest.getId());
                    StoreMemberListUpdate storeMemberListUpdate = new StoreMemberListUpdate();
                    storeMemberListUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                    storeMemberListUpdate.setMemberId(oldMember.getId());
                    storeMemberListUpdate.setMemberNum(oldMember.getMemberNum());
                    storeMemberListUpdate.setMemberName(oldMember.getMemberName());
                    storeMemberListUpdate.setSex(oldMember.getSex());
                    try {
                        storeMemberListUpdate.setMobilePhone(AESUtils.decrypt(oldMember.getMobilePhone()).replaceAll("\u0000",""));
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                    storeMemberListUpdate.setState(oldMember.getState());
                    storeMemberListUpdate.setPassword(oldMember.getPassword());
                    storeMemberListUpdate.setCashPassword(oldMember.getCashPassword());
                    storeMemberListUpdate.setUpdateId(staffResponse.getId());
                    storeMemberListUpdate.setUpdateBy(staffResponse.getStaffName());
                    storeMemberListUpdate.setUpdateDate(new Date());
                    storeMemberListUpdate.setStoreId(memberRequest.getStoreId());
                    storeMemberListUpdate.setStoreName(memberRequest.getStoreName());
                    storeMemberListUpdateMapper.insert(storeMemberListUpdate);
                    return i=0;
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"输入得两次密码不一致");
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"输入密码不能为空");
        }
        return i;
    }


    @Override
    @Transactional
    public int passwordReset(MemberRequest memberRequest) throws SmsException {
        //手机号修改独立出来 只修改其他信息
//        if(StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
//            getStoreMember(memberRequest.getMobilePhone(), null, memberRequest.getStoreId());
//        }
        StaffResponse staffResponse = redisClient.get(getKey(memberRequest.getOldPhone()));

        //查询当前会员信息，将旧信息插入表中
        StoreMemberList oldMember = dao.selectByPrimaryKey(memberRequest.getId());
        StoreMemberListUpdate storeMemberListUpdate = new StoreMemberListUpdate();
        storeMemberListUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        storeMemberListUpdate.setMemberId(oldMember.getId());
        storeMemberListUpdate.setMemberNum(oldMember.getMemberNum());
        storeMemberListUpdate.setMemberName(oldMember.getMemberName());
        storeMemberListUpdate.setSex(oldMember.getSex());
        try {
            storeMemberListUpdate.setMobilePhone(AESUtils.decrypt(oldMember.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        storeMemberListUpdate.setState(oldMember.getState());
        storeMemberListUpdate.setPassword(oldMember.getPassword());
        storeMemberListUpdate.setCashPassword(oldMember.getCashPassword());
        storeMemberListUpdate.setUpdateId(staffResponse.getId());
        storeMemberListUpdate.setUpdateBy(staffResponse.getStaffName());
        storeMemberListUpdate.setUpdateDate(new Date());
        storeMemberListUpdate.setStoreId(memberRequest.getStoreId());
        storeMemberListUpdate.setStoreName(memberRequest.getStoreName());
        storeMemberListUpdateMapper.insert(storeMemberListUpdate);




        StoreMemberList storeMemberList = new StoreMemberList();
        storeMemberList.setId(memberRequest.getId());
        StoreMemberList storeMemberList1 = dao.selectOne(storeMemberList);
        memberListRedisClient.set("MPR_"+storeMemberList1.getId()+"_"+storeMemberList1.getPassword()+"_"+AESUtils.encrypt(memberRequest.getPassword()), storeMemberList1, 10*60L);
//        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
//        storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getNewCashPassword()));
//        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
//        StaffResponse staffResponse = redisClient.get(getKey(phone));
//        storeMemberList.setModify(staffResponse.getStaffName());
//        storeMemberList.setModifyDate(new Date());
        storeMemberList1.setPassword(AESUtils.encrypt(memberRequest.getPassword()));
        //storeMemberList1.setCashPassword(AESUtils.encrypt(memberRequest.getCashPassword()));
        return dao.updateByPrimaryKeySelective(storeMemberList1);
    }

    @Override
    @Transactional
    public int CashpasswordReset(MemberRequest memberRequest) throws SmsException {
        StaffResponse staffResponse = redisClient.get(getKey(memberRequest.getOldPhone()));
        //查询当前会员信息，将旧信息插入表中
        StoreMemberList oldMember = dao.selectByPrimaryKey(memberRequest.getId());
        StoreMemberListUpdate storeMemberListUpdate = new StoreMemberListUpdate();
        storeMemberListUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        storeMemberListUpdate.setMemberId(oldMember.getId());
        storeMemberListUpdate.setMemberNum(oldMember.getMemberNum());
        storeMemberListUpdate.setMemberName(oldMember.getMemberName());
        storeMemberListUpdate.setSex(oldMember.getSex());
        try {
            storeMemberListUpdate.setMobilePhone(AESUtils.decrypt(oldMember.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        storeMemberListUpdate.setState(oldMember.getState());
        storeMemberListUpdate.setPassword(oldMember.getPassword());
        storeMemberListUpdate.setCashPassword(oldMember.getCashPassword());
        storeMemberListUpdate.setUpdateId(staffResponse.getId());
        storeMemberListUpdate.setUpdateBy(staffResponse.getStaffName());
        storeMemberListUpdate.setUpdateDate(new Date());
        storeMemberListUpdate.setStoreId(memberRequest.getStoreId());
        storeMemberListUpdate.setStoreName(memberRequest.getStoreName());
        storeMemberListUpdateMapper.insert(storeMemberListUpdate);


        //手机号修改独立出来 只修改其他信息
//        if(StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
//            getStoreMember(memberRequest.getMobilePhone(), null, memberRequest.getStoreId());
//        }

        StoreMemberList storeMemberList = new StoreMemberList();
        storeMemberList.setId(memberRequest.getId());
        StoreMemberList storeMemberList1 = dao.selectOne(storeMemberList);
        memberListRedisClient.set("MCPR_"+storeMemberList1.getId()+"_"+storeMemberList1.getCashPassword()+"_"+AESUtils.encrypt(memberRequest.getCashPassword()), storeMemberList1, 10*60L);
//        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
//        storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getNewCashPassword()));
//        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
//        StaffResponse staffResponse = redisClient.get(getKey(phone));
//        storeMemberList.setModify(staffResponse.getStaffName());
//        storeMemberList.setModifyDate(new Date());
        storeMemberList1.setCashPassword(AESUtils.encrypt(memberRequest.getCashPassword()));
        //storeMemberList1.setCashPassword(AESUtils.encrypt(memberRequest.getCashPassword()));
        return dao.updateByPrimaryKeySelective(storeMemberList1);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updateState(MemberRequest memberRequest,String phone) throws SmsException {
        int i = 0;
//        StoreMemberList storeMemberList = dao.selectByPrimaryKey(memberRequest.getId());
        StoreMemberList memberList = new StoreMemberList();
        memberList.setState(0);
        memberList.setId(memberRequest.getId());
        StaffResponse staffResponse = redisClient.get(getKey(phone));
        memberList.setModifyBy(staffResponse.getStaffName());
        memberList.setModifyDate(new Date());
        memberList.setModifyId(staffResponse.getId());

        //查询当前会员信息，将旧信息插入表中
        StoreMemberList oldMember = dao.selectByPrimaryKey(memberRequest.getId());
        StoreMemberListUpdate storeMemberListUpdate = new StoreMemberListUpdate();
        storeMemberListUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        storeMemberListUpdate.setMemberId(oldMember.getId());
        storeMemberListUpdate.setMemberNum(oldMember.getMemberNum());
        storeMemberListUpdate.setMemberName(oldMember.getMemberName());
        storeMemberListUpdate.setSex(oldMember.getSex());
        try {
            storeMemberListUpdate.setMobilePhone(AESUtils.decrypt(oldMember.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        storeMemberListUpdate.setState(oldMember.getState());
        storeMemberListUpdate.setPassword(oldMember.getPassword());
        storeMemberListUpdate.setCashPassword(oldMember.getCashPassword());
        storeMemberListUpdate.setUpdateId(staffResponse.getId());
        storeMemberListUpdate.setUpdateBy(staffResponse.getStaffName());
        storeMemberListUpdate.setUpdateDate(new Date());
        storeMemberListUpdate.setStoreId(memberRequest.getStoreId());
        storeMemberListUpdate.setStoreName(memberRequest.getStoreName());
        storeMemberListUpdateMapper.insert(storeMemberListUpdate);

//
//        //启用 密码校验 或者验证码校验
//        if (memberList.getState() == 1 || memberList.getState() == 2){ //state 1立即启用  state 2延时启用 状态改为启用中 添加定时任务到点启用
//            //启用校验手机号码是否在门店中已有使用
//            getStoreMember(memberRequest.getMobilePhone(),null,storeMemberList.getStoreId());
//            if (StringUtils.isNotBlank(memberRequest.getPassword())){
//                String password = AESUtils.encrypt(memberRequest.getPassword());
//                if (!storeMemberList.getPassword().equals(password)){
//                    throw new SmsException(ResponseCode.PASS_ERROR);
//                }
//            }
//            if (StringUtils.isNotBlank(memberRequest.getPassCode())){
//                String passCodekey = getPasscodeKey(storeMemberList.getMobilePhone());
//                if (redisClient.hasKey(passCodekey)) {
//                    if (!memberRequest.getPassCode().equals(redisClient.get(passCodekey).getPassCode())) {
//                        throw new SmsException(ResponseCode.SMS_CODE_IS_ERR);
//                    }
//                }else {
//                    throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
//                }
//            }
//            //查询启用会员门店参数
//            StoreParament storeParament = StoreParaUtils.getStorePara(storeMemberList.getStoreId(),Constant.member_using);
//            if (!"0".equals(storeParament.getParamentValue())){
//
//               //定时任务添加 修改状态
//                int day = Integer.valueOf(storeParament.getParamentValue());
//                Map map = new HashMap();
//                StoreMemberList storeMemberList1 = new StoreMemberList();
//                storeMemberList1.setState(1);
//                storeMemberList1.setId(storeMemberList.getId());
//                map.put("memberList",storeMemberList1);
//                int seconds = day * 24 * 3600;
////                int seconds = 2 * 60;
//                String corn = DateUtils.date2Cron(new Date(new Date().getTime() + seconds * 1000));
//                int j = quartzManage.addTask("storeMemberStart"+memberRequest.getId(),"storeMemberStartGroup"+memberRequest.getId(),"storeMemberStartTrigger"+memberRequest.getId(),
//                        "storeMemberStartTriggerGroup"+memberRequest.getId(), SsmStoreMemberStartTask.class,corn,map);
//                if (j == 2){
//                    log.error(String.format("SsmStoreMemberStartTask 添加失败"));
//                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
//                }
//                if (j == 1){//定时任务添加成功
//                    //更新状态为启用中
//                    i = dao.updateByPrimaryKeySelective(memberList);
//                }
//            }else {
//                //直接更新为启用
//                i = dao.updateByPrimaryKeySelective(memberList);
//            }
//        }else {

            i = dao.updateByPrimaryKeySelective(memberList);
//        }

        return i;
    }


    @Override
    public int addStoreMember(MemberRequest memberRequest, String phone) throws SmsException {
//        StoreRequest storeRequest1 = new StoreRequest();
//        storeRequest1.setId(memberRequest.getConnStoreId());
//        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest1);
//        for (BaseStores pagesorganization : pagesorganizations) {
//            if(pagesorganization.getId()==memberRequest.getStoreId()){
//                if(null == pagesorganization.getParentId()){
//                    memberRequest.setStoreId(pagesorganization.getId());
//                    memberRequest.setStoreName(pagesorganization.getStoreName());
//                    break;
//                }
//            }
//        }
        memberRequest.setStoreId(memberRequest.getConnStoreId());
        memberRequest.setStoreName(memberRequest.getConnStoreName());
        getStoreMember(memberRequest.getMobilePhone(),null,memberRequest.getStoreId());
        StoreMemberList storeMemberList = new StoreMemberList();
        BeanUtils.copyProperties(memberRequest,storeMemberList);
        if(null == memberRequest.getGrouptype()){
            storeMemberList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        }else{
            storeMemberList.setId(memberRequest.getId());
        }

        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        //会员编码

        String memberNum = getMemberNumNews(memberRequest.getMemberNumber(),memberRequest.getConnStoreId());
        String i = memberNum.substring(memberNum.length() - 6, memberNum.length());
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(memberRequest.getConnStoreId());
        BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest);
        memberNum= baseStore.getStoreNum()+i;

        storeMemberList.setMemberNum(memberNum);
        StaffResponse staffResponse = new StaffResponse();
         if (redisClient.hasKey(getKey(phone))) {
             staffResponse = redisClient.get(getKey(phone));
             storeMemberList.setInputId(staffResponse.getId());
             storeMemberList.setInputBy(staffResponse.getStaffName());
         }
        Set<String> keys = redisClient.keys(getKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
            storeMemberList.setInputId(staffResponse.getId());
            storeMemberList.setInputBy(staffResponse.getStaffName());
        }
        storeMemberList.setInputDate(new Date());
        //密码加密
//        // TODO 密码设为固定初始密码
//        storeMemberList.setPassword(AESUtils.encrypt("123456"));

        storeMemberList.setPassword(AESUtils.encrypt(memberRequest.getPassword().trim()));
        storeMemberList.setCashPassword(AESUtils.encrypt(memberRequest.getCashPassword().trim()));
        //默认未分派服务人员
        storeMemberList.setAssignState(0);
        storeMemberList.setState(1);
        storeMemberList.setIntegral(0);
        return dao.saveNotNull(storeMemberList);
    }

    @Override
    public int assignStoreMember(MemberRequest memberRequest) {
        StoreMemberList storeMemberList = new StoreMemberList();
        storeMemberList.setId(memberRequest.getId());
        storeMemberList.setStaffId(memberRequest.getStaffId());
        storeMemberList.setStaffName(memberRequest.getStaffName());
        storeMemberList.setAssignState(1);
        return dao.updateByPrimaryKeySelective(storeMemberList);
    }

    @Override
    public List<StoreMemberList> listByStaff(MemberRequest memberRequest) {
        StoreMemberList storeMemberList = new StoreMemberList();
        storeMemberList.setStaffId(memberRequest.getStaffId());
        storeMemberList.setConnStoreId(memberRequest.getStoreId());
        List<StoreMemberList> lists = dao.select(storeMemberList);
        lists.forEach(memberList -> {
            try {
                memberList.setMobilePhone(AESUtils.decrypt(memberList.getMobilePhone()).replaceAll("\u0000",""));
            } catch (Exception e) {
                log.error("SsmStoreMemberServiceImpl.selectPage:",e);
            }
        });
        return lists;
    }

    @Override
    public MemberResponse selectOne(MemberRequest memberRequest) throws SmsException {
        StoreMemberList storeMemberList = new StoreMemberList();
//        if (StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
//            storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
//        }
//        if (StringUtils.isNotBlank(memberRequest.getCard())){
//            storeMemberList.setCard(memberRequest.getCard());
//        }
//        storeMemberList.setStoreId(memberRequest.getStoreId());
//        storeMemberList.setState(1);
        StoreRequest storeRequest1 = new StoreRequest();
        storeRequest1.setId(memberRequest.getStoreId());
        List<BaseStores> pagesorganizations1 = ssmBaseStoreService.pagesorganizations(storeRequest1);
        List<Long> storeId =new ArrayList<>();
        for (BaseStores stores : pagesorganizations1) {
            storeId.add(stores.getId());
        }
        Example example = new Example(StoreMemberList.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(memberRequest.getMobilePhone())) {
            criteria.andEqualTo("mobilePhone", AESUtils.encrypt(memberRequest.getMobilePhone()));
        }
        if (StringUtils.isNotBlank(memberRequest.getCard())){
            criteria.andEqualTo("card", memberRequest.getCard());
        }
        if (StringUtils.isNotBlank(memberRequest.getMemberNum())){
            criteria.andEqualTo("memberNum", memberRequest.getMemberNum());
        }
        criteria.andEqualTo("state", 1);
        //criteria.andEqualTo("storeId", memberRequest.getStoreIdl());
        criteria.andIn("storeId",storeId);
        List<StoreMemberList> storeMemberLists = dao.selectByExample(example);
        if(storeMemberLists.size()>0){
            storeMemberList = storeMemberLists.get(0);
        }else{
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"会员");
        }
        if(null == storeMemberList){
            throw new SmsException(ResponseCode.DATA_DOES_NOT_EXISTS_S,"会员");
        }
        MemberResponse memberResponse = new MemberResponse();
        BeanUtils.copyProperties(storeMemberList,memberResponse);
        try {
            memberResponse.setMobilePhone(AESUtils.decrypt(storeMemberList.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            throw new SmsException(ResponseCode.DECRYPT_FAILED);
        }
        StoreParament parament = StoreParaUtils.getStorePara(storeMemberList.getStoreId(), Constant.member_integral);
        if ("1".equals(parament.getParamentValue())) {
            memberResponse.setIntegral(storeMemberList.getIntegral());
            //查询积分兑换比例
            StoreParament storeParament = StoreParaUtils.getStorePara(storeMemberList.getStoreId(), Constant.exc_integral_by_money);
            String value[] = storeParament.getParamentValue().split(":");
            Integer integral = Integer.parseInt(value[0]);
            Integer money = Integer.parseInt(value[1]);
            Integer consumeIntegral = (null == storeMemberList.getIntegral() ? 0 : storeMemberList.getIntegral()) - ((null == storeMemberList.getIntegral() ? 0 : storeMemberList.getIntegral()) % (integral / money));
            BigDecimal integralMoney = BigDecimalUtils.div(BigDecimal.valueOf(consumeIntegral), BigDecimal.valueOf(integral / money));
            memberResponse.setConsumeIntegral(consumeIntegral);
            memberResponse.setIntegralMoney(integralMoney);
        }

//        StoreParament storeParament = StoreParaUtils.getStorePara(memberRequest.getStoreId(), Constant.rec_debt);
//        if ("1".equals(storeParament.getParamentValue())) {
//            StoreRequest storeRequest = new StoreRequest();
//            storeRequest.setId(memberRequest.getStoreId());
//            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
//            BigDecimal debtMoney = BigDecimalUtils.bigDecimal("0");
//            for (BaseStores pagesorganization : pagesorganizations) {
//                //查询门店会员总欠款
//                DebtList debtList = new DebtList();
//                debtList.setStoreId(pagesorganization.getId());
//                debtList.setMemberId(storeMemberList.getId());
//                List<DebtList> lists = ssmDebtService.select(debtList);
//                for (DebtList list : lists) {
//                    debtMoney = BigDecimalUtils.add(debtMoney, list.getDebtMoney());
//                }
//                memberResponse.setDebtMoney(debtMoney);
//            }
//        }

        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(memberRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        BigDecimal debtMoney = BigDecimalUtils.bigDecimal("0");
        for (BaseStores pagesorganization : pagesorganizations) {
            //查询门店会员总欠款
            DebtList debtList = new DebtList();
            debtList.setStoreId(pagesorganization.getId());
            debtList.setMemberId(storeMemberList.getId());
            List<DebtList> lists = ssmDebtService.select(debtList);
            for (DebtList list : lists) {
                debtMoney = BigDecimalUtils.add(debtMoney, list.getDebtMoney());
            }
            memberResponse.setDebtMoney(debtMoney);

        }
        return memberResponse;
    }


    @Override
    public boolean checkCashWord(MemberRequest memberRequest) throws SmsException {
        StoreMemberList storeMemberList = dao.selectByPrimaryKey(memberRequest.getId());
        String cashPassword = null;
        String cashPasswords = null;
        try {
            cashPassword = AESUtils.encrypt(memberRequest.getCashPassword());
        } catch (Exception e) {
            throw new SmsException(ResponseCode.DECRYPT_FAILED);
        }
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(memberRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        BaseStores stores=null;
        for (BaseStores pagesorganization : pagesorganizations) {
            if(null==pagesorganization.getParentId()){
                stores=pagesorganization;
            }
        }
        //查询超级支付密码
        StoreParament superpsw=new StoreParament();
        BaseStore baseStore=ssmBaseStoreService.selectByPrimaryKey(memberRequest.getStoreId());
        if(baseStore.getParentId()!=null){
             superpsw=ssmStoreParaDao.selectSperpsw(baseStore.getParentId());
        }else{
             superpsw=ssmStoreParaDao.selectSperpsw(memberRequest.getStoreId());
        }


        List<StoreParament> storeParament=ssmStoreParaDao.sselectSStoreParament(memberRequest.getStoreId());
        for(StoreParament storeParament1:storeParament){
            if(storeParament1.getParamentName().equals("memberPay")&&storeParament1.getParamentName()!=null){
                if(storeParament1.getParamentValue().equals("0")||storeParament1.getParamentValue().equals("2")){

                    if (stores.getPaymentCode() != null) {
                        //对比密码是否一致
                        if (!cashPassword.equals(storeMemberList.getCashPassword())
                                && !stores.getPaymentCode().equals(cashPassword)
                                &&!superpsw.getParamentValue().equals(memberRequest.getCashPassword())){
                            return false;
                        }
                    }else{
                        //对比密码是否一致
                        if (!cashPassword.equals(storeMemberList.getCashPassword()) &&
                                !superpsw.getParamentValue().equals(memberRequest.getCashPassword())){
                            return false;
                        }
                    }


                }
            }
        }


        return true;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int changePhoneToUpdateState(MemberRequest memberRequest, String phone) throws SmsException {
        int i = 0;

        if (StringUtils.isNotBlank(memberRequest.getPassCode())){
            String passCodekey = getPasscodeKey(memberRequest.getMobilePhone());
            if (redisClient.hasKey(passCodekey)) {
                if (!memberRequest.getPassCode().equals(redisClient.get(passCodekey).getPassCode())) {
                    throw new SmsException(ResponseCode.SMS_CODE_IS_ERR);
                }
            }else {
                throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
            }
        }
        StoreMemberList memberList = new StoreMemberList();
        BeanUtils.copyProperties(memberRequest, memberList);
        memberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getKey(phone))) {
            staffResponse = redisClient.get(getKey(phone));
        }
        Set<String> keys = redisClient.keys(getKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0){
            String key =  new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        memberList.setModifyBy(staffResponse.getStaffName());
        memberList.setModifyDate(new Date());
        //查询启用会员门店参数
        StoreParament storeParament = StoreParaUtils.getStorePara(memberRequest.getStoreId(),Constant.member_using);
        if (!"0".equals(storeParament.getParamentValue())){
            //启用校验手机号码是否在门店中已有使用
            getStoreMember(memberRequest.getMobilePhone(), null, memberRequest.getStoreId());
            //定时任务添加 修改状态
            int day = Integer.valueOf(storeParament.getParamentValue());
            Map map = new HashMap();
            StoreMemberList storeMemberList1 = new StoreMemberList();
            storeMemberList1.setState(1);
            storeMemberList1.setId(memberRequest.getId());

            storeMemberList1.setModifyBy(staffResponse.getStaffName());
            storeMemberList1.setModifyDate(new Date());
            map.put("memberList",storeMemberList1);
            int seconds = day * 24 * 3600;
//                int seconds = 2 * 60;
            String corn = DateUtils.date2Cron(new Date(new Date().getTime() + seconds * 1000));
            int j = quartzManage.addTask("storeMemberStart"+memberRequest.getId(),"storeMemberStartGroup"+memberRequest.getId(),"storeMemberStartTrigger"+memberRequest.getId(),
                    "storeMemberStartTriggerGroup"+memberRequest.getId(), SsmStoreMemberStartTask.class,corn,map);
            if (j == 2){
                log.error(String.format("SsmStoreMemberStartTask 添加失败"));
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (j == 1){//定时任务添加成功
                //更新状态为启用中
                memberList.setState(2);
                i = dao.updateByPrimaryKeySelective(memberList);
            }
        }else {
            //直接更新为启用
            memberList.setState(1);
            i = dao.updateByPrimaryKeySelective(memberList);
        }
        if (i > 0) {
            //添加修改记录

            StoreMemberPhone memberPhone = new StoreMemberPhone();
            memberPhone.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            memberPhone.setInputId(staffResponse.getId());
            memberPhone.setInputBy(staffResponse.getStaffName());
            memberPhone.setInputDate(memberList.getModifyDate());
            memberPhone.setMemberId(memberList.getId());
            memberPhone.setMemberName(memberList.getMemberName());
            memberPhone.setStoreId(memberList.getStoreId());
            memberPhone.setStoreName(memberList.getStoreName());
            memberPhone.setSource(Constant.pcSource);
            memberPhone.setOldPhone(memberRequest.getOldPhone());
            i = ssmStoreMemberPhoneService.saveNotNull(memberPhone);

            //将文件上传信息保存到数据库
            List<StoreMemberFile> list = memberRequest.getUploadFiles();
            for (StoreMemberFile storeMemberFile : list) {
                storeMemberFile.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                storeMemberFile.setDocId(memberPhone.getId());
                ssmStoreMemberFileService.saveNotNull(storeMemberFile);
            }
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int start(MemberRequest memberRequest, String phone) throws SmsException {
        int i = 0;

        //启用 密码校验 或者验证码校验
//        if (memberRequest.getState() == 1 || memberRequest.getState() == 2){ //state 1立即启用  state 2延时启用 状态改为启用中 添加定时任务到点启用
//            //启用校验手机号码是否在门店中已有使用
//            getStoreMember(memberRequest.getMobilePhone(),null,storeMemberList.getStoreId());
//            if (StringUtils.isNotBlank(memberRequest.getPassword())){
//                String password = AESUtils.encrypt(memberRequest.getPassword());
//                if (!storeMemberList.getPassword().equals(password)){
//                    throw new SmsException(ResponseCode.PASS_ERROR);
//                }
//            }


//        String mobilePhone = "";
//        try {
//            //mobilePhone = AESUtils.decrypt(memberRequest.getMobilePhone()).replaceAll("\u0000","");
//        } catch (Exception e) {
//            throw new SmsException(ResponseCode.DECRYPT_FAILED);
//        }
        /*升级后去掉会员短信验证码激活*/
//        if (StringUtils.isNotBlank(memberRequest.getPassCode())){
//                String passCodekey = getPasscodeKey(mobilePhone);
//                if (redisClient.hasKey(passCodekey)) {
//                    if (!memberRequest.getPassCode().equals(redisClient.get(passCodekey).getPassCode())) {
//                        throw new SmsException(ResponseCode.SMS_CODE_IS_ERR);
//                    }
//                }else {
//                    throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
//                }
//        }
        StoreMemberList memberList = new StoreMemberList();
        BeanUtils.copyProperties(memberRequest, memberList);
        memberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getKey(phone))) {
            staffResponse = redisClient.get(getKey(phone));
        }
        Set<String> keys = redisClient.keys(getKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        //查询当前会员信息，将旧信息插入表中
        StoreMemberList oldMember = dao.selectByPrimaryKey(memberRequest.getId());
        StoreMemberListUpdate storeMemberListUpdate = new StoreMemberListUpdate();
        storeMemberListUpdate.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        storeMemberListUpdate.setMemberId(oldMember.getId());
        storeMemberListUpdate.setMemberNum(oldMember.getMemberNum());
        storeMemberListUpdate.setMemberName(oldMember.getMemberName());
        storeMemberListUpdate.setSex(oldMember.getSex());
        try {
            storeMemberListUpdate.setMobilePhone(AESUtils.decrypt(oldMember.getMobilePhone()).replaceAll("\u0000",""));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        storeMemberListUpdate.setState(oldMember.getState());
        storeMemberListUpdate.setPassword(oldMember.getPassword());
        storeMemberListUpdate.setCashPassword(oldMember.getCashPassword());
        storeMemberListUpdate.setUpdateId(staffResponse.getId());
        storeMemberListUpdate.setUpdateBy(staffResponse.getStaffName());
        storeMemberListUpdate.setUpdateDate(new Date());
        storeMemberListUpdate.setStoreId(memberRequest.getStoreId());
        storeMemberListUpdate.setStoreName(memberRequest.getStoreName());
        storeMemberListUpdateMapper.insert(storeMemberListUpdate);



        memberList.setModifyBy(staffResponse.getStaffName());
        memberList.setModifyDate(new Date());

        //查询启用会员门店参数
        StoreParament storeParament = StoreParaUtils.getStorePara(memberRequest.getStoreId(), Constant.member_using);
        if (!"0".equals(storeParament.getParamentValue())) {
            //启用校验手机号码是否在门店中已有使用
            getStoreMember(memberRequest.getMobilePhone(), null, memberRequest.getStoreId());
            //定时任务添加 修改状态
            int day = Integer.valueOf(storeParament.getParamentValue());
            Map map = new HashMap();
            StoreMemberList storeMemberList1 = new StoreMemberList();
            storeMemberList1.setState(1);
            storeMemberList1.setId(memberRequest.getId());

            storeMemberList1.setModifyBy(staffResponse.getStaffName());
            storeMemberList1.setModifyDate(new Date());
            map.put("memberList", storeMemberList1);
            int seconds = day * 24 * 3600;
//                int seconds = 2 * 60;
            String corn = DateUtils.date2Cron(new Date(new Date().getTime() + seconds * 1000));
            int j = quartzManage.addTask("storeMemberStart" + memberRequest.getId(), "storeMemberStartGroup" + memberRequest.getId(), "storeMemberStartTrigger" + memberRequest.getId(),
                    "storeMemberStartTriggerGroup" + memberRequest.getId(), SsmStoreMemberStartTask.class, corn, map);
            if (j == 2) {
                log.error(String.format("SsmStoreMemberStartTask 添加失败"));
                throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
            }
            if (j == 1) {//定时任务添加成功
                //更新状态为启用中
                memberList.setState(2);
                memberList.setStoreId(null);
                memberList.setStoreName(null);
                i = dao.updateByPrimaryKeySelective(memberList);
            }
        } else {
            //直接更新为启用
            memberList.setState(1);
            memberList.setStoreId(null);
            memberList.setStoreName(null);
            i = dao.updateByPrimaryKeySelective(memberList);
        }
        return i;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int updatePhone(MemberRequest memberRequest, String phone) throws SmsException {
        int i = 0;
        //启用校验手机号码是否在门店中已有使用
        getStoreMember(memberRequest.getMobilePhone(), null, memberRequest.getStoreId());
        StoreMemberList memberList = new StoreMemberList();
        BeanUtils.copyProperties(memberRequest, memberList);
        try {
            phone = AESUtils.decrypt(phone).replaceAll("\u0000","");
        } catch (Exception e) {
            throw new SmsException(ResponseCode.DECRYPT_FAILED);
        }
        memberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
        MemberResponse memberResponse = new MemberResponse();
        Set<String> s =  memberRedisClient.keys(getMemberKey(phone) + "*");
        if (s.size() > 0) {
            memberResponse = memberRedisClient.get(s.iterator().next());
            memberList.setModifyBy(memberResponse.getMemberName());
            memberList.setModifyDate(new Date());
        }
        i = dao.updateByPrimaryKeySelective(memberList);
        //添加修改记录
        if (i > 0){
            StoreMemberPhoneRequest memberPhoneRequest = new StoreMemberPhoneRequest();
            memberPhoneRequest.setInputId(memberResponse.getId());
            memberPhoneRequest.setInputBy(memberResponse.getMemberName());
            memberPhoneRequest.setInputDate(memberList.getModifyDate());
            memberPhoneRequest.setMemberId(memberList.getId());
            memberPhoneRequest.setMemberName(memberList.getMemberName());
            memberPhoneRequest.setStoreId(memberList.getStoreId());
            memberPhoneRequest.setStoreName(memberList.getStoreName());
            memberPhoneRequest.setSource(Constant.wechatSource);
            memberPhoneRequest.setOldPhone(memberRequest.getOldPhone());
            ssmStoreMemberPhoneService.add(memberPhoneRequest);
        }
        return i;
    }


    @Override
    @Transactional(rollbackFor=Exception.class)
    public int bothOperation(List<MemberRequest> list, String phone) throws SmsException {
        int i = 0;
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getKey(phone))) {
            staffResponse = redisClient.get(getKey(phone));
        }
        Set<String> keys = redisClient.keys(getKey(phone) + "*");
        //从redis查询 设置录单人信息 app使用
        if (keys.size() > 0) {
            String key = new ArrayList<>(keys).get(0);
            staffResponse = redisClient.get(key);
        }
        MemberRequest startMemberRequest = list.get(0);
        StoreParament storeParament = StoreParaUtils.getStorePara(startMemberRequest.getStoreId(),Constant.member_using);
        StoreMemberList startMemberList = new StoreMemberList();
        //list中第一个为需要启用的会员  第二个为需要停用的会员
        BeanUtils.copyProperties(startMemberRequest, startMemberList);
        startMemberList.setModifyBy(staffResponse.getStaffName());
        startMemberList.setModifyDate(new Date());
        //需要启用的会员
        if (0 == startMemberList.getState()) {
            String mobilePhone = "";
            try {
                mobilePhone = AESUtils.decrypt(startMemberRequest.getMobilePhone()).replaceAll("\u0000","");
            } catch (Exception e) {
                throw new SmsException(ResponseCode.DECRYPT_FAILED);
            }
            //校验验证码
            if (StringUtils.isNotBlank(startMemberRequest.getPassCode())){
                String passCodekey = getPasscodeKey(mobilePhone);
                if (redisClient.hasKey(passCodekey)) {
                    if (!list.get(0).getPassCode().equals(redisClient.get(passCodekey).getPassCode())) {
                        throw new SmsException(ResponseCode.SMS_CODE_IS_ERR);
                    }
                }else {
                    throw new SmsException(ResponseCode.SMS_CODE_IS_OVER);
                }
            }

            if (!"0".equals(storeParament.getParamentValue())){

                //定时任务添加 修改状态
                int day = Integer.valueOf(storeParament.getParamentValue());
                Map map = new HashMap();
                StoreMemberList storeMemberList1 = new StoreMemberList();
                storeMemberList1.setState(1);
                storeMemberList1.setId(startMemberRequest.getId());

                storeMemberList1.setModifyBy(staffResponse.getStaffName());
                storeMemberList1.setModifyDate(new Date());
                map.put("memberList",storeMemberList1);
                int seconds = day * 24 * 3600;
//                int seconds = 2 * 60;
                String corn = DateUtils.date2Cron(new Date(new Date().getTime() + seconds * 1000));
                int j = quartzManage.addTask("storeMemberStart"+startMemberRequest.getId(),"storeMemberStartGroup"+startMemberRequest.getId(),"storeMemberStartTrigger"+startMemberRequest.getId(),
                        "storeMemberStartTriggerGroup"+startMemberRequest.getId(), SsmStoreMemberStartTask.class,corn,map);
                if (j == 2){
                    log.error(String.format("SsmStoreMemberStartTask 添加失败"));
                    throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
                }
                if (j == 1){//定时任务添加成功
                    //更新状态为启用中
                    startMemberList.setState(2);
                    i = dao.updateByPrimaryKeySelective(startMemberList);
                }
            }else {
                //直接更新为启用
                startMemberList.setState(1);
                i = dao.updateByPrimaryKeySelective(startMemberList);
            }
        }
        //成功启用  对同手机号的另一个会员进行停用
        if (i > 0){
            StoreMemberList stopMemberList = new StoreMemberList();
            BeanUtils.copyProperties(list.get(1), stopMemberList);
            stopMemberList.setModifyBy(staffResponse.getStaffName());
            stopMemberList.setModifyDate(new Date());
            stopMemberList.setState(0);
            i = dao.updateByPrimaryKeySelective(stopMemberList);
        }

        return i;
    }

    @Override
    public List<StoreMemberList> selectList(MemberRequest memberRequest) {
        StoreMemberList storeMemberList = new StoreMemberList();
        storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone().trim()));
        if (StringUtils.isNotBlank(memberRequest.getPassword())) {
            storeMemberList.setPassword(AESUtils.encrypt(memberRequest.getPassword().trim()));
        }
        if (null != memberRequest.getStoreId()){
            storeMemberList.setStoreId(memberRequest.getStoreId());
        }
        if (null != memberRequest.getState()){
            storeMemberList.setState(memberRequest.getState());
        }
        List<StoreMemberList> lists = dao.select(storeMemberList);
        return lists;
    }

    @Override
    public List<StoreMemberList> selectList(List<Long> memberIds) {
        Example example = new Example(StoreMemberList.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("id",memberIds);

        return dao.selectByExample(example);
    }

    @Override
    public List<StoreMemberList> selectListNew(MemberRequest memberRequest) {
        StoreMemberList storeMemberList = new StoreMemberList();
        if(StringUtils.isNotBlank(memberRequest.getMobilePhone())){
            storeMemberList.setMobilePhone(AESUtils.encrypt(memberRequest.getMobilePhone()));
            memberRequest.setMobilePhone(storeMemberList.getMobilePhone());
        }
        if (StringUtils.isNotBlank(memberRequest.getPassword())) {
            storeMemberList.setPassword(AESUtils.encrypt(memberRequest.getPassword()));
        }
        if (null != memberRequest.getStoreId()){
            storeMemberList.setStoreId(memberRequest.getStoreId());
        }
        if (null != memberRequest.getState()){
            storeMemberList.setState(memberRequest.getState());
        }else
        storeMemberList.setState(1);
        List<StoreMemberList> lists;
        //        这里判断是否是指定会员列表
        if(memberRequest.getIsDesignatedMember()!=null&&memberRequest.getIsDesignatedMember()==1){
            List<String> collect = ssmBaseZengkaIssueService.selectAll().stream().map(
                    e -> e.getMemberNum()
            ).collect(Collectors.toList());
            lists = dao.select(storeMemberList)
                    .stream().filter(e->!collect.contains(e.getMemberNum())).collect(Collectors.toList());
        }else{

            lists=dao.select(storeMemberList);
        }
        for (StoreMemberList list : lists) {
            try {
                list.setMobilePhone(AESUtils.decrypt(list.getMobilePhone()).replaceAll("\u0000",""));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return lists;
    }

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

    @Override
    public List<StoreMemberList> insertBatch(List<StoreMemberList> list, Long storeId, String storeName, String phone) throws SmsException {
        //校验会员列表手机号重复
        List<StoreMemberList> unusualList = this.check(list);
        if (!unusualList.isEmpty()){
            return unusualList;
        }
        StaffResponse staffResponse = new StaffResponse();
        if (redisClient.hasKey(getKey(phone))){
            staffResponse = redisClient.get(getKey(phone));
        }
        String memberNum = this.getMemberNum(storeId);

        for (StoreMemberList memberList : list) {
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(storeId);
            BaseStore baseStore = ssmBaseStoreService.selectOne(storeRequest);

            memberList.setMemberNum(memberNum);
            //批量上传避免数据量过大时new Random()重复导致生成的ID重复
//            memberList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
            memberList.setId(SnowflakeUtil.getId());
            memberList.setMobilePhone(AESUtils.encrypt(memberList.getMobilePhone()));
            memberList.setPassword(AESUtils.encrypt(memberList.getPassword()));
            memberList.setCashPassword(AESUtils.encrypt(memberList.getCashPassword()));
            memberList.setStoreId(storeId);
            memberList.setStoreName(storeName);
            memberList.setInputId(staffResponse.getId());
            memberList.setInputBy(staffResponse.getStaffName());
            if(null == memberList.getInputDate()){
                memberList.setInputDate(new Date());
            }
            memberList.setAssignState(0);
            memberList.setConnStoreId(storeId);
            memberList.setConnStoreName(storeName);
            if(null == memberList.getMemberStoreNum()){
                BaseStore baseStore1 = new BaseStore();
                baseStore1.setStoreNum(memberList.getMemberStoreNum());
                BaseStore baseStore2 = ssmBaseStoreService.selectOne(baseStore1);
                memberList.setMemberStoreId(baseStore2.getId());
            }else{
                memberList.setMemberStoreId(storeId);
                memberList.setMemberStoreName(storeName);
                memberList.setMemberStoreNum(baseStore.getStoreNum());
            }
            int mm = Integer.parseInt(memberNum.substring(memberNum.length()-5, memberNum.length())) + 1;
            String storeNum = memberNum.substring(0,memberNum.length()-5);
            String num;
            if (mm < 10){
                num = "0000" + mm;
            }else if (mm < 100){
                num = "000" + mm;
            }else if (mm < 1000){
                num = "00" + mm;
            }else if (mm < 10000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }
            memberNum = storeNum + num;
        }
        int i = 0;
        try {
            i = dao.insertBatch(list);
        }catch (Exception e){
            log.error("SsmStoreMemberServiceImpl.insertBatch:", e);
            throw new SmsException(ResponseCode.UNKNOWN_SYSTEM_EXCEPTION);
        }
        if (i != list.size()){
            throw new SmsException(ResponseCode.ENCRYPT_ERROR);
        }else {
            throw new SmsException(ResponseCode.OK);
        }
    }

    @Override
    public int resetClass(MemberRequest memberRequest, String phone) throws SmsException {
        StoreMemberClass storeMemberClass = new StoreMemberClass();
        storeMemberClass.setStoreId(memberRequest.getStoreId());
        storeMemberClass.setState(1);
        List<StoreMemberClass> select = ssmStoreMemberClassService.select(storeMemberClass);
        StoreMemberList storeMemberList = new StoreMemberList();
        storeMemberList.setStoreId(memberRequest.getStoreId());
        List<StoreMemberList> select1 = dao.select(storeMemberList);
        for (StoreMemberList memberList : select1) {
            memberList.setClassId(null);
            memberList.setClassNum(null);
            memberList.setClassName(null);
        }
        select.sort(Comparator.comparing(StoreMemberClass::getClassRow).reversed());
        for (StoreMemberClass memberClass : select) {//所有正在使用的等级
            for (StoreMemberList memberList : select1) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
                if(memberClass.getStatisticsQuarter()==0){ //月度
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    //计算前一个月的日期
                    calendar.add(Calendar.MONTH, -1);
                    Date time = calendar.getTime();
                    //计算收银
                    //计算收银
                    CashList cashList = new CashList();
                    cashList.setMemberId(memberList.getId());
                    cashList.setCashDate(time);
                    cashList.setIsCancel(0);
                    List<CashList> cashLists = ssmCashService.selectListSalem(cashList);
                    BigDecimal syCash = cashLists.stream().map(CashList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal syCard = cashLists.stream().map(CashList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal cash = syCash.add(syCard);
                    //计算疗程
                    CourseList courseList = new CourseList();
                    courseList.setMemberId(memberList.getId());
                    courseList.setDate(time);
                    courseList.setIsCancel(0);
                    List<CourseList> courseLists = ssmCourseService.selectListSalem(courseList);
                    BigDecimal LCCash = courseLists.stream().map(CourseList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal LCCard = courseLists.stream().map(CourseList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal course = LCCash.add(LCCard);

                    //计算促销
                    DocPromotion docPromotion = new DocPromotion();
                    docPromotion.setDocDate(time);
                    docPromotion.setIsCancel(0);
                    docPromotion.setMemberId(memberList.getId());
                    List<DocPromotion> select2 = ssmDocPromotionService.select(docPromotion);
                    BigDecimal LCCash1 = select2.stream().map(DocPromotion::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal LCCard1 = select2.stream().map(DocPromotion::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                    course=course.add(LCCash1).add(LCCard1);

                    //加价转疗程
                    CardChangeInProject cardChangeInProject = new CardChangeInProject();
                    cardChangeInProject.setDocDate(time);
                    cardChangeInProject.setMemberId(memberList.getId());
                    List<CardChangeInProject> select3 = ssmCardChangeInProjectService.select(cardChangeInProject);
                    for (CardChangeInProject changeInProject : select3) {
                        CardChangeList cardChangeList1 = new CardChangeList();
                        cardChangeList1.setStoreId(changeInProject.getStoreId());
                        cardChangeList1.setDocNum(changeInProject.getDocNum());
                        CardChangeList cardChangeList = ssmCardChangeService.selectOne(cardChangeList1);
                        if(3 == cardChangeList.getState()){
                            course=course.add(changeInProject.getChangeInPayMoney());
                        }
                    }



                    //计算充值
                    RechargeList rechargeList = new RechargeList();
                    rechargeList.setMemberId(memberList.getId());
                    rechargeList.setRechargeDate(time);
                    rechargeList.setIsCancel(0);
                    List<RechargeList> rechargeLists = ssmRechargeService.selectListSalem(rechargeList);
                    BigDecimal CZCash = rechargeLists.stream().map(RechargeList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

                    //计算还款
                    RepayTradeList repayTradeList = new RepayTradeList();
                    repayTradeList.setRepayDate(time);
                    repayTradeList.setMemberId(memberList.getId());
                    List<RepayTradeList> select4 = ssmRepayTradeService.select(repayTradeList);
                    for (RepayTradeList tradeList : select4) {
                        RepayList repayList = new RepayList();
                        repayList.setStoreId(tradeList.getStoreId());
                        repayList.setMemberId(tradeList.getMemberId());
                        repayList.setRepayNum(tradeList.getRepayNum());
                        RepayList repayList1 = ssmRepayService.selectOne(repayList);
                        if(repayList1.getIsCancel()==0){
                            RepayAccountList repayAccountList = new RepayAccountList();
                            repayAccountList.setRepayTradeId(tradeList.getId());
                            repayAccountList.setAccountType(0);
                            List<RepayAccountList> select5 = ssmRepayAccountListService.select(repayAccountList);
                            BigDecimal reduce = select5.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                            if(tradeList.getDocType().equals("card_use")){
                                //疗程
                                course=course.add(tradeList.getRepayMoney()).add(reduce);
                            }else if(tradeList.getDocType().equals("card_recharge")){
                                //充值
                                CZCash=CZCash.add(tradeList.getRepayMoney());
                            }else if(tradeList.getDocType().equals("promotion_card_use")){
                                //促销疗程
                                course=course.add(tradeList.getRepayMoney()).add(reduce);
                            }else if(tradeList.getDocType().equals("card_change")){
                                //加价转疗程
                                course=course.add(tradeList.getRepayMoney()).add(reduce);
                            }

                        }
                    }


                    //计算扣除消费退
                    RefundCash refundCash = new RefundCash();
                    refundCash.setMemberId(memberList.getId());
                    refundCash.setRefundDate(time);
                    List<RefundCash> select5 = ssmRefundCashService.select(refundCash);
                    for (RefundCash refundCash1 : select5) {
                        RefundOrderList refundOrderList = new RefundOrderList();
                        refundOrderList.setStoreId(refundCash1.getStoreId());
                        refundOrderList.setRefundNum(refundCash1.getRefundNum());
                        refundOrderList.setType(2);
                        RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                        if(refundOrderList1.getState()==3){
                            cash=cash.subtract(refundCash1.getCashRefundMoney());
                        }
                    }

                    //计算扣除充值退
                    RefundRecharge refundRecharge = new RefundRecharge();
                    refundRecharge.setMemberId(memberList.getId());
                    refundRecharge.setRefundDate(time);
                    List<RefundRecharge> select6 = ssmRefundRechargeService.select(refundRecharge);
                    for (RefundRecharge refundCash1 : select6) {
                        RefundOrderList refundOrderList = new RefundOrderList();
                        refundOrderList.setStoreId(refundCash1.getStoreId());
                        refundOrderList.setRefundNum(refundCash1.getRefundNum());
                        refundOrderList.setType(0);
                        RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                        if(refundOrderList1.getState()==3){
                            CZCash=CZCash.subtract(refundCash1.getRecRefundMoney());
                        }
                    }

                    //计算扣除疗程退
                    RefundCourse refundCourse = new RefundCourse();
                    refundCourse.setMemberId(memberList.getId());
                    refundCourse.setRefundDate(time);
                    List<RefundCourse> select7 = ssmRefundCourseService.select(refundCourse);
                    for (RefundCourse refundCash1 : select7) {
                        RefundOrderList refundOrderList = new RefundOrderList();
                        refundOrderList.setStoreId(refundCash1.getStoreId());
                        refundOrderList.setRefundNum(refundCash1.getRefundNum());
                        refundOrderList.setType(1);
                        RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                        if(refundOrderList1.getState()==3){
                            course=course.subtract(refundCash1.getCourseRefundMoney());
                        }
                    }

                    if(null == memberList.getClassId()){
                        //计算收银是否符合当前等级标准
                        if(memberClass.getCashDecimal().compareTo(cash)!=1){
                            //计算疗程是否符合当前等级标准
                            if(memberClass.getCourseStandard().compareTo(course)!=1){
                                //计算收银是否符合当前等级标准
                                if(memberClass.getRechargeStandard().compareTo(CZCash)!=1){
                                    memberList.setClassId(memberClass.getId());
                                    memberList.setClassNum(memberClass.getClassNum());
                                    memberList.setClassName(memberClass.getClassName());
                                }
                            }
                        }
                    }
                }else if(memberClass.getStatisticsQuarter()==0){ //半年度
                    BigDecimal cash = BigDecimal.valueOf(0);
                    BigDecimal course = BigDecimal.valueOf(0);
                    BigDecimal recharge = BigDecimal.valueOf(0);
                    //系统上线日期
                    Date date = null;
                    try {
                        date = format.parse("2022-04");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    //计算前一个月的日期
                    calendar.add(Calendar.MONTH, -6);
                    Date time = calendar.getTime();

                    Calendar calendar2 = Calendar.getInstance();
                    calendar.setTime(new Date());
                    //计算前一个月的日期
                    Date selectdate = new Date();
                    if(date.before(time)){//满足
                        for (int i = 0; i <6; i++) {

                            calendar.setTime(selectdate);
                            //计算前一个月的日期
                            calendar.add(Calendar.MONTH, -1);
                            selectdate = calendar.getTime();

                            //计算收银
                            CashList cashList = new CashList();
                            cashList.setMemberId(memberList.getId());
                            cashList.setCashDate(selectdate);
                            cashList.setIsCancel(0);
                            List<CashList> cashLists = ssmCashService.selectListSalem(cashList);
                            BigDecimal syCash = cashLists.stream().map(CashList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal syCard = cashLists.stream().map(CashList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            cash.add(syCash).add(syCard);
                            //计算疗程
                            CourseList courseList = new CourseList();
                            courseList.setMemberId(memberList.getId());
                            courseList.setDate(selectdate);
                            courseList.setIsCancel(0);
                            List<CourseList> courseLists = ssmCourseService.selectListSalem(courseList);
                            BigDecimal LCCash = courseLists.stream().map(CourseList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard = courseLists.stream().map(CourseList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);

                            course.add(LCCash).add(LCCard);

                            //计算促销
                            DocPromotion docPromotion = new DocPromotion();
                            docPromotion.setDocDate(time);
                            docPromotion.setIsCancel(0);
                            docPromotion.setMemberId(memberList.getId());
                            List<DocPromotion> select2 = ssmDocPromotionService.select(docPromotion);
                            BigDecimal LCCash1 = select2.stream().map(DocPromotion::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard1 = select2.stream().map(DocPromotion::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            course=course.add(LCCash1).add(LCCard1);

                            //加价转疗程
                            CardChangeInProject cardChangeInProject = new CardChangeInProject();
                            cardChangeInProject.setDocDate(time);
                            cardChangeInProject.setMemberId(memberList.getId());
                            List<CardChangeInProject> select3 = ssmCardChangeInProjectService.select(cardChangeInProject);
                            for (CardChangeInProject changeInProject : select3) {
                                CardChangeList cardChangeList1 = new CardChangeList();
                                cardChangeList1.setStoreId(changeInProject.getStoreId());
                                cardChangeList1.setDocNum(changeInProject.getDocNum());
                                CardChangeList cardChangeList = ssmCardChangeService.selectOne(cardChangeList1);
                                if(3 == cardChangeList.getState()){
                                    course=course.add(changeInProject.getChangeInPayMoney());
                                }
                            }
                            //计算充值
                            RechargeList rechargeList = new RechargeList();
                            rechargeList.setMemberId(memberList.getId());
                            rechargeList.setRechargeDate(selectdate);
                            rechargeList.setIsCancel(0);
                            List<RechargeList> rechargeLists = ssmRechargeService.selectListSalem(rechargeList);
                            BigDecimal CZCash = rechargeLists.stream().map(RechargeList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            recharge.add(CZCash);

                            //计算还款
                            RepayTradeList repayTradeList = new RepayTradeList();
                            repayTradeList.setRepayDate(time);
                            repayTradeList.setMemberId(memberList.getId());
                            List<RepayTradeList> select4 = ssmRepayTradeService.select(repayTradeList);
                            for (RepayTradeList tradeList : select4) {
                                RepayList repayList = new RepayList();
                                repayList.setStoreId(tradeList.getStoreId());
                                repayList.setMemberId(tradeList.getMemberId());
                                repayList.setRepayNum(tradeList.getRepayNum());
                                RepayList repayList1 = ssmRepayService.selectOne(repayList);
                                if(repayList1.getIsCancel()==0){
                                    RepayAccountList repayAccountList = new RepayAccountList();
                                    repayAccountList.setRepayTradeId(tradeList.getId());
                                    repayAccountList.setAccountType(0);
                                    List<RepayAccountList> select5 = ssmRepayAccountListService.select(repayAccountList);
                                    BigDecimal reduce = select5.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                                    if(tradeList.getDocType().equals("card_use")){
                                        //疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_recharge")){
                                        //充值
                                        recharge=recharge.add(tradeList.getRepayMoney());
                                    }else if(tradeList.getDocType().equals("promotion_card_use")){
                                        //促销疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_change")){
                                        //加价转疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }

                                }
                            }


                            //计算扣除消费退
                            RefundCash refundCash = new RefundCash();
                            refundCash.setMemberId(memberList.getId());
                            refundCash.setRefundDate(time);
                            List<RefundCash> select5 = ssmRefundCashService.select(refundCash);
                            for (RefundCash refundCash1 : select5) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(2);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    cash=cash.subtract(refundCash1.getCashRefundMoney());
                                }
                            }

                            //计算扣除充值退
                            RefundRecharge refundRecharge = new RefundRecharge();
                            refundRecharge.setMemberId(memberList.getId());
                            refundRecharge.setRefundDate(time);
                            List<RefundRecharge> select6 = ssmRefundRechargeService.select(refundRecharge);
                            for (RefundRecharge refundCash1 : select6) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(0);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    recharge=recharge.subtract(refundCash1.getRecRefundMoney());
                                }
                            }

                            //计算扣除疗程退
                            RefundCourse refundCourse = new RefundCourse();
                            refundCourse.setMemberId(memberList.getId());
                            refundCourse.setRefundDate(time);
                            List<RefundCourse> select7 = ssmRefundCourseService.select(refundCourse);
                            for (RefundCourse refundCash1 : select7) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(1);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    course=course.subtract(refundCash1.getCourseRefundMoney());
                                }
                            }
                        }
                    }else{//不满足
                        while (date.before(selectdate)){
                            calendar.setTime(selectdate);
                            //计算前一个月的日期
                            calendar.add(Calendar.MONTH, -1);
                            selectdate = calendar.getTime();
                            //计算收银
                            CashList cashList = new CashList();
                            cashList.setMemberId(memberList.getId());
                            cashList.setCashDate(selectdate);
                            cashList.setIsCancel(0);
                            List<CashList> cashLists = ssmCashService.selectListSalem(cashList);
                            BigDecimal syCash = cashLists.stream().map(CashList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal syCard = cashLists.stream().map(CashList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            cash.add(syCash).add(syCard);
                            //计算疗程
                            CourseList courseList = new CourseList();
                            courseList.setMemberId(memberList.getId());
                            courseList.setDate(selectdate);
                            courseList.setIsCancel(0);
                            List<CourseList> courseLists = ssmCourseService.selectListSalem(courseList);
                            BigDecimal LCCash = courseLists.stream().map(CourseList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard = courseLists.stream().map(CourseList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            course.add(LCCash).add(LCCard);
                            //计算充值
                            RechargeList rechargeList = new RechargeList();
                            rechargeList.setMemberId(memberList.getId());
                            rechargeList.setRechargeDate(selectdate);
                            rechargeList.setIsCancel(0);
                            List<RechargeList> rechargeLists = ssmRechargeService.selectListSalem(rechargeList);
                            BigDecimal CZCash = rechargeLists.stream().map(RechargeList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            recharge.add(CZCash);

                            //计算促销
                            DocPromotion docPromotion = new DocPromotion();
                            docPromotion.setDocDate(time);
                            docPromotion.setIsCancel(0);
                            docPromotion.setMemberId(memberList.getId());
                            List<DocPromotion> select2 = ssmDocPromotionService.select(docPromotion);
                            BigDecimal LCCash1 = select2.stream().map(DocPromotion::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard1 = select2.stream().map(DocPromotion::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            course=course.add(LCCash1).add(LCCard1);

                            //加价转疗程
                            CardChangeInProject cardChangeInProject = new CardChangeInProject();
                            cardChangeInProject.setDocDate(time);
                            cardChangeInProject.setMemberId(memberList.getId());
                            List<CardChangeInProject> select3 = ssmCardChangeInProjectService.select(cardChangeInProject);
                            for (CardChangeInProject changeInProject : select3) {
                                CardChangeList cardChangeList1 = new CardChangeList();
                                cardChangeList1.setStoreId(changeInProject.getStoreId());
                                cardChangeList1.setDocNum(changeInProject.getDocNum());
                                CardChangeList cardChangeList = ssmCardChangeService.selectOne(cardChangeList1);
                                if(3 == cardChangeList.getState()){
                                    course=course.add(changeInProject.getChangeInPayMoney());
                                }
                            }

                            //计算还款
                            RepayTradeList repayTradeList = new RepayTradeList();
                            repayTradeList.setRepayDate(time);
                            repayTradeList.setMemberId(memberList.getId());
                            List<RepayTradeList> select4 = ssmRepayTradeService.select(repayTradeList);
                            for (RepayTradeList tradeList : select4) {
                                RepayList repayList = new RepayList();
                                repayList.setStoreId(tradeList.getStoreId());
                                repayList.setMemberId(tradeList.getMemberId());
                                repayList.setRepayNum(tradeList.getRepayNum());
                                RepayList repayList1 = ssmRepayService.selectOne(repayList);
                                if(repayList1.getIsCancel()==0){
                                    RepayAccountList repayAccountList = new RepayAccountList();
                                    repayAccountList.setRepayTradeId(tradeList.getId());
                                    repayAccountList.setAccountType(0);
                                    List<RepayAccountList> select5 = ssmRepayAccountListService.select(repayAccountList);
                                    BigDecimal reduce = select5.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                                    if(tradeList.getDocType().equals("card_use")){
                                        //疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_recharge")){
                                        //充值
                                        recharge=recharge.add(tradeList.getRepayMoney());
                                    }else if(tradeList.getDocType().equals("promotion_card_use")){
                                        //促销疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_change")){
                                        //加价转疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }

                                }
                            }


                            //计算扣除消费退
                            RefundCash refundCash = new RefundCash();
                            refundCash.setMemberId(memberList.getId());
                            refundCash.setRefundDate(time);
                            List<RefundCash> select5 = ssmRefundCashService.select(refundCash);
                            for (RefundCash refundCash1 : select5) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(2);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    cash=cash.subtract(refundCash1.getCashRefundMoney());
                                }
                            }

                            //计算扣除充值退
                            RefundRecharge refundRecharge = new RefundRecharge();
                            refundRecharge.setMemberId(memberList.getId());
                            refundRecharge.setRefundDate(time);
                            List<RefundRecharge> select6 = ssmRefundRechargeService.select(refundRecharge);
                            for (RefundRecharge refundCash1 : select6) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(0);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    recharge=recharge.subtract(refundCash1.getRecRefundMoney());
                                }
                            }

                            //计算扣除疗程退
                            RefundCourse refundCourse = new RefundCourse();
                            refundCourse.setMemberId(memberList.getId());
                            refundCourse.setRefundDate(time);
                            List<RefundCourse> select7 = ssmRefundCourseService.select(refundCourse);
                            for (RefundCourse refundCash1 : select7) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(1);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    course=course.subtract(refundCash1.getCourseRefundMoney());
                                }
                            }

                        }
                    }
                    if(null == memberList.getClassId()){
                        //计算收银是否符合当前等级标准
                        if(memberClass.getCashDecimal().compareTo(cash)!=1){
                            //计算疗程是否符合当前等级标准
                            if(memberClass.getCourseStandard().compareTo(course)!=1){
                                //计算收银是否符合当前等级标准
                                if(memberClass.getRechargeStandard().compareTo(recharge)!=1){
                                    memberList.setClassId(memberClass.getId());
                                    memberList.setClassNum(memberClass.getClassNum());
                                    memberList.setClassName(memberClass.getClassName());
                                }
                            }
                        }
                    }
                }else if(memberClass.getStatisticsQuarter()==2){ //年度
                    BigDecimal cash = BigDecimal.valueOf(0);
                    BigDecimal course = BigDecimal.valueOf(0);
                    BigDecimal recharge = BigDecimal.valueOf(0);
                    //系统上线日期
                    Date date = null;
                    try {
                        date = format.parse("2022-04");
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    //计算前一个月的日期
                    calendar.add(Calendar.YEAR, -1);
                    Date time = calendar.getTime();

                    Calendar calendar2 = Calendar.getInstance();
                    calendar.setTime(new Date());
                    //计算前一个月的日期
                    Date selectdate = new Date();
                    if(date.before(time)){//满足
                        for (int i = 0; i <12; i++) {

                            calendar.setTime(selectdate);
                            //计算前一个月的日期
                            calendar.add(Calendar.MONTH, -1);
                            selectdate = calendar.getTime();
                            //计算收银
                            CashList cashList = new CashList();
                            cashList.setMemberId(memberList.getId());
                            cashList.setCashDate(selectdate);
                            cashList.setIsCancel(0);
                            List<CashList> cashLists = ssmCashService.selectListSalem(cashList);
                            BigDecimal syCash = cashLists.stream().map(CashList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal syCard = cashLists.stream().map(CashList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            cash.add(syCash).add(syCard);
                            //计算疗程
                            CourseList courseList = new CourseList();
                            courseList.setMemberId(memberList.getId());
                            courseList.setDate(selectdate);
                            courseList.setIsCancel(0);
                            List<CourseList> courseLists = ssmCourseService.selectListSalem(courseList);
                            BigDecimal LCCash = courseLists.stream().map(CourseList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard = courseLists.stream().map(CourseList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            course.add(LCCash).add(LCCard);
                            //计算充值
                            RechargeList rechargeList = new RechargeList();
                            rechargeList.setMemberId(memberList.getId());
                            rechargeList.setRechargeDate(selectdate);
                            rechargeList.setIsCancel(0);
                            List<RechargeList> rechargeLists = ssmRechargeService.selectListSalem(rechargeList);
                            BigDecimal CZCash = rechargeLists.stream().map(RechargeList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            recharge.add(CZCash);

                            //计算促销
                            DocPromotion docPromotion = new DocPromotion();
                            docPromotion.setDocDate(time);
                            docPromotion.setIsCancel(0);
                            docPromotion.setMemberId(memberList.getId());
                            List<DocPromotion> select2 = ssmDocPromotionService.select(docPromotion);
                            BigDecimal LCCash1 = select2.stream().map(DocPromotion::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard1 = select2.stream().map(DocPromotion::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            course=course.add(LCCash1).add(LCCard1);

                            //加价转疗程
                            CardChangeInProject cardChangeInProject = new CardChangeInProject();
                            cardChangeInProject.setDocDate(time);
                            cardChangeInProject.setMemberId(memberList.getId());
                            List<CardChangeInProject> select3 = ssmCardChangeInProjectService.select(cardChangeInProject);
                            for (CardChangeInProject changeInProject : select3) {
                                CardChangeList cardChangeList1 = new CardChangeList();
                                cardChangeList1.setStoreId(changeInProject.getStoreId());
                                cardChangeList1.setDocNum(changeInProject.getDocNum());
                                CardChangeList cardChangeList = ssmCardChangeService.selectOne(cardChangeList1);
                                if(3 == cardChangeList.getState()){
                                    course=course.add(changeInProject.getChangeInPayMoney());
                                }
                            }

                            //计算还款
                            RepayTradeList repayTradeList = new RepayTradeList();
                            repayTradeList.setRepayDate(time);
                            repayTradeList.setMemberId(memberList.getId());
                            List<RepayTradeList> select4 = ssmRepayTradeService.select(repayTradeList);
                            for (RepayTradeList tradeList : select4) {
                                RepayList repayList = new RepayList();
                                repayList.setStoreId(tradeList.getStoreId());
                                repayList.setMemberId(tradeList.getMemberId());
                                repayList.setRepayNum(tradeList.getRepayNum());
                                RepayList repayList1 = ssmRepayService.selectOne(repayList);
                                if(repayList1.getIsCancel()==0){
                                    RepayAccountList repayAccountList = new RepayAccountList();
                                    repayAccountList.setRepayTradeId(tradeList.getId());
                                    repayAccountList.setAccountType(0);
                                    List<RepayAccountList> select5 = ssmRepayAccountListService.select(repayAccountList);
                                    BigDecimal reduce = select5.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                                    if(tradeList.getDocType().equals("card_use")){
                                        //疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_recharge")){
                                        //充值
                                        recharge=recharge.add(tradeList.getRepayMoney());
                                    }else if(tradeList.getDocType().equals("promotion_card_use")){
                                        //促销疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_change")){
                                        //加价转疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }

                                }
                            }


                            //计算扣除消费退
                            RefundCash refundCash = new RefundCash();
                            refundCash.setMemberId(memberList.getId());
                            refundCash.setRefundDate(time);
                            List<RefundCash> select5 = ssmRefundCashService.select(refundCash);
                            for (RefundCash refundCash1 : select5) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(2);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    cash=cash.subtract(refundCash1.getCashRefundMoney());
                                }
                            }

                            //计算扣除充值退
                            RefundRecharge refundRecharge = new RefundRecharge();
                            refundRecharge.setMemberId(memberList.getId());
                            refundRecharge.setRefundDate(time);
                            List<RefundRecharge> select6 = ssmRefundRechargeService.select(refundRecharge);
                            for (RefundRecharge refundCash1 : select6) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(0);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    recharge=recharge.subtract(refundCash1.getRecRefundMoney());
                                }
                            }

                            //计算扣除疗程退
                            RefundCourse refundCourse = new RefundCourse();
                            refundCourse.setMemberId(memberList.getId());
                            refundCourse.setRefundDate(time);
                            List<RefundCourse> select7 = ssmRefundCourseService.select(refundCourse);
                            for (RefundCourse refundCash1 : select7) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(1);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    course=course.subtract(refundCash1.getCourseRefundMoney());
                                }
                            }
                        }
                    }else{//不满足
                        while (date.before(selectdate)){
                            calendar.setTime(selectdate);
                            //计算前一个月的日期
                            calendar.add(Calendar.MONTH, -1);
                            selectdate = calendar.getTime();
                            //计算收银
                            CashList cashList = new CashList();
                            cashList.setMemberId(memberList.getId());
                            cashList.setCashDate(selectdate);
                            cashList.setIsCancel(0);
                            List<CashList> cashLists = ssmCashService.selectListSalem(cashList);
                            BigDecimal syCash = cashLists.stream().map(CashList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal syCard = cashLists.stream().map(CashList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            cash.add(syCash).add(syCard);
                            //计算疗程
                            CourseList courseList = new CourseList();
                            courseList.setMemberId(memberList.getId());
                            courseList.setDate(selectdate);
                            courseList.setIsCancel(0);
                            List<CourseList> courseLists = ssmCourseService.selectListSalem(courseList);
                            BigDecimal LCCash = courseLists.stream().map(CourseList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard = courseLists.stream().map(CourseList::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            course.add(LCCash).add(LCCard);
                            //计算充值
                            RechargeList rechargeList = new RechargeList();
                            rechargeList.setMemberId(memberList.getId());
                            rechargeList.setRechargeDate(selectdate);
                            rechargeList.setIsCancel(0);
                            List<RechargeList> rechargeLists = ssmRechargeService.selectListSalem(rechargeList);
                            BigDecimal CZCash = rechargeLists.stream().map(RechargeList::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            recharge.add(CZCash);

                            //计算促销
                            DocPromotion docPromotion = new DocPromotion();
                            docPromotion.setDocDate(time);
                            docPromotion.setIsCancel(0);
                            docPromotion.setMemberId(memberList.getId());
                            List<DocPromotion> select2 = ssmDocPromotionService.select(docPromotion);
                            BigDecimal LCCash1 = select2.stream().map(DocPromotion::getCollectionCashAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            BigDecimal LCCard1 = select2.stream().map(DocPromotion::getCollectionRechargeAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
                            course=course.add(LCCash1).add(LCCard1);

                            //加价转疗程
                            CardChangeInProject cardChangeInProject = new CardChangeInProject();
                            cardChangeInProject.setDocDate(time);
                            cardChangeInProject.setMemberId(memberList.getId());
                            List<CardChangeInProject> select3 = ssmCardChangeInProjectService.select(cardChangeInProject);
                            for (CardChangeInProject changeInProject : select3) {
                                CardChangeList cardChangeList1 = new CardChangeList();
                                cardChangeList1.setStoreId(changeInProject.getStoreId());
                                cardChangeList1.setDocNum(changeInProject.getDocNum());
                                CardChangeList cardChangeList = ssmCardChangeService.selectOne(cardChangeList1);
                                if(3 == cardChangeList.getState()){
                                    course=course.add(changeInProject.getChangeInPayMoney());
                                }
                            }

                            //计算还款
                            RepayTradeList repayTradeList = new RepayTradeList();
                            repayTradeList.setRepayDate(time);
                            repayTradeList.setMemberId(memberList.getId());
                            List<RepayTradeList> select4 = ssmRepayTradeService.select(repayTradeList);
                            for (RepayTradeList tradeList : select4) {
                                RepayList repayList = new RepayList();
                                repayList.setStoreId(tradeList.getStoreId());
                                repayList.setMemberId(tradeList.getMemberId());
                                repayList.setRepayNum(tradeList.getRepayNum());
                                RepayList repayList1 = ssmRepayService.selectOne(repayList);
                                if(repayList1.getIsCancel()==0){
                                    RepayAccountList repayAccountList = new RepayAccountList();
                                    repayAccountList.setRepayTradeId(tradeList.getId());
                                    repayAccountList.setAccountType(0);
                                    List<RepayAccountList> select5 = ssmRepayAccountListService.select(repayAccountList);
                                    BigDecimal reduce = select5.stream().map(RepayAccountList::getPayMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
                                    if(tradeList.getDocType().equals("card_use")){
                                        //疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_recharge")){
                                        //充值
                                        recharge=recharge.add(tradeList.getRepayMoney());
                                    }else if(tradeList.getDocType().equals("promotion_card_use")){
                                        //促销疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }else if(tradeList.getDocType().equals("card_change")){
                                        //加价转疗程
                                        course=course.add(tradeList.getRepayMoney()).add(reduce);
                                    }

                                }
                            }


                            //计算扣除消费退
                            RefundCash refundCash = new RefundCash();
                            refundCash.setMemberId(memberList.getId());
                            refundCash.setRefundDate(time);
                            List<RefundCash> select5 = ssmRefundCashService.select(refundCash);
                            for (RefundCash refundCash1 : select5) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(2);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    cash=cash.subtract(refundCash1.getCashRefundMoney());
                                }
                            }

                            //计算扣除充值退
                            RefundRecharge refundRecharge = new RefundRecharge();
                            refundRecharge.setMemberId(memberList.getId());
                            refundRecharge.setRefundDate(time);
                            List<RefundRecharge> select6 = ssmRefundRechargeService.select(refundRecharge);
                            for (RefundRecharge refundCash1 : select6) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(0);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    recharge=recharge.subtract(refundCash1.getRecRefundMoney());
                                }
                            }

                            //计算扣除疗程退
                            RefundCourse refundCourse = new RefundCourse();
                            refundCourse.setMemberId(memberList.getId());
                            refundCourse.setRefundDate(time);
                            List<RefundCourse> select7 = ssmRefundCourseService.select(refundCourse);
                            for (RefundCourse refundCash1 : select7) {
                                RefundOrderList refundOrderList = new RefundOrderList();
                                refundOrderList.setStoreId(refundCash1.getStoreId());
                                refundOrderList.setRefundNum(refundCash1.getRefundNum());
                                refundOrderList.setType(1);
                                RefundOrderList refundOrderList1 = ssmRefundOrderService.selectOne(refundOrderList);
                                if(refundOrderList1.getState()==3){
                                    course=course.subtract(refundCash1.getCourseRefundMoney());
                                }
                            }
                        }
                    }
                    if(null == memberList.getClassId()){
                        //计算收银是否符合当前等级标准
                        if(memberClass.getCashDecimal().compareTo(cash)!=1){
                            //计算疗程是否符合当前等级标准
                            if(memberClass.getCourseStandard().compareTo(course)!=1){
                                //计算收银是否符合当前等级标准
                                if(memberClass.getRechargeStandard().compareTo(recharge)!=1){
                                    memberList.setClassId(memberClass.getId());
                                    memberList.setClassNum(memberClass.getClassNum());
                                    memberList.setClassName(memberClass.getClassName());
                                }
                            }
                        }
                    }
                }
            }
        }
        for (StoreMemberList memberList : select1) {
            int update = dao.updateByPrimaryKeySelective(memberList);
            if(update == 0){
                throw new SmsException(ResponseCode.MSG,"统计更新会员等级失败");
            }
        }
        return 1;
    }

    @Override
    public int emptyClass(MemberRequest memberRequest, String phone) throws SmsException {
        StoreMemberList storeMemberList = new StoreMemberList();
        storeMemberList.setStoreId(memberRequest.getStoreId());
        List<StoreMemberList> select1 = dao.select(storeMemberList);
        for (StoreMemberList memberList : select1) {
            memberList.setClassId(null);
            memberList.setClassNum(null);
            memberList.setClassName(null);
            int update = dao.updateByPrimaryKey(memberList);
        }
        return 1;
    }


    public List<StoreMemberList> check(List<StoreMemberList> lists){
        List<StoreMemberList> list = new ArrayList<>();
        Map<String, List<StoreMemberList>> map = lists.stream().collect(Collectors.groupingBy(storeMemberList -> storeMemberList.getMobilePhone() + "-" + storeMemberList.getState()));
        for (String key : map.keySet()) {
            //数据重复
            if (map.get(key).size() > 1){
                list.addAll(map.get(key));
            }
        }
        return list;
    }

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


    public static String getPasscodeKey(String phone) {
        String key = "";
        if (StringUtils.isNotBlank(phone)){
            key = Constant.staffPasscode + phone;
        }
        return key;
    }

    //判断会员手机号码 实体卡是否存在
    private void getStoreMember(String mobilePhone,String card,Long storeId) throws SmsException {
        mobilePhone = AESUtils.encrypt(mobilePhone);
        Example example = new Example(StoreMemberList.class);
        Example.Criteria criteria = example.createCriteria();
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(0);
        if (mobilePhone != null) {
            criteria.andIn("state",list);
            criteria.andEqualTo("mobilePhone",mobilePhone);
            //criteria.andEqualTo("storeId",storeId);
            List<StoreMemberList> lists = selectByExample(example);
            if (lists != null && lists.size() > 0){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"会员手机号码");
            }
        }
        if (card != null){
            criteria.andIn("state",list);
            criteria.andEqualTo("card",card);
            //criteria.andEqualTo("storeId",storeId);
            List<StoreMemberList> lists = selectByExample(example);
            if (lists != null && lists.size() > 0){
                throw new SmsException(ResponseCode.DATA_ALREADY_EXISTS_S,"会员卡号");
            }
        }

    }

    /*
     * 生成会员编码 00001 00002
     * */
    public String getMemberNum(Long storeId){
        //查询门店 获取门店编码
        //StoreRequest storeRequest = new StoreRequest();
        //storeRequest.setId(storeId);
        //BaseStores pagesorganizationone = ssmBaseStoreService.pagesorganizationone(storeRequest);
        BaseStore baseStore = new BaseStore();
        baseStore.setId(storeId);
        BaseStore store = ssmBaseStoreService.selectOne(baseStore);
        //查询数据库门店编码最新的一个
        Example example = new Example(StoreMemberList.class);
        Example.Criteria criteria = example.createCriteria();
        //按会员编码降序排列
        //example.setOrderByClause("member_num desc");
        criteria.andEqualTo("storeId",store.getId());
        List<StoreMemberList> memberLists1 = dao.selectByExample(example);
        List<StoreMemberList> memberLists = memberLists1.stream().filter(item -> !item.getMemberNum().startsWith("S")).collect(Collectors.toList());
        String storeNum = store.getStoreNum();
        String num;
        int mm = 0;
        if (memberLists != null && memberLists.size() > 0) {
            StoreMemberList storeMemberList = memberLists.get(memberLists.size()-1);
            String memberNum = storeMemberList.getMemberNum();
            mm = Integer.parseInt(memberNum.substring(memberNum.length()-6, memberNum.length())) + 1;
            if (mm < 10){
                num = "00000" + mm;
            }else if (mm < 100){
                num = "0000" + mm;
            }else if (mm < 1000){
                num = "000" + mm;
            }else if (mm < 10000){
                num = "00" + mm;
            } else if (mm < 100000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }
        }else {
            num = "000001" ;
        }
        num = storeNum + num;
        return num;
    }
    public String getMemberNumNews(Integer number,Long storeId){
        //查询门店 获取门店编码
        //StoreRequest storeRequest = new StoreRequest();
        //storeRequest.setId(storeId);
        //BaseStores pagesorganizationone = ssmBaseStoreService.pagesorganizationone(storeRequest);
        BaseStore baseStore = new BaseStore();
        baseStore.setId(storeId);
        BaseStore store = ssmBaseStoreService.selectOne(baseStore);
        //查询数据库门店编码最新的一个
        Example example = new Example(StoreMemberList.class);
        Example.Criteria criteria = example.createCriteria();
        //按会员编码降序排列
        //example.setOrderByClause("member_num desc");
        criteria.andEqualTo("memberStoreId",store.getId());
        List<StoreMemberList> memberLists1 = dao.selectByExample(example);
        List<StoreMemberList> memberLists = memberLists1.stream().filter(item -> !item.getMemberNum().startsWith("S")).collect(Collectors.toList());
        String storeNum = store.getStoreNum();
        String num;
        int mm = 0;
        if (memberLists != null && memberLists.size() > 0) {
            StoreMemberList storeMemberList = memberLists.get(memberLists.size()-1);
            String memberNum = storeMemberList.getMemberNum();
            mm = Integer.parseInt(memberNum.substring(memberNum.length()-6, memberNum.length())) + 1;
//            mm = mm+number;
            if (mm < 10){
                num = "00000" + mm;
            }else if (mm < 100){
                num = "0000" + mm;
            }else if (mm < 1000){
                num = "000" + mm;
            }else if (mm < 10000){
                num = "00" + mm;
            } else if (mm < 100000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }
        }else {
            int i = Integer.parseInt("000001");
            i = i+number;
            num = ""+i;
            String str = "";
            if(num.length()<6){
                for (int x = num.length();x<6;x++){
                    str = str + "0";
                }
                num = str + num;
            }
        }
        num = storeNum + num;
        return num;
    }

    /*
     * 生成会员编码 00001 00002
     * */
    public String getMemberNums(Long storeId,String storeNums){
        //查询门店 获取门店编码

        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        BaseStores pagesorganizationone = ssmBaseStoreService.pagesorganizationone(storeRequest);
        BaseStore baseStore = new BaseStore();
        baseStore.setId(pagesorganizationone.getId());
        BaseStore store = ssmBaseStoreService.selectOne(baseStore);
        //查询数据库门店编码最新的一个
        Example example = new Example(StoreMemberList.class);
        Example.Criteria criteria = example.createCriteria();
        //按会员编码降序排列
        example.setOrderByClause("member_num desc");
        criteria.andEqualTo("storeId",store.getId());
        List<StoreMemberList> memberLists = dao.selectByExample(example);
        String storeNum = store.getStoreNum();
        String num;
        int mm = 0;
        if (memberLists != null && memberLists.size() > 0) {
            StoreMemberList storeMemberList = memberLists.get(0);
            String memberNum = storeMemberList.getMemberNum();
            mm = Integer.parseInt(memberNum.substring(memberNum.length()-5, memberNum.length())) + 1;
            if (mm < 10){
                num = "0000" + mm;
            }else if (mm < 100){
                num = "000" + mm;
            }else if (mm < 1000){
                num = "00" + mm;
            }else if (mm < 10000){
                num = "0" + mm;
            }else {
                num = String.valueOf(mm);
            }

        }else {
            num = "00001" ;
        }
        num = storeNum + num;
        return num;
    }

    /*
     * 查询门店参数
     * */
    public StoreParament getStorePara(Long storeId,String key){
        StoreParament storeParament = new StoreParament();
        storeParament.setStoreId(storeId);
        storeParament.setParamentName(key);
        storeParament = ssmStoreParaService.selectOne(storeParament);
        return storeParament;
    }

    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }
    public String getStaffKey(String phone){
        return staffKey + phone;
    }

    @Override
    public PageInfo<StoreMemberListUpdate> memberUpdatePage(MemberRequest memberRequest) {

        PageInfo pageInfo = dao.memberUpdatePage(memberRequest);
        return pageInfo;
    }
}
