package com.yem.wm.bc.bill.op;

import com.alibaba.fastjson.JSONObject;
import com.yem.ia.intebilllogon.Utils.ObjectToJsonUtils;
import com.yem.wm.utils.YEM;
import com.yem.wm.utils.YunzhijiaUtils;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.entity.validate.ValidationErrorInfo;
import kd.bos.exception.KDBizException;
import kd.bos.exception.KDException;
import kd.bos.id.ID;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author zhouc
 * @date 2024/3/11 15:49
 * @className SalesorderSignatureOp
 * @description 外销合同合同签章申请服务插件
 */
public class SalesorderSignatureOp extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_sigforminstid");
        fieldKeys.add("yem_sigflowinstid");
        fieldKeys.add("yem_sigstatus");
        fieldKeys.add("yem_siguser");
        fieldKeys.add("yem_sigdatetime");
        fieldKeys.add("yem_sigmag");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        List<ExtendedDataEntity> selectedRows = e.getSelectedRows();
        ArrayList<ExtendedDataEntity> ArrayList = new ArrayList<>();
        for (ExtendedDataEntity selectedRow : selectedRows) {
            DynamicObject dynamicObject = selectedRow.getDataEntity();
            Object pkid = dynamicObject.getPkValue();
            boolean yem_sigstatus = dynamicObject.getBoolean("yem_sigstatus");
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(dynamicObject.getDynamicObjectType().getName(), pkid, "yem_approval");
            if (attachments.size() > 0 && !yem_sigstatus) {
                JSONObject json = GetintebilllogonJson(pkid, dynamicObject);
                DynamicObject yem_billtype = BusinessDataServiceHelper.loadSingle("bos_entityobject", new QFilter[]{new QFilter("number", QCP.equals, dynamicObject.getDynamicObjectType().getName())});
                MainEntityType entityType = EntityMetadataCache.getDataEntityType("yem_ialog");
                DynamicObject yemIalog = new DynamicObject(entityType);
                try {
                    String s = YunzhijiaUtils.doPost(YunzhijiaUtils.yzjurl + "/cmmpapi/cmmp/flowCreate.do?tokenId=0C89F5DBEB704C1F8671721B148E8224", json.toString());
                    System.out.println(s);
                    JSONObject retJson = JSONObject.parseObject(s);
                    Boolean success = retJson.getBoolean("success");
                    if (success) {
//                    dynamicObject.set("yem_synfalt",null);
                        JSONObject data = retJson.getJSONObject("data");
                        String formInstId = data.getString("formInstId");//表单定义ID
                        String flowInstId = data.getString("flowInstId");//流程实例ID
                        dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.get("id"), dynamicObject.getDynamicObjectType().getName());
                        dynamicObject.set("yem_sigforminstid", formInstId);
                        dynamicObject.set("yem_sigflowinstid", flowInstId);
                        dynamicObject.set("yem_sigstatus", true);
                        dynamicObject.set("yem_siguser", YEM.getCurrentUserId());
                        dynamicObject.set("yem_sigdatetime", new Date());
                        dynamicObject.set("yem_sigmag", "同步云之家成功！");
                        SaveServiceHelper.update(dynamicObject, OperateOption.create());
                        // 根据实体名构建元数据并创建DynamicObject
                        yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
                        yemIalog.set("billno", dynamicObject.get("billno"));//单据编号
                        yemIalog.set("yem_billtype", yem_billtype);//单据类型
                        yemIalog.set("yem_success", success);//是否成功
                        yemIalog.set("yem_req", json.toString());//请求参数
                        yemIalog.set("billstatus", "A");//请求参数
                        yemIalog.set("yem_response", s);//返回参数
                        yemIalog.set("yem_flowinstid", flowInstId);//流程实例ID
                        yemIalog.set("yem_forminstid", formInstId);//表单实例ID
                    } else {
                        // 根据实体名构建元数据并创建DynamicObject
                        yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
                        yemIalog.set("billstatus", "A");//请求参数
                        yemIalog.set("billno", dynamicObject.get("billno"));//单据编号yemIalog.set("yem_billtype", yem_billtype);//单据类型
                        yemIalog.set("yem_success", false);//是否成功
                        yemIalog.set("yem_req", json.toString());//请求参数
                        yemIalog.set("yem_response", s);//返回参数
                        addErrMessage(operationResult, dynamicObject, "云之家生成流程异常：" + s);
                        dynamicObject.set("yem_sigforminstid", null);
                        dynamicObject.set("yem_sigflowinstid", null);
                        dynamicObject.set("yem_sigstatus", false);
                        dynamicObject.set("yem_sigmag", "同步失败，请查看《智能审批日志》日志！");
                        dynamicObject.set("yem_siguser", YEM.getCurrentUserId());
                        dynamicObject.set("yem_sigdatetime", new Date());
                        SaveServiceHelper.update(dynamicObject, OperateOption.create());
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                    yemIalog.getDataEntityType().getPrimaryKey().setValueFast(yemIalog, ID.genLongId());
                    yemIalog.set("billstatus", "A");//请求参数
                    yemIalog.set("billno", dynamicObject.get("billno"));//单据编号
                    yemIalog.set("yem_billtype", yem_billtype);//单据类型
                    yemIalog.set("yem_success", false);//是否成功
                    yemIalog.set("yem_req", json.toString());//请求参数
                    if (ex instanceof KDException) {
                        yemIalog.set("yem_error", ((KDException) ex).getStackTraceMessage());//异常信息
                        addErrMessage(operationResult, dynamicObject, "云之家接口调用异常：" + ((KDException) ex).getStackTraceMessage());
                    } else {
                        yemIalog.set("yem_error", ex.toString());//异常信息
                        addErrMessage(operationResult, dynamicObject, "云之家接口调用异常：" + ex.toString());
                    }
                    dynamicObject.set("yem_sigforminstid", null);
                    dynamicObject.set("yem_sigflowinstid", null);
                    dynamicObject.set("yem_sigstatus", false);
                    dynamicObject.set("yem_sigmag", "同步失败，请查看《智能审批日志》日志！");
                    dynamicObject.set("yem_siguser", YEM.getCurrentUserId());
                    dynamicObject.set("yem_sigdatetime", new Date());
                    SaveServiceHelper.update(dynamicObject, OperateOption.create());
                }
                SaveServiceHelper.save(new DynamicObject[]{yemIalog});
            } else {
                addErrMessage(operationResult, dynamicObject, "当前订单未上传国贸经理签批附件、当期订单已同步至云之家，禁止执行合同签章申请！");
            }
        }
    }

    /**
     * 获取当前单据入参
     *
     * @param pkid
     * @return
     */
    public JSONObject GetintebilllogonJson(Object pkid, DynamicObject dynamicObject) {
        JSONObject Object = new JSONObject();
        QFilter qFilter = new QFilter("yem_isdisable", QCP.equals, false);
        qFilter.and(new QFilter("billno", QCP.equals, "WXHT-YZJ"));
        DynamicObject yem_ia_intebilllogon = BusinessDataServiceHelper.loadSingle("yem_ia_intebilllogon", "id", qFilter.toArray());
        if (yem_ia_intebilllogon != null) {
            long intebilllogonID = yem_ia_intebilllogon.getLong("id");
            //查询单据注册数据
            DynamicObject data = BusinessDataServiceHelper.loadSingle(intebilllogonID, "yem_ia_intebilllogon");
            if (data != null && pkid != null && pkid != "") {
                Object = ObjectToJsonUtils.ToJson(data, pkid, dynamicObject.getDynamicObjectType().getName(), ObjectToJsonUtils.getpostcreator());
            }
        } else {
            this.operationResult.addErrorInfo(new ValidationErrorInfo("", pkid,
                    0, 0, "err", "合同签章申请", "未读取启用的《智能审批单据注册》，请修改后重试！", ErrorLevel.Error));
        }
        return Object;
    }

    /**
     * 向操作结果，添加一条错误提示
     *
     * @param operationResult 操作结果参数
     * @param dataEntity      校验数据
     * @param errMsg          异常信息
     * @return
     */
    private static void addErrMessage(OperationResult operationResult, DynamicObject dataEntity, String errMsg) {
        operationResult.setSuccess(false);
//        Object pkId = dataEntity.getPkValue();
//        int rowIndex = 0;
//        ErrorLevel errorLevel = ErrorLevel.Error;
//
//        ValidationErrorInfo errInfo = new ValidationErrorInfo("",
//                pkId, 0, rowIndex,
//                "BeforeExecuteOperationTransactionSample",
//                "接口调用异常",
//                "单据编号：【" + dataEntity.get("billno") + "】" + errMsg,
//                errorLevel);
//        operationResult.setMessage("合同签章申请失败！");
//        operationResult.addErrorInfo(errInfo);
        throw new KDBizException("单据编号：【" + dataEntity.get("billno") + "】" + errMsg);
    }
}
