package org.jeecg.modules.bytedance.common.service.impl;

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.jeecg.common.util.DateUtils;
import org.jeecg.modules.bytedance.common.entity.CtopOauthToken;
import org.jeecg.modules.bytedance.common.mapper.CtopOauthTokenMapper;
import org.jeecg.modules.bytedance.common.service.ICtopOauthTokenService;
import org.jeecg.modules.bytedance.common.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
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 {
    @Value("${bytedance.appId}")
    private String bytedanceAppId;
    @Value("${bytedance.secret}")
    private String bytedanceSecret;
    @Value("${bytedance.url.api-prefix}")
    private String bytedanceUrlApiPrefix;
    @Value("${bytedance.url.refresh-token}")
    private String bytedanceUrlRefreshToken;
    @Value("${kuaishou.api-url}")
    private String kuaishouApiUrl;

    @Resource
    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 this.getOne(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 this.getOne(queryWrapper);
    }

    /**
     * 刷新token
     *
     * @return
     */
    @Override
    public Map<String, Object> getByteDanceAccessToken(CtopOauthToken token) {
        Map<String, Object> resultMap = new HashMap<>();
        String url = bytedanceUrlApiPrefix + bytedanceUrlRefreshToken;
        Map<String, Object> param = new HashMap<>();
        param.put("app_id", bytedanceAppId);
        param.put("secret", bytedanceSecret);
        param.put("grant_type", "refresh_token");
        param.put("refresh_token", token.getRefreshToken());
        String result = HttpUtils.httpPostRequest(url, param, new HashMap<>());
        System.err.println(JSONObject.parseObject(result));
        log.info("头条刷新token;accountId:{},返回信息：{}", token.getAccountId(), result);
        if (null == result || "".equals(result.trim()) || "null".equalsIgnoreCase(result)) {
            log.info("头条刷新token失败;accountId:{},返回信息：{}", token.getAccountId(), result);
            resultMap.put("message", "token刷新失败");
            resultMap.put("token", token);
            resultMap.put("code", 0);
            return resultMap;
        }
        JSONObject resultObject = JSONObject.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String message = resultObject.getString("message");
        if (code == 0) {
            JSONObject data = resultObject.getJSONObject("data");
            CtopOauthToken updateRefreshToken = new CtopOauthToken();
            updateRefreshToken.setAccessToken(data.getString("access_token"));
            updateRefreshToken.setRefreshToken(data.getString("refresh_token"));
            Date now = new Date();
            Integer refreshTokenExpiresIn = data.getInteger("refresh_token_expires_in");
            Integer expiresIn = data.getInteger("expires_in");
            updateRefreshToken.setRefreshTokenExpiresIn(DateUtils.addSecond(now, refreshTokenExpiresIn));
            updateRefreshToken.setAccessTokenExpiresIn(DateUtils.addSecond(now, expiresIn));
            QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("access_token", token.getAccessToken());
            queryWrapper.eq("media_id", 1);
            int i = ctopOauthTokenMapper.update(updateRefreshToken, queryWrapper);
            if (i > 0) {
                log.info("头条刷新token成功:accountId:{}", token.getAccountId());
            }
            resultMap.put("message", "token刷新成功");
            resultMap.put("code", 0);
        } else {
            log.info("头条刷新token失败;accountId:{},返回信息：{}", token.getAccountId(), message);
            resultMap.put("message", message);
            resultMap.put("token", token);
            resultMap.put("code", 0);
        }
        return resultMap;
    }



    @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);
    }


    /**
     * 获取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);
    }

    @Override
    public List<CtopOauthToken> getByProjectId(Long projectId) {
        QueryWrapper<CtopOauthToken> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId).eq("account_status", 0);
        return this.list(queryWrapper);
    }

    @Override
    public CtopOauthToken selectOneByMediaId(String platformTypeKuaishou) {
        QueryWrapper<CtopOauthToken> tokenQueryWrapper = new QueryWrapper<>();
        tokenQueryWrapper.eq("media_id", platformTypeKuaishou);
        tokenQueryWrapper.orderByDesc("create_time");
        tokenQueryWrapper.last("limit 1");
        return this.getOne(tokenQueryWrapper);
    }
}
