package com.ecep.contract.ds.other.controller;

import java.util.Map;
import java.util.HashMap;

import jakarta.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ecep.contract.ds.other.service.EmployeeService;
import com.ecep.contract.model.Employee;
import com.ecep.contract.util.SecurityUtils;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/findById")
    public Employee findById(Integer id) {
        return employeeService.findById(id);
    }

    @RequestMapping("/list")
    public Page<Employee> list(
            Map<String, Object> params,
            @RequestParam(defaultValue = "0", name = "page") int pageNumber,
            @RequestParam(defaultValue = "10", name = "size") int pageSize) {
        Specification<Employee> spec = null;

        Sort sort = Sort.by(Sort.Order.desc("id"));
        Pageable pageable = PageRequest.of(pageNumber, pageSize, sort);
        return employeeService.findAll(spec, pageable);
    }

    @RequestMapping("/save")
    public Employee save(Employee employee) {
        return employeeService.save(employee);
    }

    @RequestMapping("/delete")
    public void delete(Integer id) {
        Employee employee = employeeService.findById(id);
        employeeService.delete(employee);
    }

    /**
     * 获取当前登录用户的信息
     * 包括employeeId和sessionId
     */
    @RequestMapping("/currentUser")
    public Map<String, Object> getCurrentUser(HttpSession session) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 获取当前登录用户
            User currentUser = SecurityUtils.getCurrentUser();
            if (currentUser != null) {
                // 根据用户名查找Employee对象
                Employee employee = employeeService.findByName(currentUser.getUsername());
                if (employee != null) {
                    result.put("employeeId", employee.getId());
                    result.put("sessionId", session.getId());
                    result.put("success", true);
                    return result;
                }
            }
        } catch (Exception e) {
            // 处理异常
        }
        
        // 如果获取失败，返回错误信息
        result.put("success", false);
        result.put("error", "无法获取当前用户信息");
        return result;
    }

}
