package org.dromara.common.web.core;

import cn.hutool.core.io.IoUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.dromara.common.core.domain.R;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.core.utils.file.FileUtils;

import java.io.IOException;

/**
 * web层通用数据处理
 *
 * @author shihongwei
 */
public class BaseController {

    /**
     * 响应返回结果
     *
     * @param rows 影响行数
     * @return 操作结果
     */
    protected R<Void> toAjax(int rows) {
        return rows > 0 ? R.ok() : R.fail();
    }

    /**
     * 响应返回结果
     *
     * @param result 结果
     * @return 操作结果
     */
    protected R<Void> toAjax(boolean result) {
        return result ? R.ok() : R.fail();
    }

    /**
     * 页面跳转
     */
    public String redirect(String url) {
        return StringUtils.format("redirect:{}", url);
    }

    protected void writeAttachment(HttpServletResponse response, String filename, byte[] data, String contentType) throws IOException {
        response.reset();
        response.addHeader("Access-Control-Allow-Origin", "*");
        FileUtils.setAttachmentResponseHeader(response, filename);
        response.addHeader("Content-Length", String.valueOf(data.length));
        response.setContentType(contentType == null ? "application/octet-stream; charset=UTF-8" : contentType);
        IoUtil.write(response.getOutputStream(), false, data);
    }

}
