package com.ssm.manage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ssm.core.service.impl.BaseServiceImpl;
import com.ssm.core.utils.AESUtils;
import com.ssm.core.utils.SnowflakeUtil;
import com.ssm.manage.dao.SsmBaseZengkaDao;
import com.ssm.manage.entity.*;
import com.ssm.manage.entity.BaseZengkaRequest;
import com.ssm.manage.mapper.BaseZengkaMapper;
import com.ssm.manage.query.AccountTradeRecordRequest;
import com.ssm.manage.query.ServiceOrderRequest;
import com.ssm.manage.query.StoreDailyRequest;
import com.ssm.manage.query.StoreRequest;
import com.ssm.manage.response.BaseZengkaResponse;
import com.ssm.manage.response.ResponseCode;
import com.ssm.manage.response.StaffResponse;
import com.ssm.manage.service.*;
import com.ssm.manage.utils.Constant;
import com.ssm.util.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.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.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
@Slf4j
public class SsmBaseZengkaServiceImpl  extends BaseServiceImpl<BaseZengka> implements SsmBaseZengkaService {

    @Autowired
    private SsmBaseZengkaDao dao;

    @Autowired
    private SsmBaseZengkaIssueService ssmBaseZengkaIssueService;

    @Autowired
    private SsmStoreParaService ssmStoreParaService;

    @Autowired
    private SsmRechargeTypeSevice ssmRechargeTypeSevice;

    @Autowired
    private SsmBaseStoreService ssmBaseStoreService;
    @Autowired
    private SsmStoreMemberService ssmStoreMemberService;

    @Autowired
    private SsmRechargeAccountService ssmRechargeAccountService;

    @Autowired
    private SsmAccountTradeRecordService ssmAccountTradeRecordService;

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

    @Autowired
    private RedisClient<StaffResponse> templateRedisClient;

    @Override
    public PageInfo<BaseZengkaResponse> selectPage(BaseZengkaRequest baseZengkaRequest) throws SmsException {

        List<BaseZengkaResponse> baseZengkaResponses = new ArrayList<>();

        Example example = new Example(BaseZengka.class);
        Example.Criteria criteria = example.createCriteria();

        criteria.andEqualTo("storeId",baseZengkaRequest.getStoreId());
        if (null != baseZengkaRequest.getDocNum()){
            criteria.andLike("docNum","%" + baseZengkaRequest.getDocNum() + "%");
        }
        if (null != baseZengkaRequest.getDocDate()){
            criteria.andLike("docDate","%" + baseZengkaRequest.getDocDate() + "%");
        }
        if (null != baseZengkaRequest.getState()){
            criteria.andEqualTo("state",baseZengkaRequest.getState());
        }
        if(baseZengkaRequest.getStartTime()!=null){
            criteria.andBetween("auditDate",baseZengkaRequest.getStartTime(),baseZengkaRequest.getEndTime());
        }
        baseZengkaRequest.setSort("update_date");
        PageHelper.startPage(baseZengkaRequest.getPageNum(),baseZengkaRequest.getPageSize(),baseZengkaRequest.columnCnvert("doc_date", "desc"));
        List<BaseZengka> list = dao.selectByExample(example);
        for (BaseZengka baseZengka : list) {
            BaseZengkaResponse baseZengkaResponse = new BaseZengkaResponse();
            BeanUtils.copyProperties(baseZengka,baseZengkaResponse);

            BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
            baseZengkaIssue.setZengkaId(baseZengka.getId());
            List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
            baseZengkaResponse.setBaseZengkaIssues(select);
            baseZengkaResponses.add(baseZengkaResponse);
        }
        Example examples = new Example(BaseZengka.class);
        Example.Criteria criterias = examples.createCriteria();

        criterias.andEqualTo("storeId",baseZengkaRequest.getStoreId());
        if (null != baseZengkaRequest.getDocNum()){
            criterias.andLike("docNum","%" + baseZengkaRequest.getDocNum() + "%");
        }
        if (null != baseZengkaRequest.getDocDate()){
            criterias.andLike("docDate","%" + baseZengkaRequest.getDocDate() + "%");
        }
        if (null != baseZengkaRequest.getState()){
            criterias.andEqualTo("state",baseZengkaRequest.getState());
        }
        if(baseZengkaRequest.getStartTime()!=null){
            criteria.andBetween("auditDate",baseZengkaRequest.getStartTime(),baseZengkaRequest.getEndTime());
        }
        List<BaseZengka> lists = dao.selectByExample(examples);
        PageInfo<BaseZengkaResponse> pageInfo = new PageInfo<>(baseZengkaResponses);
        pageInfo.setTotal(lists.size());
        return pageInfo;
    }


    @Override
    public List seleZengkaIssue(List<BaseZengka> z) throws SmsException {
        List lists = new ArrayList<>();
            for(BaseZengka baseZengka : z){
                BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
                baseZengkaIssue.setZengkaId(baseZengka.getId());
                List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
                lists.add(select);
            }
        return lists;
    }
    @Override
    public List<BaseZengkaIssue> seleZengkaIssueNew(List<BaseZengka> z) throws SmsException {
        List<BaseZengkaIssue> lists = new ArrayList<>();
        for(BaseZengka baseZengka : z){
            BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
            baseZengkaIssue.setZengkaId(baseZengka.getId());
            List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
            lists.addAll(select);
        }
        return lists;
    }

    @Autowired
    private BaseZengkaMapper baseZengkaMapper;

    @Override
    public BigDecimal NegativeKazinByDate(StoreDailyRequest storeDailyRequest) {
        return baseZengkaMapper.NegativeKazinByDate(storeDailyRequest);
    }

    @Override
    public List<BaseZengkaRequest> selectList(BaseZengkaRequest baseZengkaRequest) {
        return baseZengkaMapper.selectListByIds(baseZengkaRequest);
    }


    @Override
    public int add(BaseZengkaRequest baseZengkaRequest, String key) throws SmsException {
        if(null != baseZengkaRequest.getQuantity()){
            if(baseZengkaRequest.getQuantity() <= 0){
                throw new SmsException(ResponseCode.MSG,"赠送份数量不能等于小于0");
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"赠送份数量不能为空");
        }
        if(null != baseZengkaRequest.getRechargeMoney()){
            if(baseZengkaRequest.getRechargeMoney().compareTo(BigDecimal.valueOf(0))!=1){
                throw new SmsException(ResponseCode.MSG,"赠送卡金额不能等于小于0");
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"赠送卡金额不能为空");
        }
        BaseZengka baseZengka = new BaseZengka();
        BeanUtils.copyProperties(baseZengkaRequest,baseZengka);
        baseZengka.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
        if(null == baseZengka.getExpireDate()){
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            try {
                Date parse = simpleDateFormat.parse("2099-12-20 23:59:59");
                baseZengka.setExpireDate(parse);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }

        if (templateRedisClient.hasKey(getKey(key))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(key));
            baseZengka.setInputBy(staffResponse.getStaffName());
            baseZengka.setInputDate(new Date());
        }
        baseZengka.setState(0);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String format = simpleDateFormat.format(new Date());
        String num = this.getNum(format, baseZengka.getStoreId());
        baseZengka.setDocNum(num);
        baseZengka.setDocDate(new Date());
        int insert = dao.insert(baseZengka);
        if(insert >0){
            for (int i = 0; i <baseZengka.getQuantity(); i++) {
                BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
                baseZengkaIssue.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                baseZengkaIssue.setZengkaId(baseZengka.getId());
                baseZengkaIssue.setState(0);
                baseZengkaIssue.setStoreId(baseZengka.getStoreId());
                baseZengkaIssue.setStoreName(baseZengka.getStoreName());
                int insert1 = ssmBaseZengkaIssueService.insert(baseZengkaIssue);
                if(insert1==0){
                    throw new SmsException(ResponseCode.MSG,"创建赠送卡明细失败");
                }
            }

        }
        return insert;
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public int update(BaseZengkaRequest baseZengkaRequest, String key) throws SmsException {
        if(null != baseZengkaRequest.getRechargeMoney()){
            if(baseZengkaRequest.getRechargeMoney().compareTo(BigDecimal.valueOf(0))!=1){
                throw new SmsException(ResponseCode.MSG,"赠送卡金额不能等于小于0");
            }
        }else{
            throw new SmsException(ResponseCode.MSG,"赠送卡金额不能为空");
        }
        BaseZengka baseZengka = new BaseZengka();
        BeanUtils.copyProperties(baseZengkaRequest,baseZengka);
        BaseZengka baseZengka1 = dao.selectByPrimaryKey(baseZengka.getId());

        if(baseZengka1.getState()!= 0 && baseZengka1.getState()!= 2 && baseZengka1.getState()!= 4 ){
            throw new SmsException(ResponseCode.MSG,"当前会员赠送卡单据状态不允许修改");
        }

        RechargeType rechargeType = new RechargeType();
        rechargeType.setId(baseZengka.getRechargeTypeId());
        rechargeType = ssmRechargeTypeSevice.selectByPrimaryKey(rechargeType.getId());

        if (templateRedisClient.hasKey(getKey(key))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(key));
            baseZengka.setUpdateBy(staffResponse.getStaffName());
            baseZengka.setUpdateDate(new Date());
        }
        int insert = dao.updateByPrimaryKeySelective(baseZengka);
        if(insert >0){

            List<BaseZengkaIssue> baseZengkaIssues = baseZengkaRequest.getBaseZengkaIssues();
            for (BaseZengkaIssue baseZengkaIssue : baseZengkaIssues) {
                if(null != baseZengkaIssue.getMemberCard()){
                    BaseZengkaIssue baseZengkaIssue2 = new BaseZengkaIssue();
                    baseZengkaIssue2.setStoreId(baseZengka.getStoreId());
                    baseZengkaIssue2.setMemberCard(baseZengkaIssue.getMemberCard());
                    baseZengkaIssue2 = ssmBaseZengkaIssueService.selectOne(baseZengkaIssue2);
                    if(baseZengkaIssue2!=null){
                        if(!baseZengkaIssue2.getId().equals(baseZengkaIssue.getId())){
                            throw new SmsException(ResponseCode.MSG,"会员卡 ["+baseZengkaIssue.getMemberCard()+" ] 已经存在");
                        }
                    }
                }
            }
            for (BaseZengkaIssue baseZengkaIssue : baseZengkaIssues) {
                if(null != baseZengkaIssue.getMemberCard()){
                    BaseZengkaIssue baseZengkaIssue1 = ssmBaseZengkaIssueService.selectByPrimaryKey(baseZengkaIssue.getId());
                    baseZengkaIssue1.setMemberCard(baseZengkaIssue.getMemberCard());
                    baseZengkaIssue1.setMemberNum("S"+"9"+Double.valueOf(rechargeType.getDiscount().doubleValue()).intValue()+baseZengkaIssue.getMemberCard());
                    ssmBaseZengkaIssueService.updateNotNull(baseZengkaIssue1);
                    //添加赠卡记录
//                    AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
//                    accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());//交易记录id
//                    accountTradeRecord.setStoreId(baseZengkaRequest.getStoreId());//门店id
//                    accountTradeRecord.setMemberId(baseZengkaIssue.getId());
//                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);

                }

            }
        }
        return insert;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateState(BaseZengkaRequest baseZengkaRequest, String key,Long storeId) throws SmsException {
        int update=0;
        BaseZengka baseZengka = new BaseZengka();

        baseZengka.setId(baseZengkaRequest.getId());
        BaseZengka baseZengka1 = dao.selectByPrimaryKey(baseZengka.getId());

        if (templateRedisClient.hasKey(getKey(key))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(key));
            baseZengka1.setUpdateBy(staffResponse.getStaffName());
            baseZengka1.setUpdateDate(new Date());
        }

        if(baseZengkaRequest.getState()==1){
            //送审
            BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
            baseZengkaIssue.setZengkaId(baseZengka1.getId());
            baseZengkaIssue.setStoreId(baseZengka1.getStoreId());
            List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
            for (BaseZengkaIssue zengkaIssue : select) {
                if(null == zengkaIssue.getMemberCard()){
                    throw new SmsException(ResponseCode.MSG,"会员卡号还没有填完，不能送审");
                }
            }
            if(baseZengka1.getState()==0 || baseZengka1.getState() == 2 || baseZengka1.getState() == 4){
                baseZengka1.setState(baseZengkaRequest.getState());
                update = dao.updateByPrimaryKeySelective(baseZengka1);
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许送审");
            }
        }else if(baseZengkaRequest.getState()==2){//回收
            if(baseZengka1.getState()==1){
                baseZengka1.setState(baseZengkaRequest.getState());
                update = dao.updateByPrimaryKeySelective(baseZengka1);
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许回收");
            }
        }else if(baseZengkaRequest.getState()==3){//审核
            if(baseZengka1.getState()==1){
                baseZengka1.setState(baseZengkaRequest.getState());
                if (templateRedisClient.hasKey(getKey(key))){
                    StaffResponse staffResponse = templateRedisClient.get(getKey(key));
                    baseZengka1.setAuditBy(staffResponse.getStaffName());
                    baseZengka1.setAuditDate(new Date());
                }
                update = dao.updateByPrimaryKeySelective(baseZengka1);
                if(update>0){
                    BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
                    baseZengkaIssue.setZengkaId(baseZengka1.getId());
                    baseZengkaIssue.setStoreId(baseZengka1.getStoreId());
                    List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
                    for (BaseZengkaIssue zengkaIssue : select) {

                        //创建会员会员手机号码 以9+折扣+00+卡号
                        RechargeType rechargeType = new RechargeType();
                        rechargeType.setId(baseZengka1.getRechargeTypeId());
                        //查询赠卡的信息
                        rechargeType = ssmRechargeTypeSevice.selectOne(rechargeType);

                        StoreRequest storeRequest = new StoreRequest();
                        BaseStores baseStores = new BaseStores();
                        storeRequest.setId(baseZengka1.getStoreId());
                        //查询当前门店下所有门店
                        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                        for (BaseStores pagesorganization : pagesorganizations) {
                            if(null == pagesorganization.getParentId()){
                                BeanUtils.copyProperties(pagesorganization,storeRequest);
                            }
                            if(baseZengka1.getStoreId().equals(pagesorganization.getId())){
                                BeanUtils.copyProperties(pagesorganization,baseStores);
                            }
                        }
                        //                        //查询会员是否存在
//                        String memberCard = zengkaIssue.getMemberCard();//会员手机号
                        StoreMemberList memberList = new StoreMemberList();
                        memberList.setMobilePhone(AESUtils.encrypt(zengkaIssue.getMemberCard()));
                        StoreMemberList memberList1 = ssmStoreMemberService.selectOne(memberList);
                        if(memberList1 == null ){

                        }
                        StoreMemberList storeMemberList = new StoreMemberList();
                        storeMemberList.setStoreId(storeRequest.getId());
                        storeMemberList.setStoreName(storeRequest.getStoreName());

                        storeMemberList.setConnStoreId(baseStores.getId());
                        storeMemberList.setConnStoreName(baseStores.getStoreName());
                        storeMemberList.setMemberStoreId(baseStores.getId());
                        storeMemberList.setMemberStoreName(baseStores.getStoreName());
                        storeMemberList.setMemberStoreNum(baseStores.getStoreNum());

                        String regEx= "[^0-9]" ;
                        Pattern p = Pattern.compile(regEx);
                        Matcher m = p.matcher(zengkaIssue.getMemberCard());
                        String trim = m.replaceAll("").trim();

                        storeMemberList.setMobilePhone(AESUtils.encrypt("9"+rechargeType.getDiscount().intValue()+"00"+trim));
//                        storeMemberList.setMobilePhone(AESUtils.encrypt(zengkaIssue.getMemberCard()));

                        storeMemberList.setPassword(AESUtils.encrypt(zengkaIssue.getMemberCard()));
                        storeMemberList.setCashPassword(AESUtils.encrypt(zengkaIssue.getMemberCard()));
                        storeMemberList.setMemberNum(zengkaIssue.getMemberNum());
                        storeMemberList.setMemberName(zengkaIssue.getMemberNum());
                        storeMemberList.setCard(zengkaIssue.getMemberCard());
                        storeMemberList.setState(1);
                        storeMemberList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                        int save = ssmStoreMemberService.save(storeMemberList);
                        if(save>0){
                            //然后创建卡包信息
                            RechargeAccount rechargeAccount = new RechargeAccount();
                            rechargeAccount.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                            rechargeAccount.setMemberId(storeMemberList.getId());
                            rechargeAccount.setMemberName(storeMemberList.getMemberName());
                            rechargeAccount.setCard(storeMemberList.getCard());
                            rechargeAccount.setCardRechargeMoney(baseZengka1.getRechargeMoney());
                            rechargeAccount.setCardRestMoney(baseZengka1.getRechargeMoney());
                            rechargeAccount.setCardConsumeMoney(baseZengka1.getRechargeMoney());
                            rechargeAccount.setCardGiftMoney(BigDecimal.valueOf(0));
                            rechargeAccount.setGiftConsumeMoney(BigDecimal.valueOf(0));
                            rechargeAccount.setRechargeTypeId(baseZengka1.getRechargeTypeId());
                            rechargeAccount.setRechargeTypeNum(baseZengka1.getRechargeTypeNum());
                            rechargeAccount.setRechargeTypeName(baseZengka1.getRechargeTypeName());
                            rechargeAccount.setRechargeTypeName(baseZengka1.getRechargeTypeName());
                            rechargeAccount.setType(1);
                            rechargeAccount.setDiscount(baseZengka1.getDiscount());
                            rechargeAccount.setStoreId(baseZengka1.getStoreId());
                            rechargeAccount.setStoreName(baseZengka1.getStoreName());
                            rechargeAccount.setState(1);
                            rechargeAccount.setEndTime(baseZengka1.getExpireDate());
                            rechargeAccount.setEndTime(baseZengka1.getExpireDate());
                            int save1 = ssmRechargeAccountService.save(rechargeAccount);
                            if(save1>0){
                                zengkaIssue.setAccountId(rechargeAccount.getId());
                                zengkaIssue.setState(1);
                                int i = ssmBaseZengkaIssueService.updateNotNull(zengkaIssue);
                                if(i==0){
                                    throw new SmsException(ResponseCode.MSG,"审核失败");
                                }
                            }else{
                                throw new SmsException(ResponseCode.MSG,"添加会员卡包失败");
                            }
                        }else{
                            throw new SmsException(ResponseCode.MSG,"添加会员失败");
                        }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"审核失败");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许审核");
            }
        }else if(baseZengkaRequest.getState() == 4) {//反审核
            if(baseZengka1.getState()==3){
                baseZengka1.setState(baseZengkaRequest.getState());
                if (templateRedisClient.hasKey(getKey(key))){
                    StaffResponse staffResponse = templateRedisClient.get(getKey(key));
                    baseZengka1.setAuditBy(null);
                    baseZengka1.setAuditDate(null);
                }
                update = dao.updateByPrimaryKey(baseZengka1);
                if(update>0){
                    BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
                    baseZengkaIssue.setZengkaId(baseZengka1.getId());
                    baseZengkaIssue.setStoreId(baseZengka1.getStoreId());
                    List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
                    for (BaseZengkaIssue zengkaIssue : select) {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setId(zengkaIssue.getAccountId());
                        RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectOne(rechargeAccount);
                        if(rechargeAccount1.getCardRestMoney().compareTo(baseZengka1.getRechargeMoney())!=0){
                            throw new SmsException(ResponseCode.MSG,"赠卡账户存在已经消费账户，不能反审核");
                        }else{
                            int yyyy = 2022;
                            int date = 6;
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
                            try {
                                Date parse = simpleDateFormat.parse(yyyy+"-0"+date);
                                while (parse.before(new Date())){
                                    AccountTradeRecordRequest accountTradeRecord = new AccountTradeRecordRequest();
                                    accountTradeRecord.setAccountId(rechargeAccount1.getId());
                                    accountTradeRecord.setInputDate(parse);
                                    List<AccountTradeRecord> accountTradeRecords = ssmAccountTradeRecordService.selectList(accountTradeRecord);
                                    if(accountTradeRecords.size()>0){
                                        throw new SmsException(ResponseCode.MSG,"赠卡账户存在交易记录，不能反审核");
                                    }
                                    date++;
                                    if(date>12){
                                        date=1;
                                        yyyy++;
                                    }
                                    if(date>9){
                                        parse = simpleDateFormat.parse(yyyy+"-"+date);
                                    }else{
                                        parse = simpleDateFormat.parse(yyyy+"-0"+date);
                                    }
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                        }


                    }

                    for (BaseZengkaIssue zengkaIssue : select) {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setId(zengkaIssue.getAccountId());
                        RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectOne(rechargeAccount);
                        if(rechargeAccount1.getCardRestMoney().compareTo(baseZengka1.getRechargeMoney())==0){
                            int i = ssmRechargeAccountService.deleteByPrimaryKey(rechargeAccount1.getId());
                            if(i>0){
                                StoreMemberList storeMemberList = new StoreMemberList();
                                storeMemberList.setId(rechargeAccount1.getMemberId());
                                int i1 = ssmStoreMemberService.deleteByPrimaryKey(storeMemberList.getId());
                                if(i1>0){
                                    zengkaIssue.setAccountId(null);
                                    zengkaIssue.setState(0);
                                    int i2 = ssmBaseZengkaIssueService.updateByPrimaryKey(zengkaIssue);
                                    if(i2==0){
                                        throw new SmsException(ResponseCode.MSG,"审核失败");
                                    }
                                }
                            }
                        }else{
                            throw new SmsException(ResponseCode.MSG,"赠卡账户存在已经消费账户，不能反审核");
                        }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"反审核失败");
                }

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

        return update;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateState1(BaseZengkaRequest baseZengkaRequest, String key,Long storeId) throws SmsException {
        int update=0;
        BaseZengka baseZengka = new BaseZengka();

        baseZengka.setId(baseZengkaRequest.getId());
        BaseZengka baseZengka1 = dao.selectByPrimaryKey(baseZengka.getId());

        if (templateRedisClient.hasKey(getKey(key))){
            StaffResponse staffResponse = templateRedisClient.get(getKey(key));
            baseZengka1.setUpdateBy(staffResponse.getStaffName());
            baseZengka1.setUpdateDate(new Date());
        }

        if(baseZengkaRequest.getState()==1){
            //送审
            BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
            baseZengkaIssue.setZengkaId(baseZengka1.getId());
            baseZengkaIssue.setStoreId(baseZengka1.getStoreId());
            List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
            for (BaseZengkaIssue zengkaIssue : select) {
                if(null == zengkaIssue.getMemberCard()){
                    throw new SmsException(ResponseCode.MSG,"会员卡号还没有填完，不能送审");
                }
            }
            if(baseZengka1.getState()==0 || baseZengka1.getState() == 2 || baseZengka1.getState() == 4){
                baseZengka1.setState(baseZengkaRequest.getState());
                update = dao.updateByPrimaryKeySelective(baseZengka1);
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许送审");
            }
        }else if(baseZengkaRequest.getState()==2){//回收
            if(baseZengka1.getState()==1){
                baseZengka1.setState(baseZengkaRequest.getState());
                update = dao.updateByPrimaryKeySelective(baseZengka1);
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许回收");
            }
        }else if(baseZengkaRequest.getState()==3){//审核
            if(baseZengka1.getState()==1){
                baseZengka1.setState(baseZengkaRequest.getState());
                if (templateRedisClient.hasKey(getKey(key))){
                    StaffResponse staffResponse = templateRedisClient.get(getKey(key));
                    baseZengka1.setAuditBy(staffResponse.getStaffName());
                    baseZengka1.setAuditDate(new Date());
                }
                update = dao.updateByPrimaryKeySelective(baseZengka1);
                if(update>0){
                    BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
                    baseZengkaIssue.setZengkaId(baseZengka1.getId());
                    baseZengkaIssue.setStoreId(baseZengka1.getStoreId());
                    List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
                    for (BaseZengkaIssue zengkaIssue : select) {
                        RechargeType rechargeType = new RechargeType();
                        rechargeType.setId(baseZengka1.getRechargeTypeId());
                        rechargeType = ssmRechargeTypeSevice.selectOne(rechargeType);

                        StoreRequest storeRequest = new StoreRequest();
                        BaseStores baseStores = new BaseStores();
                        storeRequest.setId(baseZengka1.getStoreId());
                        List<BaseStores> pagesorganizations = ssmBaseStoreService.pagesorganizations(storeRequest);
                        for (BaseStores pagesorganization : pagesorganizations) {
                            if(null == pagesorganization.getParentId()){
                                BeanUtils.copyProperties(pagesorganization,storeRequest);
                            }
                            if(baseZengka1.getStoreId().equals(pagesorganization.getId())){
                                BeanUtils.copyProperties(pagesorganization,baseStores);
                            }
                        }
                        //查询会员是否存在
//                        String memberCard = zengkaIssue.getMemberCard();//会员手机号
                        StoreMemberList storeMemberList = new StoreMemberList();
                        storeMemberList.setMobilePhone(AESUtils.encrypt(zengkaIssue.getMemberCard()));
                        storeMemberList = ssmStoreMemberService.selectOne(storeMemberList);
                        //如果会员号为空或者id为空就说明没有数据
                        if(storeMemberList ==null || storeMemberList.getMemberNum()==null || storeMemberList.getId()==null){
                                //创建会员会员手机号码 以9+折扣+00+卡号
                                storeMemberList = new StoreMemberList();
                                storeMemberList.setStoreId(storeId);
                                storeMemberList.setStoreName(storeRequest.getStoreName());

                                storeMemberList.setConnStoreId(baseStores.getId());
                                storeMemberList.setConnStoreName(baseStores.getStoreName());
                                storeMemberList.setMemberStoreId(baseStores.getId());
                                storeMemberList.setMemberStoreName(baseStores.getStoreName());
                                storeMemberList.setMemberStoreNum(baseStores.getStoreNum());

//                                String regEx= "[^0-9]" ;
//                                Pattern p = Pattern.compile(regEx);
//                                Matcher m = p.matcher(zengkaIssue.getMemberCard());
                                String trim = zengkaIssue.getMemberCard();
                            StoreParament storeParament = new StoreParament();
                            BaseStore baseStore = ssmBaseStoreService.selectByPrimaryKey(storeId);
                            if(baseStore.getParentId()==null){
                                storeParament.setStoreId(baseStore.getId());
                            }else {
                                BaseStore baseStore1 = ssmBaseStoreService.selectByPrimaryKey(baseStore.getParentId());
                                storeParament.setStoreId(baseStore1.getId());
                            }
                            storeParament.setParamentName("gifCardPassword");
                            StoreParament storeParament1 = ssmStoreParaService.selectOne(storeParament);
                            storeMemberList.setMobilePhone(AESUtils.encrypt(trim));
//                        storeMemberList.setMobilePhone(AESUtils.encrypt(zengkaIssue.getMemberCard()));
                            if(AESUtils.encrypt(storeParament1.getParamentValue())==null){
                                throw new SmsException(ResponseCode.MSG,"本门店没有设置赠卡初始密码，请前往总店为该门店设置赠卡初始密码");
                            }
                                storeMemberList.setCashPassword(AESUtils.encrypt(storeParament1.getParamentValue()));
                                storeMemberList.setPassword(AESUtils.encrypt(zengkaIssue.getMemberCard()));
//                                storeMemberList.setCashPassword(AESUtils.encrypt(zengkaIssue.getMemberCard()));
                                storeMemberList.setMemberNum(zengkaIssue.getMemberNum());
                                storeMemberList.setMemberName(zengkaIssue.getMemberNum());
                                storeMemberList.setCard(zengkaIssue.getMemberCard());
                                storeMemberList.setState(1);
                                storeMemberList.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                                int save = ssmStoreMemberService.save(storeMemberList);
                                if(save==0){
                                    throw new SmsException(ResponseCode.MSG,"添加会员失败");
                                }
                            }
                                //然后创建卡包信息
                                RechargeAccount rechargeAccount = new RechargeAccount();
                                rechargeAccount.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());
                                rechargeAccount.setMemberId(storeMemberList.getId());
                                rechargeAccount.setMemberName(storeMemberList.getMemberName());
                                rechargeAccount.setCard(storeMemberList.getCard());
                                rechargeAccount.setCardRechargeMoney(baseZengka1.getRechargeMoney());
                                rechargeAccount.setCardRestMoney(baseZengka1.getRechargeMoney());
                                rechargeAccount.setCardConsumeMoney(baseZengka1.getRechargeMoney());
                                rechargeAccount.setCardGiftMoney(BigDecimal.valueOf(0));
                                rechargeAccount.setGiftConsumeMoney(BigDecimal.valueOf(0));
                                rechargeAccount.setRechargeTypeId(baseZengka1.getRechargeTypeId());
                                rechargeAccount.setRechargeTypeNum(baseZengka1.getRechargeTypeNum());
                                rechargeAccount.setRechargeTypeName(baseZengka1.getRechargeTypeName());
                                rechargeAccount.setRechargeTypeName(baseZengka1.getRechargeTypeName());
                                rechargeAccount.setType(1);
                                rechargeAccount.setDiscount(baseZengka1.getDiscount());
                                rechargeAccount.setStoreId(baseZengka1.getStoreId());
                                rechargeAccount.setStoreName(baseZengka1.getStoreName());
                                rechargeAccount.setState(1);
                                rechargeAccount.setEndTime(baseZengka1.getExpireDate());
                                rechargeAccount.setEndTime(baseZengka1.getExpireDate());
                                int save1 = ssmRechargeAccountService.save(rechargeAccount);
                                if(save1>0){
                                    zengkaIssue.setAccountId(rechargeAccount.getId());
                                    zengkaIssue.setState(1);
                                    int i = ssmBaseZengkaIssueService.updateNotNull(zengkaIssue);
                                    //审核成功给会员交易表插入数据
                                    //添加赠卡记录
                                    AccountTradeRecord accountTradeRecord = new AccountTradeRecord();
                                    accountTradeRecord.setId(new SnowflakeUtil(new Random().nextInt(1023)).nextId());//交易记录id
                                    accountTradeRecord.setStoreId(storeId);//门店id
                                    accountTradeRecord.setMemberId(storeMemberList.getId());//会员id
                                    accountTradeRecord.setStoreName(rechargeAccount.getStoreName());//门店名字
                                    accountTradeRecord.setMemberName(storeMemberList.getMemberName());//会员名字
                                    if(zengkaIssue.getMemberCard().trim().length()>11){
                                        throw new SmsException(ResponseCode.MSG, zengkaIssue.getMemberCard().trim()+"手机号超过了11位");
                                    }
                                    accountTradeRecord.setTradeId(rechargeAccount.getRechargeTypeId());
                                    accountTradeRecord.setTradeName(rechargeAccount.getRechargeTypeName());
                                    accountTradeRecord.setTradeMoney(rechargeAccount.getCardRestMoney());
                                    accountTradeRecord.setMemberPhone(zengkaIssue.getMemberCard().trim());//会员手机号
//                                    accountTradeRecord.setMemberIdentity();//身份证
                                    accountTradeRecord.setAccountId(rechargeAccount.getId());//账户id
                                    accountTradeRecord.setAccountName("促销赠卡");//账户名字
                                    accountTradeRecord.setAccountRestMoney(rechargeAccount.getCardRestMoney());//剩余金额
                                    accountTradeRecord.setAccountConsumeMoney(rechargeAccount.getCardConsumeMoney());//可用金额
                                    accountTradeRecord.setIsAddition(0);//是否补单
                                    accountTradeRecord.setInputBy(baseZengka1.getUpdateBy());//当前登录的电话
                                    accountTradeRecord.setOrderStatu(0);//单据状态
//                                    accountTradeRecord.setAccountConsumeCount(10);//卡的剩余可用次数
                                    accountTradeRecord.setAccountType("zengka");//交易类型为赠卡
                                    accountTradeRecord.setInputDate(new Date());
                                    ssmAccountTradeRecordService.addRecord(accountTradeRecord);
                                    if(i==0){
                                        throw new SmsException(ResponseCode.MSG,"审核失败");
                                    }
                                }else {
                                    throw new SmsException(ResponseCode.MSG, "添加会员卡包失败");
                                }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"审核失败");
                }
            }else{
                throw new SmsException(ResponseCode.MSG,"当前状态不允许审核");
            }
        }else if(baseZengkaRequest.getState() == 4) {//反审核
            if(baseZengka1.getState()==3){
                baseZengka1.setState(baseZengkaRequest.getState());
                if (templateRedisClient.hasKey(getKey(key))){
                    StaffResponse staffResponse = templateRedisClient.get(getKey(key));
                    baseZengka1.setAuditBy(null);
                    baseZengka1.setAuditDate(null);
                }
                update = dao.updateByPrimaryKey(baseZengka1);
                if(update>0){
                    BaseZengkaIssue baseZengkaIssue = new BaseZengkaIssue();
                    baseZengkaIssue.setZengkaId(baseZengka1.getId());
                    baseZengkaIssue.setStoreId(baseZengka1.getStoreId());
                    List<BaseZengkaIssue> select = ssmBaseZengkaIssueService.select(baseZengkaIssue);
                    for (BaseZengkaIssue zengkaIssue : select) {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setId(zengkaIssue.getAccountId());
                        RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectOne(rechargeAccount);
                        if(rechargeAccount1.getCardRestMoney().compareTo(baseZengka1.getRechargeMoney())!=0){
                            throw new SmsException(ResponseCode.MSG,"赠卡账户存在已经消费账户，不能反审核");
                        }else{
                            int yyyy = 2022;
                            int date = 6;
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM");
                            try {
                                Date parse = simpleDateFormat.parse(yyyy+"-0"+date);
                                while (parse.before(new Date())){
                                    AccountTradeRecordRequest accountTradeRecord = new AccountTradeRecordRequest();
                                    accountTradeRecord.setAccountId(rechargeAccount1.getId());
                                    accountTradeRecord.setInputDate(parse);
                                    List<AccountTradeRecord> accountTradeRecords = ssmAccountTradeRecordService.selectList(accountTradeRecord);
                                    if(accountTradeRecords.size()>0){
                                        throw new SmsException(ResponseCode.MSG,"赠卡账户存在交易记录，不能反审核");
                                    }
                                    date++;
                                    if(date>12){
                                        date=1;
                                        yyyy++;
                                    }
                                    if(date>9){
                                        parse = simpleDateFormat.parse(yyyy+"-"+date);
                                    }else{
                                        parse = simpleDateFormat.parse(yyyy+"-0"+date);
                                    }
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                        }


                    }

                    for (BaseZengkaIssue zengkaIssue : select) {
                        RechargeAccount rechargeAccount = new RechargeAccount();
                        rechargeAccount.setId(zengkaIssue.getAccountId());
                        RechargeAccount rechargeAccount1 = ssmRechargeAccountService.selectOne(rechargeAccount);
                        if(rechargeAccount1.getCardRestMoney().compareTo(baseZengka1.getRechargeMoney())==0){
                            int i = ssmRechargeAccountService.deleteByPrimaryKey(rechargeAccount1.getId());
                            if(i>0){
                                StoreMemberList storeMemberList = new StoreMemberList();
                                storeMemberList.setId(rechargeAccount1.getMemberId());
                                int i1 = ssmStoreMemberService.deleteByPrimaryKey(storeMemberList.getId());
                                if(i1>0){
                                    zengkaIssue.setAccountId(null);
                                    zengkaIssue.setState(0);
                                    int i2 = ssmBaseZengkaIssueService.updateByPrimaryKey(zengkaIssue);
                                    if(i2==0){
                                        throw new SmsException(ResponseCode.MSG,"审核失败");
                                    }
                                }
                            }
                        }else{
                            throw new SmsException(ResponseCode.MSG,"赠卡账户存在已经消费账户，不能反审核");
                        }
                    }
                }else{
                    throw new SmsException(ResponseCode.MSG,"反审核失败");
                }

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

        return update;
    }


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

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