package com.schisandra.auth.application.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Preconditions;
import com.schisandra.auth.application.convert.SchisandraAuthUserDTOConverter;
import com.schisandra.auth.application.dto.SchisandraAuthUserDTO;
import com.schisandra.auth.application.utils.CheckRouteCaptcha;
import com.schisandra.auth.common.entity.CaptchaResult;
import com.schisandra.auth.common.entity.Result;
import com.schisandra.auth.common.redis.RedisUtil;
import com.schisandra.auth.domain.bo.SchisandraAuthUserBO;
import com.schisandra.auth.domain.service.SchisandraAuthUserDomainService;
import com.schisandra.auth.infra.basic.entity.SchisandraAuthUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Objects;

/**
 * @Classname SchisandraAuthUserController
 * @BelongsProject: schisandra-cloud-storage
 * @BelongsPackage: com.schisandra.auth.application.controller
 * @Author: schisandra
 * @CreateTime: 2024-03-21  22:48
 * @Description: AuthUserController层
 * @Version: 1.0
 */
@RestController
@RequestMapping("/auth/user/")
@Slf4j
public class SchisandraAuthUserController {
    @Resource
    RedisUtil redisUtil;
    @Resource
    private SchisandraAuthUserDomainService schisandraAuthUserDomainService;

    private final String AUTH_PHONE_PREFIX = "auth.phone";

    @Resource
    CheckRouteCaptcha checkRouteCaptcha;

    /**
     * @description: 注册
     * @param: [schisandraAuthUserDTO]
     * @return: com.schisandra.auth.common.entity.Result
     * @author: landaiqing
     * @date: 2024/5/26 17:23
     */
    @PostMapping("register")
    public CaptchaResult register(@RequestBody SchisandraAuthUserDTO schisandraAuthUserDTO) {
        if (log.isInfoEnabled()) {
            log.info("UserController.register.dto:{}", JSON.toJSONString(schisandraAuthUserDTO));
        }
        if (schisandraAuthUserDTO.getPhone() == null) {
            log.error("UserController.register.phone is null");
            return null;
        }
        String token = schisandraAuthUserDTO.getToken();
        Double deg = schisandraAuthUserDTO.getDeg();
        CaptchaResult captchaResult = checkRouteCaptcha.checkCaptcha(token, deg);
        if (captchaResult.getCode() == 0) {
            SchisandraAuthUser schisandraAuthUser = schisandraAuthUserDomainService.queryByPhone(schisandraAuthUserDTO.getPhone());
            if (ObjectUtils.isNotEmpty(schisandraAuthUser)) {
                return CaptchaResult.failWithCode("该手机号已注册");
            } else {
                String key = redisUtil.buildKey(AUTH_PHONE_PREFIX, schisandraAuthUserDTO.getPhone());
                if (redisUtil.exist(key)) {
                    if (!Objects.equals(redisUtil.get(key), schisandraAuthUserDTO.getActiveCode())) {
                        return CaptchaResult.failWithCode("验证码错误，请重新验证");
                    }
                    try {
                        SchisandraAuthUserBO authUserBO = SchisandraAuthUserDTOConverter.INSTANCE.convertDTOToBO(schisandraAuthUserDTO);
                        if (schisandraAuthUserDomainService.register(authUserBO)) {
                            return CaptchaResult.ok("注册成功");
                        } else {
                            return CaptchaResult.failWithCode("注册失败");
                        }
                    } catch (Exception e) {
                        log.error("UserController.register.error:{}", e.getMessage(), e);
                        return CaptchaResult.failWithCode("注册用户失败");
                    }
                } else {
                    return CaptchaResult.failWithCode("验证码错误，请重新验证");
                }
            }
        }else{
            return CaptchaResult.fail();
        }
    }

    /**
     * @description: 用户登录
     * @param: [schisandraAuthUserDTO]
     * @return: com.schisandra.auth.common.entity.Result
     * @author: landaiqing
     * @date: 2024/5/31 1:19
     */
    @PostMapping("login")
    public CaptchaResult login(@RequestBody SchisandraAuthUserDTO schisandraAuthUserDTO) {

        if (schisandraAuthUserDTO.getDeg() == null && schisandraAuthUserDTO.getToken() == null) {
            return CaptchaResult.fail("验证失败！");
        }
        String token = schisandraAuthUserDTO.getToken();
        Double deg = schisandraAuthUserDTO.getDeg();
        CaptchaResult captchaResult = checkRouteCaptcha.checkCaptcha(token, deg);
        if (captchaResult.getCode() == 0) {
            HashMap<String, Object> map = new HashMap<>();
            SchisandraAuthUserBO schisandraAuthUserBO = SchisandraAuthUserDTOConverter.INSTANCE.convertDTOToBO(schisandraAuthUserDTO);
            SchisandraAuthUserBO login = schisandraAuthUserDomainService.login(schisandraAuthUserBO);
            SchisandraAuthUserDTO result = SchisandraAuthUserDTOConverter.INSTANCE.convertBOToDTO(login);
            map.put("user", result);
            if (login != null) {
                if (StpUtil.isLogin(result.getId())) {
                    StpUtil.logout(result.getId());
                    StpUtil.login(result.getId());
                    String userToken = StpUtil.getTokenValueByLoginId(result.getId());
                    map.put("token", userToken);
                    return CaptchaResult.ok(map);
                } else {
                    StpUtil.login(result.getId());
                    return CaptchaResult.ok(result);
                }
            } else {
                return CaptchaResult.failWithCode();
            }
        } else {
            return CaptchaResult.fail();
        }
    }

    /**
     * @description: 通过手机号判断用户是否注册过
     * @param: [phone]
     * @return: com.schisandra.auth.common.entity.Result<java.lang.String>
     * @author: landaiqing
     * @date: 2024/5/29 21:42
     */
    @PostMapping("isRegisterByPhone/{phone}")
    public Result<String> sendCode(@PathVariable("phone") String phone) {
        log.info("UserController.isRegisterByPhone.phone:{}", phone);
        Preconditions.checkNotNull(phone, "手机号不能为空");
        SchisandraAuthUser schisandraAuthUser = schisandraAuthUserDomainService.queryByPhone(phone);
        if (ObjectUtils.isEmpty(schisandraAuthUser)) {
            return null;
        }
        return Result.fail("该手机号已注册，请直接登录");
    }


}
