package com.dora.service.impl;

import com.dora.dto.AdminEmployeeDto;
import com.dora.dto.ApiResponse;
import com.dora.entity.AdminUser;
import com.dora.mapper.AdminUserMapper;
import com.dora.service.AdminEmployeeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 管理员员工管理服务实现
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class AdminEmployeeServiceImpl implements AdminEmployeeService {

    private final AdminUserMapper adminUserMapper;
    private final PasswordEncoder passwordEncoder;

    @Override
    public ApiResponse<AdminEmployeeDto.EmployeeListResponse> getEmployeeList(AdminEmployeeDto.EmployeeListRequest request) {
        try {
            log.info("获取员工列表，请求参数：{}", request);

            // 查询员工列表，支持分页和条件筛选
            List<AdminUser> adminUsers;
            Long total;
            
            // 计算偏移量
            int offset = (request.getPageNum() - 1) * request.getPageSize();
            
            // 根据是否有查询条件选择不同的查询方法
            if (request.getKeyword() != null && !request.getKeyword().trim().isEmpty()) {
                // 有关键词搜索
                adminUsers = adminUserMapper.selectByKeywordPaged(
                    request.getKeyword().trim(), 
                    request.getStatus(), 
                    request.getDepartment(),
                    offset, 
                    request.getPageSize()
                );
                total = adminUserMapper.countByKeyword(
                    request.getKeyword().trim(), 
                    request.getStatus(), 
                    request.getDepartment()
                );
            } else {
                // 无关键词，仅按状态和部门筛选
                adminUsers = adminUserMapper.selectByConditionPaged(
                    request.getStatus(), 
                    request.getDepartment(),
                    offset, 
                    request.getPageSize()
                );
                total = adminUserMapper.countByCondition(
                    request.getStatus(), 
                    request.getDepartment()
                );
            }
            
            List<AdminEmployeeDto.EmployeeListItem> employeeItems = new ArrayList<>();
            for (AdminUser adminUser : adminUsers) {
                AdminEmployeeDto.EmployeeListItem item = new AdminEmployeeDto.EmployeeListItem();
                item.setId(adminUser.getId());
                item.setUsername(adminUser.getUsername());
                item.setRealName(adminUser.getRealName());
                item.setEmail(adminUser.getEmail());
                item.setPhone(adminUser.getPhone());
                item.setRole(adminUser.getRole());
                item.setRoleName(getEmployeeRoleName(adminUser.getRole()));
                item.setStatus(adminUser.getStatus());
                item.setStatusName(getEmployeeStatusName(adminUser.getStatus()));
                item.setLastLoginTime(adminUser.getLastLoginTime());
                item.setCreateTime(adminUser.getCreateTime());
                item.setUpdateTime(adminUser.getUpdateTime());
                employeeItems.add(item);
            }

            AdminEmployeeDto.EmployeeListResponse response = new AdminEmployeeDto.EmployeeListResponse();
            response.setList(employeeItems);
            response.setTotal(total != null ? total : 0L);
            response.setPageNum(request.getPageNum());
            response.setPageSize(request.getPageSize());

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取员工列表失败", e);
            return ApiResponse.error("获取员工列表失败：" + e.getMessage());
        }
    }

    @Override
    public ApiResponse<AdminEmployeeDto.EmployeeDetailResponse> getEmployeeDetail(Long id) {
        try {
            log.info("获取员工详情，员工ID：{}", id);

            AdminUser adminUser = adminUserMapper.selectById(id);
            if (adminUser == null) {
                return ApiResponse.error("员工不存在");
            }

            AdminEmployeeDto.EmployeeDetailResponse response = new AdminEmployeeDto.EmployeeDetailResponse();
            
            // 员工详细信息
            AdminEmployeeDto.EmployeeDetail employeeDetail = new AdminEmployeeDto.EmployeeDetail();
            employeeDetail.setId(adminUser.getId());
            employeeDetail.setUsername(adminUser.getUsername());
            employeeDetail.setRealName(adminUser.getRealName());
            employeeDetail.setEmail(adminUser.getEmail());
            employeeDetail.setPhone(adminUser.getPhone());
            employeeDetail.setRole(adminUser.getRole());
            employeeDetail.setRoleName(getEmployeeRoleName(adminUser.getRole()));
            employeeDetail.setStatus(adminUser.getStatus());
            employeeDetail.setStatusName(getEmployeeStatusName(adminUser.getStatus()));
            employeeDetail.setDepartment(adminUser.getDepartment());
            employeeDetail.setPosition(adminUser.getPosition());
            employeeDetail.setRemark(adminUser.getRemark());
            employeeDetail.setCreateTime(adminUser.getCreateTime());
            employeeDetail.setUpdateTime(adminUser.getUpdateTime());
            employeeDetail.setLastLoginTime(adminUser.getLastLoginTime());
            employeeDetail.setLastLoginIp(adminUser.getLastLoginIp());
            response.setEmployeeDetail(employeeDetail);

            // 查询真实的统计信息
            AdminEmployeeDto.EmployeeStatistics statistics = new AdminEmployeeDto.EmployeeStatistics();
            
            // 注意：以下功能需要完善的员工操作日志系统支持
            // 当前返回0值，避免显示虚假数据
            statistics.setMonthlyLogins(0L);  // 需要员工登录日志表
            statistics.setMonthlyOperations(0L);  // 需要员工操作日志表
            statistics.setAuditCount(0L);  // 需要内容审核操作日志
            statistics.setWithdrawCount(0L);  // 需要提现审核操作日志
            
            response.setStatistics(statistics);
            
            log.info("员工统计数据查询完成，员工ID: {} - 注意：统计功能需要完善的操作日志系统支持", id);

            // 最近操作记录（当前返回空列表，避免虚假数据）
            List<AdminEmployeeDto.OperationLog> recentOperations = new ArrayList<>();
            // TODO: 实现真实的员工操作日志查询
            // 需要创建员工操作日志表记录以下操作：
            // 1. 登录操作
            // 2. 内容审核操作
            // 3. 用户管理操作
            // 4. 提现审核操作
            // 5. 系统设置操作等
            
            response.setRecentOperations(recentOperations);

            return ApiResponse.success(response);

        } catch (Exception e) {
            log.error("获取员工详情失败", e);
            return ApiResponse.error("获取员工详情失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> createEmployee(AdminEmployeeDto.EmployeeCreateRequest request) {
        try {
            log.info("创建员工，请求参数：{}", request);

            // 检查用户名是否已存在
            AdminUser existingUser = adminUserMapper.selectByUsername(request.getUsername());
            if (existingUser != null) {
                return ApiResponse.error("用户名已存在");
            }

            AdminUser adminUser = new AdminUser();
            adminUser.setUsername(request.getUsername());
            adminUser.setPasswordHash(passwordEncoder.encode(request.getPassword()));
            adminUser.setRealName(request.getRealName());
            adminUser.setEmail(request.getEmail());
            adminUser.setPhone(request.getPhone());
            adminUser.setRole(request.getRole());
            adminUser.setDepartment(request.getDepartment());
            adminUser.setPosition(request.getPosition());
            adminUser.setRemark(request.getRemark());
            adminUser.setStatus(1); // 默认启用
            adminUser.setIsDeleted(0); // 默认未删除
            adminUser.setCreateTime(LocalDateTime.now());
            adminUser.setUpdateTime(LocalDateTime.now());

            int result = adminUserMapper.insert(adminUser);
            if (result > 0) {
                return ApiResponse.success("员工创建成功");
            } else {
                return ApiResponse.error("员工创建失败");
            }

        } catch (Exception e) {
            log.error("创建员工失败", e);
            return ApiResponse.error("创建员工失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateEmployee(AdminEmployeeDto.EmployeeUpdateRequest request) {
        try {
            log.info("更新员工信息，请求参数：{}", request);

            AdminUser adminUser = adminUserMapper.selectById(request.getId());
            if (adminUser == null) {
                return ApiResponse.error("员工不存在");
            }

            adminUser.setRealName(request.getRealName());
            adminUser.setEmail(request.getEmail());
            adminUser.setPhone(request.getPhone());
            adminUser.setRole(request.getRole());
            adminUser.setDepartment(request.getDepartment());
            adminUser.setPosition(request.getPosition());
            adminUser.setRemark(request.getRemark());
            adminUser.setUpdateTime(LocalDateTime.now());

            int result = adminUserMapper.updateById(adminUser);
            if (result > 0) {
                return ApiResponse.success("员工信息更新成功");
            } else {
                return ApiResponse.error("员工信息更新失败");
            }

        } catch (Exception e) {
            log.error("更新员工信息失败", e);
            return ApiResponse.error("更新员工信息失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> deleteEmployee(Long id) {
        try {
            log.info("删除员工，员工ID：{}", id);

            AdminUser adminUser = adminUserMapper.selectById(id);
            if (adminUser == null) {
                return ApiResponse.error("员工不存在");
            }

            // 软删除：设置状态为禁用
            adminUser.setStatus(0);
            adminUser.setUpdateTime(LocalDateTime.now());

            int result = adminUserMapper.updateById(adminUser);
            if (result > 0) {
                return ApiResponse.success("员工删除成功");
            } else {
                return ApiResponse.error("员工删除失败");
            }

        } catch (Exception e) {
            log.error("删除员工失败", e);
            return ApiResponse.error("删除员工失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> resetEmployeePassword(AdminEmployeeDto.EmployeePasswordResetRequest request) {
        try {
            log.info("重置员工密码，员工ID：{}", request.getEmployeeId());

            AdminUser adminUser = adminUserMapper.selectById(request.getEmployeeId());
            if (adminUser == null) {
                return ApiResponse.error("员工不存在");
            }

            adminUser.setPasswordHash(passwordEncoder.encode(request.getNewPassword()));
            adminUser.setUpdateTime(LocalDateTime.now());

            int result = adminUserMapper.updateById(adminUser);
            if (result > 0) {
                return ApiResponse.success("员工密码重置成功");
            } else {
                return ApiResponse.error("员工密码重置失败");
            }

        } catch (Exception e) {
            log.error("重置员工密码失败", e);
            return ApiResponse.error("重置员工密码失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional
    public ApiResponse<String> updateEmployeeStatus(AdminEmployeeDto.EmployeeStatusUpdateRequest request) {
        try {
            log.info("更新员工状态，请求参数：{}", request);

            AdminUser adminUser = adminUserMapper.selectById(request.getEmployeeId());
            if (adminUser == null) {
                return ApiResponse.error("员工不存在");
            }

            adminUser.setStatus(request.getStatus());
            adminUser.setUpdateTime(LocalDateTime.now());

            int result = adminUserMapper.updateById(adminUser);
            if (result > 0) {
                return ApiResponse.success("员工状态更新成功");
            } else {
                return ApiResponse.error("员工状态更新失败");
            }

        } catch (Exception e) {
            log.error("更新员工状态失败", e);
            return ApiResponse.error("更新员工状态失败：" + e.getMessage());
        }
    }

    /**
     * 获取员工角色名称
     */
    private String getEmployeeRoleName(Integer role) {
        if (role == null) return "未知";
        switch (role) {
            case 0: return "普通员工";
            case 1: return "管理员";
            default: return "未知";
        }
    }

    /**
     * 获取员工状态名称
     */
    private String getEmployeeStatusName(Integer status) {
        if (status == null) return "未知";
        switch (status) {
            case 0: return "禁用";
            case 1: return "启用";
            default: return "未知";
        }
    }
}
