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

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hxhq.business.domain.StudyFormPlan;
import com.hxhq.business.domain.StudyFormPlanJcgj;
import com.hxhq.business.domain.StudyFormPlanQmxx;
import com.hxhq.business.utils.pdf.PdfBaseUtil;
import com.hxhq.business.utils.pdf.PdfExportUtil;
import com.hxhq.business.utils.pdf.template.TemplateBaseUtil;
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.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 供试品-试验物质配制计划表
 *
 * @author tanfei
 */
public class SYWZPZJHB {
    private static final Logger logger = LoggerFactory.getLogger(SYWZPZJHB.class.getName());
    public String language = "zh";

    /**
     * 导出
     *
     * @param studyFormPlan
     * @return
     */
    public String exportDetail(StudyFormPlan studyFormPlan, List<StudyFormPlanQmxx> studyFormPlanQmxxList, List<StudyFormPlanJcgj> studyFormPlanJcgjList, String lang, Integer jcgjlx, String localFilePath) {
        language = lang;
        Document document = null;
        FileOutputStream fos = null;
        String filePath = PdfBaseUtil.getFilePath(localFilePath, "Template");
        try {
            String sign = "hxhq";
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                sign = loginUser.getSysUser().getNickName();
            }
            document = PdfBaseUtil.init(document, fos, filePath, sign + PdfExportUtil.parseDateToStr(new Date()), studyFormPlan.getBdmc(), false);
            JSONObject bdnr = JSONObject.parseObject(studyFormPlan.getBdnr());
            JSONObject zdgxjl = JSONObject.parseObject(StringUtils.isNoneBlank(studyFormPlan.getZdgxjl()) ? studyFormPlan.getZdgxjl() : "{}");
            JSONArray fhyjjl = JSONArray.parseArray(StringUtils.isNoneBlank(studyFormPlan.getFhyjjl()) ? studyFormPlan.getFhyjjl() : "[]");

            //region 表单信息

            //试验基本信息
            PdfBaseUtil.addUnderlinedTitle(document, getName("试验基本信息"), 10, true);
            Map<String, String> formData1 = new LinkedHashMap<>();
            formData1.put(getName("试验名称"), studyFormPlan.getStudyMc());
            formData1.put(getName("试验编号"), studyFormPlan.getStudySn());
            PdfBaseUtil.addFormTableColumns(document, formData1, 2);

            PdfBaseUtil.addUnderlinedTitle(document, getName("计划信息"), 10, true);
            Map<String, String> formData2 = new LinkedHashMap<>();
            formData2.put(getName("领取时间"), (StringUtils.isNoneBlank(bdnr.getString("drawTime")) ? bdnr.getString("drawTime") : "") + TemplateBaseUtil.getCheck("_drawTime", zdgxjl) + TemplateBaseUtil.getFh("_drawTime", fhyjjl));
            formData2.put(getName("分析时间"), (StringUtils.isNoneBlank(bdnr.getString("analyzeTime")) ? bdnr.getString("analyzeTime") : "") + TemplateBaseUtil.getCheck("_analyzeTime", zdgxjl) + TemplateBaseUtil.getFh("_analyzeTime", fhyjjl));
            formData2.put(getName("试验物资"), (StringUtils.isNoneBlank(bdnr.getString("testSubstance")) ? bdnr.getString("testSubstance") : "") + TemplateBaseUtil.getCheck("_testSubstance", zdgxjl) + TemplateBaseUtil.getFh("_testSubstance", fhyjjl));
            formData2.put(getName("配置频率"), (StringUtils.isNoneBlank(bdnr.getString("configFrequency")) ? bdnr.getString("configFrequency") : "") + TemplateBaseUtil.getCheck("_configFrequency", zdgxjl) + TemplateBaseUtil.getFh("_configFrequency", fhyjjl));
            PdfBaseUtil.addFormTableColumns(document, formData2, 2);
            // 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(3);
            table.setWidthPercentage(100);
            JSONObject headerSelectFields = JSONObject.parseObject(bdnr.getString("headerSelectFields"));
            String[] headers = {
                    getName("给药剂量或组别"),
                    getName("配制浓度") + headerSelectFields.getString("preparationConcentrationUnit") + TemplateBaseUtil.getCheck("_preparationConcentrationUnit", zdgxjl) + TemplateBaseUtil.getFh("_preparationConcentrationUnit", fhyjjl),
                    getName("配制体积") + headerSelectFields.getString("preparationVolumeUnit") + TemplateBaseUtil.getCheck("_preparationVolumeUnit", zdgxjl) + TemplateBaseUtil.getFh("_preparationVolumeUnit", fhyjjl)
            };
            for (String header : headers) {
                PdfPCell cell = new PdfPCell(new Phrase(header, headerFont));
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                cell.setPadding(8);
                table.addCell(cell);
            }
            JSONArray stepTableFormData = JSONArray.parseArray(bdnr.getString("stepTableFormData"));
            if (stepTableFormData.size() > 0) {
                for (int i = 0; i < stepTableFormData.size(); i++) {
                    JSONObject obj = stepTableFormData.getJSONObject(i);
                    int rowNum = 0;
                    // 交替行颜色
                    if (rowNum % 2 == 0) {
                        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                    } else {
                        table.getDefaultCell().setBackgroundColor(BaseColor.WHITE);
                    }
                    table.addCell(PdfBaseUtil.createCell(obj.getString("startSolutionCode") + TemplateBaseUtil.getCheck("_startSolutionCode_"+(rowNum+1), zdgxjl) + TemplateBaseUtil.getFh("_startSolutionCode_"+(rowNum+1), fhyjjl), contentFont));
                    table.addCell(PdfBaseUtil.createCell(obj.getString("preparationConcentration") + TemplateBaseUtil.getCheck("_preparationConcentration_"+(rowNum+1), zdgxjl) + TemplateBaseUtil.getFh("_preparationConcentration_"+(rowNum+1), fhyjjl), contentFont));
                    table.addCell(PdfBaseUtil.createCell(obj.getString("preparationVolume") + TemplateBaseUtil.getCheck("_preparationVolume_"+(rowNum+1), zdgxjl) + TemplateBaseUtil.getFh("_preparationVolume_"+(rowNum+1), fhyjjl), contentFont));
                    rowNum++;
                }
            }
            document.add(table);
            PdfBaseUtil.addUnderlinedTitle(document, getName("备注") +  "：" +(StringUtils.isNoneBlank(bdnr.getString("remark")) ? bdnr.getString("remark") : "")+(TemplateBaseUtil.getCheck("_remark",zdgxjl)+TemplateBaseUtil.getFh("_remark",fhyjjl)), 10, false);

            //签名信息
            TemplateBaseUtil.addQmxxPlan(document, studyFormPlanQmxxList, language);
            //稽查轨迹
            TemplateBaseUtil.addJcgjPlan(document,studyFormPlanJcgjList, jcgjlx, language);
            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 name
     * @return
     */
    public String getName(String name) {
        return TemplateBaseUtil.getNameByLanguage(name, language);
    }

}
