package com.fdkankan.scene.service.impl;

import cn.hutool.core.util.StrUtil;
import com.fdkankan.dingtalk.DingTalkSendUtils;
import com.fdkankan.scene.service.IBuildSceneDTService;
import com.taobao.api.ApiException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.CompletableFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/4/20
 **/
@Slf4j
@Service
public class BuildSceneDTServiceImpl implements IBuildSceneDTService {

    public static final String DINGTALK_MSG_PATTERN = "**环境**: %s\n\n" +
        "**服务器名称**: %s\n\n" +
        "**失败原因**: %s\n\n" +
        "**num**: %s\n\n" +
        "**server-path**: %s\n\n";
//        "**algorithm-log**: [https://4dkk.4dage.com/build_log/%s/console.log](https://4dkk.4dage.com/build_log/%s/console.log)";

    public static final String contentExt = "**algorithm-log**: [https://4dkk.4dage.com/build_log/%s/console.log](https://4dkk.4dage.com/build_log/%s/console.log)";

    @Autowired
    private DingTalkSendUtils dingTalkSendUtils;
    @Value("${spring.profiles.active}")
    private String environment;

    @Override
    public void handFail(String reason, String serverPath, String num, String hostName, String contentExt) {
        CompletableFuture.runAsync(() -> {
            try {
                String contentFormat = StrUtil.isBlank(contentExt) ? this.DINGTALK_MSG_PATTERN : this.DINGTALK_MSG_PATTERN +  contentExt;
                String content = String.format(contentFormat, this.environment, hostName, reason, num, serverPath, num, num);
                log.info("发送钉钉消息，content:{}", content);
                dingTalkSendUtils.sendActioncardMsgToDingRobot(content,"场景计算失败");
            } catch (ApiException | UnsupportedEncodingException | NoSuchAlgorithmException | InvalidKeyException apiException) {
                log.error("发送钉钉消息失败", apiException);
            }
        });
    }

}
