package com.ruoyi.api.controller.user;

import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.ruoyi.api.controller.common.AbstractApiController;
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.WxUserDto;
import com.ruoyi.weixin.service.WxUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 小程序用户管理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/authorization/login")
    public R authorization(@RequestBody @Validated WxUserDto wxUserDto) {
        User user = userService.authorization(wxUserDto);
        String token = apiTokenService.generateToken(user);
        //已注册
        return R.ok(token);
    }


    /**
     * 小程序获取手机号
     */
    @PostMapping("/wx/phone")
    public R wxPhone(@RequestBody String code) {
        WxMaPhoneNumberInfo wxMaPhoneNumberInfo = wxUserService.getPhoneByCode(code);
        HashMap<String, String> result = new HashMap<>();
        result.put("phone", wxMaPhoneNumberInfo.getPhoneNumber());
        return R.ok(result);
    }

}
