package com.emotion.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.emotion.common.PageResult;
import com.emotion.dto.request.UserCreateRequest;
import com.emotion.dto.request.UserPageRequest;
import com.emotion.dto.request.UserUpdateRequest;
import com.emotion.dto.request.UserProfileUpdateRequest;
import com.emotion.dto.response.UserResponse;
import com.emotion.entity.User;
import com.emotion.mapper.UserMapper;
import com.emotion.service.UserService;
import com.emotion.util.UserContextHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户服务实现类
 * 
 * @author huazhongmin
 * @date 2025-07-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private final PasswordEncoder passwordEncoder;

    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public UserServiceImpl(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public PageResult<UserResponse> getPageWithResponse(UserPageRequest request) {
        Page<User> page = new Page<>(request.getCurrent(), request.getSize());
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(request.getKeyword())) {
            wrapper.and(w -> w.like(User::getUsername, request.getKeyword())
                    .or().like(User::getNickname, request.getKeyword())
                    .or().like(User::getEmail, request.getKeyword()));
        }
        
        // 账号查询
        if (StringUtils.hasText(request.getAccount())) {
            wrapper.eq(User::getAccount, request.getAccount());
        }

        // 用户名查询
        if (StringUtils.hasText(request.getUsername())) {
            wrapper.like(User::getUsername, request.getUsername());
        }

        // 邮箱查询
        if (StringUtils.hasText(request.getEmail())) {
            wrapper.eq(User::getEmail, request.getEmail());
        }

        // 手机号查询
        if (StringUtils.hasText(request.getPhone())) {
            wrapper.eq(User::getPhone, request.getPhone());
        }

        // 状态查询
        if (request.getStatus() != null) {
            wrapper.eq(User::getStatus, request.getStatus());
        }

        // 会员等级查询
        if (StringUtils.hasText(request.getMemberLevel())) {
            wrapper.eq(User::getMemberLevel, request.getMemberLevel());
        }

        wrapper.eq(User::getIsDeleted, 0);
        
        // 排序
        if (StringUtils.hasText(request.getOrderBy())) {
            if ("asc".equalsIgnoreCase(request.getOrderDirection())) {
                wrapper.orderByAsc(User::getCreateTime);
            } else {
                wrapper.orderByDesc(User::getCreateTime);
            }
        } else {
            wrapper.orderByDesc(User::getCreateTime);
        }
        
        Page<User> resultPage = this.page(page, wrapper);
        List<UserResponse> userResponses = resultPage.getRecords().stream()
                .map(this::convertToResponse)
                .collect(Collectors.toList());

        PageResult<UserResponse> pageResult = new PageResult<>();
        pageResult.setCurrent(resultPage.getCurrent());
        pageResult.setSize(resultPage.getSize());
        pageResult.setTotal(resultPage.getTotal());
        pageResult.setPages(resultPage.getPages());
        pageResult.setRecords(userResponses);

        return pageResult;
    }

    @Override
    public UserResponse getUserResponseById(String id) {
        User user = this.getById(id);
        if (user == null || user.getIsDeleted() == 1) {
            return null;
        }
        return convertToResponse(user);
    }

    @Override
    public UserResponse createUserWithResponse(UserCreateRequest request) {
        User user = new User();
        user.setAccount(request.getAccount());
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
        user.setPhone(request.getPhone());
        user.setNickname(request.getUsername());
        user.setMemberLevel("free");
        user.setStatus(1);
        user.setIsVerified(0);
        user.setLastActiveTime(LocalDateTime.now());

        this.save(user);
        return convertToResponse(user);
    }

    @Override
    public UserResponse updateUserWithResponse(UserUpdateRequest request) {
        User user = this.getById(request.getId());
        if (user == null || user.getIsDeleted() == 1) {
            return null;
        }

        // 只更新非空字段
        if (StringUtils.hasText(request.getUsername())) {
            user.setUsername(request.getUsername());
        }
        if (StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
        }
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }
        if (StringUtils.hasText(request.getAvatar())) {
            user.setAvatar(request.getAvatar());
        }
        if (request.getBirthDate() != null) {
            user.setBirthDate(request.getBirthDate());
        }
        if (StringUtils.hasText(request.getLocation())) {
            user.setLocation(request.getLocation());
        }
        if (StringUtils.hasText(request.getBio())) {
            user.setBio(request.getBio());
        }
        if (request.getStatus() != null) {
            user.setStatus(request.getStatus());
        }
        if (StringUtils.hasText(request.getMemberLevel())) {
            user.setMemberLevel(request.getMemberLevel());
        }

        this.updateById(user);
        return convertToResponse(user);
    }

    @Override
    public UserResponse updateCurrentUserProfileWithResponse(UserProfileUpdateRequest request) {
        // 从UserContextHolder获取当前用户ID
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }

        User user = this.getById(currentUserId);
        if (user == null || user.getIsDeleted() == 1) {
            return null;
        }

        // 只更新非空字段
        if (StringUtils.hasText(request.getNickname())) {
            user.setNickname(request.getNickname());
        }
        if (StringUtils.hasText(request.getEmail())) {
            user.setEmail(request.getEmail());
        }
        if (StringUtils.hasText(request.getPhone())) {
            user.setPhone(request.getPhone());
        }
        if (StringUtils.hasText(request.getAvatar())) {
            user.setAvatar(request.getAvatar());
        }
        if (request.getBirthDate() != null) {
            user.setBirthDate(request.getBirthDate());
        }
        if (StringUtils.hasText(request.getLocation())) {
            user.setLocation(request.getLocation());
        }
        if (StringUtils.hasText(request.getBio())) {
            user.setBio(request.getBio());
        }

        this.updateById(user);
        return convertToResponse(user);
    }

    @Override
    public UserResponse getCurrentUserProfileWithResponse() {
        // 从UserContextHolder获取当前用户ID
        String currentUserId = UserContextHolder.getCurrentUserId();
        if (currentUserId == null) {
            return null;
        }

        User user = this.getById(currentUserId);
        if (user == null || user.getIsDeleted() == 1) {
            return null;
        }
        return convertToResponse(user);
    }

    @Override
    public boolean deleteUser(String id) {
        User user = this.getById(id);
        if (user == null) {
            return false;
        }
        // 使用 MyBatis-Plus 的 removeById 方法，自动处理逻辑删除
        return this.removeById(id);
    }

    @Override
    public User getByAccount(String account) {
        if (!StringUtils.hasText(account)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getAccount, account)
                .eq(User::getIsDeleted, 0);
        return this.getOne(wrapper);
    }

    @Override
    public User getByEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getEmail, email)
                .eq(User::getIsDeleted, 0);
        return this.getOne(wrapper);
    }

    @Override
    public User getByPhone(String phone) {
        if (!StringUtils.hasText(phone)) {
            return null;
        }
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone)
                .eq(User::getIsDeleted, 0);
        return this.getOne(wrapper);
    }

    @Override
    public User createUser(String account, String username, String password, String email, String phone) {
        User user = new User();
        user.setAccount(account);
        user.setUsername(username);
        user.setNickname(username); // 默认昵称与用户名相同
        user.setPassword(passwordEncoder.encode(password)); // 加密密码
        user.setEmail(email);
        user.setPhone(phone);
        user.setMemberLevel("free"); // 默认免费会员
        user.setStatus(1); // 默认启用
        user.setIsVerified(0); // 默认未验证
        user.setLastActiveTime(LocalDateTime.now());

        this.save(user);
        return user;
    }

    @Override
    public void updateLastActiveTime(String userId, LocalDateTime lastActiveTime) {
        if (!StringUtils.hasText(userId) || lastActiveTime == null) {
            return;
        }
        User user = this.getById(userId);
        if (user != null && user.getIsDeleted() == 0) {
            user.setLastActiveTime(lastActiveTime);
            this.updateById(user);
        }
    }

    /**
     * 转换为响应对象
     */
    private UserResponse convertToResponse(User user) {
        UserResponse response = new UserResponse();
        BeanUtils.copyProperties(user, response);
        response.setId(user.getId());
        if (user.getCreateTime() != null) {
            response.setCreateTime(user.getCreateTime().format(DATE_TIME_FORMATTER));
        }
        if (user.getUpdateTime() != null) {
            response.setUpdateTime(user.getUpdateTime().format(DATE_TIME_FORMATTER));
        }
        if (user.getLastActiveTime() != null) {
            response.setLastActiveTime(user.getLastActiveTime().format(DATE_TIME_FORMATTER));
        }
        return response;
    }
}