package com.ruoyi.api.controller.user;

import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.stp.StpUtil;
import com.ruoyi.api.controller.common.AbstractApiController;
import com.ruoyi.clock.domain.Employee;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.framework.web.service.ApiTokenService;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IUserService;
import com.ruoyi.weixin.domain.WxEmployeeDto;
import com.ruoyi.weixin.domain.WxUserDto;
import com.ruoyi.weixin.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * 小程序用户管理Controller
 *
 * @author wuchao
 * @date 2022-03-03
 */
@Validated
@Api(value = "小程序用户管理控制器", tags = {"小程序用户管理管理"})
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/miniapp/user")
public class ApiUserLoginController extends AbstractApiController {
    @Autowired
    private IUserService userService;

    @Autowired
    private ApiTokenService apiTokenService;

    private final WxUserService wxUserService;

    /**
     * 小程序登录
     */
    @ApiOperation("小程序登录")
    @PostMapping("/wx/login")
    public R login(@RequestBody @Validated WxEmployeeDto wxEmployeeDto) {
        Employee user = userService.login(wxEmployeeDto);
        String token = apiTokenService.generateEmployeeToken(user);
        return R.ok(token);
    }

    @ApiOperation("登出方法")
    @PostMapping("/logout")
    public R<Void> logout(HttpServletRequest request) {
        try {
            String accessToken = request.getHeader(Constants.API_TOKEN);
            StpUtil.logoutByTokenValue(accessToken);
        } catch (NotLoginException e) {
        }
        return R.ok("退出成功");
    }

}
