package com.qmth.sop.server.api;

import com.qmth.boot.api.annotation.Aac;
import com.qmth.boot.api.constant.ApiConstant;
import com.qmth.sop.business.bean.result.LoginResult;
import com.qmth.sop.business.service.TWxappInfoService;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.util.Result;
import com.qmth.sop.common.util.ResultUtil;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * 微信 前端控制器
 * </p>
 *
 * @author wangliang
 * @since 2023-07-17
 */
@Api(tags = "微信Controller")
@RestController
@RequestMapping(ApiConstant.DEFAULT_URI_PREFIX + SystemConstant.PREFIX_URL_WXAPP)
public class WxappController {
    private final static Logger log = LoggerFactory.getLogger(WxappController.class);

    @Resource
    TWxappInfoService tWxappInfoService;

    @ApiOperation(value = "微信登录")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "微信用户信息", response = LoginResult.class)})
    @Aac(auth = false)
    public Result login(@ApiParam(value = "登录代码", required = true) @RequestParam String loginCode) throws NoSuchAlgorithmException {
        return ResultUtil.ok(tWxappInfoService.wxappLogin(loginCode));
    }

    @ApiOperation(value = "绑定微信手机号并登录（新api）")
    @RequestMapping(value = "/login/phone_code", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "微信用户信息", response = LoginResult.class)})
    @Aac(auth = false)
    public Result loginWxAppByPhoneCode(@ApiParam(value = "登录代码", required = true) @RequestParam String loginCode,
                                        @ApiParam(value = "手机代码", required = true) @RequestParam String phoneCode) throws NoSuchAlgorithmException {
        return ResultUtil.ok(tWxappInfoService.wxappLoginByPhoneCode(loginCode, phoneCode));
    }

    @ApiOperation(value = "绑定微信手机号并登录（旧api）")
    @RequestMapping(value = "/login/encrypted_data", method = RequestMethod.POST)
    @ApiResponses({@ApiResponse(code = 200, message = "微信用户信息", response = LoginResult.class)})
    @Aac(auth = false)
    public Result loginWxAppByEncryptedData(@ApiParam(value = "登录代码", required = true) @RequestParam String loginCode,
                                            @ApiParam(value = "加密数据", required = true) @RequestParam String encryptedData,
                                            @ApiParam(value = "base64数据", required = true) @RequestParam String iv) throws NoSuchAlgorithmException {
        return ResultUtil.ok(tWxappInfoService.wxappLoginByEncryptedData(loginCode, encryptedData, iv));
    }
}
