package com.ssm.manage.service.impl;

import com.alibaba.excel.exception.ExcelAnalysisException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.*;
import com.ssm.manage.dao.SsmBaseGrouponCardDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.extendEntity.AchiCommEntity;
import com.ssm.manage.mapper.BaseGrouponCardMapper;
import com.ssm.manage.query.*;
import com.ssm.manage.response.*;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.AesCbcUtil;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

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

@Service
@Slf4j
public class SsmBaseGrouponCardServiceImpl  extends BaseServiceImpl<BaseGrouponCard> implements SsmBaseGrouponCardService {

    @Autowired
    private SsmBaseGrouponCardDao dao;

    @Autowired
    private ChuangLanBeanSmsUtil chuangLanBeanSmsUtil;

    @Autowired
    private SsmPayService ssmPayService;

    @Autowired
    private SsmUploadFilesService ssmUploadFilesService;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;

    @Autowired
    private SsmSalesmanService ssmSalesmanService;

    @Autowired
    private SsmBaseGrouponListService ssmBaseGrouponListService;

    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;
    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmBaseStaffService ssmBaseStaffService;

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

    @Autowired
    private RedisClient<StaffResponse> templateRedisClient;

    @Override
    public PageInfo<BaseGrouponCardResponse> selectPage(BaseGrouponCardRequest baseGrouponCardRequest) throws SmsException {
        List<BaseGrouponCardResponse> baseGrouponCardResponses = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(baseGrouponCardRequest.getStoreId());
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());

//        Example example = new Example(BaseGrouponCard.class);
//        Example.Criteria criteria = example.createCriteria();
//
//        criteria.andIn("storeId",collect);
//        if(null != baseGrouponCardRequest.getDocNum()){
//            criteria.andEqualTo("docNum",baseGrouponCardRequest.getDocNum());
//        }
//        if(null != baseGrouponCardRequest.getDocNum()){
//            criteria.andEqualTo("docNum",baseGrouponCardRequest.getDocNum());
//        }
//        if(baseGrouponCardRequest.getStartTime()!=null && baseGrouponCardRequest.getEndTime()!=null){
//            criteria.andBetween("auditDate",baseGrouponCardRequest.getStartTime(),baseGrouponCardRequest.getEndTime());
//        }
//        if(baseGrouponCardRequest.getState()!=null){
//            criteria.andEqualTo("state",baseGrouponCardRequest.getState());
//        }

        baseGrouponCardRequest.setSort("state");
//        PageHelper.startPage(baseGrouponCardRequest.getPageNum(),baseGrouponCardRequest.getPageSize(),baseGrouponCardRequest.getOrderAndSort());
//        List<BaseGrouponCard> list = dao.selectByExample(example);
        Example examples = new Example(BaseGrouponCard.class);
        Example.Criteria criterias = examples.createCriteria();

        criterias.andIn("storeId",collect);
        if(null != baseGrouponCardRequest.getDocNum()){
            criterias.andEqualTo("docNum",baseGrouponCardRequest.getDocNum());
        }
        if(baseGrouponCardRequest.getStartTime()!=null && baseGrouponCardRequest.getEndTime()!=null){
            criterias.andBetween("auditDate",baseGrouponCardRequest.getStartTime(),baseGrouponCardRequest.getEndTime());
        }
        if(baseGrouponCardRequest.getState()!=null){
            criterias.andEqualTo("state",baseGrouponCardRequest.getState());
            criterias.andEqualTo("storeId",baseGrouponCardRequest.getStoreId());
        }
        List<BaseGrouponCard> list = dao.selectByExample(examples);
        PageHelper.startPage(baseGrouponCardRequest.getPageNum(),baseGrouponCardRequest.getPageSize(),"doc_date desc");
        List<BaseGrouponCard> lists = dao.selectByExample(examples);
        for (int i = lists.size()-1; i >= 0; i--) {
            BaseGrouponCard baseGrouponCard = lists.get(i);
            PayList payList = new PayList();
            payList.setDocId(baseGrouponCard.getDocNum());
            List<PayList> select2 = ssmPayService.select(payList);

            BaseGrouponCardResponse baseGrouponCardResponse = new BaseGrouponCardResponse();
            BeanUtils.copyProperties(baseGrouponCard,baseGrouponCardResponse);
            BaseGrouponList baseGrouponList = new BaseGrouponList();
            baseGrouponCardResponse.setPayListList(select2);
            baseGrouponList.setGrouponCardId(baseGrouponCardResponse.getId());
            List<BaseGrouponList> select = ssmBaseGrouponListService.select(baseGrouponList);
            for (BaseGrouponList grouponList : select) {
                try {
                    String decrypt = AESUtils.decrypt(grouponList.getMobilePhone());
                    grouponList.setMobilePhone(decrypt.trim());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
            List<AchiCommEntity> achiCommList = this.getAchiCommList(baseGrouponCard);

            Salesman salesman = new Salesman();
            salesman.setOrderType(9);
            salesman.setOrderId(baseGrouponCard.getId().toString());
            List<Salesman> select1 = ssmSalesmanService.select(salesman);

            baseGrouponCardResponse.setBaseGrouponListList(select);
            baseGrouponCardResponse.setStaffLists(achiCommList);
            baseGrouponCardResponse.setSalesmens(select1);


            //设置文件
            UploadFilesRequest uploadFilesRequest = new UploadFilesRequest();
            uploadFilesRequest.setDocId(baseGrouponCard.getId());
            uploadFilesRequest.setDocNum(baseGrouponCard.getDocNum());
            uploadFilesRequest.setDocType(Constant.account_type_recharge_groupon);
            List<UploadFiles> filesList = ssmUploadFilesService.selectList(uploadFilesRequest);
            baseGrouponCardResponse.setUploadFiles(filesList);

            baseGrouponCardResponses.add(baseGrouponCardResponse);
        }
//        for (BaseGrouponCard baseGrouponCard : lists) {
//
//        }
        PageInfo<BaseGrouponCardResponse> pageInfo = new PageInfo<>(baseGrouponCardResponses);
        pageInfo.setTotal(list.size());
        return pageInfo;
    }

    @Override
    public int add(BaseGrouponCardRequest baseGrouponCardRequest,String key) throws SmsException {
        BaseGrouponCard baseGrouponCard = new BaseGrouponCard();
        BeanUtils.copyProperties(baseGrouponCardRequest,baseGrouponCard);
        baseGrouponCard.setState(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        String num = this.getNum(format, baseGrouponCardRequest.getStoreId());
        baseGrouponCard.setDocNum(num);
        baseGrouponCard.setDocDate(new Date());
        List<PayList> payListList1  = JSON.parseArray(baseGrouponCardRequest.getPayListList(), PayList.class);
        List<PayList> payListList = new ArrayList<>();
        if(payListList1!=null) {
            payListList.add(payListList1.get(0));
            for (PayList payList : payListList) {
                payList.setDocId(num);
                payList.setIsCancel(1);
                payList.setType("tuangou");
                long l = new SnowflakeUtil(new Random().nextInt(1023)).nextId();
                payList.setStoreId(baseGrouponCard.getStoreId());
                payList.setId(l);
                payList.setPayDate(new Date());
            }
        }
//        PayList payList = new PayList();
//        payList.setDocId(num);
//        ssmPayService.delete(payList);
        ssmPayService.addPayList(payListList);
        if (templateRedisClient.hasKey(getKey(key))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(key));
            baseGrouponCard.setInputBy(staffResponse.getStaffName());
            baseGrouponCard.setInputDate(new Date());
        }
        String text = baseGrouponCardRequest.getStaffLists();
        System.out.println(text);
        List<StaffRequest> staffLists = JSON.parseArray(text, StaffRequest.class);
        //List<StaffRequest> staffLists = baseGrouponCardRequest.getStaffLists();
        this.setStaffValue(staffLists,baseGrouponCard);
        StaffRequest staffRequest = staffLists.get(0);
        if(staffRequest.getStoreId()==null)
            throw new SmsException(ResponseCode.MSG,"请选一个员工");
        baseGrouponCard.setStoreId(staffRequest.getStoreId());
        baseGrouponCard.setStoreName(staffRequest.getStoreName());
        baseGrouponCard.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        RechargeType rechargeType = new RechargeType();
        rechargeType.setId(baseGrouponCardRequest.getRechargeTypeId());
        RechargeType rechargeType1 = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeType.getId());
        baseGrouponCard.setTypeRatio(rechargeType1.getTypeRatio());
        int insert = dao.insert(baseGrouponCard);
        if(insert>0){
            if(!"".equals(baseGrouponCardRequest.getSalesmens())){
                //添加高管的当前单据门店信息
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(baseGrouponCard.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);

                List<Salesman> salesmens = JSON.parseArray(baseGrouponCardRequest.getSalesmens(), Salesman.class);
//                List<Salesman> salesmens = baseGrouponCardRequest.getSalesmens();
                for (Salesman salesmen : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
                    salesmen.setId(salesmen.getId()+i1);
                    salesmen.setOrderId(String.valueOf(baseGrouponCard.getId()));
                    salesmen.setOrderNum(baseGrouponCard.getDocNum());
                    salesmen.setOrderType(9);
                    salesmen.setOrderDate(new Date());
                    salesmen.setState(1);
                    salesmen.setMoney(baseGrouponCard.getRechargeMoney().multiply(BigDecimal.valueOf(baseGrouponCard.getQuantity())));
                    salesmen.setProjectId(baseGrouponCard.getRechargeTypeId());
                    salesmen.setProjectNum(baseGrouponCard.getRechargeTypeNum());
                    salesmen.setStoreNum(baseStore1.getStoreNum());
                    salesmen.setStoreName(baseStore1.getStoreName());
                    salesmen.setStoreIdOrder(baseStore1.getId());
                    salesmen.setOperatorBy(baseGrouponCard.getInputBy());
                }
                ssmSalesmanService.addBatch(salesmens);
            }

            //将文件上传信息保存到数据库
            List<UploadFiles> list = baseGrouponCardRequest.getUploadFiles();
            for (UploadFiles uploadFiles : list) {
                uploadFiles.setDocId(baseGrouponCard.getId());
                uploadFiles.setDocNum(baseGrouponCard.getDocNum());
                uploadFiles.setDocType(Constant.account_type_recharge_groupon);
                ssmUploadFilesService.add(uploadFiles);
            }
        }
        return insert;
    }

    @Override
    public int update(BaseGrouponCardRequest baseGrouponCardRequest,String key) throws SmsException, IOException {
        List<BaseGrouponList> baseGrouponLists1 = JSONArray.parseArray(baseGrouponCardRequest.getBaseGrouponLists(), BaseGrouponList.class);
        if(null != baseGrouponLists1){
            if(baseGrouponCardRequest.getQuantity()!=baseGrouponLists1.size()){
                throw new SmsException(ResponseCode.MSG,"团购份数与团购名单人数不相等");
            }
            for (BaseGrouponList baseGrouponList : baseGrouponLists1) {
                if(null == baseGrouponList.getMobilePhone()){
                    throw new SmsException(ResponseCode.MSG,"有列手机号码存在空");
                }
                if(null == baseGrouponList.getMemberName()){
                    throw new SmsException(ResponseCode.MSG,"有列团购人名称存在空");
                }
            }
        }

        BaseGrouponCard baseGrouponCard = new BaseGrouponCard();
        BeanUtils.copyProperties(baseGrouponCardRequest,baseGrouponCard);
        if (templateRedisClient.hasKey(getKey(key))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(key));
            baseGrouponCard.setUpdateBy(staffResponse.getStaffName());
            baseGrouponCard.setUpdateDate(new Date());
        }
        List<StaffRequest> staffLists1 = JSONArray.parseArray(baseGrouponCardRequest.getStaffLists(),StaffRequest.class);
        List<StaffRequest> staffLists = staffLists1.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
        this.setStaffValue(staffLists,baseGrouponCard);

        int update = dao.updateByPrimaryKeySelective(baseGrouponCard);


        List<PayList> payListList =  JSON.parseArray(baseGrouponCardRequest.getPayListList(), PayList.class);
        BaseGrouponCard grouponCard = dao.selectByPrimaryKey(baseGrouponCard.getId());
        if(payListList!=null && payListList.size()>0){
            for (PayList payList : payListList) {
                payList.setPayDate(grouponCard.getAuditDate()==null?new Date():grouponCard.getAuditDate());
                payList.setDocId(grouponCard.getDocNum());
                payList.setIsCancel(1);
                payList.setType("tuangou");
                payList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                payList.setStoreId(baseGrouponCard.getStoreId());
            }
        }
        PayList payList = new PayList();
        payList.setDocId(grouponCard.getDocNum());
        ssmPayService.delete(payList);


        ssmPayService.addPayList(payListList);
        if(update>0){
            Salesman salesman = new Salesman();
            salesman.setOrderId(baseGrouponCard.getId().toString());
            salesman.setOrderType(9);
            List<Salesman> salesmen1 = ssmSalesmanService.selectList(salesman);
            for (Salesman salesman1 : salesmen1) {
                ssmSalesmanService.deleteByPrimaryKey(salesman1.getId());
            }
            if(!"".equals(baseGrouponCardRequest.getSalesmens())){
                //添加高管的当前单据门店信息
                StoreRequest storeRequest = new StoreRequest();
                storeRequest.setId(baseGrouponCard.getStoreId());
                BaseStore baseStore1 = ssmBaseStoreService.selectOne(storeRequest);

                List<Salesman> salesmens = JSON.parseArray(baseGrouponCardRequest.getSalesmens(), Salesman.class);
//                List<Salesman> salesmens = baseGrouponCardRequest.getSalesmens();
                for (Salesman salesmen : salesmens) {
                    Random r = new Random(3);
                    int i1 = r.nextInt();
                    salesmen.setId(salesmen.getId()+i1);
                    salesmen.setOrderId(String.valueOf(baseGrouponCard.getId()));
                    salesmen.setOrderNum(baseGrouponCard.getDocNum());
                    salesmen.setOrderType(9);
                    salesmen.setOrderDate(new Date());
                    salesmen.setState(1);
                    salesmen.setMoney(baseGrouponCard.getRechargeMoney().multiply(BigDecimal.valueOf(baseGrouponCard.getQuantity())));
                    salesmen.setProjectId(baseGrouponCard.getRechargeTypeId());
                    salesmen.setProjectNum(baseGrouponCard.getRechargeTypeNum());
                    salesmen.setStoreNum(baseStore1.getStoreNum());
                    salesmen.setStoreName(baseStore1.getStoreName());
                    salesmen.setStoreIdOrder(baseStore1.getId());
                    salesmen.setOperatorBy(baseGrouponCard.getInputBy());
                }
                ssmSalesmanService.addBatch(salesmens);
            }

//            BaseGrouponList baseGrouponList = new BaseGrouponList();
//            baseGrouponList.setGrouponCardId(baseGrouponCard.getId());
//            ssmBaseGrouponListService.delete(baseGrouponList);
//
//            for (BaseGrouponList baseGrouponList1 : baseGrouponLists) {
//                baseGrouponList1.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
//                baseGrouponList1.setGrouponCardId(baseGrouponCard.getId());
//                String encrypt = AESUtils.encrypt(baseGrouponList1.getMobilePhone());
//                baseGrouponList1.setMobilePhone(encrypt);
//            }
//            int i = ssmBaseGrouponListService.insertBatch(baseGrouponLists);
//获取修改后文件上传list 新增信息
            List<UploadFiles> list = baseGrouponCardRequest.getUploadFiles();
            //存在文件更新信息 文件先删除 后新增
            if (null != list && list.size() > 0) {
                UploadFiles files = new UploadFiles();
                files.setDocId(baseGrouponCard.getId());
                files.setDocNum(baseGrouponCard.getDocNum());
                files.setDocType(Constant.account_type_recharge_groupon);
                //查询原来对应单据的文件list
                List<UploadFiles> oldList = ssmUploadFilesService.select(files);
                //数据库文件信息删除
                FtpUtils ftpUtils = new FtpUtils();
//        oldList.stream().forEach(uploadFiles -> ssmUploadFilesService.deleteByPrimaryKey(uploadFiles.getId()));
//        //文件服务器文件删除
//        oldList.stream().forEach(uploadFiles -> {
//            try {
//                ftpUtils.deleteFile(uploadFiles.getFilePath(),uploadFiles.getFileName());
//            } catch (IOException e) {
//                log.error("SsmRefundOrderServiceImpl.updateRefundOrder",e);
//                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            }
//        });
                for (UploadFiles uploadFiles : oldList) {
                    ssmUploadFilesService.deleteByPrimaryKey(uploadFiles.getId());
                    ftpUtils.deleteFile(uploadFiles.getFilePath(), uploadFiles.getFileName());
                }

                for (UploadFiles uploadFiles : list) {
                    uploadFiles.setDocId(baseGrouponCard.getId());
                    uploadFiles.setDocNum(baseGrouponCard.getDocNum());
                    files.setDocType(Constant.account_type_recharge_groupon);
                    ssmUploadFilesService.add(uploadFiles);
                }
            }
        }
        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateState(BaseGrouponCardRequest baseGrouponCardRequest, String key) throws SmsException {
        int update = 0;

        StaffResponse staffResponse = new StaffResponse();
        if (templateRedisClient.hasKey(getKey(key))){
            staffResponse = templateRedisClient.get(getKey(key));
        }
        BaseGrouponCard baseGrouponCard = new BaseGrouponCard();
        baseGrouponCard.setId(baseGrouponCardRequest.getId());
        BaseGrouponCard baseGrouponCard1 = dao.selectOne(baseGrouponCard);
        if(baseGrouponCardRequest.getState()==1){//送审
            if(baseGrouponCard1.getState()==0 || baseGrouponCard1.getState()==2 ||baseGrouponCard1.getState()==4){
                BaseGrouponList baseGrouponList = new BaseGrouponList();
                baseGrouponList.setGrouponCardId(baseGrouponCard1.getId());
                List<BaseGrouponList> baseGrouponList1 = ssmBaseGrouponListService.select(baseGrouponList);
                if(baseGrouponList1.size()>0){
                    for (BaseGrouponList grouponList : baseGrouponList1) {
                        if(null == grouponList.getMobilePhone()){
                            throw new SmsException(ResponseCode.MSG,"团购名单不完整，送审失败");
                        }
                        baseGrouponCard1.setState(baseGrouponCardRequest.getState());
                        update = dao.updateByPrimaryKeySelective(baseGrouponCard1);
                        if(update == 0){
                            throw new SmsException(ResponseCode.MSG,"送审失败");
                        }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"团购名单不存在");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"单据当前状态不允许送审");
            }

        }
        else if(baseGrouponCardRequest.getState()==2){
            if(baseGrouponCard1.getState()==1){
                baseGrouponCard1.setState(baseGrouponCardRequest.getState());
                update = dao.updateByPrimaryKeySelective(baseGrouponCard1);
                if(update == 0){
                    throw new SmsException(ResponseCode.MSG,"送审失败");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"单据当前状态不允许回收");
            }
        }
        else if(baseGrouponCardRequest.getState()==3){ //审核
            if(baseGrouponCard1.getState()==1){
                baseGrouponCard1.setState(baseGrouponCardRequest.getState());
                baseGrouponCard1.setAuditBy(staffResponse.getStaffName());
                baseGrouponCard1.setAuditDate(new Date());
                update = dao.updateByPrimaryKeySelective(baseGrouponCard1);
                PayList payList = new PayList();
                payList.setDocId(baseGrouponCard1.getDocNum());
                List<PayList> select1 = ssmPayService.select(payList);
                if(select1!=null && select1.size()>0){
                    for (PayList list : select1) {
                        list.setIsCancel(0);
                        list.setPayDate(new Date());
                        list.setStoreId(baseGrouponCard1.getStoreId());
                        ssmPayService.updateByPrimaryKey(list);
                    }
                }
                if(update >0){
                    //获取团购名单
                    BaseGrouponList baseGrouponList = new BaseGrouponList();
                    baseGrouponList.setGrouponCardId(baseGrouponCard1.getId());
                    List<BaseGrouponList> baseGrouponList1 = ssmBaseGrouponListService.select(baseGrouponList);
                    if(baseGrouponList1.size()!=baseGrouponCard1.getQuantity()){
                        throw new SmsException(ResponseCode.MSG,"团购份数与团购人数不相等");
                    }
                    StoreRequest storeRequest = new StoreRequest();
                    storeRequest.setId(baseGrouponCard1.getStoreId());
                    List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                    List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());
                    int size = baseGrouponList1.size();
                    int numberSize = 0;
                    for (BaseGrouponList grouponList : baseGrouponList1) {
                        Example example = new Example(StoreMemberList.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("mobilePhone",grouponList.getMobilePhone());
                        criteria.andIn("storeId",collect);
                        List<StoreMemberList> list = ssmStoreMemberService.selectByExample(example);
                        if(list.size()>0){
                            StoreMemberList storeMemberList2 = list.get(0);
                            RechargeAccount rechargeAccount = new RechargeAccount();
                            rechargeAccount.setMemberId(storeMemberList2.getId());
                            rechargeAccount.setRechargeTypeId(baseGrouponCard1.getRechargeTypeId());
                            RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectOne(rechargeAccount);
                            if(null == rechargeAccount1){
                                rechargeAccount1 = new RechargeAccount();
                                rechargeAccount1.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                                rechargeAccount1.setMemberId(storeMemberList2.getId());
                                rechargeAccount1.setMemberName(storeMemberList2.getMemberName());
                                rechargeAccount1.setCard(storeMemberList2.getCard());
                                rechargeAccount1.setCardRechargeMoney(baseGrouponCard1.getRechargeMoney());
                                rechargeAccount1.setCardRestMoney(baseGrouponCard1.getRechargeMoney());
                                rechargeAccount1.setCardConsumeMoney(baseGrouponCard1.getRechargeMoney());
                                rechargeAccount1.setRechargeTypeId(baseGrouponCard1.getRechargeTypeId());
                                rechargeAccount1.setRechargeTypeNum(baseGrouponCard1.getRechargeTypeNum());
                                rechargeAccount1.setRechargeTypeName(baseGrouponCard1.getRechargeTypeName());
                                rechargeAccount1.setRechargeTypeName(baseGrouponCard1.getRechargeTypeName());
                                rechargeAccount1.setType(1);
                                rechargeAccount1.setDiscount(baseGrouponCard1.getDiscount());
                                rechargeAccount1.setStoreId(baseGrouponCard1.getStoreId());
                                rechargeAccount1.setStoreName(baseGrouponCard1.getStoreName());
                                rechargeAccount1.setState(1);
                                rechargeAccount1.setEndTime(baseGrouponCard1.getExpireDate());
                                rechargeAccount1.setGiftConsumeMoney(BigDecimal.valueOf(0));
                                rechargeAccount1.setCardGiftMoney(BigDecimal.valueOf(0));
                                int save1 = ssmRechargeAccountService.save(rechargeAccount1);

                                StoreMemberList storeMemberList = new StoreMemberList();
                                storeMemberList.setId(storeMemberList2.getId());
                                StoreMemberList storeMemberList1 = ssmStoreMemberService.selectByPrimaryKey(storeMemberList.getId());
                                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(baseGrouponCard1, rechargeAccount, storeMemberList1);
                                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                                BaseStore baseStore = new BaseStore();
                                baseStore.setId(baseGrouponCard1.getStoreId());
                                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                                String decrypt = null;
//                                try {
//                                    decrypt = AESUtils.decrypt(storeMemberList2.getMobilePhone());
//                                    if(baseGrouponCardRequest.getIsSendSms()==1) {
//                                        try {
////                                            chuangLanBeanSmsUtil.sendRechargeSmsGroupPurchaseNew(baseStore1, decrypt, baseGrouponCard1.getRechargeMoney());
//                                            chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore1, decrypt,rechargeAccount1, baseGrouponCard1.getRechargeMoney(),BigDecimal.ZERO);
//                                        }catch (SmsException e){
//                                            System.out.println(e);
//                                        }
//                                    }
//                                }
//                                catch (Exception e) {
//                                    e.printStackTrace();
//                                }
                            }else{
                                rechargeAccount1.setCardRestMoney(rechargeAccount1.getCardRestMoney().add(baseGrouponCard1.getRechargeMoney()));
                                rechargeAccount1.setCardConsumeMoney(rechargeAccount1.getCardConsumeMoney().add(baseGrouponCard1.getRechargeMoney()));
                                if(null == baseGrouponCard1.getExpireDate()){
                                    rechargeAccount1.setEndTime(null);
                                }else{
                                    rechargeAccount1.setEndTime(baseGrouponCard1.getExpireDate());
                                }
                                ssmRechargeAccountService.addMoneyGrouponCard(rechargeAccount1);
                                //添加账户交易记录
                                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(baseGrouponCard1, rechargeAccount1, storeMemberList2);
                                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                                BaseStore baseStore = new BaseStore();
                                baseStore.setId(baseGrouponCard1.getStoreId());
                                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
                                String decrypt = null;
//                                try {
//                                    decrypt = AESUtils.decrypt(storeMemberList2.getMobilePhone());
//                                    if(baseGrouponCardRequest.getIsSendSms()==1) {
//                                        try {
////                                            chuangLanBeanSmsUtil.sendRechargeSmsGroupPurchaseNew(baseStore1, decrypt, baseGrouponCard1.getRechargeMoney());
//                                            chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore1, decrypt,rechargeAccount1, baseGrouponCard1.getRechargeMoney(),BigDecimal.ZERO);
//                                        }catch (SmsException e){
//                                            System.out.println(e);
//                                        }
//                                    }
//                                }catch (Exception e) {
//                                    e.printStackTrace();
//                                }
                            }

                        }
                        else{//不存在新增
                            //添加全新的会员
                            BaseStaff baseStaff = new BaseStaff();
                            baseStaff.setId(baseGrouponCard1.getSaleOneStaffId());
                            BaseStaff baseStaff1 = ssmBaseStaffService.selectByPrimaryKey(baseStaff.getId());
                            MemberRequest memberRequest = new MemberRequest();
                            memberRequest.setMemberNumber(numberSize);
                            if(numberSize<size){
                                numberSize++;
                            }
                            memberRequest.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            memberRequest.setMemberName(grouponList.getMemberName());
                            memberRequest.setSex(grouponList.getSex());
                            try {
                                String decrypt = AESUtils.decrypt(grouponList.getMobilePhone());
                                memberRequest.setMobilePhone(decrypt);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            for (BaseStores stores : pagesorganizations) {
                                if(null == stores.getParentId()){
                                    memberRequest.setStoreId(stores.getId());
                                    memberRequest.setStoreName(stores.getStoreName());
                                    break;
                                }
                            }
                            memberRequest.setConnStoreId(baseStaff1.getStoreId());
                            memberRequest.setOpeningDate(new Date());
                            memberRequest.setModifyBy(staffResponse.getStaffName());
                            memberRequest.setModifyDate(new Date());
                            memberRequest.setConnStoreName(baseStaff1.getStoreName());
                            String password = ObjectUtils.toString((int)((Math.random()*9+1)*100000));
                            String cashPassword = ObjectUtils.toString((int)((Math.random()*9+1)*100000));

                            memberRequest.setPassword(password);
                            memberRequest.setCashPassword(cashPassword);
                            memberRequest.setMemberStoreId(baseStaff1.getStoreId());
                            memberRequest.setMemberStoreName(baseStaff1.getStoreName());
                            memberRequest.setGrouptype("团购");
                            int i = ssmStoreMemberService.addStoreMember(memberRequest, key);
                            BaseStore baseStore = new BaseStore();
                            baseStore.setId(baseGrouponCard1.getStoreId());
                            baseStore = ssmBaseStoreService.selectByPrimaryKey(baseStore.getId());
//                            try {
//                                if(baseGrouponCardRequest.getIsSendSms()==1) {
//                                    chuangLanBeanSmsUtil.sendMemberInitPwdSmsTGNew(baseStore, memberRequest.getMemberName(), memberRequest.getMobilePhone(), Integer.parseInt(password), Integer.parseInt(cashPassword));
//                                }
//                            } catch (IOException e) {
//                                e.printStackTrace();
//                            }catch (Exception e){
//                                System.out.println(e);
//                            }
                            if(i>0){
                                //创建卡包
                                RechargeAccount rechargeAccount = new RechargeAccount();
                                rechargeAccount.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                                rechargeAccount.setMemberId(memberRequest.getId());
                                rechargeAccount.setMemberName(memberRequest.getMemberName());
                                rechargeAccount.setCard(memberRequest.getCard());
                                rechargeAccount.setCardRechargeMoney(baseGrouponCard1.getRechargeMoney());
                                rechargeAccount.setCardRestMoney(baseGrouponCard1.getRechargeMoney());
                                rechargeAccount.setCardConsumeMoney(baseGrouponCard1.getRechargeMoney());
                                rechargeAccount.setRechargeTypeId(baseGrouponCard1.getRechargeTypeId());
                                rechargeAccount.setRechargeTypeNum(baseGrouponCard1.getRechargeTypeNum());
                                rechargeAccount.setRechargeTypeName(baseGrouponCard1.getRechargeTypeName());
                                rechargeAccount.setRechargeTypeName(baseGrouponCard1.getRechargeTypeName());
                                rechargeAccount.setType(1);
                                rechargeAccount.setDiscount(baseGrouponCard1.getDiscount());
                                rechargeAccount.setStoreId(baseGrouponCard1.getStoreId());
                                rechargeAccount.setStoreName(baseGrouponCard1.getStoreName());
                                rechargeAccount.setState(1);
                                rechargeAccount.setEndTime(baseGrouponCard1.getExpireDate());
                                rechargeAccount.setEndTime(baseGrouponCard1.getExpireDate());
                                rechargeAccount.setGiftConsumeMoney(BigDecimal.valueOf(0));
                                rechargeAccount.setCardGiftMoney(BigDecimal.valueOf(0));
                                int save1 = ssmRechargeAccountService.save(rechargeAccount);

                                StoreMemberList storeMemberList = new StoreMemberList();
                                storeMemberList.setId(memberRequest.getId());
                                StoreMemberList storeMemberList1 = ssmStoreMemberService.selectByPrimaryKey(storeMemberList.getId());
                                AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(baseGrouponCard1, rechargeAccount, storeMemberList1);
                                ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                                String decrypt = null;
//                                try {
//                                    decrypt = AESUtils.decrypt(storeMemberList1.getMobilePhone());
//                                    if(baseGrouponCardRequest.getIsSendSms()==1) {
////                                        chuangLanBeanSmsUtil.sendRechargeSmsGroupPurchase(baseStore, decrypt, baseGrouponCard1.getRechargeMoney());
//                                        chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore, decrypt,rechargeAccount, baseGrouponCard1.getRechargeMoney(),BigDecimal.ZERO);
//                                    }
//                                } catch (SmsException e){
////                                    throw e;
//                                    System.out.println(e);
//                                }
//                                catch (Exception e) {
//                                    e.printStackTrace();
//                                }
                            }else{
                                throw new SmsException(ResponseCode.MSG,"会员创建失败");
                            }

                        }
                    }
                    Salesman salesman = new Salesman();
                    salesman.setOrderId(baseGrouponCard1.getId().toString());
                    List<Salesman> select = ssmSalesmanService.select(salesman);
                    for (Salesman salesman1 : select) {
                        salesman1.setState(0);
                        ssmSalesmanService.updateNotNull(salesman1);
                    }

                }else{
                    throw new SmsException(ResponseCode.MSG,"审核失败");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"单据当前状态不允许审核");
            }
        }
        else if(baseGrouponCardRequest.getState()==4) { //反审核
            PayList payList = new PayList();
            payList.setDocId(baseGrouponCard1.getDocNum());
            List<PayList> select1 = ssmPayService.select(payList);
            if(select1!=null && select1.size()>0){
                for (PayList list : select1) {
                    list.setIsCancel(1);

                    ssmPayService.updateByNum(list);
                }
            }
            StoreRequest storeRequest = new StoreRequest();
            storeRequest.setId(baseGrouponCard1.getStoreId());
            List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
            List<Long> collect = pagesorganizations.stream().map(BaseStores::getId).collect(Collectors.toList());

            BaseGrouponList baseGrouponList = new BaseGrouponList();
            baseGrouponList.setGrouponCardId(baseGrouponCard1.getId());
            List<BaseGrouponList> baseGrouponList1 = ssmBaseGrouponListService.select(baseGrouponList);
            for (BaseGrouponList grouponList : baseGrouponList1) {
                Example example = new Example(StoreMemberList.class);
                Example.Criteria criteria = example.createCriteria();
                criteria.andEqualTo("mobilePhone",grouponList.getMobilePhone());
                criteria.andIn("storeId",collect);
                List<StoreMemberList> list = ssmStoreMemberService.selectByExample(example);
                for (StoreMemberList storeMemberList : list) {
                    RechargeAccount rechargeAccount = new RechargeAccount();
                    rechargeAccount.setRechargeTypeId(baseGrouponCard1.getRechargeTypeId());
                    rechargeAccount.setMemberId(storeMemberList.getId());
                    List<RechargeAccount> select = ssmRechargeAccountService.select(rechargeAccount);
                    for (RechargeAccount account : select) {
                        if(account.getCardConsumeMoney().compareTo(baseGrouponCard1.getRechargeMoney())==-1) {
                            String decrypt = null;
                            try {
                                decrypt = AESUtils.decrypt(storeMemberList.getMobilePhone());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            throw new SmsException(ResponseCode.MSG, "会员" + storeMemberList.getMemberName() + ":" + decrypt + "账户余额不足，反审核失败");
                        }
                    }
                }
            }
            if(baseGrouponCard1.getState()==3) {
                baseGrouponCard1.setAuditBy(staffResponse.getStaffName());
                baseGrouponCard1.setAuditDate(new Date());
                baseGrouponCard1.setState(baseGrouponCardRequest.getState());
                update = dao.updateByPrimaryKeySelective(baseGrouponCard1);
                if (update > 0) {
                    baseGrouponList1 = ssmBaseGrouponListService.select(baseGrouponList);
                    for (BaseGrouponList grouponList : baseGrouponList1) {
                        Example example = new Example(StoreMemberList.class);
                        Example.Criteria criteria = example.createCriteria();
                        criteria.andEqualTo("mobilePhone",grouponList.getMobilePhone());
                        criteria.andIn("storeId",collect);
                        List<StoreMemberList> list = ssmStoreMemberService.selectByExample(example);
                        for (StoreMemberList storeMemberList : list) {
                            RechargeAccount rechargeAccount = new RechargeAccount();
                            rechargeAccount.setRechargeTypeId(baseGrouponCard1.getRechargeTypeId());
                            rechargeAccount.setMemberId(storeMemberList.getId());
                            List<RechargeAccount> select = ssmRechargeAccountService.select(rechargeAccount);
                            for (RechargeAccount account : select) {
                                if(account.getCardConsumeMoney().compareTo(baseGrouponCard1.getRechargeMoney())!=-1) {
                                    account.setCardRestMoney(account.getCardRestMoney().subtract(baseGrouponCard1.getRechargeMoney()));
                                    account.setCardConsumeMoney(account.getCardConsumeMoney().subtract(baseGrouponCard1.getRechargeMoney()));
                                    ssmRechargeAccountService.addMoney(account);
                                    AccountTradeRecord accountTradeRecord = this.setAccountTradeRecord(baseGrouponCard1, account, storeMemberList);
                                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                                }else {
                                    String decrypt = null;
                                    try {
                                        decrypt = AESUtils.decrypt(storeMemberList.getMobilePhone());
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    throw new SmsException(ResponseCode.MSG, "会员" + storeMemberList.getMemberName() + ":" + decrypt + "账户余额不足，反审核失败");
                                }
                            }
                        }
                    }
                }
            }
            Salesman salesman = new Salesman();
            salesman.setOrderId(baseGrouponCard1.getId().toString());
            List<Salesman> select = ssmSalesmanService.select(salesman);
            for (Salesman salesman1 : select) {
                salesman1.setState(1);
                ssmSalesmanService.updateNotNull(salesman1);
            }

        }

        return update;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delete(BaseGrouponCardRequest baseGrouponCardRequest) throws SmsException {
        BaseGrouponCard baseGrouponCard = new BaseGrouponCard();
        baseGrouponCard.setId(baseGrouponCardRequest.getId());
        BaseGrouponCard baseGrouponCard1 = dao.selectByPrimaryKey(baseGrouponCard.getId());
        PayList payList = new PayList();
        payList.setDocId(baseGrouponCard1.getDocNum());
        ssmPayService.delete(payList);
        if(baseGrouponCard1.getState()==0){
            int i = dao.deleteByPrimaryKey(baseGrouponCard1.getId());
            if(i>0){
                BaseGrouponList baseGrouponList = new BaseGrouponList();
                baseGrouponList.setGrouponCardId(baseGrouponCard1.getId());
                int delete = ssmBaseGrouponListService.delete(baseGrouponList);
            }
            return i;
        }else{
            throw new SmsException(ResponseCode.MSG,"非新建状态单据，不允许删除");
        }
    }

    @Override
    public List<BaseGrouponCardResponse> selectDates(Long storeId, String date) {
        List<BaseGrouponCardResponse> baseGrouponCardResponses = new ArrayList<>();
        Example example = new Example(BaseGrouponCard.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != storeId){
            criteria.andEqualTo("storeId", storeId);
        }
        if (null != date){
            criteria.andLike("docDate", date+"%");
        }
        criteria.andEqualTo("state",3);
        List<BaseGrouponCard> lists = dao.selectByExample(example);
        for (BaseGrouponCard list : lists) {
            BaseGrouponCardResponse baseGrouponCardResponse = new BaseGrouponCardResponse();
            BeanUtils.copyProperties(list,baseGrouponCardResponse);
            List<AchiCommEntity> achiCommList = this.getAchiCommLists(list);
            for (AchiCommEntity achiCommEntity : achiCommList) {
                if(list.getDocNum().equals(achiCommEntity.getDocNum())){
                    achiCommEntity.setProjectId(list.getRechargeTypeNum());
                }
                achiCommEntity.setDocId(list.getId());
            }
            baseGrouponCardResponse.setStaffLists(achiCommList);
            baseGrouponCardResponses.add(baseGrouponCardResponse);
        }

        return baseGrouponCardResponses;
    }

    @Override
    public List<BaseGrouponCard> selectFKJ(BaseGrouponCard baseGrouponCard) {
        return dao.selectFKJ(baseGrouponCard);
    }
    @Autowired
    private BaseGrouponCardMapper mapper;
    @Override
    public List<BaseGrouponCard> selectFKJByDate(BaseGrouponCard baseGrouponCard) {
        return mapper.selectFKJByDate(baseGrouponCard);
    }
    @Override
    public List<BaseGrouponCard> selectDateschia(Long StoreId, Date startDate, Date endDate) {
        Example example = new Example(BaseGrouponCard.class);
        Example.Criteria criteria = example.createCriteria();
        if (null != StoreId){
            criteria.andEqualTo("storeId", StoreId);
        }
        if (null != startDate && null != endDate){
            criteria.andBetween("docDate", startDate,endDate);
        }
        List<BaseGrouponCard> lists = dao.selectByExample(example);
        return lists;

    }

    @Override
    public List<BaseGrouponCard> selectNew(List<Long> baseGrouponCard) {
        return mapper.selectNew(baseGrouponCard);
    }

    @Override
    public String sendSms(BaseGrouponCardRequest baseGrouponCardRequest, String key) throws SmsException {
        BaseGrouponCard grouponCard = dao.selectByPrimaryKey(baseGrouponCardRequest.getId());
        if(grouponCard.getState()!=3){
            throw new SmsException(ResponseCode.MSG,"请审核再进行发送短信");
        }
        BaseGrouponList baseGrouponList = new BaseGrouponList();
        baseGrouponList.setGrouponCardId(baseGrouponCardRequest.getId());
        List<BaseGrouponList> select = ssmBaseGrouponListService.select(baseGrouponList);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(grouponCard.getStoreId());
        String str = "";
        for (BaseGrouponList grouponList : select) {
            String decrypt = null;
            try {
                decrypt = AESUtils.decrypt(grouponList.getMobilePhone()).replaceAll("\u0000","");
                RechargeAccount rechargeAccount = new RechargeAccount();
                StoreMemberList storeMemberList = new StoreMemberList();
                storeMemberList.setMobilePhone(grouponList.getMobilePhone());
                List<StoreMemberList> storeMemberLists = ssmStoreMemberService.select(storeMemberList);
                Long memberId = storeMemberLists.get(0).getId();
                rechargeAccount.setMemberId(memberId);
//                rechargeAccount.setRechargeTypeId(grouponCard.getRechargeTypeId());
                List<RechargeAccount> select1 = ssmRechargeAccountService.select(rechargeAccount);
                rechargeAccount = select1.get(0);
                rechargeAccount.setCardRestMoney(select1.stream().map(RechargeAccount::getCardRestMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
                rechargeAccount.setCardGiftMoney(select1.stream().map(RechargeAccount::getCardGiftMoney).reduce(BigDecimal.ZERO,BigDecimal::add));
//                rechargeAccount.setMemberName(grouponList.getMemberName());
//                rechargeAccount.setCardRestMoney(grouponCard.getRechargeMoney());
//                rechargeAccount.setCardGiftMoney(BigDecimal.ZERO);
//                if(rechargeAccount.getCardRestMoney().compareTo(grouponCard.getRechargeMoney())==1){
//                    System.out.println("------");
//                }
                List<String> memberPhone = baseGrouponCardRequest.getMemberPhone();
                if(memberPhone.contains(decrypt)){
                    System.out.println(decrypt+"----短信发送成功");
                chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore, decrypt,rechargeAccount, grouponCard.getRechargeMoney(),BigDecimal.ZERO);
                }
            }catch (SmsException smsException){
                System.out.println(decrypt+"-------短信发送失败");
                str = decrypt+smsException.getMessage();
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return str;
    }

    @Override
    public String sendSmsMemberPhone(BaseGrouponCardRequest baseGrouponCardRequest, String key) {
        BaseGrouponCard grouponCard = dao.selectByPrimaryKey(baseGrouponCardRequest.getId());
        BaseGrouponList baseGrouponList = new BaseGrouponList();
        baseGrouponList.setGrouponCardId(baseGrouponCardRequest.getId());
        List<BaseGrouponList> select = ssmBaseGrouponListService.select(baseGrouponList);
        BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(grouponCard.getStoreId());
        String str = "";
        for (BaseGrouponList grouponList : select) {
            String decrypt = null;
            try {
                decrypt = AESUtils.decrypt(grouponList.getMobilePhone()).replaceAll("\u0000","");
                RechargeAccount rechargeAccount = new RechargeAccount();
                StoreMemberList storeMemberList = new StoreMemberList();
                storeMemberList.setMobilePhone(grouponList.getMobilePhone());
                List<StoreMemberList> storeMemberLists = ssmStoreMemberService.select(storeMemberList);
                Long memberId = storeMemberLists.get(0).getId();
                rechargeAccount.setMemberId(memberId);
                rechargeAccount.setRechargeTypeId(grouponCard.getRechargeTypeId());
                List<RechargeAccount> select1 = ssmRechargeAccountService.select(rechargeAccount);
                rechargeAccount = select1.get(0);
//                rechargeAccount.setMemberName(grouponList.getMemberName());
//                rechargeAccount.setCardRestMoney(grouponCard.getRechargeMoney());
//                rechargeAccount.setCardGiftMoney(BigDecimal.ZERO);
//                if(rechargeAccount.getCardRestMoney().compareTo(grouponCard.getRechargeMoney())==1){
//                    System.out.println("------");
//                }
                if(baseGrouponCardRequest.getMemberPhone().contains(decrypt)) {
                    System.out.println("---------短信发送完成");
//                    chuangLanBeanSmsUtil.sendRechargeSmsNew(baseStore, decrypt, rechargeAccount, grouponCard.getRechargeMoney(), BigDecimal.ZERO);
                }
            }catch (SmsException smsException){
                str = smsException.getMessage();
            }
            catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return str;
    }

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

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

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

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

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

            entities.add(achiCommEntity);
        }
        return entities;
    }

    //添加交易记录
    public AccountTradeRecord setAccountTradeRecord(BaseGrouponCard baseGrouponCard, RechargeAccount rechargeAccount,StoreMemberList storeMemberList){
        AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
        accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        accountTradeRecord.setStoreId(baseGrouponCard.getStoreId());
        accountTradeRecord.setStoreName(baseGrouponCard.getStoreName());
        accountTradeRecord.setMemberId(storeMemberList.getId());
        accountTradeRecord.setMemberName(storeMemberList.getMemberName());
        try {
            String decrypt = AESUtils.decrypt(storeMemberList.getMobilePhone());
            accountTradeRecord.setMemberPhone(decrypt.trim());
        } catch (Exception e) {
            e.printStackTrace();
        }

        accountTradeRecord.setAccountId(rechargeAccount.getId());
        accountTradeRecord.setAccountName(rechargeAccount.getRechargeTypeName());
        if(baseGrouponCard.getState() == 3) {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_groupon);
            accountTradeRecord.setAccountInMoney(baseGrouponCard.getRechargeMoney());
            accountTradeRecord.setInputDate(baseGrouponCard.getDocDate());
            accountTradeRecord.setInputBy(baseGrouponCard.getAuditBy());
        }else {
            accountTradeRecord.setAccountType(Constant.account_type_recharge_groupon_cancel);
            accountTradeRecord.setAccountSpendMoney(baseGrouponCard.getRechargeMoney());
            accountTradeRecord.setInputDate(baseGrouponCard.getDocDate());
            accountTradeRecord.setInputBy(baseGrouponCard.getAuditBy());
        }
        accountTradeRecord.setDocId(baseGrouponCard.getId());
        accountTradeRecord.setDocNum(baseGrouponCard.getDocNum());
        accountTradeRecord.setDocType(Constant.recharge_groupon_card);
        accountTradeRecord.setTradeId(baseGrouponCard.getRechargeTypeId());
        accountTradeRecord.setTradeName(baseGrouponCard.getRechargeTypeName());
        accountTradeRecord.setTradeMoney(baseGrouponCard.getRechargeMoney());
        accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());
        accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());
        accountTradeRecord.setAccountGiftRestMoney(rechargeAccount.getCardGiftMoney());
        accountTradeRecord.setAccountGiftConsumeMoney(rechargeAccount.getGiftConsumeMoney());
        accountTradeRecord.setPrice(baseGrouponCard.getRechargeMoney());
        return accountTradeRecord;
    }

    /*
     * 业务员赋值
     * */
    public void setStaffValue(List<StaffRequest> staffLists, BaseGrouponCard baseGrouponCard){
        for (int i = 0; i < staffLists.size(); i++) {
            StaffRequest staffRequest = staffLists.get(i);
            if (i == 0){
                baseGrouponCard.setSaleOneStaffId(staffRequest.getId());
                baseGrouponCard.setSaleOneStaffName(staffRequest.getStaffName());
                baseGrouponCard.setSaleOneIdentity(staffRequest.getIdentityCard());
                baseGrouponCard.setSaleOneRatio(staffRequest.getRatio());
                baseGrouponCard.setSaleOneNumber(staffRequest.getBrandNumber());
            }else if (i == 1){
                baseGrouponCard.setSaleTwoStaffId(staffRequest.getId());
                baseGrouponCard.setSaleTwoStaffName(staffRequest.getStaffName());
                baseGrouponCard.setSaleTwoIdentity(staffRequest.getIdentityCard());
                baseGrouponCard.setSaleTwoRatio(staffRequest.getRatio());
                baseGrouponCard.setSaleTwoNumber(staffRequest.getBrandNumber());
            }else if (i == 2){
                baseGrouponCard.setSaleThreeStaffId(staffRequest.getId());
                baseGrouponCard.setSaleThreeStaffName(staffRequest.getStaffName());
                baseGrouponCard.setSaleThreeIdentity(staffRequest.getIdentityCard());
                baseGrouponCard.setSaleThreeRatio(staffRequest.getRatio());
                baseGrouponCard.setSaleThreeNumber(staffRequest.getBrandNumber());
            }else if(i==3){
                baseGrouponCard.setSaleFourStaffId(staffRequest.getId());
                baseGrouponCard.setSaleFourStaffName(staffRequest.getStaffName());
                baseGrouponCard.setSaleFourIdentity(staffRequest.getIdentityCard());
                baseGrouponCard.setSaleFourRatio(staffRequest.getRatio());
                baseGrouponCard.setSaleFourNumber(staffRequest.getBrandNumber());
            }
        }
    }

    public String getNum(String date,Long storeId){
        List<Long> stores = new ArrayList<>();
        StoreRequest storeRequest = new StoreRequest();
        storeRequest.setId(storeId);
        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
        for (BaseStores pagesorganization : pagesorganizations) {
            stores.add(pagesorganization.getId());
        }
        Example example = new Example(BaseGrouponCard.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLike("docDate","%" + date + "%");
        criteria.andIn("storeId",stores);
        example.setOrderByClause("id desc");
        List<BaseGrouponCard> list = dao.selectByExample(example);
        String num=null;
        if(null != list){
            if(list.size()>0 ){
                String docNum = list.get(0).getDocNum();
                int i1 = Integer.parseInt(docNum.substring(8));
                if(i1>999){
                    num = date+(i1+1);
                }else  if(i1>99){
                    num = date+"0"+(i1+1);
                }else  if(i1>9){
                    num = date+"00"+(i1+1);
                }else{

                    num = date+"000"+(i1+1);
                }
            }else{
                num = date+"0001";
            }
        }else{
            num = date+"0001";
        }
        return num.replace("-","");
    }

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

    public List<BaseGrouponList> check(List<BaseGrouponList> list){
        List<BaseGrouponList> unusualList = new ArrayList<>();
        //校验启用状态下编码是否重复
        Map<String, List<BaseGrouponList>> map = list.stream().collect(Collectors.groupingBy(baseGrouponList -> baseGrouponList.getMobilePhone()));
        for (String key : map.keySet()) {
            if (map.get(key).size() > 1){
                unusualList.addAll(map.get(key));
                list.removeAll(map.get(key));
            }
        }
        return unusualList;
    }

    public List<AchiCommEntity> getAchiCommList(BaseGrouponCard baseGrouponCard){
        List<AchiCommEntity> entities = new ArrayList<>();
        if (null != baseGrouponCard.getSaleOneStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(baseGrouponCard.getSaleOneNumber());
            achiCommEntity.setSaleStaffId(baseGrouponCard.getSaleOneStaffId());
            achiCommEntity.setSaleStaffName(baseGrouponCard.getSaleOneStaffName());
            achiCommEntity.setSaleIdentityCard(baseGrouponCard.getSaleOneIdentity());
            achiCommEntity.setSaleRatio(baseGrouponCard.getSaleOneRatio());
            entities.add(achiCommEntity);
        }
        if (null != baseGrouponCard.getSaleTwoStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(baseGrouponCard.getSaleTwoNumber());
            achiCommEntity.setSaleStaffId(baseGrouponCard.getSaleTwoStaffId());
            achiCommEntity.setSaleStaffName(baseGrouponCard.getSaleTwoStaffName());
            achiCommEntity.setSaleIdentityCard(baseGrouponCard.getSaleTwoIdentity());
            achiCommEntity.setSaleRatio(baseGrouponCard.getSaleTwoRatio());
            entities.add(achiCommEntity);
        }
        if (null != baseGrouponCard.getSaleThreeStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(baseGrouponCard.getSaleThreeNumber());
            achiCommEntity.setSaleStaffId(baseGrouponCard.getSaleThreeStaffId());
            achiCommEntity.setSaleStaffName(baseGrouponCard.getSaleThreeStaffName());
            achiCommEntity.setSaleIdentityCard(baseGrouponCard.getSaleThreeIdentity());
            achiCommEntity.setSaleRatio(baseGrouponCard.getSaleThreeRatio());
            entities.add(achiCommEntity);
        }
        if (null != baseGrouponCard.getSaleFourStaffId()){
            AchiCommEntity achiCommEntity = new AchiCommEntity();
            achiCommEntity.setBrandNumber(baseGrouponCard.getSaleFourNumber());
            achiCommEntity.setSaleStaffId(baseGrouponCard.getSaleFourStaffId());
            achiCommEntity.setSaleStaffName(baseGrouponCard.getSaleFourStaffName());
            achiCommEntity.setSaleIdentityCard(baseGrouponCard.getSaleFourIdentity());
            achiCommEntity.setSaleRatio(baseGrouponCard.getSaleFourRatio());
            entities.add(achiCommEntity);
        }
        return entities;
    }
}
