package com.hxhq.business.utils.pdf.template;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxhq.business.domain.*;
import com.hxhq.business.utils.lang.TemplateUtil;
import com.hxhq.business.utils.pdf.PdfBaseUtil;
import com.hxhq.business.utils.pdf.PdfExportUtil;
import com.hxhq.common.core.utils.StringUtils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;
import java.util.*;

/**
 * 色谱-生物样品分析溶液配制表
 *
 * @author tanfei
 */
public class TemplateBaseUtil {
    private static final Logger logger = LoggerFactory.getLogger(TemplateBaseUtil.class.getName());
    public static String language = "zh";


    /**
     * 试验试剂信息
     *
     * @param document
     * @param resource
     * @throws IOException
     * @throws DocumentException
     */
    public static void addResource(Document document, String resource, String lang) throws IOException, DocumentException {
//        [{"mc"："布洛芬","bh"："BLF260115-0014","ph"："","nd"："18ng/mL","source"："ELN配制","ndz":18,"nddw"："ng/mL","kc":1190,"kcdw"："3","syl"："4","syldw"："3","yxzq":360,"yxzqdw"："days"}]
        language = lang;
        PdfBaseUtil.addUnderlinedTitle(document, getName("试验试剂信息"), 10, true);
        // 9. 表头
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bfChinese, 10, Font.NORMAL);
        Font contentFont = new Font(bfChinese, 10, Font.NORMAL);
        // 8. 创建表格
        PdfPTable table = new PdfPTable(6);
        table.setWidthPercentage(100);
        String[] headers = {getName("试剂名称"), getName("编号"), getName("批号"), getName("浓度/含量/纯度"), getName("来源"), getName("失效日")};
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(8);
            table.addCell(cell);
        }
        if (StringUtils.isNoneBlank(resource)) {
            JSONArray jsonArray = JSONArray.parseArray(resource);
            int rowNum = 0;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                // 交替行颜色
                if (rowNum % 2 == 0) {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                } else {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                }
                table.addCell(PdfBaseUtil.createCell(obj.getString("mc"), contentFont));
                table.addCell(PdfBaseUtil.createCell(obj.getString("bh"), contentFont));
                table.addCell(PdfBaseUtil.createCell(obj.getString("ph"), contentFont));
                table.addCell(PdfBaseUtil.createCell(obj.getString("nd"), contentFont));
                table.addCell(PdfBaseUtil.createCell(obj.getString("source"), contentFont));
                table.addCell(PdfBaseUtil.createCell(StringUtils.isNoneBlank(obj.getString("sxrq")) ? obj.getString("sxrq") : "", contentFont));
                rowNum++;
            }
        }
        document.add(table);
    }

    /**
     * 仪器使用信息
     *
     * @param document
     * @param instrument
     * @throws IOException
     * @throws DocumentException
     */
    public static void addInstrument(Document document, String instrument, String lang) throws IOException, DocumentException {
        language = lang;
        PdfBaseUtil.addUnderlinedTitle(document, getName("仪器使用信息"), 10, true);
        // 9. 表头
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bfChinese, 10, Font.NORMAL);
        Font contentFont = new Font(bfChinese, 10, Font.NORMAL);
        // 8. 创建表格
        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100);
        String[] headers = {getName("仪器名称"), getName("仪器型号"), getName("仪器编号"), getName("下次测试/校准/检定日期")};
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(8);
            table.addCell(cell);
        }
        if (StringUtils.isNoneBlank(instrument)) {
//            JSONArray jsonArray = JSONArray.parseArray(instrument);
//            int rowNum = 0;
//            for (int i = 0; i < jsonArray.size(); i++) {
//                JSONObject obj = jsonArray.getJSONObject(i);
//                // 交替行颜色
//                if (rowNum % 2 == 0) {
//                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
//                } else {
//                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
//                }
//                table.addCell(PdfBaseUtil.createCell(obj.getString("mc"), contentFont));
//                table.addCell(PdfBaseUtil.createCell(obj.getString("bh"), contentFont));
//                table.addCell(PdfBaseUtil.createCell(obj.getString("ph"), contentFont));
//                table.addCell(PdfBaseUtil.createCell(obj.getString("nd"), contentFont));
//                table.addCell(PdfBaseUtil.createCell(obj.getString("source"), contentFont));
//                table.addCell(PdfBaseUtil.createCell(StringUtils.isNoneBlank(obj.getString("sxrq")) ? obj.getString("sxrq") : "", contentFont));
//                rowNum++;
//            }
        }
        document.add(table);
    }


    /**
     * 签名信息
     * 填报表单
     * @param document
     * @param studyFormFillQmxxList
     * @throws IOException
     * @throws DocumentException
     */
    public static void addQmxxFill(Document document, List<StudyFormFillQmxx> studyFormFillQmxxList, String lang, JSONObject bdnr,JSONObject zdgxjl, JSONArray fhyjjl) throws IOException, DocumentException {
        language = lang;
        PdfBaseUtil.addUnderlinedTitle(document, getName("备注") +  "：" +(StringUtils.isNoneBlank(bdnr.getString("remark")) ? bdnr.getString("remark") : "")+(getCheck("_remark",zdgxjl)+getFh("_remark",fhyjjl)), 10, false);
        PdfBaseUtil.addUnderlinedTitle(document, getName("签名信息"), 10, true);
        // 9. 表头
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bfChinese, 10, Font.NORMAL);
        Font contentFont = new Font(bfChinese, 10, Font.NORMAL);
        // 8. 创建表格
        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100);
        String[] headers = {getName("签名人"), getName("签名意义"), getName("签名时间"), getName("备注原因")};
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(8);
            table.addCell(cell);
        }
        if (studyFormFillQmxxList.size() > 0) {
            int rowNum = 0;
            for (StudyFormFillQmxx studyFormFillQmxx : studyFormFillQmxxList) {
                // 交替行颜色
                if (rowNum % 2 == 0) {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                } else {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                }
                table.addCell(PdfBaseUtil.createCell(studyFormFillQmxx.getQmrMc(), contentFont));
                table.addCell(PdfBaseUtil.createCell("en".equals(language) ? studyFormFillQmxx.getQmyyEn() : studyFormFillQmxx.getQmyy(), contentFont));
                table.addCell(PdfBaseUtil.createCell(PdfExportUtil.parseDateToStr(studyFormFillQmxx.getCreateTime()), contentFont));
                table.addCell(PdfBaseUtil.createCell(studyFormFillQmxx.getRemark(), contentFont));
                rowNum++;
            }
        }
        document.add(table);
    }

    /**
     * 稽查轨迹
     * 填报表单
     * @param document
     * @param studyFormFillJcgjList
     * @throws IOException
     * @throws DocumentException
     */
    public static void addJcgjFill(Document document, List<StudyFormFillJcgj> studyFormFillJcgjList, Integer jcgjlx, String lang) throws IOException, DocumentException {
        language = lang;
        Integer jcgjlxMark = 999;
        if (!jcgjlx.equals(jcgjlxMark)) {
            PdfBaseUtil.addUnderlinedTitle(document, getName("稽查轨迹"), 10, true);
            for (StudyFormFillJcgj jcgj : studyFormFillJcgjList) {
                StringJoiner result = new StringJoiner(", ");
                if ("en".equals(lang)) {
                    PdfBaseUtil.addUnderlinedTitle(document, PdfExportUtil.parseDateToStr(jcgj.getCreateTime()) + "     " + jcgj.getJcmcEn(), 10, false);
                    if (StringUtils.isNoneBlank(jcgj.getJcnrEn())) {
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode jsonArray = mapper.readTree(jcgj.getJcnrEn());
                        for (JsonNode node : jsonArray) {
                            if (node.get("name") != null) {
                                String name = node.get("name").asText();
                                String value = node.get("value") != null ? node.get("value").asText() : "";
                                result.add(name + "：" + value);
                            }
                        }
                    }
                } else {
                    PdfBaseUtil.addUnderlinedTitle(document, PdfExportUtil.parseDateToStr(jcgj.getCreateTime()) + "     " + jcgj.getJcmc(), 10, false);
                    if (StringUtils.isNoneBlank(jcgj.getJcnr())) {
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode jsonArray = mapper.readTree(jcgj.getJcnr());
                        for (JsonNode node : jsonArray) {
                            if (node.get("name") != null) {
                                String name = node.get("name").asText();
                                String value = node.get("value") != null ? node.get("value").asText() : "";
                                result.add(name + "：" + value);
                            }
                        }
                    }
                }

                if (StringUtils.isNoneBlank(jcgj.getRemark())) {
                    result.add(getName("备注") + "：" + jcgj.getRemark());
                }
                if (StringUtils.isNoneBlank(jcgj.getQmrMc())) {
                    result.add(getName("签名人") + "：" + jcgj.getQmrMc());
                }
                PdfBaseUtil.addUnderlinedTitle(document, result.toString(), 10, false);
            }
        }
    }


    /**
     * 签名信息
     * 计划表单
     * @param document
     * @param studyFormPlanQmxxList
     * @throws IOException
     * @throws DocumentException
     */
    public static void addQmxxPlan(Document document, List<StudyFormPlanQmxx> studyFormPlanQmxxList, String lang) throws IOException, DocumentException {
        language = lang;
        PdfBaseUtil.addUnderlinedTitle(document, getName("签名信息"), 10, true);
        // 9. 表头
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bfChinese, 10, Font.NORMAL);
        Font contentFont = new Font(bfChinese, 10, Font.NORMAL);
        // 8. 创建表格
        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100);
        String[] headers = {getName("签名人"), getName("签名意义"), getName("签名时间"), getName("备注原因")};
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(8);
            table.addCell(cell);
        }
        if (studyFormPlanQmxxList.size() > 0) {
            int rowNum = 0;
            for (StudyFormPlanQmxx studyFormPlanQmxx : studyFormPlanQmxxList) {
                // 交替行颜色
                if (rowNum % 2 == 0) {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                } else {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                }
                table.addCell(PdfBaseUtil.createCell(studyFormPlanQmxx.getQmrMc(), contentFont));
                table.addCell(PdfBaseUtil.createCell("en".equals(language) ? studyFormPlanQmxx.getQmyyEn() : studyFormPlanQmxx.getQmyy(), contentFont));
                table.addCell(PdfBaseUtil.createCell(PdfExportUtil.parseDateToStr(studyFormPlanQmxx.getCreateTime()), contentFont));
                table.addCell(PdfBaseUtil.createCell(studyFormPlanQmxx.getRemark(), contentFont));
                rowNum++;
            }
        }
        document.add(table);
    }

    /**
     * 稽查轨迹
     * 计划表单
     * @param document
     * @param studyFormPlanJcgjList
     * @throws IOException
     * @throws DocumentException
     */
    public static void addJcgjPlan(Document document, List<StudyFormPlanJcgj> studyFormPlanJcgjList, Integer jcgjlx, String lang) throws IOException, DocumentException {
        language = lang;
        Integer jcgjlxMark = 999;
        if (!jcgjlx.equals(jcgjlxMark)) {
            PdfBaseUtil.addUnderlinedTitle(document, getName("稽查轨迹"), 10, true);
            for (StudyFormPlanJcgj jcgj : studyFormPlanJcgjList) {
                StringJoiner result = new StringJoiner(", ");
                if ("en".equals(lang)) {
                    PdfBaseUtil.addUnderlinedTitle(document, PdfExportUtil.parseDateToStr(jcgj.getCreateTime()) + "     " + jcgj.getJcmcEn(), 10, false);
                    if (StringUtils.isNoneBlank(jcgj.getJcnrEn())) {
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode jsonArray = mapper.readTree(jcgj.getJcnrEn());
                        for (JsonNode node : jsonArray) {
                            if (node.get("name") != null) {
                                String name = node.get("name").asText();
                                String value = node.get("value") != null ? node.get("value").asText() : "";
                                result.add(name + "：" + value);
                            }
                        }
                    }
                } else {
                    PdfBaseUtil.addUnderlinedTitle(document, PdfExportUtil.parseDateToStr(jcgj.getCreateTime()) + "     " + jcgj.getJcmc(), 10, false);
                    if (StringUtils.isNoneBlank(jcgj.getJcnr())) {
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode jsonArray = mapper.readTree(jcgj.getJcnr());
                        for (JsonNode node : jsonArray) {
                            if (node.get("name") != null) {
                                String name = node.get("name").asText();
                                String value = node.get("value") != null ? node.get("value").asText() : "";
                                result.add(name + "：" + value);
                            }
                        }
                    }
                }

                if (StringUtils.isNoneBlank(jcgj.getRemark())) {
                    result.add(getName("备注") + "：" + jcgj.getRemark());
                }
                if (StringUtils.isNoneBlank(jcgj.getQmrMc())) {
                    result.add(getName("签名人") + "：" + jcgj.getQmrMc());
                }
                PdfBaseUtil.addUnderlinedTitle(document, result.toString(), 10, false);
            }
        }
    }

    /**
     * 签名信息
     * 申请表单
     * @param document
     * @param studyFormApplyQmxxList
     * @throws IOException
     * @throws DocumentException
     */
    public static void addQmxxApply(Document document, List<StudyFormApplyQmxx> studyFormApplyQmxxList, String lang) throws IOException, DocumentException {
        language = lang;
        PdfBaseUtil.addUnderlinedTitle(document, getName("签名信息"), 10, true);
        // 9. 表头
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bfChinese, 10, Font.NORMAL);
        Font contentFont = new Font(bfChinese, 10, Font.NORMAL);
        // 8. 创建表格
        PdfPTable table = new PdfPTable(4);
        table.setWidthPercentage(100);
        String[] headers = {getName("签名人"), getName("签名意义"), getName("签名时间"), getName("备注原因")};
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setPadding(8);
            table.addCell(cell);
        }
        if (studyFormApplyQmxxList.size() > 0) {
            int rowNum = 0;
            for (StudyFormApplyQmxx studyFormApplyQmxx : studyFormApplyQmxxList) {
                // 交替行颜色
                if (rowNum % 2 == 0) {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                } else {
                    table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                }
                table.addCell(PdfBaseUtil.createCell(studyFormApplyQmxx.getQmrMc(), contentFont));
                table.addCell(PdfBaseUtil.createCell("en".equals(language) ? studyFormApplyQmxx.getQmyyEn() : studyFormApplyQmxx.getQmyy(), contentFont));
                table.addCell(PdfBaseUtil.createCell(PdfExportUtil.parseDateToStr(studyFormApplyQmxx.getCreateTime()), contentFont));
                table.addCell(PdfBaseUtil.createCell(studyFormApplyQmxx.getRemark(), contentFont));
                rowNum++;
            }
        }
        document.add(table);
    }

    /**
     * 稽查轨迹
     * 申请表单
     * @param document
     * @param studyFormApplyJcgjList
     * @throws IOException
     * @throws DocumentException
     */
    public static void addJcgjApply(Document document, List<StudyFormApplyJcgj> studyFormApplyJcgjList, Integer jcgjlx, String lang) throws IOException, DocumentException {
        language = lang;
        Integer jcgjlxMark = 999;
        if (!jcgjlx.equals(jcgjlxMark)) {
            PdfBaseUtil.addUnderlinedTitle(document, getName("稽查轨迹"), 10, true);
            for (StudyFormApplyJcgj jcgj : studyFormApplyJcgjList) {
                StringJoiner result = new StringJoiner(", ");
                if ("en".equals(lang)) {
                    PdfBaseUtil.addUnderlinedTitle(document, PdfExportUtil.parseDateToStr(jcgj.getCreateTime()) + "     " + jcgj.getJcmcEn(), 10, false);
                    if (StringUtils.isNoneBlank(jcgj.getJcnrEn())) {
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode jsonArray = mapper.readTree(jcgj.getJcnrEn());
                        for (JsonNode node : jsonArray) {
                            if (node.get("name") != null) {
                                String name = node.get("name").asText();
                                String value = node.get("value") != null ? node.get("value").asText() : "";
                                result.add(name + "：" + value);
                            }
                        }
                    }
                } else {
                    PdfBaseUtil.addUnderlinedTitle(document, PdfExportUtil.parseDateToStr(jcgj.getCreateTime()) + "     " + jcgj.getJcmc(), 10, false);
                    if (StringUtils.isNoneBlank(jcgj.getJcnr())) {
                        ObjectMapper mapper = new ObjectMapper();
                        JsonNode jsonArray = mapper.readTree(jcgj.getJcnr());
                        for (JsonNode node : jsonArray) {
                            if (node.get("name") != null) {
                                String name = node.get("name").asText();
                                String value = node.get("value") != null ? node.get("value").asText() : "";
                                result.add(name + "：" + value);
                            }
                        }
                    }
                }

                if (StringUtils.isNoneBlank(jcgj.getRemark())) {
                    result.add(getName("备注") + "：" + jcgj.getRemark());
                }
                if (StringUtils.isNoneBlank(jcgj.getQmrMc())) {
                    result.add(getName("签名人") + "：" + jcgj.getQmrMc());
                }
                PdfBaseUtil.addUnderlinedTitle(document, result.toString(), 10, false);
            }
        }
    }


    /**
     * 获取名称
     *
     * @param name
     * @return
     */
    public static String getNameByLanguage(String name, String lang) {
        return "en".equals(lang) ? TemplateUtil.getEn(name) : name;
    }

    /**
     * 获取名称
     *
     * @param name
     * @return
     */
    public static String getName(String name) {
        return "en".equals(language) ? TemplateUtil.getEn(name) : name;
    }

    /**
     * 获取勾选标志
     *
     * @param key
     * @param key
     * @return
     */
    public static String  getCheck(String key, JSONObject jsonObject) {
        Boolean result = false;
        if (jsonObject.getString(key) != null) {
            result = true;
        }
        return result?" √ ":"";
    }

    /**
     * 获取复核标志
     *
     * @param key
     * @param jsonArray
     * @return
     */
    public static String getFh(String key, JSONArray jsonArray) {
        Boolean result = false;
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            if (obj != null && key.equals(obj.getString("key"))) {
                result = true;
                break;
            }
        }
        return result?" ? ":"";
    }


}
