package com.tzld.piaoquan.growth.common.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import com.tzld.piaoquan.growth.common.component.ProxyHttpPoolClient;
import com.tzld.piaoquan.growth.common.dao.mapper.CorpMapper;
import com.tzld.piaoquan.growth.common.model.po.Corp;
import com.tzld.piaoquan.growth.common.model.po.CorpExample;
import com.tzld.piaoquan.growth.common.service.WeComAccessTokenService;
import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.tzld.piaoquan.growth.common.common.constant.RedisConstant.WE_COM_ACCESS_TOKEN;
import static com.tzld.piaoquan.growth.common.common.constant.WeComConstant.GET_WE_COM_ACCESS_TOKEN_URL;

@Slf4j
@Service
public class WeComAccessTokenServiceImpl implements WeComAccessTokenService {

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Autowired
    private ProxyHttpPoolClient proxyHttpPoolClient;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private CorpMapper corpMapper;

    @Override
    public String getWeComAccessToken(Long corpId) {
        try {
            String key = String.format(WE_COM_ACCESS_TOKEN, corpId);
            String accessToken = (String) redisTemplate.opsForValue().get(key);
            if (StringUtils.isNotEmpty(accessToken)) {
                return accessToken;
            }
            CorpExample example = new CorpExample();
            example.createCriteria().andIdEqualTo(corpId);
            List<Corp> corps = corpMapper.selectByExample(example);
            if (CollectionUtils.isEmpty(corps)) {
                LarkRobotUtil.sendMessage("查询不到主体，获取access_token失败");
                return "";
            }
            Corp corp = corps.get(0);
            String cropId = corp.getCorpId();
            String secret = corp.getSecret();
            String res;
            if (corpId == 1L) {
                res = httpPoolClient.get(String.format(GET_WE_COM_ACCESS_TOKEN_URL +
                        "?corpid=%s&corpsecret=%s", cropId, secret));
            } else {
                res = proxyHttpPoolClient.get(String.format(GET_WE_COM_ACCESS_TOKEN_URL +
                        "?corpid=%s&corpsecret=%s", cropId, secret));
            }
            JSONObject jsonObject = JSONObject.parseObject(res);
            Long expiresIn = jsonObject.getLong("expires_in");
            String newAccessToken = jsonObject.getString("access_token");
            redisTemplate.opsForValue().set(key, newAccessToken, expiresIn, TimeUnit.SECONDS);
            return newAccessToken;
        } catch (IOException e) {
            LarkRobotUtil.sendMessage("getWeComAccessToken error:" + e);
            log.error("getWeComAccessToken error", e);
        }
        return "";
    }
}
