package com.ruixuan.isc.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.doudian.open.api.token_refresh.TokenRefreshRequest;
import com.doudian.open.api.token_refresh.TokenRefreshResponse;
import com.doudian.open.api.token_refresh.param.TokenRefreshParam;
import com.doudian.open.core.AccessToken;
import com.doudian.open.core.AccessTokenBuilder;
import com.kuaishou.merchant.open.api.KsMerchantApiException;
import com.kuaishou.merchant.open.api.client.oauth.OauthAccessTokenKsClient;
import com.kuaishou.merchant.open.api.response.oauth.KsAccessTokenResponse;
import com.ruixuan.bytedance.service.IBytedanceAccessTokenService;
import com.ruixuan.common.utils.Check;
import com.ruixuan.isc.entity.KuaishouAccessToken;
import com.ruixuan.isc.mapper.AccessTokenMapper;
import com.ruixuan.isc.service.IAccessTokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class AccessTokenServiceImpl implements IAccessTokenService {
    @Autowired
    private AccessTokenMapper accessTokenMapper;
    @Autowired
    private IBytedanceAccessTokenService tokenService;


    @Override
    public KuaishouAccessToken getAccessToken(Long regId) {
        return accessTokenMapper.getAccessToken(regId);
    }

    @Override
    public void refreshAccessToken() {
        refreshKuaiShouAccessToken();
        refreshByteDanceAccessToken();
    }

    public void refreshKuaiShouAccessToken() {
        List<KuaishouAccessToken> tokens = accessTokenMapper.getTokenInfos();
        if (!Check.isNull(tokens)) {
            for (KuaishouAccessToken token : tokens) {
                String appKey = token.getAppKey();
                String appSecret = token.getAppSecret();
                String refreshToken = token.getRefreshToken();
                OauthAccessTokenKsClient oauthAccessTokenKsClient = new OauthAccessTokenKsClient(appKey, appSecret);
                try {
                    KsAccessTokenResponse response = oauthAccessTokenKsClient.refreshAccessToken(refreshToken);
                    JSONObject jsonObject = JSONObject.parseObject(JSON.toJSONString(response));
                    log.info("刷新token,id:{},返回结果:{}", token.getId(), jsonObject);
                    if (jsonObject.getInteger("result") == 1) {
                        KuaishouAccessToken updateToken = new KuaishouAccessToken();
                        updateToken.setId(token.getId());
                        updateToken.setAccessToken(jsonObject.getString("accessToken"));
                        updateToken.setRefreshToken(jsonObject.getString("refreshToken"));
                        accessTokenMapper.update(updateToken);
                    }


                } catch (KsMerchantApiException e) {
                    e.printStackTrace();

                }

            }


        }
    }

    @Override
    public void refreshByteDanceAccessToken() {
        List<KuaishouAccessToken> tokens = accessTokenMapper.getByteDanceTokenInfos();
        if (!Check.isNull(tokens)) {
            for (KuaishouAccessToken token : tokens) {
                TokenRefreshRequest request = new TokenRefreshRequest();
                TokenRefreshParam param = request.getParam();
                param.setRefreshToken(token.getRefreshToken());
                param.setGrantType("refresh_token");
                AccessToken accessToken = tokenService.getAccessToken(1L);
                TokenRefreshResponse response = request.execute(accessToken);
                if (!Check.isNull(response)) {
                    JSONObject jsonObject = JSONObject.parseObject(response.toString());
                    if (jsonObject.getInteger("code") == 10000) {
                        JSONObject data = jsonObject.getJSONObject("data");
                        if (!Check.isNull(data)) {
                            String access_token = data.getString("access_token");
                            String refresh_token = data.getString("refresh_token");
                            KuaishouAccessToken update = new KuaishouAccessToken();
                            update.setId(token.getId());
                            update.setAccessToken(access_token);
                            update.setRefreshToken(refresh_token);
                            update.setUpdateTime(new Date());
                            accessTokenMapper.updateBytedance(update);
                            log.info("抖音更新token成功");
                        }
                    }
                }


            }
        }
    }
}
