package com.jd.lightapplication.controller;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.code.kaptcha.Producer;
import com.jd.lightapplication.common.lang.Const;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.model.SysRole;
import com.jd.lightapplication.model.SysUser;
import com.jd.lightapplication.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.Principal;
import java.util.List;
import java.util.UUID;

/**
 * 功能描述：验证控制器
 *
 * @Author WaiterXiaoYY
 * @Date 2022/1/17 13:51
 * @Version 1.0
 */

@RestController
public class AuthController extends BaseController {

    @Autowired
    Producer producer;

    @Resource
    private SysRoleService sysRoleService;

    @GetMapping("/captcha")
    public R captcha() throws IOException {
        String key = UUID.randomUUID().toString();
        String code = producer.createText();


        BufferedImage image = producer.createImage(code);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";

        String base64Img = str + encoder.encode(outputStream.toByteArray());

        redisUtil.hset(Const.CAPTCHA_KEY, key, code, 120);

        return R.success(
                MapUtil.builder()
                        .put("token", key)
                        .put("captchaImg", base64Img)
                        .build()

        );
    }

    /**
     * 获取用户信息接口
     *
     * @param principal
     * @return
     */
    @GetMapping("/sys/userInfo")
    public R userInfo(Principal principal) {

        //SysUser sysUser = sysUserService.getByUsername(principal.getName());
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        return R.success(MapUtil.builder()
                .put("id", sysUser.getId())
                .put("username", sysUser.getUsername())
                .put("usernameShow", sysUser.getUsernameShow())
                .put("avatar", sysUser.getAvatar())
                .put("created", sysUser.getCreated())
                .map()
        );
    }

    /**
     * 获取用户信息和角色接口
     *
     * @return
     */
    @GetMapping("/sys/userInfoAndRole")
    public R userInfoAndRole() {
        //从SecurityContextHolder里面取认证信息强转成SysUser实体类，这个实体是在权限认证成功后放入到SecurityContextHolder的
        SysUser sysUser = (SysUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //获取用户权限
        List<SysRole> roleList = sysRoleService.list(
                Wrappers.lambdaQuery(new SysRole())
                        .inSql(SysRole::getId,"SELECT role_id FROM sys_user_role WHERE user_id = " + sysUser.getId())
        );
        return R.success(MapUtil.builder()
                .put("id", sysUser.getId())
                .put("usernameShow", sysUser.getUsernameShow())
                .put("nickName",sysUser.getNickName())
                .put("phone",sysUser.getPhone())
                .put("headImgUrl",sysUser.getHeadImgUrl())
                .put("created", sysUser.getCreated())
                .put("roleList",roleList)
                .map()
        );
    }
}
