package com.miaxis.wx.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.miaxis.common.constant.Constants;
import com.miaxis.common.core.redis.RedisCache;
import com.miaxis.feign.service.IWxSendService;
import com.miaxis.wx.service.IWxXcxMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * 电影订单Service业务层处理
 *
 * @author miaxis
 * @date 2021-05-07
 */
@Service
@Slf4j
public class WxXcxMesageServiceImpl implements IWxXcxMessageService {


    @Resource
    private RedisCache redisCache;

    @Resource
    private IWxSendService wxSendService;

    @Value("${app.appid}")
    private String appid;

    @Value("${app.secret}")
    private String secret;


    @Override
    public String getXcxMessageToken() {
        Object cacheObject = redisCache.getCacheObject(Constants.XCX_MESSAGE_TOKEN);
        //如果过期，重新获取并保存到redis
        if (cacheObject == null){
            String result = wxSendService.getAccessToken("client_credential",appid,secret);
            JSONObject json = JSONObject.parseObject(result);
            String token = json.getString("access_token");
            int expiresIn = json.getIntValue("expires_in");
            redisCache.setCacheObject(Constants.XCX_MESSAGE_TOKEN,token,expiresIn, TimeUnit.SECONDS);
            return token;
        }else {
            return String.valueOf(cacheObject);
        }

    }
}
