package org.springblade.wx.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.wx.config.ConfigForOfficial;
import org.springblade.wx.constant.MiniProgramType;
import org.springblade.wx.service.WeChatService;
import org.springblade.wx.utils.Sign;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author cy-computer
 */
@RestController
@Slf4j
@RequestMapping("/wxOfficial")
@Api(tags = "微信公众号")
@AllArgsConstructor
public class WxOfficialController {

	private WeChatService weChatService;
	private ConfigForOfficial configForOfficial;
	private StringRedisTemplate stringRedisTemplate;
	private static final String JsAPI_TICKET = "jsApi_ticket:";

	@GetMapping("/getShareData")
	@ApiOperation("获取分享所需参数")
	public R getShareData(String url) throws UnsupportedEncodingException {
		url = URLDecoder.decode(url, "UTF-8");
		//获取app的accessToken
		String accessToken = weChatService.fetchAccessToken(MiniProgramType.OFFICIAL);
		Assert.notNull(accessToken, "获取程序accessToken失败");
		String jsApiTicket = getJsApiTicket(accessToken);
		Assert.notNull(jsApiTicket, "获取jsApiTicket失败");
		Map<String, String> ret = Sign.getSign(jsApiTicket, url);
		ret.put("appId", configForOfficial.getAppId());
		return R.data(ret);
	}
	/**
	 *
	 * @pram accessToken
	 * @return
	 */
	private String getJsApiTicket(String accessToken){
		String ticket = stringRedisTemplate.opsForValue().get(JsAPI_TICKET + accessToken);
		if (StringUtil.isBlank(ticket)) {
			//这个url链接和参数不能变
			String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ accessToken +"&type=jsapi";
			String s = HttpUtil.get(url);
			JSONObject jsonObject = JSON.parseObject(s);
			ticket = jsonObject.getString("ticket");
			if (StringUtil.isNotBlank(ticket)) {
				stringRedisTemplate.opsForValue().set(JsAPI_TICKET+accessToken,ticket,7000,TimeUnit.SECONDS);
			}
		}
		return ticket;
	}
}
