package com.eitc.web.controller.common;

import com.eitc.common.config.EitcConfig;
import com.eitc.common.constant.Constants;
import com.eitc.common.core.controller.BaseController;
import com.eitc.common.utils.StringUtils;
import com.eitc.common.utils.file.FileUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;


/**
 * 通用请求处理
 *
 * @author eitc
 */
@RestController
@RequestMapping("/download")
public class DownloadController extends BaseController {

    /**
     * 硬件app
     */
    @GetMapping("/hardware")
    public void hardware(HttpServletResponse response) throws Exception {
        String resource = "/profile/app/huishitong.apk";
        resourceDownload("慧视通APP.apk", resource, response);
    }

    @GetMapping("/hospital")
    public void hospital(HttpServletResponse response) throws Exception {
        String resource = "/profile/app/kouqiangyiyuan_1.0.0_1_240830_release.apk";
        resourceDownload("口腔医院.apk", resource, response);
    }

    @GetMapping("/document")
    public void document(HttpServletResponse response) throws Exception {
        String resource = "/profile/app/document.pdf";
        resourceDownload("慧视通APP操作乎册.pdf", resource, response);
    }

    public void resourceDownload(String downloadName, String resource, HttpServletResponse response) throws Exception {
        // 禁止目录上跳级别
        if (StringUtils.contains(resource, "..")) {
            throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
        }
        // 本地资源路径
        String localPath = EitcConfig.getProfile();
        // 数据库资源地址
        String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        FileUtils.setAttachmentResponseHeader(response, downloadName);
        FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }

}
