package com.xueyi.system.notice.controller.api;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xueyi.common.core.web.result.R;
import com.xueyi.common.redis.service.RedisService;
import com.xueyi.common.sms.configure.SmsProperties;
import com.xueyi.common.sms.service.SmsService;
import com.xueyi.system.api.sms.domain.vo.SmsReqCodeEntity;
import com.xueyi.system.api.sms.domain.vo.SmsReqEntity;
import com.xueyi.system.api.sms.feign.RemoteSmsService;
import org.springframework.beans.factory.annotation.Autowired;
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;

/**
 * @author yk
 * @description
 * @date 2023-04-26 19:20
 */
@RestController
@RequestMapping(value = "/sms/api")
public class SmsApiController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RemoteSmsService remoteSmsService;

    @Autowired
    private SmsProperties smsProperties;

    @Autowired
    private RedisService redisService;

    /**
     * @Author yangkai
     * @Description //验证码发送接口
     * @Date 2023/4/26
     * @Param
     * @return
     **/
    @PostMapping("/send-code")
    public R<String> sendCode(@RequestBody SmsReqEntity smsReqEntity){
        String code = smsService.sendCode();

        if (StringUtils.isEmpty(smsReqEntity.getPhone())){
            return R.fail("手机号为空");
        } else {
            String cachedCode = redisService.getCacheObject("codes:phones:"+smsReqEntity.getPhone());
            if (StringUtils.isNotEmpty(cachedCode) && redisService.hasKey("codes:"+cachedCode)) {
                return R.fail("之前请求的验证码并未失效，禁止重复请求验证码");
            } else {
                redisService.setCacheObject("codes:phones:"+smsReqEntity.getPhone(), code);
            }

            smsReqEntity.setTemplate(smsProperties.getCodeTemplate());
            JSONObject map = new JSONObject();
            map.put("code", code);
            smsReqEntity.setDataMap(map.toJSONString());

            remoteSmsService.sendSms(smsReqEntity);
        }
        return R.ok();
    }


    /**
     * @Author yangkai
     * @Description //验证验证码
     * @Date 2023/4/26
     * @Param
     * @return
     **/
    @PostMapping("/confirm-code")
    public R<String> confirmCode(@RequestBody SmsReqCodeEntity entity){
        if (StringUtils.isEmpty(entity.getCode())){
            return R.fail("验证码为空");
        } else {
            Boolean valid = smsService.checkCode(entity.getCode());
            if (valid) {
                return R.ok();
            } else {
                return R.fail("验证码校验失败，请重试");
            }
        }

    }
}
