package com.duanledexianxianxian.demo.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.duanledexianxianxian.demo.common.util.BeanUtils;
import com.duanledexianxianxian.demo.dao.MenuDao;
import com.duanledexianxianxian.demo.domain.dto.MenuDTO;
import com.duanledexianxianxian.demo.domain.dto.UserDTO;
import com.duanledexianxianxian.demo.domain.entity.Menu;
import com.duanledexianxianxian.demo.domain.entity.User;
import com.duanledexianxianxian.demo.dao.UserDao;
import com.duanledexianxianxian.demo.domain.model.query.UserForm;
import com.duanledexianxianxian.demo.domain.model.query.UserQuery;
import com.duanledexianxianxian.demo.service.IMenuService;
import com.duanledexianxianxian.demo.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 用户服务接口实现类
 *
 * @author duanledexianxianxian
 * @since 2020 -03-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements IUserService {
    @Autowired
    IMenuService menuService;

    @Override
    public IPage getUserListPage(UserQuery query) {
        IPage page = new Page(query.getPageNum(), query.getPageSize());
        List<User> userList = this.baseMapper.getList(page, query);
        page.setRecords(BeanUtils.copyList(userList, UserDTO.class));
        return page;
    }

    @Override
    public UserDTO getUserDetail(Long userId) {
        User user = this.baseMapper.selectById(userId);
        // 需要检查用户是否存在
        UserDTO userDTO = BeanUtils.copyObject(user, UserDTO.class);
        List<MenuDTO> menuDTOList = menuService.getUserMenuList(userId);
        userDTO.setMenuList(menuDTOList);
        return userDTO;
    }


    @Override
    public Long addUser(UserForm form) {
        // 做插入前检查
        User user = BeanUtils.copyObject(form, User.class);
        this.baseMapper.insert(user);
        return user.getUserId();
    }

    @Override
    public Boolean editUser(UserForm form) {
        // 做编辑前检查
        User user = BeanUtils.copyObject(form, User.class);
        return SqlHelper.retBool(this.baseMapper.updateById(user));
    }

    @Override
    public Boolean deleteUser(Long userId) {
        // 做删除前检查
        return SqlHelper.retBool(this.baseMapper.deleteById(userId));
    }
}
