package com.ecep.contract.api.controller;

import static com.ecep.contract.SpringApp.getBean;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.ecep.contract.ds.other.service.EmployeeAuthBindService;
import com.ecep.contract.ds.other.service.EmployeeLoginHistoryService;
import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.model.Employee;
import com.ecep.contract.model.EmployeeAuthBind;
import com.ecep.contract.model.EmployeeLoginHistory;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.Data;

@RestController
@RequestMapping("/api")
public class LoginApiController {
    private static final Logger logger = LoggerFactory.getLogger(LoginApiController.class);

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmployeeAuthBindService employeeAuthBindService;

    /**
     * JSON格式的登录API
     * 使用Spring Security进行认证，返回JSON格式的响应
     */
    @PostMapping("/login")
    public Map<String, Object> jsonLogin(@RequestBody LoginRequest loginRequest, HttpServletRequest request) {
        // 获取HttpSession
        HttpSession session = request.getSession();

        // 添加日志记录，确认方法被调用
        logger.debug("jsonLogin方法被调用，请求类型: {}", loginRequest.getType());
        logger.debug("请求用户名: {}", loginRequest.getUsername());
        logger.debug("会话ID: {}", session != null ? session.getId() : "null");
        Map<String, Object> result = new HashMap<>();

        try {
            Employee employee = null;
            if ("client".equals(loginRequest.getType())) {
                // 根据用户名查找Employee对象
                employee = employeeService.findByAccount(loginRequest.getUsername());
                if (employee == null) {
                    result.put("success", false);
                    result.put("error", "用户信息不存在");
                    return result;
                }
                List<EmployeeAuthBind> authBinds = employeeAuthBindService.findAllByEmployee(employee, Sort.unsorted());
                if (authBinds.isEmpty()) {
                    result.put("success", false);
                    result.put("error", "用户未绑定认证信息");
                    return result;
                }

                EmployeeAuthBind matched = null;
                Map<String, String> signMap = loginRequest.getSign();
                if (signMap != null) {
                    for (EmployeeAuthBind authBind : authBinds) {
                        String clientIp = signMap.get(authBind.getMac());
                        if (clientIp != null && authBind.getIp().equals(clientIp)) {
                            matched = authBind;
                            break;
                        }
                    }
                }
                if (matched == null) {
                    result.put("success", false);
                    result.put("error", "认证信息错误");
                    return result;
                }
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(), "default123");

                // 使用AuthenticationManager进行认证
                Authentication authentication = authenticationManager.authenticate(authenticationToken);

                // 设置认证结果到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);
                session.setAttribute("ip", matched.getIp());
                session.setAttribute("mac", matched.getMac());

            } else {
                // 创建认证令牌
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(), loginRequest.getPassword());

                // 使用AuthenticationManager进行认证
                Authentication authentication = authenticationManager.authenticate(authenticationToken);

                // 设置认证结果到SecurityContext
                SecurityContextHolder.getContext().setAuthentication(authentication);

                employee = employeeService.findByAccount(loginRequest.getUsername());
            }

            if (employee != null) {
                // 获取当前登录用户
                User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
                // 返回登录成功的信息
                result.put("success", true);
                result.put("employeeId", employee.getId());
                result.put("sessionId", session.getId());
                result.put("username", employee.getAccount());
                result.put("roles", currentUser.getAuthorities());
                result.put("message", "登录成功");

                // 登录成功后，发送系统通知
                EmployeeLoginHistoryService employeeLoginHistoryService = getBean(EmployeeLoginHistoryService.class);
                EmployeeLoginHistory employeeLoginHistory = new EmployeeLoginHistory();
                employeeLoginHistory.setEmployee(employee);
                String userId = (String) session.getAttribute("ip");
                if (userId == null) {
                    userId = request.getRemoteAddr();
                }
                employeeLoginHistory.setIp(userId);
                employeeLoginHistory.setMac((String) session.getAttribute("mac"));
                employeeLoginHistory.setLoginTime(LocalDateTime.now());
                EmployeeLoginHistory saved = employeeLoginHistoryService.save(employeeLoginHistory);
                if (saved != null) {
                    session.setAttribute("loginHistoryId", saved.getId());
                }
                session.setAttribute("employeeId", employee.getId());
            } else {
                // 用户不存在
                result.put("success", false);
                result.put("error", "用户信息不存在");
            }

        } catch (AuthenticationException e) {
            // 认证失败
            result.put("success", false);
            result.put("error", "用户名或密码错误");
        } catch (Exception e) {
            // 其他错误
            result.put("success", false);
            result.put("error", "登录过程中发生错误: " + e.getMessage());
        }

        return result;
    }

    /**
     * 登录请求的JSON数据模型
     */
    @Data
    public static class LoginRequest {
        private String type;
        private String username;
        private String password;

        private Map<String, String> sign = new HashMap<>();

    }
}