package com.sysu.admin.site;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.sysu.admin.support.base.BaseComponent;
import com.sysu.admin.support.system.user_role.UserRoleService;
import com.xiesx.fastboot.base.result.BaseResult;
import com.xiesx.fastboot.base.result.R;
import com.xiesx.fastboot.core.token.JwtHelper;
import com.xiesx.fastboot.core.token.cfg.TokenCfg;
import com.sysu.admin.support.system.role_permission.RolePermissionService;
import com.sysu.admin.support.system.user.User;
import com.sysu.admin.support.system.user.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/site/user")
public class SiteUserController extends BaseComponent {

    @Autowired
    UserService userService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    RolePermissionService rolePermissionService;

    @RequestMapping("login")
    public BaseResult login(@RequestBody String data){
        UserVo userVo = JSON.parseObject(data, UserVo.class);
        validate(userVo);
        // 密码加密
        String password = DigestUtils.md5Hex(userVo.getUserName() + userVo.getPwd());
        // 查找用户
        User user = userService.findByUsername(userVo.getUserName());
        // 判断密码
        if (!password.equals(user.getPassword())) {
           return R.fail("密码错误！");
        }
        BeanUtils.copyProperties(user, userVo);
        Map<String, Object> claims = Maps.newConcurrentMap();
        claims.put(TokenCfg.USERID, user.getId());
        claims.put(TokenCfg.USERNAME, user.getUsername());
        String token = JwtHelper.create("zedu", "api", claims, JwtHelper.JWT_EXPIRE_D_7);
        userVo.setToken(token);
        Long roleId = userRoleService.getRoleByUsers(user.getId()).stream().findFirst().get().getPk().roles();
        userVo.setRoleId(roleId.intValue());
        userVo.setPermissions(rolePermissionService.getPermissions(roleId));
        return R.succ(userVo);
    }
}
