package com.innovation.platform.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.innovation.platform.controller.UserController.CreateUserRequest;
import com.innovation.platform.controller.UserController.UpdateProfileRequest;
import com.innovation.platform.controller.UserController.UpdateUserRequest;
import com.innovation.platform.dto.LoginRequest;
import com.innovation.platform.dto.LoginResponse;
import com.innovation.platform.dto.RegisterRequest;
import com.innovation.platform.entity.SysUser;
import com.innovation.platform.mapper.SysUserMapper;
import com.innovation.platform.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 用户服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements SysUserService {

    private final SysUserMapper sysUserMapper;

    @Override
    public LoginResponse login(LoginRequest request) {
        // 查询用户
        SysUser user = getByUsername(request.getUsername());
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 验证密码
        if (!BCrypt.checkpw(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("用户名或密码错误");
        }
        
        // 检查用户状态
        if (user.getStatus() != null && user.getStatus() == 0) {
            throw new RuntimeException("账号已被禁用");
        }
        
        // 登录
        StpUtil.login(user.getId());
        
        // 返回登录信息
        return LoginResponse.builder()
                .token(StpUtil.getTokenValue())
                .userId(user.getId())
                .username(user.getUsername())
                .realName(user.getRealName())
                .avatar(user.getAvatar())
                .roleType(user.getRoleType())
                .build();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(RegisterRequest request) {
        // 检查用户名是否已存在
        if (getByUsername(request.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 创建用户
        SysUser user = new SysUser();
        user.setUsername(request.getUsername());
        user.setPassword(BCrypt.hashpw(request.getPassword()));
        user.setRealName(request.getRealName());
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setGender(request.getGender());
        user.setRoleType(request.getRoleType() != null ? request.getRoleType() : 0);
        user.setStatus(1);
        
        sysUserMapper.insert(user);
    }

    @Override
    public void logout() {
        StpUtil.logout();
    }

    @Override
    public SysUser getByUsername(String username) {
        return sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
        );
    }

    @Override
    public SysUser getById(Long id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public Page<SysUser> getUserList(Integer page, Integer size, String keyword, Integer roleType, Integer status) {
        Page<SysUser> userPage = new Page<>(page, size);
        
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索（用户名、姓名、手机号）
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w
                    .like(SysUser::getUsername, keyword)
                    .or()
                    .like(SysUser::getRealName, keyword)
                    .or()
                    .like(SysUser::getPhone, keyword)
            );
        }
        
        // 角色类型过滤
        if (roleType != null) {
            wrapper.eq(SysUser::getRoleType, roleType);
        }
        
        // 状态过滤
        if (status != null) {
            wrapper.eq(SysUser::getStatus, status);
        }
        
        return sysUserMapper.selectPage(userPage, wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUser createUser(CreateUserRequest request) {
        // 检查用户名是否已存在
        if (getByUsername(request.getUsername()) != null) {
            throw new RuntimeException("用户名已存在");
        }
        
        // 检查邮箱是否已存在
        if (StringUtils.hasText(request.getEmail()) && getByEmail(request.getEmail()) != null) {
            throw new RuntimeException("邮箱已被使用");
        }
        
        // 创建用户
        SysUser user = new SysUser();
        user.setUsername(request.getUsername());
        user.setPassword(BCrypt.hashpw(request.getPassword() != null ? request.getPassword() : "123456"));
        user.setRealName(request.getRealName());
        user.setGender(request.getGender());
        user.setPhone(request.getPhone());
        user.setEmail(request.getEmail());
        user.setAvatar(request.getAvatar());
        user.setRoleType(request.getRoleType() != null ? request.getRoleType() : 0);
        user.setStatus(1);
        
        sysUserMapper.insert(user);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUser updateUser(Long id, UpdateUserRequest request) {
        SysUser user = sysUserMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查邮箱是否已被其他用户使用
        if (StringUtils.hasText(request.getEmail())) {
            SysUser existUser = getByEmail(request.getEmail());
            if (existUser != null && !existUser.getId().equals(id)) {
                throw new RuntimeException("邮箱已被其他用户使用");
            }
            user.setEmail(request.getEmail());
        }
        
        user.setRealName(request.getRealName());
        user.setGender(request.getGender());
        user.setPhone(request.getPhone());
        user.setAvatar(request.getAvatar());
        user.setRoleType(request.getRoleType());
        user.setStatus(request.getStatus());
        
        sysUserMapper.updateById(user);
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUser(Long id) {
        SysUser user = sysUserMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        sysUserMapper.deleteById(id);
    }

    @Override
    public List<SysUser> getTeacherList() {
        return sysUserMapper.selectList(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getRoleType, 1)  // 1 = 教师
                        .eq(SysUser::getStatus, 1)     // 只查询启用的用户
        );
    }

    @Override
    public void changePassword(String oldPassword, String newPassword) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();
        SysUser user = sysUserMapper.selectById(userId);
        
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 验证旧密码
        if (!BCrypt.checkpw(oldPassword, user.getPassword())) {
            throw new RuntimeException("旧密码错误");
        }
        
        // 更新密码
        user.setPassword(BCrypt.hashpw(newPassword));
        sysUserMapper.updateById(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUser updateProfile(UpdateProfileRequest request) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();
        SysUser user = sysUserMapper.selectById(userId);
        
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 检查邮箱是否已被其他用户使用
        if (StringUtils.hasText(request.getEmail())) {
            SysUser existUser = getByEmail(request.getEmail());
            if (existUser != null && !existUser.getId().equals(userId)) {
                throw new RuntimeException("邮箱已被其他用户使用");
            }
            user.setEmail(request.getEmail());
        }
        
        user.setRealName(request.getRealName());
        user.setPhone(request.getPhone());
        user.setAvatar(request.getAvatar());
        
        sysUserMapper.updateById(user);
        return user;
    }

    /**
     * 根据邮箱查询用户
     */
    private SysUser getByEmail(String email) {
        return sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getEmail, email)
        );
    }
}
