package com.crunii.micro.service.sysmgr.controller;

import com.crunii.micro.common.dto.Result;
import com.crunii.micro.domain.entity.main.WechatJsConfigVO;
import com.crunii.micro.feign.client.dto.WechatLoginDto;
import com.crunii.micro.feign.client.dto.WechatLoginVo;
import com.crunii.micro.service.sysmgr.service.WechatService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

/**
 * 微信公众号交互
 */
@Api("微信授权")
@RestController
@RequestMapping("/wechatController")
public class WechatController {

    @Autowired
    private WechatService wechatService;

    /**
     * 获取授权url
     * @param map
     * @return
     * @throws UnsupportedEncodingException
     */
    @PostMapping("/authorization")
    public String authorization(@RequestBody Map<String, String> map) throws UnsupportedEncodingException {
        String url = map.get("url");
        return wechatService.authorization(url);
    }

    @PostMapping("/serverAuth")
    public String serverAuth(@RequestParam Map<String, String> map) throws NoSuchAlgorithmException {
        return wechatService.serverAuth(map);
    }

    /**
     * 微信公众号单点登录
     * @param request
     * @param wechatLoginDto
     * @return
     */
    @PostMapping("/wechatLogin")
    public Result<WechatLoginVo> wechatLogin(HttpServletRequest request, @RequestBody WechatLoginDto wechatLoginDto) {
        return wechatService.wechatLogin(request, wechatLoginDto);
    }

    /**
     * h5获取照片权限所需的签名
     * @param map
     * @return
     */
    @PostMapping("/getJsConfig")
    public Result<WechatJsConfigVO> getJsConfig(@RequestBody Map<String, String> map) {
        String url = map.get("url");
        return wechatService.getJsConfig(url);
    }

    @GetMapping("/getOpenId/{code}")
    public Result<String> getOpenId(@PathVariable("code") String code) {
        return Result.ofSuccess(wechatService.getOpenId(code));
    }
}
