package jnpf.certificate.controller.app;

import jnpf.base.ActionResult;
import jnpf.certificate.service.CertificateAppReminderService;
import jnpf.model.certificate.req.app.CertificateAppBatchRemindReq;
import jnpf.model.certificate.req.app.CertificateAppSingleRemindReq;
import jnpf.util.UserProvider;
import jnpf.util.context.ThreadContext;
import lombok.RequiredArgsConstructor;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * App端证照提醒控制器。
 */
@RestController
@Validated
@RequestMapping("/app/certificate-reminder")
public class AppCertificateReminderController {

    /**
     * 证照提醒服务。
     */
    @Autowired
    private CertificateAppReminderService certificateAppReminderService;
    @Autowired
    private ThreadPoolTaskExecutor commonExecutor;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String REMIND_LOCK_KEY_PREFIX = "certificate-reminder:";

    /**
     * 一键提醒。
     *
     * @param req 提醒参数（主体类型）
     * @return 操作结果
     */
    @PostMapping("/batch-remind")
    public ActionResult<Void> batchRemind(@Validated @RequestBody CertificateAppBatchRemindReq req) {
        Boolean succ = stringRedisTemplate.opsForValue().setIfAbsent(buildRemindLockKey(),"1", 10, TimeUnit.SECONDS);
        if(Objects.isNull(succ) || !succ){
            return ActionResult.fail("操作太快了，请稍后在操作!");
        }
        //可能数据过多，但由于内部过滤数据，无法通过单独的线程执行，所以先暂时这样。
        certificateAppReminderService.batchRemind(req);
        return ActionResult.success();
    }

    /**
     * 单个提醒。
     *
     * @param req 提醒参数（证照实例ID）
     * @return 操作结果
     */
    @PostMapping("/single-remind")
    public ActionResult<Void> singleRemind(@Validated @RequestBody CertificateAppSingleRemindReq req) {
        Boolean succ = stringRedisTemplate.opsForValue().setIfAbsent(buildRemindLockKey(),"1", 10, TimeUnit.SECONDS);
        if(Objects.isNull(succ) || !succ){
            return ActionResult.fail("操作太快了，请稍后在操作!");
        }
        certificateAppReminderService.singleRemind(req);
        return ActionResult.success();
    }

    private String buildRemindLockKey() {
        String userId = UserProvider.getLoginUserId();
        return REMIND_LOCK_KEY_PREFIX + userId;
    }

}
