package com.bonus.sgzb.auth.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.bonus.sgzb.auth.utils.RsaUtil;
import com.bonus.sgzb.auth.form.*;
import com.bonus.sgzb.auth.service.NwRegisterService;
import com.bonus.sgzb.auth.service.NwUserLoginService;
import com.bonus.sgzb.common.core.constant.CacheConstants;
import com.bonus.sgzb.common.core.exception.ServiceException;
import com.bonus.sgzb.common.core.utils.GlobalConstants;
import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.common.redis.service.RedisService;
import com.bonus.sgzb.system.api.RemoteUserService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.bonus.sgzb.auth.service.SysLoginService;
import com.bonus.sgzb.common.core.domain.R;
import com.bonus.sgzb.common.core.utils.JwtUtils;
import com.bonus.sgzb.common.core.utils.StringUtils;
import com.bonus.sgzb.common.security.auth.AuthUtil;
import com.bonus.sgzb.common.security.service.TokenService;
import com.bonus.sgzb.common.security.utils.SecurityUtils;
import com.bonus.sgzb.system.api.model.LoginUser;

import java.util.Map;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
@Slf4j
public class TokenController {

    private final String USER_PASSWORD = "NwCc@2024*";

    private final String privateKey = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEAqhHyZfSsYourNxaY7Nt+PrgrxkiA50efORdI5U5lsW79MmFnusUA355oaSXcLhu5xxB38SMSyP2KvuKNPuH3owIDAQABAkAfoiLyL+Z4lf4Myxk6xUDgLaWGximj20CUf+5BKKnlrK+Ed8gAkM0HqoTt2UZwA5E2MzS4EI2gjfQhz5X28uqxAiEA3wNFxfrCZlSZHb0gn2zDpWowcSxQAgiCstxGUoOqlW8CIQDDOerGKH5OmCJ4Z21v+F25WaHYPxCFMvwxpcw99EcvDQIgIdhDTIqD2jfYjPTY8Jj3EDGPbH2HHuffvflECt3Ek60CIQCFRlCkHpi7hthhYhovyloRYsM+IS9h/0BzlEAuO0ktMQIgSPT3aFAgJYwKpqRYKlLDVcflZFCKY7u3UP8iWi1Qw0Y=";

    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Resource
    private RedisService redisService;

    @Resource
    private RemoteUserService remoteUserService;

    @Resource
    private NwUserLoginService nwUserLoginService;

    @Autowired
    private NwRegisterService registerService;

    /**
     * web端登录
     *
     * @param form
     * @return
     * @throws Exception
     */
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) throws Exception {
        //优先校验图形验证码
        String uuid = form.getUuid();
        Object cacheObject = redisService.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
        String captcha = cacheObject == null ? null : cacheObject.toString();
        // 获取后立即删除图形验证码缓存
        redisService.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
        if (StringUtils.isBlank(captcha)) {
            throw new ServiceException("图形验证码失效，请重新刷新获取");
        }
        if (form.getCode() != null && !form.getCode().equals(captcha)) {
            throw new ServiceException("图形验证码错误");
        }
        //根据用户名查询用户信息
        LoginUser user = sysLoginService.selectByName(form.getUsername());
        if (StringUtils.isNull(user)) {
            throw new ServiceException("用户名不存在/密码错误");
        }
        //获取查询的用户手机号
        String phone = user.getSysUser().getPhonenumber();
        if ("adminBns".equals(form.getUsername())) {
            if (!StringUtils.isNotBlank(phone)) {
                throw new ServiceException("手机号为空，请联系管理员！");
            }
            //管理员用户需要额外校验手机短信验证码
            String redisCode = redisService.getCacheObject("code_" + phone);
            if (StringUtils.isEmpty(redisCode)) {
                throw new ServiceException("短信验证码失效", 500);
            }
            if (!StringUtils.equals(redisCode.split(GlobalConstants.STRING_UNDERLINE)[0], form.getTextCode())) {
                throw new ServiceException("短信验证码错误", 500);
            }
        }
        String decryptedData = RsaUtil.decryptByPrivateKey(form.getPassword(), privateKey);
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), decryptedData);
        if (decryptedData.equals(USER_PASSWORD)) {
            userInfo.setCode(1);
        }
        if (form.getCode() != null && form.getCode().equals(captcha)) {
            redisService.deleteObject("code_" + phone);
            // 获取登录token
            return R.ok(tokenService.createToken(userInfo));
        } else {
            return R.fail("登录失败，请联系管理员！");
        }
    }

    /**
     * App端登录
     *
     * @param form
     * @return
     */
    @PostMapping("loginApp")
    public R<?> loginApp(@RequestBody LoginBody form) {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        if (userInfo != null) {
            userInfo.setLoginMethod("mobile");
            return R.ok(tokenService.createToken(userInfo));
        } else {
            return R.fail("登录信息为空，请重试");
        }
    }

    @PostMapping("sendCode")
    public R<?> sendCode(@RequestBody LoginBody form) {
        if ("adminBns".equals(form.getUsername())) {
            // 根据用户名查询用户信息
            LoginUser userInfo = sysLoginService.selectByName(form.getUsername());
            //获取查询的用户手机号
            String phone = userInfo.getSysUser().getPhonenumber();
            if (StringUtils.isBlank(phone)) {
                throw new ServiceException("手机号为空，请联系管理员！");
            }
            //图形验证码校验成功，发送短信
            R<Boolean> sendState = remoteUserService.sendCode(phone);
            return sendState;
        } else {
            String uuid = form.getUuid();
            String captcha = redisService.getCacheObject(CacheConstants.CAPTCHA_CODE_KEY + uuid).toString();
            if (StringUtils.isBlank(captcha)) {
                // 删除验证码缓存
                redisService.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
                return R.fail("验证码超时，请重新刷新");
            }
            if (form.getCode() != null && !form.getCode().equals(captcha)) {
                // 删除验证码缓存
                redisService.deleteObject(CacheConstants.CAPTCHA_CODE_KEY + uuid);
                return R.fail("验证码错误");
            }
            R<Boolean> sendState = remoteUserService.sendCode(form.getPhone());
            return sendState;
        }
    }

    @PostMapping("checkCode")
    public R<?> checkCode(@RequestBody LoginBody form) {
        // 校验验证码
        LoginUser loginUser = sysLoginService.loginCode(form.getPhone(), form.getCode());
        if (StringUtils.isNotNull(loginUser)) {
            loginUser.setLoginMethod("mobile");
            // 创建token
            Map<String, Object> tokenMap = tokenService.createToken(loginUser);
            return R.ok(tokenService.createToken(loginUser));
        } else {
            return R.fail(null, "验证码错误");
        }
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    //@PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody) {
        // 用户注册
        sysLoginService.register(registerBody);
        return R.ok(null, "注册成功");
    }

    @PostMapping("loginByMall")
    public R<?> loginByMall(@RequestBody LoginUser loginUser) {
        // 用户注册
        Map map = sysLoginService.loginByMall(loginUser);
        if ("1".equals(map.get("status").toString())) {
            return R.fail("登录用户未注册");
        } else if ("2".equals(map.get("login_user").toString())) {
            return R.fail("未携带token");
        }
        return R.ok(map);
    }

    @ApiOperation("微服务平台认证接口")
    @PostMapping(value = "/onlineApprove")
    public R<?> onlineApprove(@RequestBody AuthenticationLoginFrom loginForm) {
        if (loginForm == null || StringUtils.isBlank(loginForm.getType())) {
            return R.fail("参数异常");
        }
        try {
            return nwUserLoginService.onlineApprove(loginForm);
        } catch (Exception e) {
            log.error("微服务平台认证登陆 异常: ", e);
            return R.fail("微服务平台认证失败");
        }
    }


    @ApiOperation("用户中心注册")
    //@PostMapping("/registers")
    public AjaxResult registers(HttpServletRequest request, @RequestBody RegisterForms registerForms) {
        AccountRegister accountRegister = new AccountRegister();
        accountRegister.setCode(1);
        accountRegister.setDesc("个人用户注册");
        accountRegister.setRemark("个人用户注册");
        registerForms.setIsPersonal(accountRegister.getCode());
        return AjaxResult.success("success", registerService.registersNew(request, registerForms));
    }

}
