package com.ema.admin.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.ema.admin.modules.system.converter.SysUserConverter;
import com.ema.admin.modules.system.entity.SysRole;
import com.ema.admin.modules.system.entity.SysUser;
import com.ema.admin.modules.system.entity.SysUserRole;
import com.ema.admin.modules.system.mapper.SysUserMapper;
import com.ema.admin.modules.system.service.SysRoleService;
import com.ema.admin.modules.system.service.SysUserRoleService;
import com.ema.admin.modules.system.service.SysUserService;
import com.ema.admin.modules.system.vo.SysUserInfoVo;
import com.ema.admin.modules.system.vo.SysUserQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户信息表 服务层实现。
 *
 * @author LIJIAN
 * @since 2026-03-23
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser>  implements SysUserService{

    @Resource
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysUserConverter sysUserConverter;
    @Autowired
    private SysRoleService sysRoleService;

    @Override
    public SysUser getByAccount(String account) {
        return this.queryChain().eq(SysUser::getAccount, account).one();
    }

    @Override
    public void saveUserRole(String userId, String roleId) {
        SysUserRole sysUserRole = SysUserRole.builder()
                .userId(userId)
                .roleId(roleId)
                .build();
        sysUserRoleService.save(sysUserRole);
    }

    @Override
    public Page<SysUserInfoVo> page(SysUserQueryVo queryVo) {
        Page<SysUser> userPage = pageSysUser(queryVo);
        List<SysUserInfoVo> voList = userPage.getRecords().stream().map(sysUser -> {
            List<SysRole> roleList = sysRoleService.getRoleByUserId(sysUser.getId());
            return sysUserConverter.toSysUserInfoVo(sysUser,roleList);
        }).collect(Collectors.toList());
        return new Page(voList,  userPage.getPageNumber(), userPage.getPageSize(), userPage.getTotalRow());
    }

    @Override
    public Page<SysUser> pageSysUser(SysUserQueryVo queryVo) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.like(SysUser::getAccount, queryVo.getAccount(), StrUtil.isNotBlank(queryVo.getAccount()));
        queryWrapper.like(SysUser::getName, queryVo.getName(), StrUtil.isNotBlank(queryVo.getName()));
        queryWrapper.like(SysUser::getPhone, queryVo.getPhone(), StrUtil.isNotBlank(queryVo.getPhone()));
        queryWrapper.like(SysUser::getEmail, queryVo.getEmail(), StrUtil.isNotBlank(queryVo.getEmail()));
        queryWrapper.eq(SysUser::getStatus, queryVo.getStatus(), StrUtil.isNotBlank(queryVo.getStatus()));
        return this.page(new Page<>(queryVo.getPageNumber(), queryVo.getPageSize()), queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRolesToUser(String userId, List<String> roleIds) {

        // 先删除用户角色关联
        sysUserRoleService.remove(sysUserRoleService.queryChain()
                .eq(SysUserRole::getUserId, userId));

        if(CollUtil.isNotEmpty(roleIds)){
            // 批量创建用户角色关联
            List<SysUserRole> userRoles = roleIds.stream()
                    .map(roleId -> SysUserRole.builder()
                            .userId(userId)
                            .roleId(roleId)
                            .build())
                    .collect(Collectors.toList());
            sysUserRoleService.saveBatch(userRoles);
        }
    }
}
