package com.slodon.bbc.starter.thirdParty.client;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.slodon.b2b2c.core.exception.MallException;
import com.slodon.b2b2c.core.util.StringUtil;
import com.slodon.bbc.starter.thirdParty.constant.ThirdPartyConst;
import com.slodon.bbc.starter.thirdParty.entity.SlodonThirdPartyQrCodeRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * 抖音
 *
 */
@Slf4j
public class DouyinClient implements ThirdPartyBaseClient {

    /**
     * 获取二维码
     * https://microapp.bytedance.com/docs/zh-CN/mini-app/develop/server/qr-code/create-qr-code
     *
     * @param stringRedisTemplate redis操作工具
     * @param qrCodeRequest       业务参数
     * @return 二维码图片
     */
    @Override
    public BufferedImage getQrCode(StringRedisTemplate stringRedisTemplate, SlodonThirdPartyQrCodeRequest qrCodeRequest) throws Exception{
        //获取凭证，优先使用缓存
        String access_token = stringRedisTemplate.opsForValue().get(ThirdPartyConst.REDIS_ACCESS_TOKEN_KEY_DOUYIN);
        if (StringUtils.isEmpty(access_token)){
            //缓存不存在或已过期，重新获取并缓存
            access_token = this.getAccessToken(stringRedisTemplate);
            //缓存1小时
            stringRedisTemplate.opsForValue().set(ThirdPartyConst.REDIS_ACCESS_TOKEN_KEY_DOUYIN,access_token,1L, TimeUnit.HOURS);
        }

        String qrUrl = "https://developer.toutiao.com/api/apps/qrcode";
        StringBuilder path = new StringBuilder(qrCodeRequest.getPage());//扫码跳转地址
        path.append("?");
        qrCodeRequest.getParams().forEach((k,v) -> {
            path.append(k).append("=").append(v).append("&");
        });
        //构造json参数
        ModelMap modelMap = new ModelMap();
        modelMap.put("access_token", access_token);
        modelMap.put("width", 430);
        modelMap.put("appname","douyin");
//        modelMap.put("set_icon","TRUE");//发布后才可以添加
        modelMap.put("path", URLEncoder.encode( path.toString().substring(0,path.length()-1),"utf-8"));//发布后才可以添加

        HttpResponse execute = HttpUtil.createPost(qrUrl).body(JSON.toJSONString(modelMap), "application/json").execute();
        if (!execute.isOk()){
            //请求失败
            log.error("生成抖音二维码失败：" + execute.body());
            throw new MallException("小程序维护中，请稍后再试");
        }

        return ImageIO.read(execute.bodyStream());
    }

    /**
     * 获取access_token，失效时间为2小时
     *
     * @param stringRedisTemplate redis操作工具
     * @return access_token
     */
    private String getAccessToken(StringRedisTemplate stringRedisTemplate){
        String ACCESS_TOKEN_URL = "https://developer.toutiao.com/api/apps/token";//获取access_token地址
        String appId = stringRedisTemplate.opsForValue().get("third_party_douyin_appid");
        String secret = stringRedisTemplate.opsForValue().get("third_party_douyin_secret");
        ModelMap modelMap = new ModelMap();
        modelMap.put("appid", appId);
        modelMap.put("secret", secret);
        modelMap.put("grant_type", "client_credential");
        String resp = HttpUtil.get(ACCESS_TOKEN_URL,modelMap);
        JSONObject respJson = JSON.parseObject(resp);

        //请求失败格式 {"errcode":40015,"errmsg":"bad appid","error":2,"message":"bad appid"}
        //成功格式 {"access_token":"0801121846712b786b6655512b4d66515a2b324c7335573463673d3d","expires_in":7200}
        if (!StringUtil.isNullOrZero(respJson.getInteger("errcode"))){
            //请求失败
            log.error("获取抖音小程序二维码失败：" + respJson.getString("errmsg"));
            throw new MallException("小程序维护中，请稍后再试");
        }
        //请求成功
        return respJson.getString("access_token");
    }
}
