package org.ta.pddserver.PDFTemplate;

import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.ta.pddserver.cos.Uploader;
import org.ta.pddserver.model.to.PrintOrderInfoTO;
import org.ta.pddserver.utils.TimeTool;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static org.ta.pddserver.PDFTemplate.BarCodeUtils.getBarCode;
import static org.ta.pddserver.PDFTemplate.BarCodeUtils.insertWords;

@Slf4j
public class PdfUtil {
    private static final String SALE_SAMPLE_PDF = "./pdfs/FormSale-sample.pdf";
    private static final String LOTTE_LOGO = "lotte_logo.png";
    private static final String LOTTE_T = "lotte_T.png";


    public String printSaleInfo(PrintOrderInfoTO formData, HttpServletResponse response) throws Exception{
        String returnString="";
        try {
            //文件路径
            Map<String, Object> data = new HashMap<>();//要插入的数据
            data.put("pageNo", "1/1");
            data.put("feeTag", "배송비고:");
            data.put("goodNameTag", "상품명:");
            data.put("goodName", "E-commerce consuming goods");
            data.put("printTime", new TimeTool().getNowDateString());

            data.put("recipient", "받는분: " + formData.getRecipient());
            data.put("detailedAddress", "상품명: " + formData.getDetailedAddress());

            data.put("expressTag", formData.getExpressTag());
            data.put("expressUid", formData.getExpressUid());
            data.put("addressUpperLeft", formData.getAddressUpperLeft());
            data.put("addressUpperRight", formData.getAddressUpperRight());
            data.put("addressBottomLeft", formData.getAddressBottomLeft());
            data.put("addressBottomRight", formData.getAddressBottomRight());
            data.put("expressUidDown", formData.getExpressUid());
            data.put("orderCore", formData.getOrderCore());

            //生成图片
            log.info("formData.getExpressUid() = " + formData.getExpressUid());
            //BufferedImage image = insertWords(getBarCode(formData.getExpressUid(), 600, 100), formData.getExpressUid(), 600, 140, 100);
            BufferedImage image =getBarCode(formData.getExpressUid(), 600, 100);


            //初始化itext
            // 设置编码  todo 此处处理编码问题
            //  之前的BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            // 创建韩文字体
            // BaseFont baseFont = BaseFont.createFont("Gothic.ttf",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            // BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/Malgun Gothic.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            BaseFont baseFont = BaseFont.createFont("C:/Windows/Fonts/Malgun Gothic.ttf", "UniKSC-UCS2-H", BaseFont.NOT_EMBEDDED);


            PdfReader pdfReader = new PdfReader(SALE_SAMPLE_PDF);//获取地址
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            PdfStamper pdfStamper = new PdfStamper(pdfReader, output);
            AcroFields form = pdfStamper.getAcroFields();
            form.addSubstitutionFont(baseFont);
            //写入数据
            for (String key : data.keySet()) {
                String value = data.get(key).toString();
                //key对应模板数据域的名称
                form.setField(key, new String(value.getBytes("UTF-8"), "UTF-8"));
            }



            //添加图片
            int pageNo = form.getFieldPositions("expressCodeUp").get(0).page;
            Rectangle signRect = form.getFieldPositions("expressCodeUp").get(0).position;
            float x = signRect.getLeft();
            float y = signRect.getBottom();

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            if (!ImageIO.write(image, "jpeg", stream)) {
                return returnString;
            }
            byte[] imageBytes = stream.toByteArray();
            Image imagePath = Image.getInstance(imageBytes);
            PdfContentByte under = pdfStamper.getOverContent(pageNo);
            // 设置图片大小
            imagePath.scaleToFit(signRect.getWidth(), signRect.getHeight());
            //设置图片位置
            imagePath.setAbsolutePosition(x, y);
            under.addImage(imagePath);


            //添加图片
            int pageNoMiddle = form.getFieldPositions("expressCodeMiddle").get(0).page;
            Rectangle signRectMiddle = form.getFieldPositions("expressCodeMiddle").get(0).position;
            float xMiddle = signRectMiddle.getLeft();
            float yMiddle = signRectMiddle.getBottom();

            ByteArrayOutputStream streamMiddle = new ByteArrayOutputStream();
            if (!ImageIO.write(image, "jpeg", streamMiddle)) {
                return returnString;
            }
            byte[] imageBytesMiddle = streamMiddle.toByteArray();
            Image imagePathMiddle = Image.getInstance(imageBytesMiddle);
            PdfContentByte undeMiddle = pdfStamper.getOverContent(pageNoMiddle);
            // 设置图片大小
            imagePathMiddle.scaleToFit(signRectMiddle.getWidth(), signRectMiddle.getHeight());
            //设置图片位置
            imagePathMiddle.setAbsolutePosition(xMiddle, yMiddle);
            undeMiddle.addImage(imagePathMiddle);


            //添加图片
            int pageNoDown = form.getFieldPositions("expressCodeDown").get(0).page;
            Rectangle signRectDown = form.getFieldPositions("expressCodeDown").get(0).position;
            float xDown = signRectDown.getLeft();
            float yDown = signRectDown.getBottom();

            ByteArrayOutputStream streamDown = new ByteArrayOutputStream();
            if (!ImageIO.write(image, "jpeg", streamDown)) {
                return returnString;
            }
            byte[] imageBytesDown = streamDown.toByteArray();
            Image imagePathDown = Image.getInstance(imageBytesDown);
            PdfContentByte undeDown = pdfStamper.getOverContent(pageNoDown);
            // 设置图片大小
            imagePathDown.scaleToFit(signRectDown.getWidth(), signRectDown.getHeight());
            //设置图片位置
            imagePathDown.setAbsolutePosition(xDown, yDown);
            undeDown.addImage(imagePathDown);




            //生成图片
            log.info("formData.getLandingUid() = " + formData.getLandingUid());
           // BufferedImage imageLanding = insertWords(getBarCode(formData.getLandingUid(), 600, 100), formData.getLandingUid(), 600, 140, 100);
            BufferedImage imageLanding = getBarCode(formData.getLandingUid(), 610, 220);
            //初始化itext
            // 设置编码
            //BaseFont baseFontLanding = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            PdfReader pdfReaderLanding = new PdfReader(SALE_SAMPLE_PDF);//获取地址
            ByteArrayOutputStream outputLanding = new ByteArrayOutputStream();
            PdfStamper pdfStamperLanding = new PdfStamper(pdfReaderLanding, outputLanding);
            AcroFields formLanding = pdfStamperLanding.getAcroFields();
            formLanding.addSubstitutionFont(baseFont);
            //写入数据
            for (String key : data.keySet()) {
                String value = data.get(key).toString();
                //key对应模板数据域的名称
                formLanding.setField(key, new String(value.getBytes("UTF-8"), "UTF-8"));
            }

            //添加图片
            int pageNoLandingCode = formLanding.getFieldPositions("landingCode").get(0).page;
            Rectangle signRectLandingCode = formLanding.getFieldPositions("landingCode").get(0).position;
            float xLandingCode = signRectLandingCode.getLeft();
            float yLandingCode = signRectLandingCode.getBottom();

            ByteArrayOutputStream streamLandingCode = new ByteArrayOutputStream();
            if (!ImageIO.write(imageLanding, "jpeg", streamLandingCode)) {
                return returnString;
            }
            byte[] imageBytesLandingCode = streamLandingCode.toByteArray();
            Image imagePathLandingCode = Image.getInstance(imageBytesLandingCode);
            PdfContentByte underLandingCode = pdfStamper.getOverContent(pageNoLandingCode);
            // 设置图片大小
            imagePathLandingCode.scaleToFit(signRectLandingCode.getWidth(), signRectLandingCode.getHeight());
            //设置图片位置
            imagePathLandingCode.setAbsolutePosition(xLandingCode, yLandingCode);
            underLandingCode.addImage(imagePathLandingCode);




            //添加图片
            int pageNoLogo = form.getFieldPositions("expressLogo").get(0).page;
            Rectangle signRectLogo = form.getFieldPositions("expressLogo").get(0).position;
            float xLogo = signRectLogo.getLeft();
            float yLogo = signRectLogo.getBottom();
            Image imagePathLogo = Image.getInstance(LOTTE_LOGO);//获取地址
            PdfContentByte underLogo = pdfStamper.getOverContent(pageNoLogo);
            // 设置图片大小
            imagePathLogo.scaleToFit(signRectLogo.getWidth(), signRectLogo.getHeight());
//            image.scaleAbsolute(signRect.getWidth(), signRect.getHeight());
            //设置图片位置
            imagePathLogo.setAbsolutePosition(xLogo, yLogo);
            underLogo.addImage(imagePathLogo);

            //添加图片
            int pageNoHere = form.getFieldPositions("pasteHere").get(0).page;
            Rectangle signRectHere = form.getFieldPositions("pasteHere").get(0).position;
            float xHere  = signRectHere.getLeft();
            float yHere  = signRectHere.getBottom();
            Image imagePathHere  = Image.getInstance(LOTTE_T);//获取地址
            PdfContentByte underHere = pdfStamper.getOverContent(pageNoHere);
            // 设置图片大小
            imagePathHere.scaleToFit(signRectHere.getWidth(), signRectHere.getHeight());
//            image.scaleAbsolute(signRect.getWidth(), signRect.getHeight());
            //设置图片位置
            imagePathHere.setAbsolutePosition(xHere, yHere);
            underHere.addImage(imagePathHere);




            //设置不可编辑
            pdfStamper.setFormFlattening(true);
            pdfStamper.close();
           // returnString= Uploader.uploadOssStream(output,System.currentTimeMillis()+"-"+ formData.getOrderCore()+ ".pdf");
             this.writeSinglePdf("Order",output,System.currentTimeMillis()+"-"+ formData.getOrderCore(), response);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            return returnString;
        }
    }


    private boolean writeSinglePdf(String name,ByteArrayOutputStream stream, String code, HttpServletResponse response) throws IOException {
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("fileName", name+"-" + code + ".pdf");
        ServletOutputStream stream1 = response.getOutputStream();
        try {

            byte[] buf = new byte[1024];
            byte[] data = stream.toByteArray();
            ByteArrayInputStream in = new ByteArrayInputStream(data);
            int len;
            while ((len = in.read(buf)) != -1) {
                stream1.write(buf, 0, len);
            }
            in.close();
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            stream1.close();
        }
        return false;
    }

/*    public static void main1(String[] args) throws Exception {
        HttpServletResponse response = null;
        PrintOrderInfoTO formData = new PrintOrderInfoTO();
        formData.setExpressTag("운송장번호");
        formData.setExpressUid("317758904816");
        formData.setLandingUid("123456789012");
        formData.setAddressUpperLeft("B-26-평64");
        formData.setAddressUpperRight("부평(대)");
        formData.setAddressBottomLeft("X 부평구 부평5동");
        formData.setAddressBottomRight("평64-이구용");
        formData.setRecipient("받는분: REN SUPING 010-3619-****21353");
        formData.setDetailedAddress("인천광역시 부평구 부평동 126-9 유진마젤란주상복합 오피스텔1205");
        formData.setOrderCore("PP25111223915187411540070");
        printSaleInfo(formData,response);
    }*/



}
