package com.boman.auth.controller;

import com.boman.auth.service.SysLoginService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import com.boman.common.core.exception.BaseException;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.security.service.TokenService;
import com.boman.domain.SysUser;
import com.boman.domain.WechatEnum;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.dto.R;
import com.boman.domain.form.LoginBody;
import com.boman.system.api.model.LoginUser;
import com.boman.wechat.api.RemoteWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;


/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
//@CrossOrigin
public class TokenController {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysLoginService sysLoginService;
    @Resource
    private RemoteWechatService remoteWechatService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        String openId = "";
        // 验证是pc还是小程序
        if (form.getLogintype() != null && form.getLogintype().equals(WechatEnum.W.getValue())) {
            AjaxResult result = remoteWechatService.getWechatInfo(form);
            if ((Integer) result.get(AjaxResult.CODE_TAG) != 0) {
                throw new BaseException((String) result.get(AjaxResult.MSG_TAG));
            }
            Map<String, Object> jsonObject = (Map<String, Object>) result.get(AjaxResult.DATA_TAG);
            if (jsonObject == null) {
                throw new BaseException("未获取到微信鉴权相关信息！");
            }
            openId = (String) jsonObject.get("openId");
        }
        // 用户登录
        LoginUser userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
        // 如果是微信登录并且获取到的用户的unionId不为空
        if (form.getLogintype() != null
                && form.getLogintype().equals(WechatEnum.W.getValue())
                && StringUtils.isNotEmpty(openId)) {
            SysUser sysUser = new SysUser();
            sysUser.setId(userInfo.getSysUser().getId());
            sysUser.setOpenId(openId);
            AjaxResult updateResult = sysLoginService.updateUnionId(sysUser);
            if ((Integer) updateResult.get(AjaxResult.CODE_TAG) != 0) {
                throw new BaseException("保存小程序唯一标识出错！");
            }
        }
        // 获取登录token
        return R.ok(tokenService.createToken(userInfo));
    }


    /**
     * 产生uuid二维码
     */
    @PostMapping("getQrCode")
    public R<?> getQrCode() {
        String qrCode = tokenService.getQrCode();
        return R.ok(qrCode);
    }


    /**
     * 判断二维码是否被扫描
     */
    @GetMapping("getPool/{uuid}")
    public R<?> getPool(@PathVariable String uuid) {
        return tokenService.getPool(uuid);
    }


    /**
     * 扫码成功进入确认登录页面记录状态
     *
     * @param uuid
     * @return
     */
    @GetMapping(value = "scanCode/{uuid}")
    public R<?> scanCode(@PathVariable String uuid) {
        return tokenService.scanCode(uuid);
    }

    /**
     * app扫码登录
     *
     * @param form
     * @return
     */
    @PostMapping("phoneScanLogin")
    public R<?> phoneScanLogin(@RequestBody LoginBody form) {
        return sysLoginService.phoneScanLogin(form);
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            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();
    }
}
