package com.miaxis.wx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.miaxis.wx.domain.WxForeverCode;
import com.miaxis.wx.mapper.WxForeverCodeMapper;
import com.miaxis.wx.service.IWxForeverCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Random;

/**
 * 微信永久二维码口令Service业务层处理
 *
 * @author miaxis
 * @date 2022-01-17
 */
@Service
public class WxForeverCodeServiceImpl extends ServiceImpl<WxForeverCodeMapper, WxForeverCode> implements IWxForeverCodeService {
    @Autowired
    private WxForeverCodeMapper wxForeverCodeMapper;

    /**
     * 查询微信永久二维码口令列表
     *
     * @param wxForeverCode 微信永久二维码口令
     * @return 微信永久二维码口令
     */
    @Override
    @Transactional
    public List<WxForeverCode> selectWxForeverCodeList(WxForeverCode wxForeverCode){
        List<WxForeverCode> wxForeverCodes = wxForeverCodeMapper.selectWxForeverCodeList(wxForeverCode);
        // 若目前无数据，则创建一个
        if (CollectionUtils.isEmpty(wxForeverCodes)){
            creatNewCode();
        }else{
            //查询未被使用的口令个数，如果等于0 ，创建一个
            long count = wxForeverCodes.stream().filter(o -> o.getOpenid() == null).count();
            if (count == 0l){
                creatNewCode();
            }
        }
        return wxForeverCodeMapper.selectWxForeverCodeList(wxForeverCode);
    }

    private void creatNewCode() {
        WxForeverCode newWxForeverCode = new WxForeverCode();
        String code = null ;
        do {
            code  = getRandomString(6);
        }while (isRepeat(code));
        newWxForeverCode.setCode(code);
        this.save(newWxForeverCode);
    }

    private boolean isRepeat(String code) {
        QueryWrapper<WxForeverCode> wrapper = new QueryWrapper<WxForeverCode>();
        wrapper.eq("code",code);
        WxForeverCode one = this.getOne(wrapper);
        return one!= null;
    }


    //length用户要求产生字符串的长度
    public static String getRandomString(int length){
        String str="abcdefghjkmnpqrstuvwxyz123456789";
        Random random=new Random();
        StringBuffer sb=new StringBuffer();
        int bound = str.length();
        for(int i=0;i<length;i++){
            int number=random.nextInt(bound);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Random random=new Random();
        for(int i =0 ;i <100;i++){
            System.out.println(random.nextInt(1));
        }
    }
}
