package com.qmth.exam.reserve.controller.student;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.boot.core.exception.StatusException;
import com.qmth.exam.reserve.bean.Constants;
import com.qmth.exam.reserve.bean.student.StudentInfo;
import com.qmth.exam.reserve.bean.student.WechatBindReq;
import com.qmth.exam.reserve.config.WxProperty;
import com.qmth.exam.reserve.controller.BaseController;
import com.qmth.exam.reserve.service.StudentService;
import com.qmth.exam.reserve.weixin.OauthAccessTokenRequest;
import com.qmth.exam.reserve.weixin.response.OauthAccessTokenResponseJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(tags = "【考生端】考生相关接口")
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + "/student")
@Aac(strict = false, auth = true)
public class StudentController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(StudentController.class);

    @Autowired
    private StudentService studentService;

    @Autowired
    private WxProperty wxProperty;

    @ApiOperation(value = "考生账号与微信号绑定")
    @PostMapping(value = "/wechat/binding")
    public void binding(@RequestBody WechatBindReq req) {
        req.setStudentId(curLoginStudent().getId());
        studentService.bindingWechat(req);
    }

    @ApiOperation(value = "考生账号与微信号解绑")
    @PostMapping(value = "/wechat/unbind")
    public void unbind() {
        studentService.unbindWechatByStudentId(curLoginStudent().getId());
    }

    @ApiOperation(value = "获取考生信息")
    @PostMapping(value = "/info")
    public StudentInfo info() {
        return studentService.findInfoByStudentId(curLoginStudent().getId());
    }

    @Aac(strict = false, auth = false)
    @ApiOperation(value = "获取微信用户的openid")
    @PostMapping(value = "/wechat/get/openid")
    public String getOpenid(@ApiParam("微信用户code") @RequestParam String code) {
        OauthAccessTokenRequest tokenRequest = new OauthAccessTokenRequest(code, wxProperty.getAppId(), wxProperty.getAppSecret());
        OauthAccessTokenResponseJson response = tokenRequest.request();
        if (response.getErrcode() != 0) {
            log.warn("获取微信用户的openid失败！code:{}", code);
            throw new StatusException(Constants.REQUEST_API_BUSY);
        }
        return response.getOpenid();
    }

}
