package com.lesingle.creation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.creation.dto.teacher.CreateTeacherDTO;
import com.lesingle.creation.dto.teacher.UpdateTeacherDTO;
import com.lesingle.creation.entity.Department;
import com.lesingle.creation.entity.Teacher;
import com.lesingle.creation.entity.User;
import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.mapper.TeacherMapper;
import com.lesingle.creation.mapper.UserMapper;
import com.lesingle.creation.service.DepartmentService;
import com.lesingle.creation.service.TeacherService;
import com.lesingle.creation.vo.teacher.TeacherVO;
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.util.List;
import java.util.stream.Collectors;

/**
 * 教师服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    private final TeacherMapper teacherMapper;
    private final UserMapper userMapper;
    private final DepartmentService departmentService;
    private final PasswordEncoder passwordEncoder;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TeacherVO create(CreateTeacherDTO dto, Long tenantId, Long creatorId) {
        // 检查用户名是否已存在
        User existingUser = userMapper.selectByUsername(dto.getUsername());
        if (existingUser != null) {
            throw new BusinessException("用户名已存在");
        }

        // 检查工号是否已存在
        Teacher existingTeacher = teacherMapper.selectByEmployeeNo(tenantId, dto.getEmployeeNo());
        if (existingTeacher != null) {
            throw new BusinessException("工号已存在");
        }

        // 检查部门是否存在
        Department department = departmentService.getById(dto.getDepartmentId());
        if (department == null || !department.getTenantId().equals(tenantId)) {
            throw new BusinessException("部门不存在");
        }

        // 创建用户账号
        User user = new User();
        user.setTenantId(tenantId);
        user.setUsername(dto.getUsername());
        user.setPassword(passwordEncoder.encode(dto.getPassword()));
        user.setNickname(dto.getNickname());
        user.setEmail(dto.getEmail());
        user.setAvatar(dto.getAvatar());
        user.setUserType("teacher"); // 教师用户
        user.setStatus("active");
        user.setUserSource("admin_created");

        userMapper.insert(user);
        log.info("创建用户账号成功，ID={}, 用户名={}", user.getId(), dto.getUsername());

        // 创建教师信息
        Teacher teacher = new Teacher();
        teacher.setTenantId(tenantId);
        teacher.setUserId(user.getId());
        teacher.setDepartmentId(dto.getDepartmentId());
        teacher.setEmployeeNo(dto.getEmployeeNo());
        teacher.setPhone(dto.getPhone());
        teacher.setIdCard(dto.getIdCard());
        teacher.setGender(dto.getGender());
        teacher.setBirthDate(dto.getBirthDate());
        teacher.setHireDate(dto.getHireDate());
        teacher.setSubject(dto.getSubject());
        teacher.setTitle(dto.getTitle());
        teacher.setDescription(dto.getDescription());
        teacher.setValidState(1);

        teacherMapper.insert(teacher);
        log.info("创建教师成功，ID={}, 工号={}", teacher.getId(), dto.getEmployeeNo());

        return convertToVO(teacher, user, department);
    }

    @Override
    public List<TeacherVO> list(Long tenantId, Long departmentId, String nickname, String username) {
        LambdaQueryWrapper<Teacher> wrapper = new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getTenantId, tenantId)
                .eq(Teacher::getDeleted, 0)
                .eq(departmentId != null, Teacher::getDepartmentId, departmentId)
                .orderByDesc(Teacher::getCreateTime);

        List<Teacher> teachers = this.list(wrapper);

        // 过滤用户名和昵称
        if (username != null || nickname != null) {
            List<Long> userIds = teachers.stream().map(Teacher::getUserId).collect(Collectors.toList());
            LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<User>()
                    .in(User::getId, userIds)
                    .eq(User::getDeleted, 0);

            if (username != null && !username.isEmpty()) {
                userWrapper.like(User::getUsername, username);
            }
            if (nickname != null && !nickname.isEmpty()) {
                userWrapper.like(User::getNickname, nickname);
            }

            List<User> users = userMapper.selectList(userWrapper);
            List<Long> validUserIds = users.stream().map(User::getId).collect(Collectors.toList());

            teachers = teachers.stream()
                    .filter(t -> validUserIds.contains(t.getUserId()))
                    .collect(Collectors.toList());
        }

        // 转换为 VO
        return teachers.stream()
                .map(teacher -> {
                    User user = userMapper.selectById(teacher.getUserId());
                    Department dept = departmentService.getById(teacher.getDepartmentId());
                    return convertToVO(teacher, user, dept);
                })
                .collect(Collectors.toList());
    }

    @Override
    public TeacherVO getDetail(Long id, Long tenantId) {
        Teacher teacher = this.getById(id);
        if (teacher == null || !teacher.getTenantId().equals(tenantId)) {
            throw new BusinessException("教师不存在");
        }

        User user = userMapper.selectById(teacher.getUserId());
        Department department = departmentService.getById(teacher.getDepartmentId());

        return convertToVO(teacher, user, department);
    }

    @Override
    public TeacherVO getByUserId(Long userId, Long tenantId) {
        Teacher teacher = teacherMapper.selectByUserId(userId);
        if (teacher == null || !teacher.getTenantId().equals(tenantId)) {
            throw new BusinessException("教师不存在");
        }

        User user = userMapper.selectById(teacher.getUserId());
        Department department = departmentService.getById(teacher.getDepartmentId());

        return convertToVO(teacher, user, department);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public TeacherVO update(Long id, UpdateTeacherDTO dto, Long tenantId, Long modifierId) {
        Teacher teacher = this.getById(id);
        if (teacher == null || !teacher.getTenantId().equals(tenantId)) {
            throw new BusinessException("教师不存在");
        }

        // 检查工号是否已被其他教师使用
        if (dto.getEmployeeNo() != null) {
            Teacher existingTeacher = teacherMapper.selectByEmployeeNo(tenantId, dto.getEmployeeNo());
            if (existingTeacher != null && !existingTeacher.getId().equals(id)) {
                throw new BusinessException("工号已存在");
            }
            teacher.setEmployeeNo(dto.getEmployeeNo());
        }

        // 更新教师信息
        if (dto.getDepartmentId() != null) {
            Department department = departmentService.getById(dto.getDepartmentId());
            if (department == null || !department.getTenantId().equals(tenantId)) {
                throw new BusinessException("部门不存在");
            }
            teacher.setDepartmentId(dto.getDepartmentId());
        }
        if (dto.getPhone() != null) {
            teacher.setPhone(dto.getPhone());
        }
        if (dto.getIdCard() != null) {
            teacher.setIdCard(dto.getIdCard());
        }
        if (dto.getGender() != null) {
            teacher.setGender(dto.getGender());
        }
        if (dto.getBirthDate() != null) {
            teacher.setBirthDate(dto.getBirthDate());
        }
        if (dto.getHireDate() != null) {
            teacher.setHireDate(dto.getHireDate());
        }
        if (dto.getSubject() != null) {
            teacher.setSubject(dto.getSubject());
        }
        if (dto.getTitle() != null) {
            teacher.setTitle(dto.getTitle());
        }
        if (dto.getDescription() != null) {
            teacher.setDescription(dto.getDescription());
        }
        if (dto.getValidState() != null) {
            teacher.setValidState(dto.getValidState());
        }

        // 更新用户信息（如果有）
        if (dto.getNickname() != null || dto.getEmail() != null || dto.getAvatar() != null) {
            User user = userMapper.selectById(teacher.getUserId());
            if (user != null) {
                if (dto.getNickname() != null) {
                    user.setNickname(dto.getNickname());
                }
                if (dto.getEmail() != null) {
                    user.setEmail(dto.getEmail());
                }
                if (dto.getAvatar() != null) {
                    user.setAvatar(dto.getAvatar());
                }
                userMapper.updateById(user);
            }
        }

        this.updateById(teacher);
        log.info("更新教师成功，ID={}", id);

        User user = userMapper.selectById(teacher.getUserId());
        Department department = departmentService.getById(teacher.getDepartmentId());
        return convertToVO(teacher, user, department);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id, Long tenantId) {
        Teacher teacher = this.getById(id);
        if (teacher == null || !teacher.getTenantId().equals(tenantId)) {
            throw new BusinessException("教师不存在");
        }

        // 逻辑删除教师
        teacher.setDeleted(1);
        this.updateById(teacher);

        // 同时禁用关联的用户账号
        User user = userMapper.selectById(teacher.getUserId());
        if (user != null) {
            user.setStatus("disabled"); // 禁用状态
            userMapper.updateById(user);
        }

        log.info("删除教师成功，ID={}, 用户 ID={}", id, teacher.getUserId());
    }

    /**
     * 转换为 VO
     */
    private TeacherVO convertToVO(Teacher teacher, User user, Department department) {
        TeacherVO vo = new TeacherVO();
        vo.setId(teacher.getId());
        vo.setUserId(teacher.getUserId());
        vo.setTenantId(teacher.getTenantId());
        vo.setDepartmentId(teacher.getDepartmentId());
        vo.setEmployeeNo(teacher.getEmployeeNo());
        vo.setPhone(teacher.getPhone());
        vo.setIdCard(teacher.getIdCard());
        vo.setGender(teacher.getGender());
        vo.setBirthDate(teacher.getBirthDate());
        vo.setHireDate(teacher.getHireDate());
        vo.setSubject(teacher.getSubject());
        vo.setTitle(teacher.getTitle());
        vo.setDescription(teacher.getDescription());
        vo.setValidState(teacher.getValidState());
        vo.setCreateTime(teacher.getCreateTime());
        vo.setUpdateTime(teacher.getUpdateTime());

        // 用户信息
        if (user != null) {
            TeacherVO.UserInfo userInfo = new TeacherVO.UserInfo();
            userInfo.setUsername(user.getUsername());
            userInfo.setNickname(user.getNickname());
            userInfo.setEmail(user.getEmail());
            userInfo.setAvatar(user.getAvatar());
            vo.setUserInfo(userInfo);
        }

        // 部门信息
        if (department != null) {
            TeacherVO.DepartmentInfo deptInfo = new TeacherVO.DepartmentInfo();
            deptInfo.setId(department.getId());
            deptInfo.setName(department.getName());
            deptInfo.setCode(department.getCode());
            vo.setDepartment(deptInfo);
        }

        return vo;
    }
}
