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.operate.result.OperationResult;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
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.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


public class MerChantApplySynOp extends AbstractOperationServicePlugIn {
    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        for (ExtendedDataEntity dataEntity : e.getSelectedRows()) {
            DynamicObject billObj = dataEntity.getDataEntity();
            billObj = BusinessDataServiceHelper.loadSingle(billObj.get("id"), "yem_merchantapply");
            boolean yem_issyneas = billObj.getBoolean("yem_issyneas");
            if (yem_issyneas) {
                throw new KDBizException("当前单据已同步EAS禁止再次同步！");
            }
            DynamicObjectCollection groupColl = billObj.getDynamicObjectCollection("yem_merchantapply_e");
            boolean MaxCustomerNum = true;
            String yem_easnumber = "";
            for (DynamicObject groupObj : groupColl) {
                if (groupObj.getDynamicObject("yem_standardid").getString("number").equals("customerGroupStandard")) {
                    String groupNum = groupObj.getDynamicObject("yem_groupid").getString("number");
                    //获取EAS编码最大值
                    List<Map<String, Object>> maxCustomerNum = RequestEAS.getMaxCustomerNum(groupNum);
                    for (Map<String, Object> stringObjectMap : maxCustomerNum) {
                        String fnumber = (String) stringObjectMap.get("fnumber");
                        String[] split = fnumber.split(groupNum + "");
                        String s = split[split.length - 1];
                        Integer i = Integer.parseInt(s) + 1;
                        String s1 = i.toString();
                        int i1 = s.length() - s1.length();
                        if (i1 < 0) {
                            addErrMessage(operationResult, dataEntity, "获取EAS客户分类编码为：【" + groupNum + "】时已经超出最大长度,请联系EAS管理员维护");
                            MaxCustomerNum = false;
                            continue;
                        }
                        for (int j = 0; j < i1; j++) {
                            s1 = "0" + s1;
                        }
                        yem_easnumber = groupNum + "" + s1;
                        billObj.set("yem_easnumber", yem_easnumber);
                        SaveServiceHelper.update(billObj);
                    }

                    if (maxCustomerNum.isEmpty()) {
                        yem_easnumber = groupNum + "00001";
                        billObj.set("yem_easnumber", yem_easnumber);
                        SaveServiceHelper.update(billObj);
                    }
                }

            }
            if (MaxCustomerNum) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                StringBuilder xml = new StringBuilder();
                xml.append(" <DataInfo bostype=\"BF0C040E\" op=\"4\">\n");
                xml.append("\t<DataHead>\n");
                xml.append("\t\t<creator>user</creator>\n");
                xml.append("\t\t<createTime>" + sdf.format(new Date()) + "</createTime>\n");
                xml.append("\t\t<CU>" + BusinessDataServiceHelper.loadSingle(100000l, "bos_org").getString("number") + "</CU>\n");
                xml.append("\t\t<number>" + yem_easnumber + "</number>\n");
                xml.append("\t\t<name>" + billObj.getString("yem_merchantstnames") + "</name>\n");
                DynamicObjectCollection standardColl = billObj.getDynamicObjectCollection("yem_merchantapply_e");
                String groupNum = "";
                String groupFullName = "";
                for (DynamicObject standardobj : standardColl) {
                    if ("customerGroupStandard".equals(standardobj.getDynamicObject("yem_standardid").getString("number"))) {
                        DynamicObject groupObj = standardobj.getDynamicObject("yem_groupid");
                        groupNum = groupObj
                                .getString("number");
                        long id = groupObj.getLong("id");
                        standardobj = BusinessDataServiceHelper.loadSingle(id, "bd_customergroup");
                        groupFullName = standardobj.getString("fullname");
                        groupFullName = groupFullName.replace("!", ".");
                    }
                }
                xml.append("         <browseGroup>" + groupNum + "</browseGroup>\t\t\t\t\n");
                xml.append("\t\t<usedStatus>0</usedStatus>\n");
                xml.append("\t\t<version>0</version>\n");
                xml.append("         <isInternalCompany>false</isInternalCompany>\n");
                xml.append("<internalCompany></internalCompany>\n");
                xml.append("         </DataHead>\n");
                xml.append("\t<DataEntries>\n");
                xml.append("\t   \t   <entry>\n");
                xml.append("                <customerGroupStandard>customerGroupStandard</customerGroupStandard>\n");
                xml.append("\t\t\t<customerGroup>" + groupNum + "</customerGroup>\n");
                xml.append("\t\t\t<customerGroupFullName>" + groupFullName + "</customerGroupFullName>\n");
                xml.append("\t   \t   </entry>\n");
                xml.append("      </DataEntries>\n");
                xml.append("</DataInfo>\n");
                JSONObject json = XML.toJSONObject(xml.toString());
                System.out.println(json);
                String retXml = RequestEAS.generateCustomer(xml.toString());
                System.out.println(retXml);
                Boolean b = parseXml(retXml, dataEntity);
                if (b) {
                    String xml1 = xml.toString().replaceAll("op=\"4\">\n", "op=\"1\">\n");
                    String s = RequestEAS.generateCustomer(xml1);
                    Boolean b1 = parseXml(s, dataEntity);
                    if (b1) {
                        billObj.set("yem_issyneas", true);
                        billObj.set("yem_issyneasmag", "同步成功！");
                        System.out.println(s);
                        SaveServiceHelper.update(billObj);
                        //更新当前苍穹客户编码
                        upcustomer(billObj.getString("yem_erpnumber"), yem_easnumber);

                        // 是否集团客户
                        String iscompclient = billObj.getString("yem_iscompclient");
                        DynamicObject single = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter[]{new QFilter("number", QCP.equals, yem_easnumber)});
                        if ("A".equals(iscompclient)) {
                            DynamicObject groupcustomers = billObj.getDynamicObject("yem_groupcustomers");

                            if (single != null) {
                                single.set("yem_groupcustomers", groupcustomers);
                                SaveServiceHelper.update(single);
                            }
                        } else {
                            if (single != null) {
                                single.set("yem_groupcustomers", single);
                                SaveServiceHelper.update(single);
                            }
                        }

                        AssignEASCustomerTask(billObj);
                        SynFinancial(dataEntity, billObj, e);
                    }
                }
            } else {

            }
        }
    }

    private boolean parseXml(String retXml, ExtendedDataEntity dataEntity) {
        JSONObject json = XML.toJSONObject(retXml);
        int retstatus = json.getJSONObject("Result").getInt("retstatus");
        if (0 != retstatus) {
            String content = json.getJSONObject("Result").getJSONObject("errorMessages").getJSONObject("errorMessage").getString("content");
            addErrMessage(operationResult, dataEntity, content);
            DynamicObject billObj = dataEntity.getDataEntity();
            billObj.set("yem_issyneas", false);
            billObj.set("yem_issyneasmag", content);
            SaveServiceHelper.update(billObj);
            return false;
        }
        return true;
    }

    private static void addErrMessage(OperationResult operationResult, ExtendedDataEntity dataEntity, String errMsg) {

        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") + "】" + errMsg,
                errorLevel);

        operationResult.addErrorInfo(errInfo);
    }

    /**
     * 更新现有系统客户编码
     */
    public void upcustomer(String yem_erpnumber, String yem_easnumber) {
        DynamicObject load = BusinessDataServiceHelper.loadSingle("bd_customer", "id",
                new QFilter[]{new QFilter("number", QCP.equals, yem_erpnumber)});
        if (load != null) {
            DynamicObject customer = BusinessDataServiceHelper.loadSingle(load.get("id"), "bd_customer");
            customer.set("number", yem_easnumber);
            customer.set("yem_issyneas", true);

            SaveServiceHelper.update(customer);
        }
    }

    /**
     * 分配EAS客户
     *
     * @param bill
     */
    public void AssignEASCustomerTask(DynamicObject bill) {
        ArrayList<String> list = new ArrayList<>();
        DynamicObject masterOrg = BusinessDataServiceHelper.loadSingle(100000l, "bos_org");
        DynamicObjectCollection assignColl = bill.getDynamicObjectCollection("yem_merchantapply_a");
        for (DynamicObject assObj : assignColl) {
            DynamicObject useOrg = BusinessDataServiceHelper.loadSingle(
                    assObj.getDynamicObject("yem_assignorg").get("id"),
                    assObj.getDynamicObject("yem_assignorg").getDataEntityType().getName()).getDynamicObject("org");
            //assObj.getBoolean("yem_isassign") &&
            if (!assObj.getBoolean("yem_isassigneas")) {
                list.add(useOrg.getString("number"));
            }
        }
        String xml = "<AssignData>" +
                "   <AssignHead>" +
                "       <sourceCU>" + masterOrg.getString("number") + "</sourceCU>" +
                "       <dataNumber>" + bill.getString("yem_easnumber") + "</dataNumber>" +
                "   </AssignHead>" +
                "   <AssignCUS>";
        for (String s : list) {
            xml = xml + "        <AssignCU>" +
                    "             <cuNumber> " + s + "</cuNumber>" +
                    "        </AssignCU>";
        }
        xml = xml + "   </AssignCUS>" +
                "</AssignData>";
        String s = RequestEAS.assignCustomer(xml);
        JSONObject json = XML.toJSONObject(s);
        int retstatus = json.getJSONObject("Result").getInt("retstatus");
        if (retstatus == 0) {
            for (DynamicObject assignObj : assignColl) {
                assignObj.set("yem_isassigneas", true);
            }
            SaveServiceHelper.update(new DynamicObject[]{bill});
        }
    }

    /**
     * 同步财务信息
     *
     * @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;
    }

}
