package com.zehong.web.controller.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.zehong.common.config.GassafetyProgressConfig;
import com.zehong.common.constant.Constants;
import com.zehong.common.core.domain.AjaxResult;
import com.zehong.common.utils.StringUtils;
import com.zehong.common.utils.file.FileUploadUtils;
import com.zehong.common.utils.file.FileUtils;
import com.zehong.framework.config.ServerConfig;

/**
 * 通用请求处理
 *
 * @author zehong
 */
@RestController
public class CommonController
{
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete 是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            log.info("开始下载文件，fileName={}, delete={}", fileName, delete);

            if (!FileUtils.checkAllowDownload(fileName))
            {
                log.error("文件名称非法，不允许下载: {}", fileName);
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = GassafetyProgressConfig.getDownloadPath() + fileName;

            log.info("文件完整路径: {}", filePath);

            // 检查文件是否存在
            java.io.File file = new java.io.File(filePath);
            if (!file.exists()) {
                log.error("文件不存在: {}", filePath);
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("文件不存在：" + fileName);
                return;
            }

            log.info("文件大小: {} bytes", file.length());

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());

            log.info("文件下载成功");

            if (delete)
            {
                FileUtils.deleteFile(filePath);
                log.info("已删除临时文件: {}", fileName);
            }
        }
        catch (Exception e)
        {
            log.error("下载文件失败，fileName={}", fileName, e);
            try {
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().write("下载失败：" + e.getMessage());
            } catch (Exception ex) {
                log.error("写入错误信息失败", ex);
            }
        }
    }

    /**
     * 通用上传请求
     */
    @PostMapping("/common/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = GassafetyProgressConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = file.getOriginalFilename();
            //本地存储地址
//            String fileName=filePath+FileUploadUtils.upload(filePath, file);
            String fileServer = serverConfig.getUrl();
            if(fileServer.contains("frrq.zhkjgf.com")){
                fileServer = serverConfig.getUrl().replace("http://frrq.zhkjgf.com","https://frrq.zhkjgf.com:8908");
            }
            String url = fileServer + FileUploadUtils.upload(filePath, file);
            AjaxResult ajax = AjaxResult.success();
//            ajax.put("fileName", fileName);
            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception
    {
        try
        {
            if (!FileUtils.checkAllowDownload(resource))
            {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = GassafetyProgressConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        }
        catch (Exception e)
        {
            log.error("下载文件失败", e);
        }
    }
}
