package com.lesingle.creation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lesingle.creation.dto.student.CreateStudentDTO;
import com.lesingle.creation.dto.student.UpdateStudentDTO;
import com.lesingle.creation.entity.SchoolClass;
import com.lesingle.creation.entity.Student;
import com.lesingle.creation.entity.User;
import com.lesingle.creation.common.exception.BusinessException;
import com.lesingle.creation.mapper.StudentMapper;
import com.lesingle.creation.mapper.UserMapper;
import com.lesingle.creation.mapper.SchoolClassMapper;
import com.lesingle.creation.service.SchoolClassService;
import com.lesingle.creation.service.StudentService;
import com.lesingle.creation.vo.student.StudentVO;
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 StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    private final StudentMapper studentMapper;
    private final UserMapper userMapper;
    private final SchoolClassService schoolClassService;
    private final SchoolClassMapper schoolClassMapper;
    private final PasswordEncoder passwordEncoder;

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

        // 检查学号是否已存在
        Student existingStudent = studentMapper.selectByStudentNo(tenantId, dto.getStudentNo());
        if (existingStudent != null) {
            throw new BusinessException("学号已存在");
        }

        // 检查班级是否存在
        SchoolClass schoolClass = schoolClassMapper.selectById(dto.getClassId());
        if (schoolClass == null || !schoolClass.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("student"); // 学生用户
        user.setStatus("active");
        user.setUserSource("admin_created");

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

        // 创建学生信息
        Student student = new Student();
        student.setTenantId(tenantId);
        student.setUserId(user.getId());
        student.setClassId(dto.getClassId());
        student.setStudentNo(dto.getStudentNo());
        student.setPhone(dto.getPhone());
        student.setIdCard(dto.getIdCard());
        student.setGender(dto.getGender());
        student.setBirthDate(dto.getBirthDate());
        student.setEnrollmentDate(dto.getEnrollmentDate());
        student.setParentName(dto.getParentName());
        student.setParentPhone(dto.getParentPhone());
        student.setAddress(dto.getAddress());
        student.setDescription(dto.getDescription());
        student.setValidState(1);

        studentMapper.insert(student);
        log.info("创建学生成功，ID={}, 学号={}", student.getId(), dto.getStudentNo());

        return convertToVO(student, user, schoolClass);
    }

    @Override
    public List<StudentVO> list(Long tenantId, Integer page, Integer pageSize, Long classId) {
        LambdaQueryWrapper<Student> wrapper = new LambdaQueryWrapper<Student>()
                .eq(Student::getTenantId, tenantId)
                .eq(Student::getDeleted, 0)
                .eq(classId != null, Student::getClassId, classId)
                .orderByDesc(Student::getCreateTime);

        Page<Student> studentPage = this.page(new Page<>(page, pageSize), wrapper);

        // 转换为 VO
        return studentPage.getRecords().stream()
                .map(student -> {
                    User user = userMapper.selectById(student.getUserId());
                    SchoolClass schoolClass = schoolClassMapper.selectById(student.getClassId());
                    return convertToVO(student, user, schoolClass);
                })
                .collect(Collectors.toList());
    }

    @Override
    public StudentVO getDetail(Long id, Long tenantId) {
        Student student = this.getById(id);
        if (student == null || !student.getTenantId().equals(tenantId)) {
            throw new BusinessException("学生不存在");
        }

        User user = userMapper.selectById(student.getUserId());
        SchoolClass schoolClass = schoolClassMapper.selectById(student.getClassId());

        return convertToVO(student, user, schoolClass);
    }

    @Override
    public StudentVO getByUserId(Long userId, Long tenantId) {
        Student student = studentMapper.selectByUserId(userId);
        if (student == null || !student.getTenantId().equals(tenantId)) {
            throw new BusinessException("学生不存在");
        }

        User user = userMapper.selectById(student.getUserId());
        SchoolClass schoolClass = schoolClassMapper.selectById(student.getClassId());

        return convertToVO(student, user, schoolClass);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StudentVO update(Long id, UpdateStudentDTO dto, Long tenantId, Long modifierId) {
        Student student = this.getById(id);
        if (student == null || !student.getTenantId().equals(tenantId)) {
            throw new BusinessException("学生不存在");
        }

        // 检查学号是否已被其他学生使用
        if (dto.getStudentNo() != null) {
            Student existingStudent = studentMapper.selectByStudentNo(tenantId, dto.getStudentNo());
            if (existingStudent != null && !existingStudent.getId().equals(id)) {
                throw new BusinessException("学号已存在");
            }
            student.setStudentNo(dto.getStudentNo());
        }

        // 更新学生信息
        if (dto.getClassId() != null) {
            SchoolClass schoolClass = schoolClassMapper.selectById(dto.getClassId());
            if (schoolClass == null || !schoolClass.getTenantId().equals(tenantId)) {
                throw new BusinessException("班级不存在");
            }
            student.setClassId(dto.getClassId());
        }
        if (dto.getPhone() != null) {
            student.setPhone(dto.getPhone());
        }
        if (dto.getIdCard() != null) {
            student.setIdCard(dto.getIdCard());
        }
        if (dto.getGender() != null) {
            student.setGender(dto.getGender());
        }
        if (dto.getBirthDate() != null) {
            student.setBirthDate(dto.getBirthDate());
        }
        if (dto.getEnrollmentDate() != null) {
            student.setEnrollmentDate(dto.getEnrollmentDate());
        }
        if (dto.getParentName() != null) {
            student.setParentName(dto.getParentName());
        }
        if (dto.getParentPhone() != null) {
            student.setParentPhone(dto.getParentPhone());
        }
        if (dto.getAddress() != null) {
            student.setAddress(dto.getAddress());
        }
        if (dto.getDescription() != null) {
            student.setDescription(dto.getDescription());
        }
        if (dto.getValidState() != null) {
            student.setValidState(dto.getValidState());
        }

        // 更新用户信息（如果有）
        if (dto.getNickname() != null || dto.getEmail() != null || dto.getAvatar() != null) {
            User user = userMapper.selectById(student.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(student);
        log.info("更新学生成功，ID={}", id);

        User user = userMapper.selectById(student.getUserId());
        SchoolClass schoolClass = schoolClassMapper.selectById(student.getClassId());
        return convertToVO(student, user, schoolClass);
    }

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

        // 逻辑删除学生
        student.setDeleted(1);
        this.updateById(student);

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

        log.info("删除学生成功，ID={}, 用户 ID={}", id, student.getUserId());
    }

    /**
     * 转换为 VO
     */
    private StudentVO convertToVO(Student student, User user, SchoolClass schoolClass) {
        StudentVO vo = new StudentVO();
        vo.setId(student.getId());
        vo.setUserId(student.getUserId());
        vo.setTenantId(student.getTenantId());
        vo.setClassId(student.getClassId());
        vo.setStudentNo(student.getStudentNo());
        vo.setPhone(student.getPhone());
        vo.setIdCard(student.getIdCard());
        vo.setGender(student.getGender());
        vo.setBirthDate(student.getBirthDate());
        vo.setEnrollmentDate(student.getEnrollmentDate());
        vo.setParentName(student.getParentName());
        vo.setParentPhone(student.getParentPhone());
        vo.setAddress(student.getAddress());
        vo.setDescription(student.getDescription());
        vo.setValidState(student.getValidState());
        vo.setCreateTime(student.getCreateTime());
        vo.setUpdateTime(student.getUpdateTime());

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

        // 班级信息
        if (schoolClass != null) {
            StudentVO.ClassInfo classInfo = new StudentVO.ClassInfo();
            classInfo.setId(schoolClass.getId());
            classInfo.setName(schoolClass.getName());
            classInfo.setCode(schoolClass.getCode());
            vo.setClassInfo(classInfo);
        }

        return vo;
    }
}
