package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.CtopOauthToken;
import cn.com.ctop.common.module.mapper.CtopOauthTokenMapper;
import cn.com.ctop.common.module.service.ICtopOauthTokenService;
import cn.com.ctop.common.module.utils.Check;
import cn.com.ctop.common.module.utils.HttpUtils;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: oauth授权码
 * @Author: jeecg-boot
 * @Date: 2019-07-09
 * @Version: V1.0
 */
@Slf4j
@Service
public class CtopOauthTokenServiceImpl extends ServiceImpl<CtopOauthTokenMapper, CtopOauthToken> implements ICtopOauthTokenService {
    @Autowired
    private CtopOauthTokenMapper cTopOauthTokenMapper;

    @Override
    public CtopOauthToken getOauthTokenByAccountId(String accountId) {
        QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId).orderByDesc("create_time");
        queryWrapper.last("limit 1");
        return cTopOauthTokenMapper.selectOne(queryWrapper);
    }


    @Override
    public CtopOauthToken getTokenByAccountId(Long accountId) {
        QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId).orderByDesc("create_time");
        queryWrapper.last("limit 1");
        return cTopOauthTokenMapper.selectOne(queryWrapper);
    }

    /**
     * 刷新token
     *
     * @param accountId
     * @return
     */
    @Override
    public Map<String, Object> getByteDanceAccessToken(String accountId) {
        Map<String, Object> resultMap = new HashMap<>();
        CtopOauthToken token = this.getOauthTokenByAccountId(accountId);
        if (null == token) {
            resultMap.put("message", "token信息不存在");
            resultMap.put("code", -1);
            return resultMap;
        }
        String url = PropertiesUtils.getValue("bytedance_config", "bytedance_api_url") + "/oauth2/refresh_token";
        Map<String, Object> param = new HashMap<>();
        param.put("app_id", PropertiesUtils.getValue("bytedance_config", "bytedance_appid"));
        param.put("secret", PropertiesUtils.getValue("bytedance_config", "bytedance_secret"));
        param.put("grant_type", "refresh_token");
        param.put("refresh_token", token.getRefreshToken());
        String result = HttpUtils.httpPostRequest(url, param, new HashMap<>());
        JSONObject resultObject = JSONObject.parseObject(result);
        Integer code = resultObject.getInteger("code");
        if (null == code || code != 0) {
            log.info("刷新token异常；accountId：{}", accountId);
            resultMap.put("message", "刷新token异常");
            resultMap.put("code", -1);
            return resultMap;
        }
        JSONObject data = resultObject.getJSONObject("data");
        CtopOauthToken refreshToken = new CtopOauthToken(token, data);
        QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", accountId);
        queryWrapper.eq("media_id", 1);

        int i = cTopOauthTokenMapper.update(refreshToken, queryWrapper);
        if (i > 0) {
            log.info("头条刷新token成功:accountId:{}", accountId);
        }
        resultMap.put("message", "token刷新成功");
        resultMap.put("code", 0);
        return resultMap;
    }

    /**
     * 快手 刷新token
     *
     * @param accountId
     * @param refreshToken
     * @return
     */
    @Override
    public void getKuaiShouRefreshToken(Long accountId, String refreshToken, Integer agentType) {
        String url = PropertiesUtils.getConfig("kuaishou_api_url") + "/rest/openapi/oauth2/authorize/refresh_token";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", " application/json");
        Map<String, Object> param = new HashMap<>();
        if (agentType == 1) {
            param.put("app_id", PropertiesUtils.getConfig("kuaishou_appid"));
            param.put("secret", PropertiesUtils.getConfig("kuaishou_secret"));
        } else if (agentType == 0) {
            param.put("app_id", PropertiesUtils.getConfig("kuaishou_third_appid"));
            param.put("secret", PropertiesUtils.getConfig("kuaishou_third_secret"));
        }

        param.put("refresh_token", refreshToken);
        try {
            CtopOauthToken oauthToken = cTopOauthTokenMapper.selectByAccountId(accountId);
            if (null == oauthToken) {
                log.error("查询token信息返回结果为空,accountId：{}", accountId);
                return;
            }
            String result = HttpUtils.httpPostRequest(url, param, headers);
            JSONObject resultJson = JSONObject.parseObject(result);
            if (Check.isNull(resultJson)) {
                log.error("快手刷新token返回结果为空,accountId：{}", accountId);
                return;
            }
            Integer code = resultJson.getInteger("code");
            if (null == code || code != 0) {
                log.error("快手刷新token失败,accountId:{},result:{}", accountId, resultJson);
                return;
            }
            JSONObject dataJson = resultJson.getJSONObject("data");
            if (null == dataJson) {
                log.error("快手刷新token失败,accountId:{},result:{}", accountId, resultJson);
                return;
            }
            oauthToken.setAccessToken(dataJson.getString("access_token"));
            long accessTokenExpireIn = dataJson.getLong("access_token_expires_in") * 1000L;
            long now = System.currentTimeMillis();
            Date accessTokenExpireInDate = new Date(now + accessTokenExpireIn);
            oauthToken.setAccessTokenExpiresIn(accessTokenExpireInDate);
            oauthToken.setRefreshToken(dataJson.getString("refresh_token"));
            long refreshTokenExpireIn = dataJson.getLong("refresh_token_expires_in") * 1000L;
            Date refreshTokenExpireInDate = new Date(now + refreshTokenExpireIn);
            oauthToken.setRefreshTokenExpiresIn(refreshTokenExpireInDate);
            oauthToken.setUpdateTime(new Date());
            QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("account_id", accountId);
            queryWrapper.eq("media_id", 2);
            int i = cTopOauthTokenMapper.update(oauthToken, queryWrapper);
            if (i > 0) {
                log.info("快手刷新token成功，accountId:{}", accountId);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            log.error("快手刷新token失败,accountId{}", accountId);
        }
    }

    @Override
    public List<CtopOauthToken> getTokenListByType(String platformType) {
        QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
        if (null != platformType && !"".equals(platformType.trim())) {
            queryWrapper.eq("media_id", platformType);
        }
        queryWrapper.orderByDesc("account_id");
        return this.list(queryWrapper);
    }

    /**
     * 获取快手有效账户列表
     *
     * @return
     */

    @Override
    public List<CtopOauthToken> selectKuaiShouToken() {
        return cTopOauthTokenMapper.selectKuaiShouToken();
    }


    /**
     * 获取toutiao有效账户列表
     *
     * @return
     */

    @Override
    public List<CtopOauthToken> selectToutiaoToken() {
        return cTopOauthTokenMapper.selectToutiaoToken();
    }


    @Override
    public CtopOauthToken getAccessTokenByAccountIdAndMediaId(Integer mediaId, Long accountId) {
        return cTopOauthTokenMapper.getAccessTokenByAccountIdAndMediaId(mediaId, accountId);
    }

    @Override
    public List<CtopOauthToken> getToutiaoTokenByCreateTime(String createTime) {
        return cTopOauthTokenMapper.getToutiaoTokenByCreateTime(createTime);
    }


}
