package org.springblade.wx.controller;

import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.wx.config.WXConfiger;
import org.springblade.wx.dto.DataDto;
import org.springblade.wx.dto.JumpWxa;
import org.springblade.wx.dto.SchemeDto;
import org.springframework.boot.web.servlet.server.Jsp;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Base64;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @author cy-computer
 */
@RestController
@Slf4j
@RequestMapping("/wx-app")
@Api(tags = "微信小程序登录模块")
public class WxAppController {
	@Resource
	private WXConfiger wxConfiger;
	@Resource
	private StringRedisTemplate stringRedisTemplate;

	private static final String ACCESS_TOKEN = "access_token:";


	@ApiOperation("获取开发数据")
	@PostMapping("/getOpenData")
	public R getOpenData(@RequestBody DataDto dataDto) {
		byte[] key = Base64.getDecoder().decode(dataDto.getSessionKey().replaceAll(" ", "+"));
		byte[] iv = Base64.getDecoder().decode(dataDto.getIv().replaceAll(" ", "+"));
		byte[] content = Base64.getDecoder().decode(dataDto.getEncryptedData().replaceAll(" ", "+"));
		AES aes = new AES(Mode.CBC, Padding.PKCS5Padding, key, iv);
		return R.data(new String(aes.decrypt(content)));
	}

	@ApiOperation("获取access_token")
	@GetMapping("/getAccessToken")
	public R getAccessTokenOfClient() {

		String appId = wxConfiger.getAppId();
		String appSecret = wxConfiger.getAppSecret();
		String accessTokenKey = ACCESS_TOKEN + appId;
		//从缓存中获取
		String accessToken = stringRedisTemplate.opsForValue().get(accessTokenKey);
		if (StringUtil.isBlank(accessToken)) {
			StringBuilder sb = new StringBuilder("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=");
			sb.append(appId).append("&secret=").append(appSecret);
			String url = sb.toString();
			String s = HttpUtil.get(url);
			JSONObject jsonObject = JSON.parseObject(s);
			accessToken = jsonObject.getString("access_token");
			if (StringUtil.isNotBlank(accessToken)) {
				stringRedisTemplate.opsForValue().set(accessTokenKey, accessToken, 7000, TimeUnit.SECONDS);
			}
		}
		return R.data(accessToken);
	}

	@ApiOperation("获取GenerateScheme")
	@GetMapping("/getGenerateScheme")
	public R getGenerateScheme(String path,String query) {
		SchemeDto schemeDto = new SchemeDto();
		schemeDto.setJump_wxa(new JumpWxa(path,query));
		String accessToken = (String)this.getAccessTokenOfClient().getData();
		String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token=" + accessToken;

		String s = HttpRequest.post(url)
			.header(Header.CONTENT_TYPE, "application/json")
			.body(JSON.toJSONString(schemeDto))
			.execute().body();
		JSONObject jsonObject = JSON.parseObject(s);
		return R.data(jsonObject);
	}

	@ApiOperation("获取openId")
	@GetMapping("/getOpenId")
	public R getOpenId(String code) {
		StringBuilder sb = new StringBuilder("https://api.weixin.qq.com/sns/jscode2session?appid=");
		sb.append(wxConfiger.getAppId())
			.append("&secret=")
			.append(wxConfiger.getAppSecret())
			.append("&js_code=")
			.append(code)
			.append("&grant_type=authorization_code");
		String url = sb.toString();
		String s = HttpUtil.get(url);
		JSONObject jsonObject = JSON.parseObject(s);
		return R.data(jsonObject);
	}

}
