package com.liquidnet.service.adam.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liquidnet.common.cache.redis.util.RedisUtil;
import com.liquidnet.service.adam.constant.AdamRedisConst;
import com.liquidnet.service.adam.entity.AdamUserMember;
import com.liquidnet.service.adam.mapper.AdamMemberCodeMapper;
import com.liquidnet.service.adam.mapper.AdamUserMemberMapper;
import com.liquidnet.service.adam.service.IAdamUserMemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.MongoConverter;
import org.springframework.stereotype.Service;

import java.util.regex.Pattern;

@Slf4j
@Service
public class AdamUserMemberServiceImpl extends ServiceImpl<AdamUserMemberMapper, AdamUserMember> implements IAdamUserMemberService {

    @Autowired
    AdamUserMemberMapper adamUserMemberMapper;
    @Autowired
    AdamMemberCodeMapper adamMemberCodeMapper;
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    MongoConverter mongoConverter;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    RedisUtil redisUtil;

    @Override
    public void createUserMemberInfo(String memberId) {
        // todo  创建用户
        AdamUserMember userMember = new AdamUserMember();
        adamUserMemberMapper.insert(userMember);
        // 获取最大会员号
        getMaxMemberNo(memberId);
    }

    @Override
    public String getMaxMemberNo(String memberId) {
        String memberNoMaxKey = AdamRedisConst.MEMBER_MEMBER_NO_MAX_KEY.concat(memberId);
        Object maxNumber = redisUtil.get(memberNoMaxKey);

        if (null !=maxNumber) {
            maxNumber = maxNumber.toString();
            String newNumber = String.valueOf(redisUtil.incr(memberNoMaxKey, 1));
            Integer newNumberInt = newNumber.length() - 1;
            String pattern = "/([\\d])\\1{" + newNumberInt + "}/";
            if (Pattern.matches(pattern, newNumber)) {// 不能是完全相同的数字
                newNumber = String.valueOf(redisUtil.incr(memberNoMaxKey, 1));
            }
            return newNumber;
        } else {
            maxNumber = adamMemberCodeMapper.getMaxMemberNo(memberId);// 1000
            if (null != maxNumber) {
                redisUtil.set(memberNoMaxKey, maxNumber);
                redisUtil.incr(memberNoMaxKey, 1);
            }
            return redisUtil.get(memberNoMaxKey).toString();
        }
    }
}
