package com.yem.wm.im.merchantapply.op;

import com.yem.wm.utils.RequestEAS;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
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.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.json.JSONObject;
import org.json.XML;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhouc
 * @date 2024/3/30 11:20
 * @className MerChantApplySynEASFiOp
 * @description 同步EAS财务信息
 */
public class MerChantApplySynEASFiOp extends AbstractOperationServicePlugIn {
    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        for (ExtendedDataEntity dataEntity : e.getSelectedRows()) {
            DynamicObject billObj = dataEntity.getDataEntity();
            billObj = BusinessDataServiceHelper.loadSingle(billObj.getPkValue(), billObj.getDynamicObjectType().getName());
            SynFinancial(dataEntity, billObj, e);
        }
    }

    /**
     * 同步财务信息
     *
     * @param bill
     */
    public void SynFinancial(ExtendedDataEntity dataEntity, DynamicObject bill, BeforeOperationArgs e) {
        StringBuilder Erg = new StringBuilder();
        DynamicObjectCollection yem_merchantapply_a = bill.getDynamicObjectCollection("yem_merchantapply_a");
        for (int i = 0; i < yem_merchantapply_a.size(); i++) {
            DynamicObject merchantapply_a = yem_merchantapply_a.get(i);
            DynamicObject yem_finorg = merchantapply_a.getDynamicObject("yem_finorg");
            boolean yem_isassigneas = merchantapply_a.getBoolean("yem_isassigneas");//是否同步EAS
            boolean yem_isfieassyn = merchantapply_a.getBoolean("yem_isfieassyn");//是否同步财务
            if (yem_isassigneas && !yem_isfieassyn) {
                if (yem_finorg != null) {
                    String json1 = getJson(bill, yem_finorg.getString("number"), "BB01");
                    JSONObject json = XML.toJSONObject(json1);
                    int retstatus = json.getJSONObject("Result").getInt("retstatus");
                    if (retstatus == 0) {
                        merchantapply_a.set("yem_isfieassyn", true);
                    } else {
                        JSONObject jsonObject = json.getJSONObject("Result").getJSONObject("errorMessages").getJSONObject("errorMessage");
                        Erg.append(jsonObject.getString("content")).append("\r\n");
//                        {"Result":{"errorMessages":{"errorMessage":{"number":"","content":"BillXmlFormat IS ERROR!"}},"retstatus":1}}
                    }
                }
            }
        }
        SaveServiceHelper.update(new DynamicObject[]{bill});
        if (Erg.length() > 0) {
            Object pkId = dataEntity.getDataEntity().getPkValue();
            int dataIndex = dataEntity.getDataEntityIndex();
            int rowIndex = 0;
            ErrorLevel errorLevel = ErrorLevel.Error;
            ValidationErrorInfo errInfo = new ValidationErrorInfo("",
                    pkId, dataIndex, rowIndex,
                    "BeforeExecuteOperationTransactionSample",
                    "接口调用异常",
                    "单据编号：【" + dataEntity.getDataEntity().get("billno") + "】" + Erg.toString(),
                    errorLevel);
            operationResult.addErrorInfo(errInfo);
        }
    }

    /**
     * 拼接XML
     *
     * @param bill
     * @param companyOrgUnit
     * @param settlementCurrency
     * @return
     */
    public String getJson(DynamicObject bill, String companyOrgUnit, String settlementCurrency) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        StringBuilder materialXmlStr = new StringBuilder();
        materialXmlStr.append("<DataInfo bostype=\"7751B8D7\" op=\"3\">");
        materialXmlStr.append("<DataHead>");
        materialXmlStr.append("<createTime>" + sdf.format(new Date()) + "</createTime>");
        materialXmlStr.append("<CU>100</CU>");//控制单元
        materialXmlStr.append("<customer>" + bill.getString("yem_easnumber") + "</customer>");//客户编码
        materialXmlStr.append("<companyOrgUnit>" + companyOrgUnit + "</companyOrgUnit>");//财务组织
        materialXmlStr.append("<settlementCurrency>" + settlementCurrency + "</settlementCurrency>");
//        materialXmlStr.append("<settlementType></settlementType>");
//        materialXmlStr.append("<paymentType></paymentType>");
        materialXmlStr.append("<usingStatus>0</usingStatus>");
//        materialXmlStr.append("<accountingClassfication> </accountingClassfication>");
//        materialXmlStr.append("<isFreezeIssueInvoice>0</isFreezeIssueInvoice>");
//        materialXmlStr.append("<payCondition> </payCondition>");
        materialXmlStr.append("</DataHead>");
//        materialXmlStr.append("<DataEntries>");
//        materialXmlStr.append("<entry>");
//        materialXmlStr.append("<bankAccount>000212451</bankAccount>");//客户银行-银行帐号
//        materialXmlStr.append("<accountName>测试</accountName>");//客户银行-帐户名称
//        materialXmlStr.append("<bank>11444</bank>");//客户银行-开户银行
//        materialXmlStr.append("</entry>");
//        materialXmlStr.append("</DataEntries>");
        materialXmlStr.append("</DataInfo>");
        String s = RequestEAS.genEASUtils(materialXmlStr.toString(), "importCustomerCompanyData");
        return s;
    }
}
