package com.seeyon.apps.esign.node;

import com.seeyon.apps.common.workflow.node.ACommonSuperNode;
import com.seeyon.apps.esign.constants.EsignConfigConstants;
import com.seeyon.apps.esign.constants.FlowFormFieldConstants;
import com.seeyon.apps.esign.utils.DocumentA4Checker;
import com.seeyon.apps.esign.utils.FileUtil;
import com.seeyon.apps.ext.workflow.vo.FieldDataVo;
import com.seeyon.apps.ext.workflow.vo.FormDataVo;
import com.seeyon.apps.ext.workflow.vo.SuperNodeContext;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;
import java.util.List;


public class A4CheckNode extends ACommonSuperNode {

    private static final Log log = LogFactory.getLog(A4CheckNode.class);

    @Override
    public String getPluginId() {
        return EsignConfigConstants.getPluginId();
    }

    @Override
    public String getFormParse() {
        return "";
    }

    @Override
    public SuperNodeContext proceed(String s, FormDataVo formDataVo, FormDataMasterBean formDataMasterBean) throws Exception {
        SuperNodeContext context = new SuperNodeContext();
        context.setNeedSave(true);
        log.info("进入文件A4格式校验超级节点");
        try {
            FieldDataVo fieldData = formDataVo.getFieldData(FlowFormFieldConstants.CONTRACT_APPROVAL_ATTACHMENT);
            String attachmentId = fieldData.getStringValue();
            if (attachmentId == null) throw new RuntimeException("合同文件不能为空");
            String tempDir = System.getProperty("java.io.tmpdir");
            File file = null;
            FileUtil fileUtil = new FileUtil();
            List<String> paths = fileUtil.fieldFileDownload(Long.parseLong(attachmentId), tempDir + File.separator + "oafile" + File.separator);
            for (String path : paths) {
                file = new File(path);
                boolean firstPageA4 = DocumentA4Checker.isFirstPageA4(file);
                if (!firstPageA4) {
                    String errMsg = "上传的附件中" + file.getName() +"非标准A4格式的，请修改后再上传(标准A4为21:29)";
                    formDataVo.getNewFieldDataMap().put("合同审批附件格式校验结果", errMsg);
                    return context.back(errMsg);
                }
                file.delete();
            }

            return context.success("文件A4格式校验通过");
        } catch (Exception e) {
            log.error("校验产生错误", e);
            e.printStackTrace();
            context.setErrMsg("校验产生错误: " + e.getMessage());
            return context.back("校验产生错误: " + e.getMessage());
        }
    }


    @Override
    public String getNodeId() {
        return "nd_20260512";
    }

    @Override
    public String getNodeName() {
        return "A4格式校验节点";
    }
}
