package cn.datax.service.data.market.api.call.service.impl;

import cn.datax.common.core.R;
import cn.datax.common.utils.MD5Util;
import cn.datax.common.utils.SecurityUtil;
import cn.datax.service.data.market.api.call.config.MappingHandlerMapping;
import cn.datax.service.data.market.api.call.service.ApiExecuteService;
import cn.datax.service.data.market.api.feign.DataApiServiceFeign;
import cn.datax.service.data.market.api.vo.ApiHeader;
import cn.datax.service.data.market.api.vo.DataApiVo;
import cn.hutool.core.util.ObjectUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ApiExecuteServiceImpl implements ApiExecuteService {

    @Autowired
    private MappingHandlerMapping mappingHandlerMapping;

    @Autowired
    private DataApiServiceFeign dataApiServiceFeign;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public ApiHeader getApiHeader(String id) {
        ApiHeader apiHeader = new ApiHeader();
        try {
            MD5Util mt = MD5Util.getInstance();
            apiHeader.setApiKey(mt.encode(id));
            apiHeader.setSecretKey(mt.encode(SecurityUtil.getUserId()));
        } catch (Exception e) {
        }
        return apiHeader;
    }

    @Override
    public void registerApi(String id) {
        R apiResult = dataApiServiceFeign.getDataApiById(id);
        if(apiResult == null || !apiResult.isSuccess() || ObjectUtil.isEmpty(apiResult.getData())){
            return;
        }
        DataApiVo dataApiVo = null;
        try {
            dataApiVo = objectMapper.readValue(objectMapper.writeValueAsString(apiResult.getData()), DataApiVo.class);
        } catch (JsonProcessingException e) {
        }
        if (dataApiVo != null) {
            mappingHandlerMapping.registerMapping(dataApiVo);
        }
    }

    @Override
    public void unRegisterApi(String id) {
        R apiResult = dataApiServiceFeign.getDataApiById(id);
        if(apiResult == null || !apiResult.isSuccess() || ObjectUtil.isEmpty(apiResult.getData())){
            return;
        }
        DataApiVo dataApiVo = null;
        try {
            dataApiVo = objectMapper.readValue(objectMapper.writeValueAsString(apiResult.getData()), DataApiVo.class);
        } catch (JsonProcessingException e) {
        }
        if (dataApiVo != null) {
            mappingHandlerMapping.unregisterMapping(dataApiVo);
        }
    }
}
