package com.fuyuanshen.app.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.util.RandomUtil;
import com.fuyuanshen.app.domain.dto.APPForgotPasswordDTO;
import com.fuyuanshen.app.domain.dto.APPForgotPasswordSmsDTO;
import com.fuyuanshen.app.domain.dto.APPUpdateUserDTO;
import com.fuyuanshen.app.domain.vo.APPUserInfoVo;
import com.fuyuanshen.app.service.IAppUserService;
import com.fuyuanshen.common.core.constant.Constants;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.domain.R;
import com.fuyuanshen.common.ratelimiter.annotation.RateLimiter;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.common.web.core.BaseController;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import org.dromara.sms4j.api.SmsBlend;
import org.dromara.sms4j.api.entity.SmsResponse;
import org.dromara.sms4j.core.factory.SmsFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.Duration;
import java.util.LinkedHashMap;

/**
 * APP 用户管理
 * @date 2025-06-27
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/app/user")
public class AppUserController extends BaseController {

    private final IAppUserService appUserService;

    /**
     * 个人中心
     */
    @GetMapping("/getUserInfo")
    public R<APPUserInfoVo> getUserInfo() {
        return R.ok(appUserService.getUserInfo());
    }

    /**
     * 修改个人信息
     */
    @PostMapping("/updateUser")
    public R<Void> updateUser(@Validated @ModelAttribute APPUpdateUserDTO bo) {
        return toAjax(appUserService.updateUser(bo));
    }

    /**
     * 忘记密码
     */
    @SaIgnore
    @PostMapping("/forgotPassword")
    public R<Void> forgotPassword(@RequestBody APPForgotPasswordDTO bo) {
        return toAjax(appUserService.forgotPassword(bo));
    }


    /**
     * 发送忘记密码短信
     *
     * @param phonenumber 用户手机号
     */
    @SaIgnore
    @RateLimiter(key = "#phonenumber", time = 60, count = 1)
    @GetMapping("/sendForgotPasswordSms")
    public R<Void> smsCode(@NotBlank(message = "{user.phonenumber.not.blank}") String phonenumber) {
        String key = GlobalConstants.APP_FORGOT_PASSWORD_SMS_KEY + phonenumber;
        String code = RandomUtil.randomNumbers(4);
        RedisUtils.setCacheObject(key, code, Duration.ofMinutes(Constants.CAPTCHA_EXPIRATION));
        // 验证码模板id 自行处理 (查数据库或写死均可)
        String templateId = "";
        LinkedHashMap<String, String> map = new LinkedHashMap<>(1);
        map.put("code", code);
        SmsBlend smsBlend = SmsFactory.getSmsBlend("config1");
        SmsResponse smsResponse = smsBlend.sendMessage(phonenumber, map);
        if (!smsResponse.isSuccess()) {
            return R.fail(smsResponse.getData().toString());
        }
        return R.ok();
    }
}
