package com.xunmei.file.service;

import cn.hutool.core.date.DateUtil;
import com.lowagie.text.Document;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.xunmei.common.core.utils.uuid.UUID;
import com.xunmei.file.utils.FileDownUtils;
import com.xunmei.file.utils.FileUploadUtils;
import com.xunmei.file.utils.PdfUtil;
import com.xunmei.file.vo.ItextPdfTableVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

/**
 * 本地文件存储
 *
 * @author xunmei
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService {

    private static final Logger log = LoggerFactory.getLogger(LocalSysFileServiceImpl.class);

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    @Autowired
    private HttpServletRequest request;

    private static String getLocalFilePath(String businessType, String fileName) {
        return File.separator + businessType + File.separator + DateUtil.format(new Date(), "yyyy" + File.separator + "MM" + File.separator + "dd" + File.separator) + fileName;
    }

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        String name = FileUploadUtils.upload(localFilePath, file);
//        String url = domain + localFilePrefix + name;
        return name;
    }

    @Override
    public String uploadFile(MultipartFile file, String busType) throws Exception {
        String name = FileUploadUtils.upload(localFilePath, file, busType);
//        String url = domain + localFilePrefix + name;
        return name;
    }

    @Override
    public void downloadFile(HttpServletResponse response, String filePath) {
        ByteArrayOutputStream out = null;
        try {
            filePath = localFilePath + filePath;
            filePath = URLDecoder.decode(filePath, "UTF-8");
            out = FileDownUtils.downloadFile(filePath);
            String fileSuffix = FileDownUtils.getFileSuffix(filePath);
            String formFileName = UUID.randomUUID().toString() + fileSuffix;
            String userAgent = request.getHeader("User-Agent");

            // 针对IE或者以IE为内核的浏览器：
            if (StringUtils.isNotEmpty(userAgent) && (userAgent.contains("MSIE") || userAgent.contains("Trident"))) {
                formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
            } else {
                // 非IE浏览器的处理：
                formFileName = new String(formFileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + formFileName);
            response.addHeader("Content-Length", "" + out.size());
            out.writeTo(response.getOutputStream());
            response.setContentType("application/octet-stream");
            out.flush();
            out.close();
        } catch (IOException e) {
            log.error("文件下载失败! ");
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public String generateEduTrainingPdf(Map<String, Object> data, String filename) throws Exception {
        String filePath = this.localFilePath + getLocalFilePath("edu", filename);
        final ItextPdfTableVo pdfTableVo = PdfUtil.createTable(filePath, 6, 10);
        final Document document = pdfTableVo.getDocument();
        final PdfWriter writer = pdfTableVo.getWriter();
        final PdfPTable table = pdfTableVo.getTable();
        final BaseFont fs = pdfTableVo.getFs();
        final Font tableFont = pdfTableVo.getTableFont();

        PdfUtil.dealHeader(document, fs, "学 习 教 育 记 录", 24);

        PdfUtil.dealEduBody(document, table, tableFont, data);

        document.close();
        writer.close();

        return filePath;
    }

}
