package com.philisense.www.api.repository.impl;

import com.alibaba.fastjson.JSONObject;
import com.philisense.www.api.repository.VcodeRepository;
import com.philisense.www.consts.ErrorConst;
import com.philisense.www.consts.VcodeKeys;
import com.philisense.www.enums.VcodeType;
import com.philisense.www.exception.UtilsException;
import com.philisense.www.properties.VcodeProperties;
import com.philisense.www.utils.RedisUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

public class RedisVcodeRepository implements VcodeRepository {

    @Resource
    private VcodeProperties vcodeProperties;
    @Resource
    private RedisUtils redisUtils;

    @Override
    public String save(ServletWebRequest request, Object vcodeValue, VcodeType type) {
        // 设置redis的key
        String key = "vcode_key_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        redisUtils.setExpire(VcodeKeys.REDIS_V_CODE + key, JSONObject.toJSONString(vcodeValue), vcodeProperties.getCodeExpiration());
        return key;
    }

    @Override
    public Object get(ServletWebRequest request, VcodeType type) {
        // 获取请求提交过来的key
        String key = request.getParameter("vcodeKey");
        if (StringUtils.isEmpty(key)) {
            throw new UtilsException("参数vcodeKey缺失");
        }
        if (Boolean.FALSE.equals(redisUtils.exists(VcodeKeys.REDIS_V_CODE + key))) {
            throw new UtilsException(type.getDesc() + "不存在或者已过期", ErrorConst.ERR_CODE);
        }
        return redisUtils.get(VcodeKeys.REDIS_V_CODE + key);
    }

    @Override
    public void remove(ServletWebRequest request, VcodeType type) {
        String key = request.getParameter("vcodeKey");
        if (StringUtils.isEmpty(key)) {
            throw new UtilsException("参数vcodeKey缺失");
        }
        if (Boolean.TRUE.equals(redisUtils.exists(VcodeKeys.REDIS_V_CODE + key))) {
            redisUtils.del(VcodeKeys.REDIS_V_CODE + key);
        }
    }
}
