package cn.reghao.bnt.web.devops.app.model.vo.msg;

import cn.reghao.bnt.web.admin.service.notifier.ding.DingMsg;
import cn.reghao.bnt.web.devops.app.model.po.log.BuildLog;
import cn.reghao.bnt.web.devops.app.model.po.log.DeployLog;
import cn.reghao.jutil.jdk.converter.DateTimeConverter;
import cn.reghao.jutil.jdk.web.result.ResultStatus;
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, DeployLog deployLog) {
        this.buildId = buildLog.getBuildLogId();
        this.appId = buildLog.getAppConfig().getAppId();
        this.env = buildLog.getAppConfig().getEnv();
        this.repoBranch = buildLog.getAppConfig().getRepoBranch();
        this.commitId = buildLog.getCommitId();
        this.commitTime = DateTimeConverter.format(buildLog.getCommitTime());
        this.machineIpv4 = deployLog.getMachineHost().getMachineIpv4();
        int code = deployLog.getCode();
        if (code == ResultStatus.SUCCESS.getCode()) {
            this.deployResult = ResultStatus.SUCCESS.getMsg();
        } else {
            this.deployResult = deployLog.getMsg();
        }
        this.deployTime = DateTimeConverter.format(deployLog.getDeployTime());
        this.deployBy = deployLog.getDeployBy();
    }

    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);
    }
}
