package com.xueyi.system.staff.service.impl;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xueyi.common.web.entity.service.impl.BaseServiceImpl;
import com.xueyi.system.api.digitalmans.domain.dto.DmVisitRecordsDto;
import com.xueyi.system.staff.domain.query.DmVisitRecordsQuery;
import com.xueyi.system.staff.manager.IDmVisitRecordsManager;
import com.xueyi.system.staff.service.IDmVisitRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 访客管理 服务层处理
 *
 * @author xueyi
 */
@Service
public class DmVisitRecordsServiceImpl extends BaseServiceImpl<DmVisitRecordsQuery, DmVisitRecordsDto, IDmVisitRecordsManager> implements IDmVisitRecordsService {


    private static final int CODE_LENGTH = 4;
    private static final String REDIS_KEY_PREFIX = "visitor:verification_code:";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    public String generateCode() {
        /*try {
            Random random = SecureRandom.getInstanceStrong();
            StringBuilder codeBuilder = new StringBuilder(CODE_LENGTH);

            for (int i = 0; i < CODE_LENGTH; i++) {
                int digit = random.nextInt(10);
                codeBuilder.append(digit);
            }
            return codeBuilder.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }*/
        String timeStr = String.valueOf(System.currentTimeMillis());
        timeStr.substring(timeStr.length() - 4 );

        return timeStr.substring(timeStr.length() - 4 );
    }

    public boolean storeCode(String code) {
        String redisKey = REDIS_KEY_PREFIX + code;
        Boolean success = redisTemplate.opsForValue().setIfAbsent(redisKey, code, 1, TimeUnit.DAYS);
        return success != null && success;
    }

    /**
     * 查询访客对象列表 | 数据权限
     *
     * @param dmVisitRecords 访客对象
     * @return 访客对象集合
     */
    @Override
    //@DataScope(userAlias = "createBy", mapperScope = {"DmVisitRecordsMapper"})
    public List<DmVisitRecordsDto> selectListScope(DmVisitRecordsQuery dmVisitRecords) {
        return baseManager.selectList(dmVisitRecords);
    }

    public String  genVisitorCode(){
        String code = "";
        while (true) {
            code = generateCode();
            if (StringUtils.isNotEmpty(code) && storeCode(code)){
                return code;
            }
        }
    }


}