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

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hxhq.business.domain.GspJcgj;
import com.hxhq.business.domain.GspTz;
import com.hxhq.business.dto.gsp.GspDto;
import com.hxhq.business.enums.zykgl.ZjztEnum;
import com.hxhq.business.utils.lang.GyzjJcnrUtil;
import com.hxhq.business.utils.pdf.PdfBaseUtil;
import com.hxhq.business.utils.pdf.PdfExportUtil;
import com.hxhq.common.core.utils.StringUtils;
import com.hxhq.common.security.utils.SecurityUtils;
import com.hxhq.system.api.model.LoginUser;
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.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.*;

/**
 * 供试品详情
 *
 * @author HanLong
 */
public class GspPdf {
    private static final Logger logger = LoggerFactory.getLogger(GspPdf.class.getName());
    public String language="zh";
    /**
     * 导出
     *
     * @param gsp
     * @return
     */
    public String exportDetail(GspDto gsp, List<GspTz> tzList, List<GspJcgj> jcgjList, String lang,String version, String localFilePath) {
        language=lang;
        Document document = null;
        FileOutputStream fos = null;
        String filePath = PdfBaseUtil.getFilePath(localFilePath,"Gsp");
        try {
            String sign = "hxhq";
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                sign = loginUser.getSysUser().getNickName()+"   "+ PdfExportUtil.parseDateToStr(new Date());
            }
            document = PdfBaseUtil.init(document, fos, filePath,  sign +"   "+version+"   ", getName("给药制剂详情"),false);
            // 基本信息
            PdfBaseUtil.addUnderlinedTitle(document, getName("基本信息"), 10, true);
            Map<String, String> formData1 = new LinkedHashMap<>();
            formData1.put(getName("名称"), gsp.getMc());
            formData1.put(getName("编号"), gsp.getBh());
            formData1.put(getName("批号"), gsp.getPh());
            formData1.put(getName("规格"), gsp.getGg());
            //formData1.put(getName("接收日期"), gsp.getGg() + gsp.getGgdw());
            formData1.put(getName("库存量"), gsp.getKc() + gsp.getKcdw());
            formData1.put(getName("有效期"), PdfExportUtil.parseDateToStr(gsp.getYxq()));
            formData1.put(getName("状态"), "en".equals(language) ? (GyzjJcnrUtil.getEn(ZjztEnum.getEnumByValue(gsp.getZjzt()).getText())) : ZjztEnum.getEnumByValue(gsp.getZjzt()).getText());
            PdfBaseUtil.addFormTableColumns(document, formData1, 2);
            // 台账
            addTz(document, tzList, lang);
            PdfBaseUtil.addUnderlinedTitle(document, getName("稽查轨迹") , 10, true);
            //稽查轨迹
            addJcgj(document, jcgjList, lang);
            logger.info("生成成功：{}", filePath);
        } catch (Exception e) {
            logger.error("生成失败", e);
            throw new RuntimeException("生成失败: " + e.getMessage());
        } finally {
            if (document != null) {
                document.close();
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    logger.error("关闭文件流失败", e);
                }
            }
        }
        return filePath;
    }

    /**
     * 台账
     *
     * @param document
     * @param tzList
     * @throws IOException
     * @throws DocumentException
     */
    public void addTz(Document document, List<GspTz> tzList, String lang) throws IOException, DocumentException {

        // 9. 表头
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        Font headerFont = new Font(bfChinese, 8, Font.NORMAL);
        Font contentFont = new Font(bfChinese, 8, Font.NORMAL);
        // 8. 创建表格
        PdfPTable table = new PdfPTable(8);
        table.setWidthPercentage(100);
        String[] headers = {getName("使用人"),getName("领取/归还人/入库申请人"),getName("发放/接收人"),getName("操作类型"),getName("表单名称"),getName("操作量"),getName("备注/原因"),getName("操作时间")};
        for (String header : headers) {
            PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
            cell.setPadding(8);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
            cell.setBackgroundColor(BaseColor.WHITE);
            cell.setBorderWidth(1);
            table.addCell(cell);
        }
        int rowNum = 0;
        for (GspTz gspTz : tzList) {
            // 交替行颜色
            if (rowNum % 2 == 0) {
                table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
            } else {
                table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
            }
            table.addCell(PdfBaseUtil.createCell(gspTz.getQmrMc(), contentFont));
            table.addCell(PdfBaseUtil.createCell(StringUtils.isNoneBlank(gspTz.getLqrMc()) ? gspTz.getLqrMc() : "" + (StringUtils.isNoneBlank(gspTz.getGhrMc()) ? gspTz.getGhrMc() : ""), contentFont));
            table.addCell(PdfBaseUtil.createCell(StringUtils.isNoneBlank(gspTz.getFfrMc()) ? gspTz.getFfrMc() : "" + (StringUtils.isNoneBlank(gspTz.getJsrMc()) ? gspTz.getJsrMc() : ""), contentFont));
            table.addCell(PdfBaseUtil.createCell(gspTz.getQmyy(), contentFont));
            table.addCell(PdfBaseUtil.createCell(gspTz.getBdMc(), contentFont));
            table.addCell(PdfBaseUtil.createCell(gspTz.getCzl() + gspTz.getCzldw(), contentFont));
            table.addCell(PdfBaseUtil.createCell(gspTz.getRemark(), contentFont));
            table.addCell(PdfBaseUtil.createCell(PdfExportUtil.parseDateToStr(gspTz.getCreateTime()), contentFont));
            rowNum++;
        }
        document.add(table);
    }

    /**
     * 稽查轨迹
     *
     * @param document
     * @param jcgjList
     * @throws IOException
     * @throws DocumentException
     */
    public void addJcgj(Document document, List<GspJcgj> jcgjList, String lang) throws IOException, DocumentException {
        for (GspJcgj jcgj : jcgjList) {
            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 String getName(String name){
       return  "en".equals(language) ? GyzjJcnrUtil.getEn(name) : name;
    }


}
