package com.yx.face.controller.api;

import com.yx.face.boot.core.BaseController;
import com.yx.face.boot.restful.RestResponse;
import com.yx.face.boot.restful.RestResult;
import com.yx.face.model.dto.WxInfoDTO;
import com.yx.face.service.FaceService;
import com.yx.face.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @description: 地址编码表(AreaCode)表控制层 <br>
 * @author: PWB <br>
 * @since: 1.0 <br>
 * @date: 2021-06-04 14:25:45 <br>
 */

@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Api(tags = "A 人脸下发相关功能接口 ＡＰＩ")
@RestController
@RequestMapping("api/next")
public class ApiController extends BaseController {

    /**
     * 服务对象
     */
    private final FaceService faceService;
    private final UserInfoService userInfoService;

    /**
     * 小程序访问
     * @param taskId
     * @return
     */
    @ApiOperation(value = "查询人脸下发是否成功")
    @GetMapping("doQueryFaceSuccess")
    public RestResult<Map<String, Object>> doQueryFaceSuccess(@RequestParam String taskId) {
        return RestResponse.ok(faceService.queryFaceSuccess(taskId));
    }

    @ApiOperation(value = "获取微信用户绑定的手机号")
    @PostMapping("doGetPhone")
    public RestResult<String> phone(@RequestBody WxInfoDTO dto) {
        return RestResponse.ok(userInfoService.getWxPhone(dto));
    }

    @ApiOperation(value = "人脸下发")
    @GetMapping("doGetFacePass")
    public RestResult<Map<String, Object>> doGetFacePass(Integer userId, String taskId) {
        return RestResponse.ok(userInfoService.doGetFacePass(userId, taskId));
    }

    @ApiOperation(value = "注册人脸认证回调接口")
    @PostMapping("doConfirmFaceNotify")
    public void doConfirmFaceNotify(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        try (InputStream is = request.getInputStream();
             BufferedInputStream bis = new BufferedInputStream(is)) {
            byte[] buffer = new byte[1024];
            int read;
            while ((read = bis.read(buffer)) != -1) {
                sb.append(new String(buffer, 0, read, StandardCharsets.UTF_8));
            }
        } catch (IOException e) {
            return;
        }
        userInfoService.confirmFaceNotify(sb.toString());
    }


}

