package cn.reghao.autodop.dmaster.app.service.bd;

import cn.reghao.autodop.common.msg.rpc.dto.app.AppStatus;
import cn.reghao.autodop.common.msg.rpc.dto.app.DeployResult;
import cn.reghao.autodop.dmaster.app.model.po.log.BuildLog;
import cn.reghao.autodop.dmaster.notification.service.notifier.ding.DingMsg;
import cn.reghao.jdkutil.converter.DateTimeConverter;
import lombok.Data;

/**
 * 应用部署通知消息
 *
 * @author reghao
 * @date 2020-06-24 10:32:34
 */
@Data
public class DeployNotifyMsg {
    private String buildId;
    private String appId;
    private String env;
    private String repoBranch;
    private String commitId;
    private String commitTime;
    private String machineIpv4;
    private String deployResult;
    private String deployTime;
    private String deployBy;

    public DeployNotifyMsg(BuildLog buildLog, DeployResult deployResult) {
        this.buildId = buildLog.getId();
        this.appId = buildLog.getAppId();
        this.env = buildLog.getEnv();
        this.repoBranch = buildLog.getRepoBranch();
        this.commitId = buildLog.getCommitInfo().getCommitId();
        this.commitTime = DateTimeConverter.format(buildLog.getCommitInfo().getMsCommitTime());
        this.machineIpv4 = deployResult.getMachineIpv4();
        this.deployResult = deployResult.getResult().getMsg();
        AppStatus appStatus = deployResult.getAppStatus();
        if (appStatus != null) {
            this.deployTime = DateTimeConverter.format(appStatus.getStartTime());
        } else {
            this.deployTime = DateTimeConverter.format(0);
        }
        this.deployBy = "某人";
    }

    public DingMsg dingMsg() {
        String title = "应用部署消息";

        StringBuilder sb = new StringBuilder();
        sb.append("应用部署").append(System.lineSeparator());
        sb.append("# 构建 ID: ").append(buildId).append(System.lineSeparator());
        sb.append("# 应用: ").append(appId).append(System.lineSeparator());
        sb.append("# 环境: ").append(env).append(System.lineSeparator());
        sb.append("# 分支: ").append(repoBranch).append(System.lineSeparator());
        sb.append("# 版本: ").append(commitId).append(System.lineSeparator());
        sb.append("# 提交时间: ").append(commitTime).append(System.lineSeparator());
        sb.append("# 部署结果: ").append(machineIpv4).append(" -> ").append(deployResult)
                .append(System.lineSeparator());
        sb.append("# 部署时间: ").append(deployTime)
                .append(System.lineSeparator());
        sb.append("# 执行用户: ").append(deployBy);
        String text = sb.toString();
        return new DingMsg(title, text);
    }
}
