package com.eleadmin.common.system.controller;

import cn.hutool.http.HttpUtil;
import com.eleadmin.common.core.config.ConfigProperties;
import com.eleadmin.common.core.security.JwtSubject;
import com.eleadmin.common.core.security.JwtUtil;
import com.eleadmin.common.core.utils.CommonUtil;
import com.eleadmin.common.core.utils.JSONUtil;
import com.eleadmin.common.core.web.ApiResult;
import com.eleadmin.common.core.web.BaseController;
import com.eleadmin.common.system.entity.*;
import com.eleadmin.common.system.param.UserParam;
import com.eleadmin.common.system.result.LoginResult;
import com.eleadmin.common.system.service.UserRoleService;
import com.eleadmin.common.system.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 第三方登录认证控制器
 *
 * @author 科技小王子
 * @since 2018-12-24 16:10:11
 */
@Api(tags = "第三方登录认证")
@RestController
@RequestMapping("/api/auth")
public class AuthController extends BaseController {
    @Resource
    private ConfigProperties configProperties;
    @Resource
    private UserService userService;
    @Resource
    private UserRoleService userRoleService;

    @ApiOperation("获取sessionId")
    @GetMapping("getSessionId")
    public String getSessionId(String code){
      return userService.getSessionId(code);
    }

    @ApiOperation("第三方登录")
    @PostMapping("/login")
    public ApiResult<LoginResult> login(@RequestBody UserParam param, HttpServletRequest request) {
        Integer tenantId = param.getTenantId();
        String code = param.getCode();

        // 获取openid
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code";
        String replaceUrl = url.replace("{0}","wx2766b62be0ef0e6f").replace("{1}","205451097a44ef67b6684f50c93c23af").replace("{2}",code);
        String res = HttpUtil.get(replaceUrl);
        Map<String,String> map = JSONUtil.parseObject(res, Map.class);
        String openid = map.get("openid");

        System.out.println(param);

        // 根据openid查询用户是否存在，不存在则创建，存在则登录成功并返回
        User user = userService.getByOpenid(openid, tenantId);
        if (user == null) {
            // 添加用户
            User u = new User();
            u.setOpenid(openid);
            u.setTenantId(param.getTenantId());
            u.setUsername("wx_" + CommonUtil.randomUUID16());
            u.setNickname(param.getNickname());
            u.setAvatar(param.getAvatar());
            u.setSex(param.getSex());
            u.setPassword(userService.encodePassword(CommonUtil.randomUUID16()));
            userService.saveUser(u);

            // 添加默认角色(普通用户)
            UserRole userRole = new UserRole();
            userRole.setUserId(u.getUserId());
            userRole.setRoleId(5);
            userRole.setTenantId(u.getTenantId());
            userRoleService.save(userRole);

            user = u;
        }
        // 移除敏感信息
        user.setPassword(null);
        user.setOpenid(null);
        // 签发token
        String access_token = JwtUtil.buildToken(new JwtSubject(user.getUsername(), tenantId),
                configProperties.getTokenExpireTime(), configProperties.getTokenKey());
        return success("登录成功", new LoginResult(access_token, user));
    }
}
