package com.fdage.service.impl;

import com.fdage.dao.base.TbRoleMapper;
import com.fdage.dao.cust.TbRoleMapperCust;
import com.fdage.pojo.TbRole;
import com.fdage.request.RequestBase;
import com.fdage.respon.ResponRole;
import com.fdage.respon.ResponUser;
import com.fdage.service.IRoleService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Hb_zzZ on 2020/7/27.
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private TbRoleMapper roleMapper;

    @Autowired
    private TbRoleMapperCust roleMapperCust;

    @Override
    public TbRole findById(Long id) {
        return roleMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(TbRole role) {
        return roleMapper.insertSelective(role);
    }

    @Override
    public int update(TbRole role) {
        return roleMapper.updateByPrimaryKeySelective(role);
    }

    @Override
    public void deleteRoleResource(Long roleId) {
        roleMapperCust.deleteRoleResource(roleId);
    }

    @Override
    public void saveRoleResource(Long roleId, Long resourceId) {
        Map<String, Object> map = new HashMap<>();
        map.put("roleId", roleId);
        map.put("resourceId", resourceId);
        roleMapperCust.saveRoleResource(map);
    }

    @Override
    public int saveRoleUser(Long roleId, Long userId) {
        Map<String, Object> map = new HashMap<>();
        map.put("roleId", roleId);
        map.put("userId", userId);

        return roleMapperCust.saveRoleUser(map);
    }

    @Override
    public int deleteRoleUser(Long userId) {
        return roleMapperCust.deleteRoleUser(userId);
    }

    @Override
    public List<ResponRole> findRoleList(RequestBase bo) {
        int pageNum = bo.getPageNum() == 0? 1: bo.getPageNum();
        int pageSize = bo.getPageSize() == 0? 10: bo.getPageSize();
        PageHelper.startPage(pageNum, pageSize);
        List<ResponRole> list = roleMapperCust.findRoleList();
        for(ResponRole responRole : list){
            responRole.setUserName(roleMapperCust.findUserNameByRoleId(responRole.getId()));
        }
        return list;
    }

    @Override
    public List<ResponUser> findUserListByRoleId(Long roleId) {
        return roleMapperCust.findUserByRoleId(roleId);
    }

    @Override
    public List<String> findUserNameByRoleId(Long roleId) {
        return roleMapperCust.findUserNameByRoleId(roleId);
    }

    @Override
    public ResponRole findRoleById(Long roleId) {
        TbRole role = roleMapper.selectByPrimaryKey(roleId);
        ResponRole responRole = new ResponRole();

        BeanUtils.copyProperties(role, responRole);
        responRole.setUserName(roleMapperCust.findUserNameByRoleId(responRole.getId()));
        return responRole;
    }
}
