package com.jd.lightapplication.weChat;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.jd.lightapplication.common.lang.R;
import com.jd.lightapplication.common.lang.WeChatConfig;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController()
@RequestMapping("/api/wechat")
@ApiOperation("微信相关接口")
@AllArgsConstructor
public class WeChatController {

    private RedisTemplate redisTemplate;

    //跳转的页面路径
    private final String PAGE = "pages/login/login";
    //小程序版本 release:正式版 trial:体验版 develop:开发版
    private final String ENV_VERSION = "trial";

    private WeChatConfig weChatConfig;

    private final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s";
    private final String GET_QRCODE_URL = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=%s";


    @PostMapping("/getQrCode")
    @ApiOperation("获取小程序码")
    public void getQrCode(@RequestBody Map<Object,Object> params, HttpServletResponse response) throws IOException {
        //把参数存到redis里面并设置过期时间
        String uuid = IdUtil.simpleUUID();
        redisTemplate.opsForValue().set(uuid, params, 2, TimeUnit.HOURS);

        //拼接请求路径
        String url = String.format(GET_QRCODE_URL, this.getAccessToken());
        //封装请求参数
        Map<Object, Object> requestParams = MapUtil.builder()
                .put("scene", uuid)
                .put("page", PAGE)
                .put("env_version", ENV_VERSION)
                .map();
        //拿到response输出流
        OutputStream outputStream = response.getOutputStream();
        //拿到微信返回的二维码输入流
        InputStream inputStream = HttpRequest.post(url)
                .body(JSONUtil.parse(requestParams).toString())
                .execute()
                .bodyStream();
        //写如输出流
        int len;
        byte[] arr = new byte[1024];
        while ((len = inputStream.read(arr)) != -1) {
            outputStream.write(arr, 0, len);
            outputStream.flush();
        }
        //关闭输出流和输入流
        outputStream.close();
        inputStream.close();
    }

    @GetMapping("/getQrCodeParams")
    @ApiOperation("获取小程序码里面的参数")
    public R getQrCodeParams(String key) throws IOException {
        Object qrCodeParams = redisTemplate.opsForValue().get(key);
        return qrCodeParams == null ? R.fail("二维码已失效。") : R.success(qrCodeParams);
    }

    /**
     * 获取accessToken
     *
     * @return
     */
    private String getAccessToken() {
        //拼接access_token请求地址
        String accessTokenUrl = String.format(ACCESS_TOKEN_URL, weChatConfig.getAppId(), weChatConfig.getAppSecret());
        //先获取access_token
        String accessTokenResult = HttpRequest.get(accessTokenUrl)
                .execute()
                .charset("UTF-8")
                .body();
        JSONObject result = JSONUtil.parseObj(accessTokenResult);
        String accessToken = result.get("access_token").toString();
        return accessToken;
    }

}
