package com.cpop.system.business.service.impl;

import com.cpop.common.constant.Constants;
import com.cpop.common.utils.StringUtils;
import com.cpop.common.utils.bean.BeanUtils;
import com.cpop.core.base.entity.LoginUser;
import com.cpop.core.base.entity.PageDomain;
import com.cpop.core.base.enums.InitRoleEnum;
import com.cpop.core.utils.SecurityUtils;
import com.cpop.core.utils.SpringUtils;
import com.cpop.core.utils.sql.SqlUtils;
import com.cpop.system.business.bo.RoleBo;
import com.cpop.system.business.bo.RolePageBo;
import com.cpop.system.business.bo.RoleStatusBo;
import com.cpop.system.business.entity.RoleMenu;
import com.cpop.system.business.service.RoleMenuService;
import com.cpop.system.business.vo.RolePageVo;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.cpop.system.business.entity.Role;
import com.cpop.system.business.mapper.RoleMapper;
import com.cpop.system.business.service.RoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.cpop.system.business.entity.table.RoleMenuTableDef.ROLE_MENU;
import static com.cpop.system.business.entity.table.RoleTableDef.ROLE;

/**
 * 系统角色表 服务层实现。
 *
 * @author DB
 * @since 2023-10-19
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    /**
     * @descriptions
     * @author DB
     * @date 2023/10/19 17:13
     * @param bo 请求参数
     * @return: com.mybatisflex.core.paginate.Page<com.cpop.system.business.vo.RolePageVo>
     */
    @Override
    public Page<RolePageVo> getSysRolePageList(RolePageBo bo) {
        //获取当前用户
        LoginUser loginUser = SecurityUtils.getInstance().getLoginUser();
        PageDomain pageDomain = SqlUtils.getInstance().getPageDomain();
        Page<RolePageVo> page = this.mapper.paginateAs(pageDomain.getPageNum(), pageDomain.getPageSize(),
                QueryWrapper.create()
                        .select(ROLE.ALL_COLUMNS)
                        .where(ROLE.ID.ne(InitRoleEnum.SUPER_OAM_ROLE.getId()))
                        .and(ROLE.ROLE_NAME.like(bo.getRoleName()))
                        .and(ROLE.STATUS.eq(bo.getStatus()))
                        .and(ROLE.USER_TYPE.eq(loginUser.getUserType()))
                        .orderBy(ROLE.ORDER_NO.asc())
                , RolePageVo.class);
        if (!page.getRecords().isEmpty()) {
            //根据角色查询中间表
            List<RoleMenu> roleMenuList = SpringUtils.getBean(RoleMenuService.class).list(QueryWrapper.create()
                    .where(ROLE_MENU.ROLE_ID.in(page.getRecords().stream().map(RolePageVo::getId).collect(Collectors.toSet()))));
            page.getRecords().forEach(item -> {
                List<String> filterMenuIds = roleMenuList.stream()
                        .filter(s -> StringUtils.equals(s.getRoleId(), item.getId()))
                        .map(RoleMenu::getMenuId).collect(Collectors.toList());
                item.setMenuIds(filterMenuIds);
            });
        }
        return page;
    }

    /**
     * @descriptions
     * @author DB
     * @date 2023/10/19 17:13
     * @param bo 请求参数
     * @return: void
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertSysRole(RoleBo bo) {
        LoginUser loginUser = SecurityUtils.getInstance().getLoginUser();
        Role role = BeanUtils.mapToClass(bo, Role.class);
        role.setUserType(loginUser.getUserType());
        this.save(role);
        //将菜单信息录入中间表
        if (!bo.getMenuIds().isEmpty()) {
            List<RoleMenu> roleMenus = new ArrayList<>();
            bo.getMenuIds().forEach(item -> {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setMenuId(item);
                roleMenu.setRoleId(role.getId());
                roleMenus.add(roleMenu);
            });
            SpringUtils.getBean(RoleMenuService.class).saveBatch(roleMenus);
        }
    }

    /**
     * @descriptions
     * @author DB
     * @date 2023/10/19 17:14
     * @param bo 请求参数
     * @return: void
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysRole(RoleBo bo) {
        Role entity = new Role();
        BeanUtils.copyBeanProp(entity, bo);
        this.updateById(entity);
        //将菜单信息录入中间表
        if (!bo.getMenuIds().isEmpty()) {
            //先删后存
            RoleMenuService sysRoleMenuService = SpringUtils.getBean(RoleMenuService.class);
            sysRoleMenuService.remove(QueryWrapper.create()
                    .where(ROLE_MENU.ROLE_ID.eq(entity.getId())));
            List<RoleMenu> roleMenus = new ArrayList<>();
            bo.getMenuIds().forEach(item -> {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setMenuId(item);
                roleMenu.setRoleId(entity.getId());
                roleMenus.add(roleMenu);
            });
            sysRoleMenuService.saveBatch(roleMenus);
        }
    }

    /**
     * @descriptions
     * @author DB
     * @date 2023/10/19 17:14
     * @param id 主键
     * @return: void
     */
    @Override
    public void removeSysRole(String id) {
        this.removeById(id);
        //删除相关联菜单
        SpringUtils.getBean(RoleMenuService.class).remove(QueryWrapper.create().where(ROLE_MENU.ROLE_ID.eq(id)));
    }

    /**
     * @descriptions
     * @author DB
     * @date 2023/10/19 17:14
     * @param bo 请求参数
     * @return: void
     */
    @Override
    public void setSysRoleStatus(RoleStatusBo bo) {
        this.updateById(BeanUtils.mapToClass(bo, Role.class));
    }




}
