package com.zt.plat.module.base.service.masterdatasync.support;

import cn.hutool.core.util.StrUtil;
import com.zt.plat.framework.common.util.json.JsonUtils;
import com.zt.plat.module.base.framework.sync.config.MasterDataSyncProperties;
import com.zt.plat.module.base.service.masterdatasync.dto.MasterDataSyncReport;
import lombok.extern.slf4j.Slf4j;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 在同步结束后发送回调通知。
 */
@Slf4j
@Component
public class MasterDataSyncNotifier {

    private static final MediaType JSON = MediaType.get("application/json; charset=UTF-8");

    private final OkHttpClient httpClient;
    private final MasterDataSyncProperties properties;

    public MasterDataSyncNotifier(@Qualifier("masterDataSyncOkHttpClient") OkHttpClient httpClient,
                                  MasterDataSyncProperties properties) {
        this.httpClient = httpClient;
        this.properties = properties;
    }

    public void dispatch(MasterDataSyncReport report, Throwable failure) {
        if (report == null || StrUtil.isBlank(properties.getCallbackUrl())) {
            return;
        }
        if (report.isSuccess() && !properties.isNotifyOnSuccess()) {
            return;
        }
        if (!report.isSuccess() && !properties.isNotifyOnFailure()) {
            return;
        }
        MasterDataSyncNotificationPayload payload = new MasterDataSyncNotificationPayload(report,
                failure == null ? null : failure.getMessage());
        RequestBody body = RequestBody.create(JSON, JsonUtils.toJsonString(payload));
        Request.Builder builder = new Request.Builder()
                .url(properties.getCallbackUrl())
                .post(body);
        properties.getCallbackHeaders().forEach(builder::addHeader);
        try (Response response = httpClient.newCall(builder.build()).execute()) {
            if (!response.isSuccessful()) {
                log.warn("主数据同步回调响应非成功状态: {}", response.code());
            }
        } catch (IOException ex) {
            log.warn("调用主数据同步回调接口失败", ex);
        }
    }
}
