package yem.wm.cm.htqs.op;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.file.ByteArrayOutputStream;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.fileservice.FileService;
import kd.bos.fileservice.FileServiceFactory;
import kd.bos.ksql.util.StringUtil;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.print.api.PrintTask;
import kd.bos.print.api.PrintWork;
import kd.bos.print.core.service.PrtAttach;
import kd.bos.print.service.BosPrintServiceHelper;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserConfigServiceHelper;
import kd.sdk.plugin.Plugin;
import yem.base.common.utils.YEM;
import yem.wm.cm.htqs.util.DoPrint;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 单据操作插件
 * @description 打印至附件操作
 * @author yibo
 * @date 2023年6月3日
 */
public class PrintContractWithType extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        //模板类型
        fieldKeys.add("yem_templatetype");
        //附件存储内容
        fieldKeys.add("yem_attachmentcon");
        //数据库中实际存储的附件存储内容
        fieldKeys.add("yem_attachmentcon_tag");
    }

    /**
     * 操作前校验
     *
     * @param e
     */
    @Override
    public void onAddValidators(AddValidatorsEventArgs e) {
        super.onAddValidators(e);
        e.addValidator(new AbstractValidator() {
            @Override
            public void validate() {
                ExtendedDataEntity[] dataEntities = this.getDataEntities();
                for (ExtendedDataEntity dataEntity : dataEntities) {
                    DynamicObject data = dataEntity.getDataEntity();
                    String formKey = data.getDataEntityType().getName();
                    String billStatus = data.getString("billstatus");
                    if ("A".equals(billStatus)){
                        this.addErrorMessage(dataEntity, "暂存状态不可用");
                        return;
                    }

                    String templatetype = data.getString("yem_templatetype"); // 获取模板类型
//                    // 判断是否为对方模板
//                    if (templatetype == "" || !"A".equals(templatetype))
//                        return;
                    String name = data.getDataEntityType().getName();
                    String tplId = "";
                    String setting = UserConfigServiceHelper.getSetting(RequestContext.get().getCurrUserId(),
                            name + "_printsetting");
                    if (setting != null) {
                        JSONObject fromJsonString = SerializationUtils.fromJsonString(setting, JSONObject.class);
                        if (fromJsonString != null) {
                            tplId = fromJsonString.getString("templateid");
                        }
                    }
                    if (YEM.isEmpty(tplId)) {
                        this.addErrorMessage(dataEntity, "请在打印设置中选择当前合同默认模板!");
                        return;
                    }

                }


            }
        });

    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        for (DynamicObject dataEntity : e.getDataEntities()) {
            CreatPrintFile(dataEntity);
        }
    }


    private void CreatPrintFile(DynamicObject data) {
        String formKey = data.getDataEntityType().getName();
        String templatetype = data.getString("yem_templatetype"); // 获取模板类型
        // 判断是否为对方模板
        if (templatetype == "" || !"A".equals(templatetype))
            return;

        //获取打印模板名称
        String name = data.getDataEntityType().getName();
        String tplId = "";
        String printLang = "";
        String setting = UserConfigServiceHelper.getSetting(RequestContext.get().getCurrUserId(),
                name + "_printsetting");
        if (setting != null) {
            JSONObject fromJsonString = SerializationUtils.fromJsonString(setting, JSONObject.class);
            if (fromJsonString != null) {
                tplId = fromJsonString.getString("templateid");
                printLang = fromJsonString.getString("printlang");
            }
        }

        String settingName = "";
        //根据打印模板id获取打印模板名称
        DynamicObject printtpl = BusinessDataServiceHelper.
                loadSingle("bos_manageprinttpl", new QFilter[]{new QFilter("printtplid", QCP.equals, tplId)});
        settingName = printtpl.getString("name");

        String billno = data.getString("billno");

        //开始打印
        if (!YEM.isEmpty(tplId)) {
            ArrayList<Object> pkIds = new ArrayList<>();
            pkIds.add(data.getPkValue());
            // 打印任务
            ArrayList<PrintTask> taskList = new ArrayList<>();
            PrintTask printTask = new PrintTask();
            printTask.setTplId(tplId);// 打印模板的id
            printTask.setPkIds(pkIds);
            printTask.setPrintType("billForm");// 打印对象的类型，是单据（billForm),报表（report)，还是动态表单(dynamic)
            printTask.setFormId(name);
            taskList.add(printTask);
            // 打印作业
            PrintWork printWork = new PrintWork();
            printWork.setPrintLang(YEM.isEmpty(printLang) ? "zh_CN" : printLang);
            printWork.setExpType("pdf");
            printWork.setTaskList(taskList);
            // 生成打印模板生成的pdf文件
            PrtAttach doPrint = BosPrintServiceHelper.doPrint(printWork);
            List<PrtAttach.AttachDetail> attachDetails = doPrint.getAttachDetail();
            PrtAttach.AttachDetail attachDetail = attachDetails.get(0);
            // 将文件保存到附件
            List<Map<String, Object>> atts = new ArrayList<Map<String, Object>>();
            //
            Map<String, Object> map = DoPrint.createAttInfo(attachDetail, data.getString("billno"),settingName);
            atts.add(map);
            // 上传附件到采购订单的附件面板中
            AttachmentServiceHelper.upload(name, data.getPkValue(), "attachmentpanel", atts);
            // 更新附件信息
            DoPrint.uploadFiles(data, name, (String) map.get("uid") , tplId,"合同");
        }
    }



}