package com.bcxin.backend.domain.syncs.services.impls;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.backend.domain.apps.AppDefinition;
import com.bcxin.backend.domain.apps.TriggerDefinition;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
@Slf4j
public class GetAppTaskJobServiceImpl {
    private final HttpClient httpClient;

    @Value("${myapps.domain.url}")
    private String URL;

    public GetAppTaskJobServiceImpl(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    @Cacheable(value = "triggerList")
    public List<TriggerDefinition> getApps() throws Exception {

        String GETAPPURL = URL + "/api/v2/runtime/definitions/apps";
        String TRIGGERSURL = URL + "/api/v2/runtime/definitions/apps/%s/triggers";
        List triggerList = new ArrayList<TriggerDefinition>();
        Set<TriggerDefinition> triggerSet = new HashSet<>();
        try {
            HttpResponse response = this.httpClient.execute(new HttpGet(GETAPPURL));
            String appsJsonStr = EntityUtils.toString(response.getEntity());
            if (response.getStatusLine().getStatusCode() < 300) {
                List<AppDefinition> apps = JSONObject.parseArray(appsJsonStr, AppDefinition.class);
                if (!ObjectUtils.isEmpty(apps)) {
                    apps.stream().forEach(appDefinition -> {
                        String format = String.format(TRIGGERSURL, appDefinition.getId());
                        boolean ok = false;
                        String tggResStr = null;
                        try {
                            HttpGet get = new HttpGet(format);
                            HttpResponse tggRes = this.httpClient.execute(get);
                            tggResStr = EntityUtils.toString(tggRes.getEntity());

                            ok = tggRes.getStatusLine().getStatusCode() < 300;
                        } catch (Exception e) {
                            log.error("执行请求({})发生异常", format, e);
                        }

                        List<TriggerDefinition> list = new ArrayList<>();
                        if (ok) {
                            list = JSONObject.parseArray(tggResStr, TriggerDefinition.class);
                        } else {
                            log.error("获取定时任务ID(url={})出现异常:{}", format, tggResStr);
                        }
                        if (!ObjectUtils.isEmpty(list)) {
                            list.forEach(tir -> {
                                triggerSet.add(tir);
                            });
                        }
                    });
                    triggerList.addAll(triggerSet);
                }
            } else {
                log.error(appsJsonStr);
            }
        } catch (Exception e) {
            //如果请求失败，就清除缓存
            log.error("获取连接({})失败，执行清除缓存", GETAPPURL, e);
            throw e;
        }

        return triggerList;
    }


    @CacheEvict(value = "triggerList")
    public void cleanAppTaskIdsCache() {
        log.error("缓存已清除");
    }

}
