package com.chushang.system.remote;

import com.chushang.common.core.util.StringUtils;
import com.chushang.common.core.web.Result;
import com.chushang.datascope.entity.DataScopeEntity;
import com.chushang.security.annotation.InnerAuth;
import com.chushang.security.entity.vo.LoginUser;
import com.chushang.system.entity.po.SysUser;
import com.chushang.system.feign.RemoteUserService;
import com.chushang.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping(value = "/user")
public class RemoteUserController implements RemoteUserService {

    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysPostService sysPostService;
    @Autowired
    ISysPermissionService permissionService;

    @InnerAuth
    @GetMapping("/info/{username}")
    public Result<LoginUser<SysUser, DataScopeEntity>> getUserInfo(@PathVariable("username") String username, String source)
    {
        SysUser sysUser = sysUserService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return Result.failed("用户名或密码错误");
        }

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        // 数据权限集合
        List<DataScopeEntity> dataScopes = permissionService.getDataScopes(sysUser);

        LoginUser<SysUser, DataScopeEntity> sysUserVo = new LoginUser<>();
        sysUserVo.setUserId(sysUser.getUserId());
        sysUserVo.setUsername(sysUser.getUsername());
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setScopes(dataScopes);
        sysUserVo.setPermissions(permissions);
        // todo 用户拥有的数据权限
//        List<SysUserData> userDataList = userDataService.listUserData(sysUser);
        // 默认传递一个空Map --> 拥有管理员
        sysUserVo.setAuthDataMap(new HashMap<>());
//        if (CollectionUtil.isNotEmpty(userDataList)){
//            Map<String, Set<String>> authDataMap = new HashMap<>();
//            // 对应的数据权限
//            for (SysUserData sysUserData : userDataList) {
//                authDataMap.put(sysUserData.getDataType().getCodeType(),
//                        new HashSet<>(JSONUtil.toList(sysUserData.getDataValue(), String.class)));
//            }
//            sysUserVo.setAuthDataMap(authDataMap);
//        }
        return Result.ok(sysUserVo);
    }

}
