package com.yanzhu.auth.controller;

import com.yanzhu.auth.form.LoginBody;
import com.yanzhu.auth.form.RegisterBody;
import com.yanzhu.auth.form.WxMaLoginBody;
import com.yanzhu.auth.form.WxMaOpenIdBody;
import com.yanzhu.auth.service.SysLoginService;
import com.yanzhu.common.core.constant.SecurityConstants;
import com.yanzhu.common.core.domain.R;
import com.yanzhu.common.core.text.Convert;
import com.yanzhu.common.core.utils.JwtUtils;
import com.yanzhu.common.core.utils.StringUtils;
import com.yanzhu.common.security.auth.AuthUtil;
import com.yanzhu.common.security.service.TokenService;
import com.yanzhu.common.security.utils.SecurityUtils;
import com.yanzhu.system.api.RemoteProService;
import com.yanzhu.system.api.RemoteUserService;
import com.yanzhu.system.api.domain.SysUser;
import com.yanzhu.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
import java.util.Objects;

/**
 * token 控制
 * 
 * @author ruoyi
 */
@RestController
public class TokenController
{
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private RemoteProService remoteProService;

    @Autowired
    private RemoteUserService remoteUserService;

    /**
     * 账号密码登录
     * @param form
     * @return
     */
    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form)
    {
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }

    /**
     * 获取小程序授权
     * @param body 请求参数
     * @return
     */
    @PostMapping("getMaOpenId")
    public R<?> getMaOpenId(@RequestBody @Valid WxMaOpenIdBody body)
    {
        String maOpenId = sysLoginService.getMaOpenId(body.getCode());
        // 获取授权openId
        return R.ok(maOpenId);
    }

    /**
     * 微信小程序一键登录
     * @param body 请求参数
     * @return
     */
    @PostMapping("maLogin")
    public R<?> maLogin(@RequestBody @Valid WxMaLoginBody body)
    {
        // 用户登录
        Map<String,Object> result = sysLoginService.maLogin(body);
        // 获取登录token
        return R.ok(result);
    }

    /**
     * 切换项目登录
     * @param proId 切换项目登录
     * @return
     */
    @GetMapping("/switchProject/{proId}")
    public R<?> switchProject(@PathVariable("proId") Long proId,HttpServletRequest request)
    {
        if(SecurityUtils.isAdmin(SecurityUtils.getUserId()) || SecurityUtils.isGSAdmin()){
            LoginUser loginUser = tokenService.getLoginUser(request);
            if (StringUtils.isNotNull(loginUser))
            {
                R<Map<String, Object>> dataResult = remoteProService.info(proId,SecurityConstants.INNER);
                Map<String, Object> proData = dataResult.getData();
                SysUser user = loginUser.getSysUser();
                user.setActiveComId(Convert.toLong(proData.get("comId")));
                user.setActiveComName(Convert.toStr(proData.get("comName")));
                user.setActiveProjectId(Convert.toLong(proData.get("id")));
                user.setActiveProjectName(Convert.toStr(proData.get("projectName")));
                loginUser.setSysUser(user);
                loginUser.setProjectId(Convert.toLong(proData.get("id")));
                loginUser.setProjectName(Convert.toStr(proData.get("projectName")));
                loginUser.setProjectDeptId(Convert.toLong(proData.get("comId")));
                loginUser.setProjectDeptName(Convert.toStr(proData.get("comName")));
                // 刷新令牌有效期
                tokenService.refreshToken(loginUser);
                return R.ok();
            }
        }else{
            // 查询用户信息
            R<LoginUser> userResult = remoteUserService.getUserInfo(SecurityUtils.getUsername(), proId, SecurityConstants.INNER);
            LoginUser userInfo = userResult.getData();
            SysUser user = userResult.getData().getSysUser();
            // 补充用户项目信息
            if(Objects.nonNull(user.getActiveComId())){
                userInfo.setProjectDeptId(user.getActiveComId());
            }
            if(Objects.nonNull(user.getActiveComName())){
                userInfo.setProjectDeptName(user.getActiveComName());
            }
            if(Objects.nonNull(user.getActiveProjectId())){
                userInfo.setProjectId(user.getActiveProjectId());
            }
            if(Objects.nonNull(user.getActiveProjectName())){
                userInfo.setProjectName(user.getActiveProjectName());
            }
            // 刷新令牌有效期
            tokenService.refreshToken(userInfo);
            return R.ok();
        }
        return R.fail();
    }

    /**
     * 取消项目登录
     * @return
     */
    @GetMapping("/cancelProject")
    public R<?> cancelProject(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(SecurityUtils.isAdmin(loginUser.getUserid())){
            SysUser user = loginUser.getSysUser();
            user.setActiveComId(null);
            user.setActiveProjectId(null);
            user.setActiveProjectName(null);
            loginUser.setSysUser(user);
            loginUser.setProjectId(null);
            loginUser.setProjectName(null);
            loginUser.setProjectDeptId(null);
        }else{
            SysUser user = loginUser.getSysUser();
            user.setActiveProjectId(null);
            user.setActiveProjectName(null);
            loginUser.setSysUser(user);
            loginUser.setProjectId(null);
            loginUser.setProjectName(null);
        }
        // 刷新令牌有效期
        tokenService.refreshToken(loginUser);
        return R.ok();
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request)
    {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token))
        {
            String username = JwtUtils.getUserName(token);
            // 删除用户缓存记录
            AuthUtil.logoutByToken(token);
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request)
    {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser))
        {
            // 刷新令牌有效期
            tokenService.refreshToken(loginUser);
            return R.ok();
        }
        return R.ok();
    }

    @PostMapping("register")
    public R<?> register(@RequestBody RegisterBody registerBody)
    {
        // 用户注册
        sysLoginService.register(registerBody.getUsername(), registerBody.getPassword());
        return R.ok();
    }
}
