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


import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.bcxin.backend.domain.apps.TriggerDefinition;
import com.bcxin.backend.domain.syncs.services.ExecuteAppTaskJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import java.util.*;

@Service
@Slf4j
public class ExecuteAppTaskJobServiceImpl implements ExecuteAppTaskJobService {
    @Value("${myapps.domain.url}")
    private String url;

    @Autowired
    GetAppTaskJobServiceImpl getAppTaskJobService;

    @Override
    public void executeTaskByTaskId() {
        String TRIGGERS_EXECUTEURL = url + "/api/v2/runtime/definitions/apps/%s/triggers/%s/execute";
        try {
            List<TriggerDefinition> tirggList = getAppTaskJobService.getApps();
            if (!ObjectUtils.isEmpty(tirggList)) {
                tirggList.stream().parallel().forEach(tri -> {
                    String format = String.format(TRIGGERS_EXECUTEURL, tri.getAppId(), tri.getId());
                    log.error(format);
                    try {
                        HttpRequest httpRequest = HttpUtil.createPost(format);
                        HttpResponse execute = httpRequest.execute();
                        boolean ok = execute.isOk();
                        if (ok){
                            String appsJsonStr = execute.body();
                            log.error("Finish the schedule Task(请求={};响应={})！",format,appsJsonStr);
                        }else {
                            log.error("Error for the schedule Task({})", format);
                        }

                        Thread.sleep(5 * 1000);
                    }catch (Exception e) {
                        log.error("接口请求({})发生异常", format, e);
                    }
                });
            }
            log.error("executeTaskByTaskId 执行完毕！");
        } catch (Exception e) {
            log.error("executeTaskByTaskId 执行发生异常", e);
        }
    }
}
