package com.css.simulation.resource.server.infra.util;

import api.common.pojo.constants.DictConstants;
import api.common.pojo.vo.scene.ScenePackageSublistVO;
import api.common.util.CollectionUtil;
import api.common.util.HttpUtil;
import api.common.util.LinuxUtil;
import com.css.simulation.resource.server.infra.db.mysql.mapper.ScoringRulesMapper;
import lombok.SneakyThrows;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.config.RequestConfig;
import org.springframework.stereotype.Component;

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

/**
 * 任务结果打分
 */
@Component
@Slf4j
public class SceneUtil {

    @Resource
    private ScoringRulesMapper scoringRulesMapper;

    public void checkRules(String scenePackageId) {
        final List<String> ruleIds = scoringRulesMapper.selectDeletedRulesByPackageId(scenePackageId);
        if (CollectionUtil.isNotEmpty(ruleIds)) {
            final List<String> ruleNames = scoringRulesMapper.selectRuleNamesByRuleIds(ruleIds);
            throw new RuntimeException("场景测试包存在已被删除的评分规则：" + ruleNames);
        }
    }

    public void checkRulesByScenePackageSublistVO(ScenePackageSublistVO scenePackageSublistVO) {
        final List<ScenePackageSublistVO> children = scenePackageSublistVO.getChildren();
        if (CollectionUtil.isNotEmpty(children)) {
            for (ScenePackageSublistVO child : children) {
                checkRulesByScenePackageSublistVO(child);
            }
        } else {
            final String[] ruleIdArray = scenePackageSublistVO.getRuleNameArrayS();
            final String ruleId = ruleIdArray[ruleIdArray.length - 1];
            final String isDeleted = scoringRulesMapper.selectIsDeletedByRuleId(ruleId);
            if (DictConstants.IS_DELETED.equals(isDeleted)) {
                throw new RuntimeException("指标【" + scenePackageSublistVO.getSublistName() + "】关联的评分规则【"
                        + scenePackageSublistVO.getRuleName()+"】已被删除。");
            }
        }
    }

    @Synchronized
    @SneakyThrows
    public String callGeneralService(RequestConfig requestConfig, String generalUrl, Map map) {
        String post;
        try {
            post = HttpUtil.post(HttpUtil.getHttpClient(), requestConfig, generalUrl, null, map);
        } catch (Exception e) {
            log.error("泛化接口服务崩溃，重启。");
            LinuxUtil.execute("./service-manager.sh restart", "/root/");
            TimeUnit.SECONDS.sleep(3);
            post = HttpUtil.post(HttpUtil.getHttpClient(), requestConfig, generalUrl, null, map);
        }
        log.info("调用泛化接口：" + generalUrl + "，响应结果为：" + post);
        return post;
    }
}
