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

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.hxhq.business.domain.*;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

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

    /**
     * 导出
     *
     * @param studyFormFill
     * @return
     */
    public String exportDetail(StudyFormFill studyFormFill, List<StudyFormFillQmxx> studyFormFillQmxxList, List<StudyFormFillJcgj> studyFormFillJcgjList, 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()), studyFormFill.getBdmc(),false);
            JSONObject bdnr = JSONObject.parseObject(studyFormFill.getBdnr());
            JSONObject zdgxjl = JSONObject.parseObject(StringUtils.isNoneBlank(studyFormFill.getZdgxjl())?studyFormFill.getZdgxjl():"{}");
            JSONArray fhyjjl = JSONArray.parseArray(StringUtils.isNoneBlank(studyFormFill.getFhyjjl())?studyFormFill.getFhyjjl():"[]");

            //region 表单信息

            //试验基本信息
            PdfBaseUtil.addUnderlinedTitle(document, getName("试验基本信息"), 10, true);
            Map<String, String> formData1 = new LinkedHashMap<>();
            formData1.put(getName("试验名称"), studyFormFill.getStudyMc());
            formData1.put(getName("试验编号"), studyFormFill.getStudySn());
            formData1.put(getName("方法编号"), (StringUtils.isNoneBlank(bdnr.getString("methodCode")) ? bdnr.getString("methodCode") : "")+TemplateBaseUtil.getCheck("_methodCode",zdgxjl)+TemplateBaseUtil.getFh("_methodCode",fhyjjl));
            formData1.put(getName("版本号"), (StringUtils.isNoneBlank(bdnr.getString("versionNum")) ? bdnr.getString("versionNum") : "")+TemplateBaseUtil.getCheck("_versionNum",zdgxjl)+TemplateBaseUtil.getFh("_versionNum",fhyjjl));
            PdfBaseUtil.addFormTableColumns(document, formData1, 2);

            PdfBaseUtil.addUnderlinedTitle(document, getName("试验配置条件"), 10, true);
            Map<String, String> formData2 = new LinkedHashMap<>();
            formData2.put(getName("预填"),(StringUtils.isNoneBlank(bdnr.getString("pre"))? bdnr.getString("pre"):"") + (StringUtils.isNoneBlank(bdnr.getString("preOther")) ? bdnr.getString("preOther") : ""));
            formData2.put(getName("实际"),(StringUtils.isNoneBlank(bdnr.getString("act"))? bdnr.getString("act"):"") + (StringUtils.isNoneBlank(bdnr.getString("actOther")) ? bdnr.getString("actOther") : "")+TemplateBaseUtil.getCheck("_act",zdgxjl)+TemplateBaseUtil.getFh("_act",fhyjjl));
            PdfBaseUtil.addFormTableColumns(document, formData2, 2);

            PdfBaseUtil.addUnderlinedTitle(document, getName("配置时间"), 10, true);
            Map<String, String> formData3 = new LinkedHashMap<>();
            formData3.put(getName("开始时间"), studyFormFill.getStartDate() != null ? PdfExportUtil.parseDateToStr(studyFormFill.getStartDate()) : "");
            formData3.put(getName("结束时间"), studyFormFill.getEndDate() != null ? PdfExportUtil.parseDateToStr(studyFormFill.getEndDate()) : "");
            PdfBaseUtil.addFormTableColumns(document, formData3, 2);

            // 试验试剂信息
            TemplateBaseUtil.addResource(document, studyFormFill.getResource(),language);
            //仪器使用信息
            TemplateBaseUtil.addInstrument(document, "",language);

            PdfBaseUtil.addUnderlinedTitle(document, getName("存储条件"), 10, true);

            Map<String, String> formData4 = new LinkedHashMap<>();
            formData4.put(getName("存储条件"), bdnr.getString("storageCondition") + (StringUtils.isNoneBlank(bdnr.getString("storageConditionOther")) ? bdnr.getString("storageConditionOther") : ""));
            PdfBaseUtil.addFormTableColumns(document, formData4, 1);

            PdfBaseUtil.addUnderlinedTitle(document, getName("操作步骤"), 10, true);
            Map<String, String> formData5 = new LinkedHashMap<>();
            formData5.put(getName("目标溶液名称"), bdnr.getString("targetName"));
            formData5.put(getName("目标溶液编号"), bdnr.getString("targetCode") + bdnr.getString("targetCodeSn"));
            formData5.put(getName("目标溶液预计浓度"), bdnr.getString("targetPreConcentration") + bdnr.getString("targetPreConcentrationUnit"));
            formData5.put(getName("目标溶液实际浓度"), bdnr.getString("targetActConcentration") + bdnr.getString("targetPreConcentrationUnit")+TemplateBaseUtil.getCheck("_targetActConcentration",zdgxjl)+TemplateBaseUtil.getFh("_targetActConcentration",fhyjjl));
            formData5.put(getName("目标溶液预计体积"), bdnr.getString("targetPreVolume") + bdnr.getString("targetPreVolumeUnit"));
            formData5.put(getName("目标溶液实际体积"), bdnr.getString("targetActVolume") + bdnr.getString("targetActVolumeUnit")+TemplateBaseUtil.getCheck("_targetActVolume",zdgxjl)+TemplateBaseUtil.getFh("_targetActVolume",fhyjjl));
            formData5.put(getName("有效周期"), bdnr.getString("effectivePeriod") + bdnr.getString("effectivePeriodUnit"));
            formData5.put(getName("失效日"), bdnr.getString("expireDate"));
            PdfBaseUtil.addFormTableColumns(document, formData5, 2);
            //endregion

            //备注，签名信息
            TemplateBaseUtil.addQmxxFill(document, studyFormFillQmxxList,language,bdnr,zdgxjl,fhyjjl);
            //稽查轨迹
            TemplateBaseUtil.addJcgjFill(document, studyFormFillJcgjList,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);
    }

}
