package com.greenorange.promotion.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.greenorange.promotion.common.ErrorCode;
import com.greenorange.promotion.common.ResultUtils;
import com.greenorange.promotion.constant.CommonConstant;
import com.greenorange.promotion.exception.BusinessException;
import com.greenorange.promotion.exception.ThrowUtils;
import com.greenorange.promotion.model.dto.CommonBatchRequest;
import com.greenorange.promotion.model.dto.CommonRequest;
import com.greenorange.promotion.model.dto.user.UserAddRequest;
import com.greenorange.promotion.model.dto.user.UserQueryRequest;
import com.greenorange.promotion.model.dto.user.UserUpdateRequest;
import com.greenorange.promotion.model.entity.User;
import com.greenorange.promotion.model.enums.UserRoleEnum;
import com.greenorange.promotion.model.vo.user.UserVO;
import com.greenorange.promotion.service.common.CommonService;
import com.greenorange.promotion.service.user.UserService;
import com.greenorange.promotion.mapper.UserMapper;
import com.greenorange.promotion.utils.SqlUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.greenorange.promotion.constant.UserConstant.USER_LOGIN_STATE;

/**
* @author 35880
* @description 针对表【user(用户表)】的数据库操作Service实现
* @createDate 2025-03-30 23:03:14
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{


    @Resource
    private CommonService commonService;

    /**
     * 获取查询条件
     */
    @Override
    public QueryWrapper<User> getQueryWrapper(UserQueryRequest userQueryRequest) {
        Long id = userQueryRequest.getId();
        String userName = userQueryRequest.getUserName();
        String userRole = userQueryRequest.getUserRole();
        String sortField = userQueryRequest.getSortField();
        String sortOrder = userQueryRequest.getSortOrder();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        queryWrapper.eq(StringUtils.isNotBlank(userRole), "userRole", userRole);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }



    /**
     * 分页查询用户
     */
    @Override
    public Page<UserVO> listUserByPage(UserQueryRequest userQueryRequest) {
        if (userQueryRequest == null) throw new BusinessException(ErrorCode.PARAMS_ERROR);
        long current = userQueryRequest.getCurrent();
        long pageSize = userQueryRequest.getPageSize();
        QueryWrapper<User> queryWrapper = this.getQueryWrapper(userQueryRequest);
        Page<User> page = this.page(new Page<>(current, pageSize), queryWrapper);
        List<User> userList = page.getRecords();
        List<UserVO> userVOList = commonService.convertList(userList, UserVO.class);
        Page<UserVO> voPage = new Page<>();
        voPage.setRecords(userVOList);
        voPage.setPages(page.getPages());
        voPage.setCurrent(page.getCurrent());
        voPage.setTotal(page.getTotal());
        voPage.setSize(page.getSize());
        return voPage;
    }

    /**
     * 根据id查询用户
     */
    @Override
    public UserVO queryUserById(CommonRequest commonRequest) {
        if (commonRequest == null || commonRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = this.getById(commonRequest.getId());
        ThrowUtils.throwIf(user == null, ErrorCode.OPERATION_ERROR, "用户不存在");
        return commonService.copyProperties(user, UserVO.class);
    }

    /**
     * 添加用户
     */
    @Override
    public Long addUser(UserAddRequest userAddRequest) {
        if (userAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = commonService.copyProperties(userAddRequest, User.class);
        boolean result = this.save(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "用户添加失败");
        return user.getId();
    }

    /**
     * 更新用户
     */
    @Override
    public boolean updateUser(UserUpdateRequest userUpdateRequest) {
        if (userUpdateRequest == null || userUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = commonService.copyProperties(userUpdateRequest, User.class);
        boolean result = this.updateById(user);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "用户更新失败");
        return true;
    }

    /**
     * 删除用户
     */
    @Override
    public boolean deleteUser(CommonRequest commonRequest) {
        if (commonRequest == null || commonRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = commonRequest.getId();
        boolean result = this.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "用户删除失败");
        return true;
    }

    /**
     * 批量删除用户
     */
    @Override
    public boolean delBatchUser(CommonBatchRequest commonBatchRequest) {
        if (commonBatchRequest == null || CollectionUtils.isEmpty(commonBatchRequest.getIds())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        List<Long> ids = commonBatchRequest.getIds();
        boolean result = this.removeByIds(ids);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "用户批量删除失败");
        return true;
    }


    /**
     * 获取当前登录用户
     */
    @Override
    public User getLoginUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        Object userObj = session.getAttribute(USER_LOGIN_STATE);
        User currentUser = (User) userObj;
        if (currentUser == null || currentUser.getId() == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //根据id进行查询
        Long userId = currentUser.getId();
        currentUser = this.getById(userId);
        if (currentUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        //被封号
        if (UserRoleEnum.BAN.getValue().equals(currentUser.getUserRole())) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR);
        }
        return currentUser;
    }

}




