package com.ruoyi.credit.controller;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.credit.domain.EmployeeInfo;
import com.ruoyi.credit.domain.EmployeeLibrary;
import com.ruoyi.credit.dto.EmployeeRequestDTO;
import com.ruoyi.credit.service.IEmployeeManagerService;
import com.ruoyi.credit.util.EmployeeConverter;

/**
 * 员工管理Controller
 *
 * @author ruoyi
 * @date 2025-12-22
 */
@RestController
@RequestMapping("/credit/employee")
public class EmployeeManagerController extends BaseController {

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

    @Autowired
    private IEmployeeManagerService employeeManagerService;



    // ==================== 员工库管理 ====================
    /**
     * 创建员工库
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:add')")
    @Log(title = "员工库", businessType = BusinessType.INSERT)
    @PostMapping("/library")
    public AjaxResult createEmployeeLibrary(@RequestBody CreateLibraryRequest request) {
        EmployeeLibrary library = employeeManagerService.createEmployeeLibrary(
                request.getCompanyId(), request.getLibraryName(), request.getDescription());
        return success(library);
    }

    /**
     * 查询员工库列表
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:list')")
    @GetMapping("/library")
    public TableDataInfo getEmployeeLibraryList(EmployeeLibrary employeeLibrary) {
        startPage();
        List<EmployeeLibrary> list = employeeManagerService.selectEmployeeLibraryList(employeeLibrary);
        return getDataTable(list);
    }

    /**
     * 获取员工库详细信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:query')")
    @GetMapping("/library/{libraryId}")
    public AjaxResult getEmployeeLibraryInfo(@PathVariable("libraryId") Long libraryId) {
        return success(employeeManagerService.selectEmployeeLibraryByLibraryId(libraryId));
    }

    /**
     * 根据公司ID获取员工库
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:query')")
    @GetMapping("/library/company/{companyId}")
    public AjaxResult getEmployeeLibraryByCompanyId(@PathVariable("companyId") Long companyId) {
        return success(employeeManagerService.selectEmployeeLibraryByCompanyId(companyId));
    }

    /**
     * 修改员工库
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:edit')")
    @Log(title = "员工库", businessType = BusinessType.UPDATE)
    @PutMapping("/library")
    public AjaxResult updateEmployeeLibrary(@RequestBody EmployeeLibrary employeeLibrary) {
        return toAjax(employeeManagerService.updateEmployeeLibrary(employeeLibrary));
    }

    /**
     * 删除员工库
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:remove')")
    @Log(title = "员工库", businessType = BusinessType.DELETE)
    @DeleteMapping("/library/{libraryId}")
    public AjaxResult deleteEmployeeLibrary(@PathVariable Long libraryId) {
        try {
            return toAjax(employeeManagerService.deleteEmployeeLibraryByLibraryId(libraryId));
        } catch (RuntimeException e) {
            log.error("删除员工库失败: libraryId={}, error={}", libraryId, e.getMessage());
            return error(e.getMessage());
        }
    }

    // ==================== 员工信息管理 ====================
    /**
     * 批量导入ERP格式的员工数据
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:import')")
    @Log(title = "员工信息", businessType = BusinessType.IMPORT)
    @PostMapping("/import")
    public AjaxResult importEmployees(@RequestParam("file") MultipartFile file,
            @RequestParam("libraryId") Long libraryId,
            @RequestParam(value = "format", defaultValue = "EXCEL") String format) {
        Map<String, Object> result = employeeManagerService.importEmployeesFromERP(file, libraryId, format);
        return success(result);
    }

    /**
     * 创建员工信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:add')")
    @Log(title = "员工信息", businessType = BusinessType.INSERT)
    @PostMapping("")
    public AjaxResult createEmployee(@RequestBody EmployeeRequestDTO employeeRequestDTO) {
        // 将DTO转换为实体类
        EmployeeInfo employeeInfo = EmployeeConverter.convertToEntity(employeeRequestDTO);
        return toAjax(employeeManagerService.createEmployee(employeeInfo));
    }

    /**
     * 查询员工信息列表
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:list')")
    @GetMapping("")
    public TableDataInfo getEmployeeInfoList(EmployeeInfo employeeInfo) {
        startPage();
        List<EmployeeInfo> list = employeeManagerService.selectEmployeeInfoList(employeeInfo);
        return getDataTable(list);
    }

    /**
     * 获取员工信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:query')")
    @GetMapping("/{employeeId}")
    public AjaxResult getEmployeeInfo(@PathVariable("employeeId") Long employeeId) {
        EmployeeInfo employeeInfo = employeeManagerService.selectEmployeeInfoByEmployeeId(employeeId);
        // 将实体类转换为DTO返回给前端
        EmployeeRequestDTO employeeDTO = EmployeeConverter.convertToDTO(employeeInfo);
        return success(employeeDTO);
    }

    /**
     * 根据员工库ID查询员工信息列表
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:list')")
    @GetMapping("/library/{libraryId}/employees")
    public AjaxResult getEmployeesByLibraryId(@PathVariable("libraryId") Long libraryId) {
        List<EmployeeInfo> employees = employeeManagerService.selectEmployeeInfosByLibraryId(libraryId);
        return success(employees);
    }

    /**
     * 根据岗位查询员工信息列表
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:list')")
    @GetMapping("/position/{position}")
    public AjaxResult getEmployeesByPosition(@PathVariable("position") String position) {
        List<EmployeeInfo> employees = employeeManagerService.selectEmployeeInfosByPosition(position);
        return success(employees);
    }

    /**
     * 修改员工信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:edit')")
    @Log(title = "员工信息", businessType = BusinessType.UPDATE)
    @PutMapping("")
    public AjaxResult updateEmployee(@RequestBody EmployeeRequestDTO employeeRequestDTO) {
        log.info("接收到员工更新请求: employeeId={}, name={}, monthlySalary={}, dailySalary={}, hourlySalary={}", 
                employeeRequestDTO.getEmployeeId(), employeeRequestDTO.getName(),
                employeeRequestDTO.getMonthlySalary(), employeeRequestDTO.getDailySalary(), employeeRequestDTO.getHourlySalary());
        
        // 将DTO转换为实体类
        EmployeeInfo employeeInfo = EmployeeConverter.convertToEntity(employeeRequestDTO);
        
        log.info("转换后的员工实体: employeeId={}, employeeName={}, monthlySalary={}, dailySalary={}, hourlySalary={}", 
                employeeInfo.getEmployeeId(), employeeInfo.getEmployeeName(),
                employeeInfo.getMonthlySalary(), employeeInfo.getDailySalary(), employeeInfo.getHourlySalary());
        
        return toAjax(employeeManagerService.updateEmployeeInfo(employeeInfo));
    }

    /**
     * 删除员工信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:remove')")
    @Log(title = "员工信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{employeeId}")
    public AjaxResult deleteEmployee(@PathVariable Long employeeId) {
        return toAjax(employeeManagerService.deleteEmployeeInfoByEmployeeId(employeeId));
    }

    /**
     * 添加临时员工
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:add')")
    @Log(title = "临时员工", businessType = BusinessType.INSERT)
    @PostMapping("/temporary")
    public AjaxResult addTemporaryEmployee(@RequestBody AddTemporaryEmployeeRequest request) {
        return toAjax(employeeManagerService.addTemporaryEmployee(request.getEmployeeInfo(), request.isSyncToLibrary()));
    }

    /**
     * 导出员工信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:export')")
    @Log(title = "员工信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void exportEmployees(HttpServletResponse response, EmployeeInfo employeeInfo) {
        List<EmployeeInfo> list = employeeManagerService.selectEmployeeInfoList(employeeInfo);
        ExcelUtil<EmployeeInfo> util = new ExcelUtil<>(EmployeeInfo.class);
        util.exportExcel(response, list, "员工信息数据");
    }

    // ==================== 员工信息管理 ====================
    // ==================== 员工批量操作 ====================
    /**
     * 批量修改员工信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:edit')")
    @Log(title = "员工信息", businessType = BusinessType.UPDATE)
    @PutMapping("/batch")
    public AjaxResult batchUpdateEmployees(@RequestBody BatchUpdateEmployeeRequest request) {
        log.info("批量修改员工信息: employeeIds={}, updateFields={}", 
                request.getEmployeeIds(), request.getUpdateFields());
        
        if (request.getEmployeeIds() == null || request.getEmployeeIds().isEmpty()) {
            return error("员工ID列表不能为空");
        }
        
        if (request.getUpdateFields() == null || request.getUpdateFields().isEmpty()) {
            return error("更新字段不能为空");
        }
        
        int successCount = employeeManagerService.batchUpdateEmployees(
                request.getEmployeeIds(), request.getUpdateFields());
        
        return success("成功修改 " + successCount + " 个员工信息");
    }

    /**
     * 批量删除员工信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:remove')")
    @Log(title = "员工信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch")
    public AjaxResult batchDeleteEmployees(@RequestBody BatchDeleteEmployeeRequest request) {
        log.info("批量删除员工信息: employeeIds={}", request.getEmployeeIds());
        
        if (request.getEmployeeIds() == null || request.getEmployeeIds().isEmpty()) {
            return error("员工ID列表不能为空");
        }
        
        int successCount = employeeManagerService.batchDeleteEmployees(request.getEmployeeIds());
        
        return success("成功删除 " + successCount + " 个员工");
    }

    /**
     * 批量转移员工到其他员工库
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:edit')")
    @Log(title = "员工信息", businessType = BusinessType.UPDATE)
    @PutMapping("/batch/transfer")
    public AjaxResult batchTransferEmployees(@RequestBody BatchTransferEmployeeRequest request) {
        log.info("批量转移员工: employeeIds={}, targetLibraryId={}", 
                request.getEmployeeIds(), request.getTargetLibraryId());
        
        if (request.getEmployeeIds() == null || request.getEmployeeIds().isEmpty()) {
            return error("员工ID列表不能为空");
        }
        
        if (request.getTargetLibraryId() == null) {
            return error("目标员工库ID不能为空");
        }
        
        int successCount = employeeManagerService.batchTransferEmployees(
                request.getEmployeeIds(), request.getTargetLibraryId());
        
        return success("成功转移 " + successCount + " 个员工到新的员工库");
    }

    // ==================== OCR和数据提取 ====================
    /**
     * 通过OCR提取员工相关信息
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:ocr')")
    @Log(title = "OCR提取", businessType = BusinessType.OTHER)
    @PostMapping("/ocr-extract")
    public AjaxResult extractEmployeeInfoFromOCR(@RequestParam("file") MultipartFile contractFile) {
        Map<String, Object> result = employeeManagerService.extractEmployeeInfoFromOCR(contractFile);
        return success(result);
    }

    /**
     * 验证员工数据完整性
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:validate')")
    @PostMapping("/validate")
    public AjaxResult validateEmployeeData(@RequestBody Map<String, Object> employeeData) {
        Map<String, Object> result = employeeManagerService.validateEmployeeData(employeeData);
        return success(result);
    }

    /**
     * 生成员工工号
     */
    @PreAuthorize("@ss.hasPermi('credit:employee:add')")
    @GetMapping("/generate-number/{libraryId}")
    public AjaxResult generateEmployeeNumber(@PathVariable("libraryId") Long libraryId) {
        String employeeNumber = employeeManagerService.generateEmployeeNumber(libraryId);
        return success(employeeNumber);
    }

    // ==================== 内部请求类 ====================
    public static class CreateLibraryRequest {

        private Long companyId;
        private String libraryName;
        private String description;

        public Long getCompanyId() {
            return companyId;
        }

        public void setCompanyId(Long companyId) {
            this.companyId = companyId;
        }

        public String getLibraryName() {
            return libraryName;
        }

        public void setLibraryName(String libraryName) {
            this.libraryName = libraryName;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }
    }

    public static class AddTemporaryEmployeeRequest {

        private EmployeeInfo employeeInfo;
        private boolean syncToLibrary;

        public EmployeeInfo getEmployeeInfo() {
            return employeeInfo;
        }

        public void setEmployeeInfo(EmployeeInfo employeeInfo) {
            this.employeeInfo = employeeInfo;
        }

        public boolean isSyncToLibrary() {
            return syncToLibrary;
        }

        public void setSyncToLibrary(boolean syncToLibrary) {
            this.syncToLibrary = syncToLibrary;
        }
    }

    public static class BatchUpdateEmployeeRequest {
        private List<Long> employeeIds;
        private Map<String, Object> updateFields;

        public List<Long> getEmployeeIds() {
            return employeeIds;
        }

        public void setEmployeeIds(List<Long> employeeIds) {
            this.employeeIds = employeeIds;
        }

        public Map<String, Object> getUpdateFields() {
            return updateFields;
        }

        public void setUpdateFields(Map<String, Object> updateFields) {
            this.updateFields = updateFields;
        }
    }

    public static class BatchDeleteEmployeeRequest {
        private List<Long> employeeIds;

        public List<Long> getEmployeeIds() {
            return employeeIds;
        }

        public void setEmployeeIds(List<Long> employeeIds) {
            this.employeeIds = employeeIds;
        }
    }

    public static class BatchTransferEmployeeRequest {
        private List<Long> employeeIds;
        private Long targetLibraryId;

        public List<Long> getEmployeeIds() {
            return employeeIds;
        }

        public void setEmployeeIds(List<Long> employeeIds) {
            this.employeeIds = employeeIds;
        }

        public Long getTargetLibraryId() {
            return targetLibraryId;
        }

        public void setTargetLibraryId(Long targetLibraryId) {
            this.targetLibraryId = targetLibraryId;
        }
    }

    public static class AssignEmployeeRequest {

        private Long employeeId;
        private String memberRole;

        public Long getEmployeeId() {
            return employeeId;
        }

        public void setEmployeeId(Long employeeId) {
            this.employeeId = employeeId;
        }

        public String getMemberRole() {
            return memberRole;
        }

        public void setMemberRole(String memberRole) {
            this.memberRole = memberRole;
        }
    }

    public static class BatchAssignEmployeeRequest {

        private List<Long> employeeIds;
        private String memberRole;

        public List<Long> getEmployeeIds() {
            return employeeIds;
        }

        public void setEmployeeIds(List<Long> employeeIds) {
            this.employeeIds = employeeIds;
        }

        public String getMemberRole() {
            return memberRole;
        }

        public void setMemberRole(String memberRole) {
            this.memberRole = memberRole;
        }

        @Override
        public String toString() {
            return "BatchAssignEmployeeRequest{"
                    + "employeeIds=" + employeeIds
                    + ", memberRole='" + memberRole + '\''
                    + '}';
        }
    }
}
