package cn.pluss.platform.jty;

import cn.pluss.platform.cacheInfo.CacheInfoService;
import cn.pluss.platform.entity.CacheInfo;
import cn.pluss.platform.entity.DeviceStock;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.jty.constant.JtyConstant;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Map;

/**
 * TODO
 * 佳天亿设备业务处理handler
 * @author crystal
 * @date 2022/3/17 15:37
 */
@Slf4j
@Component
public class JtyDeviceHandler {

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private CacheInfoService cacheInfoService;

    /**
     * 发送设备消息
     * @param orderAmt
     * @param type
     * @param deviceStock
     * @return
     */
    public String sendNotice(Double orderAmt,String type,DeviceStock deviceStock){
        String url = JtyConstant.API_TEST_DOMAIN + JtyConstant.PAY_NOTICE_METHOD;
        JtyYxApiAuth auth = new JtyYxApiAuth();
        String authSign = getAuthSign(auth);
        JtyYxPayNotice notice = new JtyYxPayNotice(deviceStock.getDeviceNo(),type,BigDecimal.valueOf(orderAmt));
        HttpHeaders headers = new HttpHeaders();
        headers.add("FB_OP_SIGNATURE",authSign);
        headers.add("FB_OP_API_VERSION",JtyConstant.VERSION);
        HttpEntity<JtyYxPayNotice>  httpEntity = new HttpEntity<>(notice,headers);
        try {
            JtyResponse response = restTemplate.postForObject(url, httpEntity, JtyResponse.class);
            log.info("【佳天亿】接口返回：{}",JSON.toJSONString(response));
            if(!JtyConstant.SUCCESS_CODE.equals(response.getCode())){
                MsgException.throwException(response.getMessage());
            }
            return ((Map<String, String>)response.getResult()).get("requestNum");
        }catch (Exception e){
            MsgException.throwException(e.getMessage());
        }
        return null;
    }

    public String getAuthSign(JtyYxApiAuth auth) {
        CacheInfo cacheInfo = cacheInfoService.getCacheInfoByKeyCode(JtyConstant.CACHE_KEY_CODE_PRIFIX + auth.getAppId());
        if(cacheInfo == null){
            Long time = System.currentTimeMillis();
            JtyResponse response = getReqAuthSign(auth);
            Object result = response.getResult();
            JtyResult jtyResult = JSONObject.parseObject(JSON.toJSONString(result), JtyResult.class);
            Long exprieTime = jtyResult.getExpirationTime();
            Long expiresIn = (time + exprieTime) / 1000;
            CacheInfo cache = new CacheInfo(auth.getAppId(),auth.getAppSecret(),JtyConstant.CACHE_KEY_CODE_PRIFIX + auth.getAppId(),jtyResult.getAuthSign(),expiresIn);
            cacheInfoService.save(cache);
            return jtyResult.getAuthSign();
        }else{
            long time = System.currentTimeMillis();
            long expiresIn = cacheInfo.getExpiresIn();
            if(time / 1000  >= expiresIn - 200){
                JtyResponse response = getReqAuthSign(auth);
                Object result = response.getResult();
                JtyResult jtyResult = JSONObject.parseObject(JSON.toJSONString(result), JtyResult.class);
                Long nextExpiresIn = (time + jtyResult.getExpirationTime()) / 1000;
                cacheInfo.setExpiresIn(nextExpiresIn);
                cacheInfo.setAccessToken(jtyResult.getAuthSign());
                cacheInfoService.updateById(cacheInfo);
                return jtyResult.getAuthSign();
            }else{
                return cacheInfo.getAccessToken();
            }
        }
    }

    private JtyResponse getReqAuthSign(JtyYxApiAuth auth) {
        String authUrl = JtyConstant.API_TEST_DOMAIN + JtyConstant.API_AUTH_METHOD;
        JtyResponse response = restTemplate.postForObject(authUrl, auth, JtyResponse.class);
        if(response == null){
            MsgException.throwException("获取佳天亿授权sign异常");
        }
        if(!JtyConstant.SUCCESS_CODE.equals(response.getCode())){
            MsgException.throwException(response.getMessage());
        }
        return response;
    }
}
