package com.qnfhq.modules.user.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qnfhq.common.exception.ErrorCode;
import com.qnfhq.common.exception.RenException;
import com.qnfhq.common.utils.MessageUtils;
import com.qnfhq.common.utils.Result;
import com.qnfhq.common.validator.AssertUtils;
import com.qnfhq.common.validator.ValidatorUtils;
import com.qnfhq.modules.user.entity.AppUserEntity;
import com.qnfhq.modules.user.dto.*;
import com.qnfhq.modules.user.service.AppUserService;
import com.qnfhq.modules.user.service.AppuserLoginLogService;
import com.qnfhq.modules.user.service.CaptchaService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;


/**
 * 注册接口
 * 登录接口
 * 退出接口
 * @author yelz
 */
@RestController
@RequestMapping("/user")
@Tag(name = "App用户接口")
public class ApiAppUserController {
    private static final Logger logger = LoggerFactory.getLogger(ApiAppUserController.class);

    @Resource
    private AppuserLoginLogService appuserLoginLogService;

    @Resource
    private AppUserService appUserService;

    @Resource
    private CaptchaService captchaService;


    /**
     * 邮箱+手机号码注册
     * @param dto
     * @param request
     * @return
     */
    @PostMapping("/register")
    @Operation(summary = "注册")
    public Result register(@RequestBody AppRegisterDTO dto, HttpServletRequest request) {
        ValidatorUtils.validateEntity(dto);
        return appUserService.register(dto,request);
    }



    @PostMapping("/login")
    @Operation(summary = "登录")
    public Result login(@RequestBody AppLoginDTO dto, HttpServletRequest request) {
        ValidatorUtils.validateEntity(dto);
        return appUserService.login(dto,request);
    }

    @GetMapping("/info")
    @Operation(summary = "登陆用户信息")
    public Result info() throws IOException {
        Result result = new Result();
        if(StpUtil.isLogin()) {
            Long userId = StpUtil.getLoginIdAsLong();
            logger.info("userId = {}", userId);
            AppUserEntity user = appUserService.getUserByUserId(userId);

            result.setMsg("success");
            result.setData(user);
            return result;
        } else {
            return result.error(MessageUtils.message("user.not.login.err"));//未登陆

        }
    }


    @PostMapping("/logout")
    @Operation(summary = "退出")
    public Result logout(HttpServletRequest request) {
        if(StpUtil.isLogin()) {
            Long userId = StpUtil.getLoginIdAsLong();
            StpUtil.logout(userId);
            AppUserEntity one = appUserService.getUserByUserId(userId);
            appuserLoginLogService.insertAppActionLog(one, "用户退出", "0", request);
        }
        return new Result();
    }



    @Operation(summary = "发送email通用验证码")
    @PostMapping("/sendEmailCode")
    public Result sendEmailCode(@RequestBody SendEmailCodeDTO sendCodeDTO) {

        ValidatorUtils.validateEntity(sendCodeDTO);

        return appUserService.sendEmailCode(sendCodeDTO.getCodeType(),sendCodeDTO.getEmail());

    }


    @Operation(summary = "发送手机通用验证码")
    @PostMapping("/sendMobileCode")
    public Result sendMobileCode (@RequestBody SendPhoneCodeDTO codeDTO){
        ValidatorUtils.validateEntity(codeDTO);
        return appUserService.sendMobileCode(codeDTO.getCodeType(),codeDTO.getPhone(),codeDTO.getZone());
    }


    @GetMapping("/captcha")
    @Operation(summary = "获取图形验证码")
    @Parameter(in = ParameterIn.QUERY, ref = "string", name = "uuid", required = true)
    public void captcha(HttpServletResponse response, String uuid) throws IOException {
        //唯一标识不能为空
        AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL);
        //生成验证码
        captchaService.create(response, uuid);
    }




    /**
     * 重置登陆密码 old
     *
     * @return
     */
//    @PostMapping("/resetPwdByEmail")
//    public Result resetPwdByEmail (@RequestBody ResetPwdByEmailDTO codeDTO){
//        ValidatorUtils.validateEntity(codeDTO);
//        return appUserService.resetPwdByEmail(codeDTO);
//    }

    /**
     * 重置登陆密码 old
     *
     * @return
     */
//    @PostMapping("/resetPwdByPhone")
//    public Result resetPwdByPhone (@RequestBody ResetPwdByPhoneDTO codeDTO){
//        ValidatorUtils.validateEntity(codeDTO);
//
//        return appUserService.resetPwdByPhone(codeDTO);
//    }


    @PostMapping("/checkCaptcha")
    @Operation(summary = "验证图形验证码")
    public Result checkCaptcha(@RequestBody CheckCaptchaDTO dto, HttpServletRequest request) {
        ValidatorUtils.validateEntity(dto);
        return appUserService.checkCaptcha(dto,request);
    }


    @Operation(summary = "验证手机验证码")
    @PostMapping("/checkPhoneCode")
    public Result checkPhoneCode (@RequestBody CheckPhoneCodeDTO dto){
        ValidatorUtils.validateEntity(dto);
        return appUserService.checkPhoneCode(dto.getCodeType(),dto.getZone(),dto.getPhone(),dto.getCode());
    }


    @Operation(summary = "验证邮箱验证码")
    @PostMapping("/checkEmailCode")
    public Result checkEmailCode (@RequestBody CheckEmailCodeDTO dto){
        ValidatorUtils.validateEntity(dto);
        return appUserService.checkEmailCode(dto.getCodeType(),dto.getEmail(),dto.getCode());
    }


    @Operation(summary = "按邮箱重置登陆密码")
    @PostMapping("/resetPwdEmail")
    public Result resetPwdEmail (@RequestBody ResetPwdEmailDTO dto){
        ValidatorUtils.validateEntity(dto);
        return appUserService.resetPwdByEmail(dto.getEmail(),dto.getNewPwd());
    }


    @Operation(summary = "按手机重置登陆密码")
    @PostMapping("/resetPwdPhone")
    public Result resetPwdPhone (@RequestBody ResetPwdPhoneDTO dto){
        ValidatorUtils.validateEntity(dto);
        return appUserService.resetPwdByPhone(dto.getZone(),dto.getPhone(),dto.getNewPwd());
    }
}
