package com.sifang.modules.customer.pdf;


import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.jfinal.plugin.activerecord.Record;
import com.sifang.modules.customer.utils.CreatePdfUtil;
import com.sifang.modules.flowpath.entity.ExamineInfo;
import com.sifang.modules.sys.common.UserUtils;
import com.sifang.modules.sys.common.utils.DateUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class OrderPdf {

    private static Font headfont;
    private static Font keyfont;
    private static Font textfont;
    // 最大宽度
    private static int maxWidth = 492;

    private static Font titlefont;

    private  Logger logger = LoggerFactory.getLogger(getClass());

    // 静态代码块
    static {
        try {
            // 不同字体（这里定义为同一种字体：包含不同字号、不同style）
            BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            titlefont = new Font(bfChinese, 16, Font.BOLD);
            headfont = new Font(bfChinese, 12, Font.NORMAL);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 11, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void getOrderPdf(Document document,Record order, List<Record> details) throws DocumentException, IOException {
        logger.info(">>>>>>>>>>>getOrderPdf  导出订单");

        CreatePdfUtil.addTitle(document,"上海能辉科技股份有限公司（含子公司）-出库及结算单",Element.ALIGN_CENTER);
        document.add(new Paragraph("    "));
        PdfPTable table1 = CreatePdfUtil.createTable(new float[] {90});
        CreatePdfUtil.addNoBorderCell(table1, StringUtils.join("出库编号：",order.getStr("number")));
        CreatePdfUtil.addNoBorderCell(table1, StringUtils.join("出库日期：",order.getDate("deliver_time") == null ?"":DateUtils.formatDate(order.getDate("deliver_time"),"yyyy-MM-dd")));
        document.add(table1);
        document.add(new Paragraph("    "));
        PdfPTable table = CreatePdfUtil.createTable(new float[] { 50,90, 90, 130, 90,90, 90, 90});
        table.addCell(CreatePdfUtil.createCell("编号", headfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("产品编号", headfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("产品名称", headfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("产品规格", headfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("数量", headfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("单位", headfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("单品价值", headfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("总价值", headfont, Element.ALIGN_CENTER, 1));
        int i=1;
        BigDecimal totalPrice = BigDecimal.ZERO;
        for(Record record:details){
            table.addCell(CreatePdfUtil.createCell(""+i, textfont, Element.ALIGN_CENTER, 1));
            table.addCell(CreatePdfUtil.createCell(record.getStr("qq_code"), textfont, Element.ALIGN_CENTER, 1));
            table.addCell(CreatePdfUtil.createCell(record.getStr("material_name"), textfont, Element.ALIGN_CENTER, 1));
            table.addCell(CreatePdfUtil.createCell(record.getStr("material_spec"), textfont, Element.ALIGN_CENTER, 1));
            table.addCell(CreatePdfUtil.createCell(record.getBigDecimal("apply_amount")!=null?String.valueOf(record.getBigDecimal("apply_amount")):"", textfont, Element.ALIGN_CENTER, 1));
            table.addCell(CreatePdfUtil.createCell(record.getStr("unit_name"), textfont, Element.ALIGN_CENTER, 1));
            table.addCell(CreatePdfUtil.createCell(record.getBigDecimal("sales_price")!=null?String.valueOf(record.getBigDecimal("sales_price")):"", textfont, Element.ALIGN_CENTER, 1));
            BigDecimal price = record.getBigDecimal("sales_price").multiply(record.getBigDecimal("apply_amount"));
            totalPrice = totalPrice.add(price);
            table.addCell(CreatePdfUtil.createCell(price.stripTrailingZeros().toPlainString(), textfont, Element.ALIGN_CENTER, 1));

            i++;
        }
        table.addCell(CreatePdfUtil.createCell("",textfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("", textfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("", textfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("", textfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("", textfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("", textfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell("合计", textfont, Element.ALIGN_CENTER, 1));
        table.addCell(CreatePdfUtil.createCell(totalPrice.stripTrailingZeros().toPlainString(), textfont, Element.ALIGN_CENTER, 1));
        document.add(table);
        PdfPTable table2 = new PdfPTable(3);
        table2.setTotalWidth(500);
        table2.setLockedWidth(true);
        table2.addCell(CreatePdfUtil.createCell("库管员:"+order.getStr("person_in_charge"), Element.ALIGN_LEFT));
        //TODO审核人暂时默认为空
        table2.addCell(CreatePdfUtil.createCell("审核人:", Element.ALIGN_CENTER));
        table2.addCell(CreatePdfUtil.createCell("制单人:"+ UserUtils.getUser().getUserName(), Element.ALIGN_RIGHT));
        document.add(table2);
        document.add(new Paragraph("    "));
        document.add(new Paragraph("注意事项：1.装卸搬运小心轻放，请放在室内储存；2.如有质量问题，请收货当天通知对方，否则视为合格产 品，3.领用单位签字或盖章视为生效，4.扫描件和原价同法律效力。感谢配合。",textfont));
        document.add(new Paragraph("    "));
        document.add(new Paragraph("领用及购买单位："+order.getStr("applyOrderTrader"),textfont));
        Date receiveTime = order.getDate("receive_time");
        if (receiveTime != null){
            document.add(new Paragraph("领用及接收日期："+ DateUtils.formatDate(receiveTime,"yyyy-MM-dd"),textfont));
        }else {
            document.add(new Paragraph("领用及接收日期：",textfont));
        }
    }

    public static void createOrderPdf(OutputStream outputStream,Record order, List<Record> details){
        try {
            Document document = new Document(PageSize.A4);// 建立一个Document对象
            PdfWriter writer = PdfWriter.getInstance(document, outputStream);
            // 3.打开文档
            document.open();
            document.addTitle("物质需求单_"+order.getStr("number"));// 标题
            document.addAuthor("Author@sifangTechnology");// 作者
            document.addSubject("Subject@iText pdf sample");// 主题
            document.addKeywords("Keywords@iTextpdf");// 关键字
            document.addCreator("Creator@sifangTechnology");// 创建者
            // 4.向文档中添加内容
            new OrderPdf().getOrderPdf(document,order,details);
            // 5.关闭文档
            document.close();
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
