package com.yiboshi.science.utils;

import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.properties.*;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.yiboshi.science.param.dto.*;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.io.font.PdfEncodings;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.yiboshi.science.utils.PdfUtil.*;
import static com.yiboshi.science.utils.ProjectInfoToPDF.getCurrentOperatingSystem;

public class TaskToPDF {

    static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    static SimpleDateFormat sdfM = new SimpleDateFormat("yyyy年MM月");

    static float borderWidth = 1f;
    static Border unitedBorder = new SolidBorder(new DeviceRgb(0, 0, 0), borderWidth);

    private static PdfFont createFont(String fontName) {
        try {
            if ("linux".equals(getCurrentOperatingSystem())) {
                if (fontName.toLowerCase().endsWith(".ttc"))
                    return PdfFontFactory.createFont("/usr/share/fonts/" + fontName + ",0", PdfEncodings.IDENTITY_H);
                else
                    return PdfFontFactory.createFont("/usr/share/fonts/" + fontName, PdfEncodings.IDENTITY_H);
            } else {
                if (fontName.toLowerCase().endsWith(".ttc"))
                    return PdfFontFactory.createFont("c:/Windows/Fonts/" + fontName + ",0", PdfEncodings.IDENTITY_H);
                else
                    return PdfFontFactory.createFont("c:/Windows/Fonts/" + fontName, PdfEncodings.IDENTITY_H);
            }
        } catch (Exception e) {
            throw new RuntimeException("加载字体文件失败，请确保系统中存在字体文件 " + fontName + "：" + e.getMessage(), e);
        }
    }

    /**
     * 生成项目合同书PDF
     *
     * @param dto 项目任务信息
     * @return PDF文件字节数组
     */
    public static byte[] createContractPdf1(ComProjectTaskDTO dto) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos));
            Document document = new Document(pdfDoc);
            document.setMargins(72f, 54f, 72f, 54f);
//          添加中文字体支持
            // 宋体
            PdfFont sfChinese = createFont("simsun.ttc");
            // 仿宋
            PdfFont fsChinese = createFont("simfang.ttf");
            document.setFont(sfChinese);
            float[] columnWidths = {20f, 20f, 20f, 40f};
            Table table = new Table(columnWidths);
            table.setWidth(UnitValue.createPercentValue(100));
            // 设置单元格样式
            for (int i = 0; i < 3; i++) {
                for (int j = 0; j < 4; j++) {
                    Cell cell = new Cell();
                    cell.setHeight(40f);
                    cell.setBorder(new SolidBorder(new DeviceRgb(0, 0, 0), 0.5f));
                    cell.setTextAlignment(TextAlignment.CENTER);
                    // 使用中文测试文本
                    cell.add(new Paragraph("单元格 " + (i + 1) + "-" + (j + 1)).setFont(sfChinese));
                    table.addCell(cell);
                }
            }
            // 添加表格到文档
            document.add(table);
            // 关闭文档
            document.close();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 生成项目合同书PDF
     *
     * @param dto 项目任务信息
     * @return PDF文件字节数组
     */
    public static byte[] createContractPdf(ComProjectTaskDTO dto) throws DocumentException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos));
        Document document = new Document(pdfDoc);
        try {
            // 设置页边距 (左, 右, 上, 下)
            document.setMargins(72f, 54f, 72f, 54f);
            // 宋体
            PdfFont sfChinese = createFont("simsun.ttc");
            // 仿宋
            PdfFont fsChinese = createFont("simfang.ttf");
            // 首页
            firstPageInfo(document, dto, sfChinese, fsChinese);
            // 项目基本信息
            baseProjectInfo(document, dto, sfChinese, fsChinese);
            // 关闭文档
            document.close();
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    private static void firstPageInfo(Document document, ComProjectTaskDTO dto, PdfFont bfChinese, PdfFont fsChinese) throws DocumentException {
        // 附件编号
        Paragraph paragraph = new Paragraph("附件4").setFont(bfChinese).setFontSize(16);
        paragraph.setTextAlignment(TextAlignment.LEFT);
        document.add(paragraph);
        document.add(new Paragraph("\n"));

        // 项目编号
        Paragraph no = new Paragraph("项目编号：" + dto.getProjNo()).setFont(bfChinese).setFontSize(16);
        no.setTextAlignment(TextAlignment.LEFT);
        document.add(no);
        document.add(new Paragraph("\n\n\n\n\n\n"));

        // 添加标题
        Paragraph title = new Paragraph("省级临床医学中心科研项目合同书").setFont(bfChinese).setFontSize(22);
        title.setTextAlignment(TextAlignment.CENTER);
        document.add(title);
        document.add(new Paragraph("\n\n\n\n\n\n"));


        float[] columnWidths = {65f, 15f, 15f, 55f, 200f};
        Table table = new Table(columnWidths);
        // 设置表格水平居中
        table.setHorizontalAlignment(HorizontalAlignment.CENTER);
        table.setWidth(UnitValue.createPointValue(400f));
//      table.setBorder(unitedBorder);

        // 添加表格内容
        addTablePageCell(table, "项目名称:", dto.getProjName(), null, 4, bfChinese);
        addTablePageCell(table, "项目下达单位（甲方）:", dto.getAppUnitName(), 4, null, bfChinese);
        addTablePageCell(table, "项目承担单位（乙方）:", dto.getAppUnitName(), 4, null, bfChinese);
        addTablePageCell(table, "项目负责人:", dto.getAppPersonName(), 2, 3, bfChinese);
        addTablePageCell(table, "项目起止年限:", sdf.format(dto.getStartDate()) + " 至 " + sdf.format(dto.getEndDate()), 3, 2, bfChinese);
        document.add(table);
    }

    private static void baseProjectInfo(Document document, ComProjectTaskDTO dto, PdfFont bfChinese, PdfFont fsChinese) throws DocumentException {
        // 添加新页面
        document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
//        document.setMargins(72f, 54f, 72f, 54f);
        // 添加段落标题
        setParagraph(document, "一、项目基本情况", bfChinese, 12f, true);
        // 创建表格
        float[] column = {80f, 80f, 30f, 60f, 60f, 80f, 30f, 100f};
        Table table = new Table(column);
        table.setWidth(UnitValue.createPercentValue(100));

        table.setBorderTop(unitedBorder);
        table.setBorderLeft(unitedBorder);

        // 添加表格内容
        addValueCell(table, "单位名称:", null, dto.getAppUnitName(), 7, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(table, "注册单位类型", null, "医疗机构", 4, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(table, "组织机构代码/统一社会信用代码", 2, dto.getOrganizationCode(), null, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(table, "通讯地址", null, dto.getUnitAddress(), 7, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(table, "注册所在地", null, dto.getRegisteredAddress(), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(table, "邮编", null, dto.getPostCode(), null, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(table, "法定代表人", null, dto.getLegalPerson(), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addCell(table, "职工总数 " + dto.getWorkCount() + " （人）", 2, null, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addCell(table, "其中专科以上人员 " + dto.getSpecializedPersonnel() + " （人）", 4, null, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addCell(table, "研究开发人员 " + dto.getResearchPersonnel() + " （人）", 2, null, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(table, "开户银行", null, dto.getDepositBank(), 4, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(table, "银行账号", null, dto.getBankAccount(), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(table, "开户银行地址", null, dto.getDepositBankAddress(), 4, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(table, "银行联行号", null, dto.getInterbankNumber(), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        document.add(table);

        // 添加项目内容章节
        setParagraph(document, "二、项目基本情况", bfChinese, 12f, true);
        // 创建表格
        float[] column2 = {40f, 80f, 60f, 90f, 20f, 20f, 100f, 80f, 20f, 60f};
        Table projTable = new Table(column2);
        projTable.setWidth(UnitValue.createPercentValue(100));

        addValueCell(projTable, "项目编号:", 2, dto.getProjNo(), 8, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "项目名称", 2, dto.getProjName(), 8, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "所属我省重点领域", 2, dto.getKeyAreas(), 8, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "项目开始时间", 2, sdf.format(dto.getStartDate()), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(projTable, "项目结束时间", 3, sdf.format(dto.getEndDate()), 3, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "项目负责人", 2, dto.getAppUnitName(), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(projTable, "联系电话", 3, dto.getMobile(), 3, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "项目联系人姓名", 2, dto.getLinkName(), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(projTable, "联系人电话", 3, dto.getLinkMobile(), 3, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "传真", 2, dto.getLinkFax(), 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(projTable, "电子邮箱", 3, dto.getLinkEmail(), 3, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "项目总经费（万元）", 2, Objects.nonNull(dto.getTotalFunding()) ? dto.getTotalFunding().toString() : "", 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(projTable, "财政经费（万元）", 2, Objects.nonNull(dto.getGovFunding()) ? dto.getGovFunding().toString() : "", null, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);
        addValueCell(projTable, "自筹经费（万元）", null, Objects.nonNull(dto.getSelfFunding()) ? dto.getSelfFunding().toString() : "", 2, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "是否科技报告:", 2, dto.getIsTechnologyReport().equals(1) ? "是" : "否", 8, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addValueCell(projTable, "科技报告类型:", 2, "", 8, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addCell(projTable, "项目主要参与单位及分工", 10, null, null, bfChinese,null, VerticalAlignment.MIDDLE, HorizontalAlignment.LEFT);

        addCell(projTable, "序号", null, null, null, null, null, null,null);
        addCell(projTable, "单位名称", 2, null, null, null, null, null,null);
        addCell(projTable, "单位地址", 2, null, null, null, null, null,null);
        addCell(projTable, "组织机构代码/统一社会信用代码", 2, null, null, null, null, null,null);
        addCell(projTable, "分 工", 2, null, null, null, null, null,null);
        addCell(projTable, "签字", null, null, null, null, null, null,null);

        for (int i = dto.getCooperativeUnits() != null ? dto.getCooperativeUnits().size() : 0; i < 2; i++) {
            if (dto.getCooperativeUnits() == null) {
                List<ComProjectCooperativeUnitsDTO> list = new ArrayList<>();
                dto.setCooperativeUnits(list);
            }
            dto.getCooperativeUnits().add(new ComProjectCooperativeUnitsDTO());
        }
        for (int i = 0; i < dto.getCooperativeUnits().size(); i++) {
            addCell(projTable, String.valueOf(i + 1), null, null, null, null, null, null,null);
            addCell(projTable, dto.getCooperativeUnits().get(i).getUnitName(), 2, null, null, null, null, null,null);
            addCell(projTable, dto.getCooperativeUnits().get(i).getUnitAddress(), 2, null, null, null, null, null,null);
            addCell(projTable, dto.getCooperativeUnits().get(i).getOrganizationCode(), 2, null, null, null, null, null,null);
            addCell(projTable, dto.getCooperativeUnits().get(i).getProjectWork(), 2, null, null, null, null, null,null);
            addCell(projTable, "", null, null, null, null, null, null,null);
        }
        document.add(projTable);
    }
}
