package com.yem.wm.es.salescontrac.validator;

import com.yem.wm.utils.ContactSignUtils;
import com.yem.wm.utils.YEM;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentDto;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.url.UrlService;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBookmark;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2024/10/21 15:23
 * @className SalesOrderSignatureValidetor
 * @description 框架合同【提交】校验Word文档是否包含标签{ensign}
 */
public class SalescontracValidetor extends AbstractValidator {
    @Override
    public void validate() {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for (ExtendedDataEntity dataEntitie : dataEntities) {
            boolean pass = false;
            final String BOOKMARK = "ensign";
            DynamicObject dataEntity = dataEntitie.getDataEntity();
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            String formId = dataEntity.getDataEntityType().getName();
            long pkId = dataEntity.getLong("id");
            // 获取衣晓明签字
            DynamicObject user = BusinessDataServiceHelper.loadSingle("bos_user", new QFilter[]{new QFilter("number", "=", "10437")});
            String imageId = user.getString("yem_signature");
            if (YEM.isEmpty(imageId)) {
                this.addMessage(dataEntitie, "获取工号 10437 的用户签章失败，请检查是否上传签章！！");
            }
            // 下载签字图片文件
            String imageUrl = UrlService.getImageFullUrl(imageId);
            imageUrl = imageUrl + "?access_token=" + RequestContext.get().getGlobalSessionId();
            InputStream imageIn;
            ByteArrayOutputStream buffer;
            try {
                URL url = new URL(imageUrl);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                imageIn = connection.getInputStream();
                // 图片数据缓存，InputStream多次使用
                buffer = new ByteArrayOutputStream();
                int nRead;
                byte[] data = new byte[1024];
                while ((nRead = imageIn.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, nRead);
                }
                buffer.flush();
                connection.disconnect();
            } catch (IOException ex) {
                this.addMessage(dataEntitie, "下载工号 10437 的用户签章失败！！");
            }
            final String DOWNLOAD_ATTACHMENT_KEY = "attachmentpanel";
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(formId, pkId, DOWNLOAD_ATTACHMENT_KEY);
            for (Map<String, Object> attachment : attachments) {
                // 获取Word附件
                AttachmentDto attDao = AttachmentServiceHelper.getAttachmentInfoByAttPk(attachment.get("attPkId"));
                String fileUrl = attDao.getResourcePath();
                String filename = attDao.getFilename();
                /**
                 *  2024-09-20 增加只校验 word文件
                 */
                if (filename.endsWith(".docx") || filename.endsWith(".doc")) {
//                    validatorFileExtension(filename);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    FileServiceFactory.getAttachmentFileService().download(fileUrl, out, null);
                    InputStream in = new ByteArrayInputStream(out.toByteArray());
                    InputStream validatorStream = new ByteArrayInputStream(out.toByteArray());

                    // 获取书签
                    List<CTBookmark> bookMarks = ContactSignUtils.getFileBookMarks(validatorStream);
                    for (CTBookmark bookMark : bookMarks) {
                        String bookMarkName = bookMark.getName();
                        if (bookMarkName.contains(BOOKMARK)) {
                            pass = true;
                            break;
                        }
                    }
                    if (!pass) {
                        this.addMessage(dataEntitie, "未在文件 " + filename + " 中找到包含书签： " + BOOKMARK + "请上传添加书签后的Word文件！！");
                    }
                }
            }
        }
    }
}
