package net.lab1024.sa.admin.util;

import com.alibaba.fastjson.JSONObject;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import org.apache.commons.collections4.CollectionUtils;

import java.util.List;
import java.util.function.Consumer;

public class ResponseDTOUtil {
    private ResponseDTOUtil() {
        // 私有构造函数，防止实例化
    }

    /**
     * 构建返回结果
     * @param joiner Msg信息
     * @return ResponseDTO<String>
     */
    public static ResponseDTO<String> buildResponseDTO(JoinerResult joiner) {
        JSONObject jsonObject = new JSONObject();
        if (joiner.getSussMsg() != null) {
            jsonObject.put("success", joiner.getSussMsg().toString());
        }

        if (joiner.getErrorMsg() != null) {
            jsonObject.put("error", joiner.getErrorMsg().toString());
        }
        return ResponseDTO.ok(jsonObject.toString());
    }

    /**
     * 构建返回结果
     * @param insertList 新增集合对象
     * @param updateList 更新集合对象
     * @param saveBatchFunction 批量新增函数
     * @param updateBatchFunction 批量更新函数
     * @param joiner Msg信息
     */
    public static <T> ResponseDTO<String> buildResponseDTO(
            List<T> insertList,
            List<T> updateList,
            Consumer<List<T>> saveBatchFunction,
            Consumer<List<T>> updateBatchFunction,
            JoinerResult joiner
            ) {

        if (CollectionUtils.isNotEmpty(insertList)) {
            saveBatchFunction.accept(insertList);
            String msg = String.format("新增%s条", insertList.size());
            joiner.getSussMsg().add(msg);
        }

        if (CollectionUtils.isNotEmpty(updateList)) {
            updateBatchFunction.accept(updateList);
            String msg = String.format("更新%s条", updateList.size());
            joiner.getSussMsg().add(msg);
        }

        return buildResponseDTO(joiner);
    }



}
