package com.zjrs.zwnw.auth.controller;

import com.zjrs.zwnw.auth.entity.FwOperator;
import com.zjrs.zwnw.auth.entity.FwOperatorMapper;
import com.zjrs.zwnw.auth.service.AuthRedisService;
import com.zjrs.zwnw.auth.util.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 认证控制器
 * 提供登录（/api/auth/password/login）和登出（/api/auth/logout）接口，
 * 对应原 leaf6-uni-cloud-auth 服务的核心功能。
 */
@RestController
public class AuthController {

    private static final Logger log = LoggerFactory.getLogger(AuthController.class);

    @Autowired
    private FwOperatorMapper fwOperatorMapper;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private AuthRedisService authRedisService;

    /**
     * 用户名密码登录接口 (支持 Form-Encoded)
     */
    @PostMapping(value = "/api/auth/password/login", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public Map<String, Object> loginForm(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            @RequestParam(value = "captcha", required = false) String captcha,
            @RequestParam(value = "reqid", required = false) String reqid,
            HttpServletRequest request) {
        return doLogin(username, password, captcha, request);
    }

    /**
     * 用户名密码登录接口 (支持 JSON)
     */
    @PostMapping(value = "/api/auth/password/login", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> loginJson(@RequestBody Map<String, String> body, HttpServletRequest request) {
        String username = body.get("username");
        String password = body.get("password");
        String captcha = body.get("captcha");
        return doLogin(username, password, captcha, request);
    }

    /**
     * 核心登录逻辑
     */
    private Map<String, Object> doLogin(String username, String password, String captcha, HttpServletRequest request) {
        log.info("[Auth] 用户 {} 发起登录请求", username);

        if (username == null || username.isEmpty()) {
            throw new org.springframework.web.server.ResponseStatusException(
                    org.springframework.http.HttpStatus.BAD_REQUEST, "用户名不能为空");
        }

        // 1. 查询用户
        FwOperator operator = fwOperatorMapper.selectByLoginId(username);
        if (operator == null) {
            log.warn("[Auth] 登录失败：用户 {} 不存在", username);
            throw new org.springframework.web.server.ResponseStatusException(
                    org.springframework.http.HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }

        // 2. 验证状态
        if (!"1".equals(operator.getAae100())) {
            log.warn("[Auth] 登录失败：用户 {} 已被禁用", username);
            throw new org.springframework.web.server.ResponseStatusException(
                    org.springframework.http.HttpStatus.UNAUTHORIZED, "用户已被禁用");
        }

        // 3. 验证密码
        if (!checkPassword(password, operator.getPassword(), operator.getPwencrypt())) {
            log.warn("[Auth] 登录失败：用户 {} 密码错误", username);
            throw new org.springframework.web.server.ResponseStatusException(
                    org.springframework.http.HttpStatus.UNAUTHORIZED, "用户名或密码错误");
        }

        // 4. 生成 JWT Token
        String token = jwtUtil.generateToken(
                operator.getLoginid(),
                operator.getOpername(),
                operator.getOperid(),
                operator.getOperunitid());

        // 5. 将用户信息存入 Redis
        String userId = operator.getSguserid();
        if (!StringUtils.hasText(userId)) {
            userId = operator.getOperid();
        }
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", userId);
        userInfo.put("loginId", operator.getLoginid());
        userInfo.put("userName", operator.getOpername());
        userInfo.put("operunitid", operator.getOperunitid());
        userInfo.put("bae001", operator.getBae001());
        userInfo.put("opertype", operator.getOpertype());
        authRedisService.saveToken(token, userInfo, jwtUtil.getExpireSeconds());

        // 6. 返回前端期望的格式
        Map<String, Object> result = new HashMap<>();
        Map<String, Object> mapData = new HashMap<>();
        mapData.put("Access-Token", token);
        mapData.put("msg", "登录成功");
        result.put("map", mapData);

        log.info("[Auth] 用户 {} 登录成功", username);
        return result;
    }

    /**
     * 登出接口：清除 Redis 中的 Token
     * GET /api/auth/logout
     */
    @GetMapping("/api/auth/logout")
    public Map<String, Object> logout(HttpServletRequest request) {
        String token = request.getHeader("Access-Token");
        if (token != null && !token.isEmpty()) {
            authRedisService.deleteToken(token);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", "200");
        result.put("msg", "退出成功");
        return result;
    }

    /**
     * 校验密码
     *
     * @param inputPwd  用户输入的明文密码
     * @param dbPwd     数据库中存储的密码
     * @param pwEncrypt 加密标志：'0'-明文，'1'-MD5
     */
    private boolean checkPassword(String inputPwd, String dbPwd, String pwEncrypt) {
        if (dbPwd == null) {
            return false;
        }
        if ("1".equals(pwEncrypt)) {
            // MD5 验证
            String md5Input = DigestUtils.md5DigestAsHex(inputPwd.getBytes(StandardCharsets.UTF_8));
            return md5Input.equalsIgnoreCase(dbPwd);
        } else {
            // 明文比较（PWENCRYPT='0'）
            return inputPwd.equals(dbPwd);
        }
    }
}
