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

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.operate.result.IOperateInfo;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import org.json.JSONObject;
import org.json.XML;

import java.text.SimpleDateFormat;
import java.util.*;

public class MerChantApplyAuditOp extends AbstractOperationServicePlugIn implements Plugin {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> keys = e.getFieldKeys();
        keys.add("yem_merchantstnames");
        keys.add("yem_simplename");
        keys.add("yem_simplepinyin");
        keys.add("yem_bizfunction");
        keys.add("yem_group");
        keys.add("yem_type");
        keys.add("yem_country");
        keys.add("*");
        keys.add("yem_societycreditcode");
        keys.add("yem_tx_register_no");
        keys.add("yem_duns");
        keys.add("yem_artificialperson");
        keys.add("yem_curegcapital");//注册资本币种
        keys.add("yem_regcapital");//注册资本
        keys.add("yem_businessterm");//营业期限
        keys.add("yem_businessscope");//经营范围
        keys.add("yem_linkman");//联系人
        keys.add("yem_bizpartner_phone");//联系电话
        keys.add("yem_bizpartner_fax");//传真
        keys.add("yem_postal_code");//电子邮箱
        keys.add("yem_url");//公司网址
        keys.add("yem_admindivision");//行政区划
        keys.add("yem_bizpartner_address");//详细地址
        keys.add("yem_idno");//身份证号
        keys.add("yem_bankinfor.yem_bankaccount");//银行账号
        keys.add("yem_bankinfor.yem_accountname");//账户名称
        keys.add("yem_bankinfor.yem_iban");//国际银行账户号码
        keys.add("yem_bankinfor.yem_bank");//开户银行
        keys.add("yem_bankinfor.yem_swfitcode");//账户名称
        keys.add("yem_bankinfor.yem_currency");//币别
        keys.add("yem_bankinfor.yem_isdefault_bank");//默认
        keys.add("yem_merchantapply_e.yem_standardid");
        keys.add("yem_merchantapply_e.yem_groupid");
        keys.add("yem_easnumber");
        keys.add("yem_merchantstnames_en");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        //获取按钮
        String key = e.getOperationKey();
        //定义通过校验实体
        List<ExtendedDataEntity> passDataEntitys = new ArrayList<>();
        if (key.equals("audit")) {
            for (ExtendedDataEntity dataEntity : e.getSelectedRows()) {
                DynamicObject billObj = dataEntity.getDataEntity();
                //TODO
                DynamicObject[] load = BusinessDataServiceHelper.load("bd_customer", "id",
                        new QFilter[]{new QFilter("number", QCP.equals, billObj.get("billno"))});
                for (DynamicObject dynamicObject : load) {
                    dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.get("id"), "bd_customer");
                    OperationResult result = OperationServiceHelper.executeOperate("delete", "bd_customer",
                            new DynamicObject[]{dynamicObject}, OperateOption.create());
                    System.out.println(result);
                }
                //TODO
                billObj = BusinessDataServiceHelper.loadSingle(billObj.get("id"), billObj.getDynamicObjectType());
                MainEntityType entityType = EntityMetadataCache.getDataEntityType("bd_customer");
                DynamicObject customerObj = new DynamicObject(entityType);
                customerObj.set("name", billObj.get("yem_merchantstnames"));//名称

                customerObj.set("ctrlstrategy", "2");//管控策略默认自由分配

                customerObj.set("status", "A");//状态
                customerObj.set("enable", "1");//状态

                customerObj.set("simplename", billObj.get("yem_simplename"));//简称
                customerObj.set("simplepinyin", billObj.get("yem_simplepinyin"));//简拼
                customerObj.set("bizfunction", billObj.get("yem_bizfunction"));//业务职能
                customerObj.set("group", billObj.get("yem_group"));//客户分组
                customerObj.set("type", billObj.get("yem_type"));//伙伴类型
                customerObj.set("createorg", BusinessDataServiceHelper.loadSingle(100000l, "bos_org"));//TODO 创建组织默认根组织
                customerObj.set("country", billObj.get("yem_country"));//国家地区
                customerObj.set("societycreditcode", billObj.get("yem_societycreditcode"));//统一社会信用代码
                customerObj.set("tx_register_no", billObj.get("yem_tx_register_no"));//纳税人识别号
                customerObj.set("duns", billObj.get("yem_duns"));//邓白氏编码
                customerObj.set("artificialperson", billObj.get("yem_artificialperson"));//法人代表
                customerObj.set("curegcapital", billObj.get("yem_curegcapital"));//注册资本币种
                customerObj.set("regcapital", billObj.get("yem_regcapital"));//注册资本
                customerObj.set("businessterm", billObj.get("yem_businessterm"));//营业期限
                customerObj.set("businessscope", billObj.get("yem_businessscope"));//经营范围
                customerObj.set("linkman", billObj.get("yem_linkman"));//联系人
                customerObj.set("bizpartner_phone", billObj.get("yem_bizpartner_phone"));//联系电话
                customerObj.set("bizpartner_fax", billObj.get("yem_bizpartner_fax"));//传真
                customerObj.set("postal_code", billObj.get("yem_postal_code"));//电子邮箱
                customerObj.set("url", billObj.get("yem_url"));//公司网址
                customerObj.set("admindivision", billObj.get("yem_admindivision"));//行政区划
                customerObj.set("bizpartner_address", billObj.get("yem_bizpartner_address"));//详细地址
                customerObj.set("idno", billObj.get("yem_idno"));//身份证号
                customerObj.set("yem_mfzcsh", billObj.getLong("yem_mfzcsh"));//买方信保注册登记号/税号
                customerObj.set("yem_creditinsurance", billObj.get("yem_creditinsurance"));//信保通客户名称
                customerObj.set("yem_customer", billObj.get("yem_customer"));//信保通买方代码
                customerObj.set("yem_payoutratio", billObj.get("yem_payoutratio"));//赔付比例
                customerObj.set("yem_merchantapplyid", billObj.getLong("id"));//客户准入ID
                DynamicObjectCollection bankinfors = billObj.getDynamicObjectCollection("yem_bankinfor");
                DynamicObjectCollection cusbankColl = customerObj.getDynamicObjectCollection("entry_bank");
                for (DynamicObject bankinfor : bankinfors) {
                    //银行账号信息组装
                    DynamicObject cusbankObj = cusbankColl.addNew();
                    cusbankObj.set("bankaccount", bankinfor.get("yem_bankaccount"));//银行账号
                    cusbankObj.set("accountname", bankinfor.get("yem_accountname"));//账户名称
                    cusbankObj.set("iban", bankinfor.get("yem_iban"));//国际银行账户号码
                    cusbankObj.set("bank", bankinfor.get("yem_bank"));//开户银行
                    //cusbankObj.set("",bankinfor.get("yem_swfitcode"));//账户名称
                    cusbankObj.set("currency", bankinfor.get("yem_currency"));//币别
                    cusbankObj.set("isdefault_bank", bankinfor.get("yem_isdefault_bank"));//默认
                }
                //TODO 待定
                DynamicObjectCollection groupColl = billObj.getDynamicObjectCollection("yem_merchantapply_e");
                DynamicObjectCollection cusgroupColl = customerObj.getDynamicObjectCollection("entry_groupstandard");
                boolean b = true;
                for (DynamicObject groupObj : groupColl) {
                    //分类信息组装
                    DynamicObject cusgroupObj = cusgroupColl.addNew();
                    cusgroupObj.set("standardid", groupObj.get("yem_standardid"));//分类标准
                    cusgroupObj.set("groupid", groupObj.get("yem_groupid"));//分类
                    //根据当前当前获取最新编码
//                    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管理员维护");
//                                b = false;
//                                continue;
//                            }
//                            for (int j = 0; j < i1; j++) {
//                                s1 = "0"+s1;
//                            }
//                            fnumber = groupNum+""+s1;
//                            billObj.set("yem_easnumber",fnumber);
//                            SaveServiceHelper.update(billObj);
//                        }
//                    }
                }
//                if(!b){
//                    continue;
//                }
//                customerObj.set("number",billObj.get("yem_easnumber"));//编码
                customerObj.set("number", billObj.get("yem_erpnumber"));//编码
                OperationResult result = OperationServiceHelper.executeOperate("save",
                        "bd_customer", new DynamicObject[]{customerObj}, OperateOption.create());
                if (result.isSuccess()) {
                    result = OperationServiceHelper.executeOperate("submit",
                            "bd_customer", new DynamicObject[]{customerObj}, OperateOption.create());
                    if (!result.isSuccess()) {
                        throw new KDBizException(String.format("生成的客户 [ %s ] 提交失败，原因：%s", billObj.get("yem_erpnumber"), result.getMessage()));
                    }
                    result = OperationServiceHelper.executeOperate("audit",
                            "bd_customer", new DynamicObject[]{customerObj}, OperateOption.create());
//                    System.out.println(result);
                    if (result.isSuccess()) {
                        passDataEntitys.add(dataEntity);
                        Map<Object, String> billNos = result.getBillNos();
                        Set<Map.Entry<Object, String>> entries = billNos.entrySet();
                        Map.Entry<Object, String> next = entries.iterator().next();
                        String billno = next.getValue();
                        DynamicObject dynamicObject = dataEntity.getDataEntity();

                        dynamicObject.set("yem_easnumber", billno);
                        dynamicObject.set("yem_erpnumber", billno);

                        SaveServiceHelper.update(dynamicObject);
                        //生成EAS客户 end by zhouc 禁用 2024-03-20
//                   String xml = generateXml(billObj);
//                   String retXml = RequestEAS.generateCustomer(xml);
//                    b = parseXml(retXml,dataEntity);
//                    if(!b){
//                        addErrMessage(operationResult,dataEntity,"生成EAS客户错误！");
//                        continue;
//                    }
//                    String xml1 = xml.toString().replaceAll("op=\"4\">\n", "op=\"1\">\n");
//                    RequestEAS.generateCustomer(xml1);
                    } else {
                        addErrMessage(result, dataEntity, result.getMessage());
                    }
                } else {
                    StringBuilder errInfos = new StringBuilder();
                    List<IOperateInfo> allErrorOrValidateInfo = result.getAllErrorOrValidateInfo();
                    String message = result.getMessage();
                    for (int i = 0; i < allErrorOrValidateInfo.size(); i++) {
                        IOperateInfo iOperateInfo = allErrorOrValidateInfo.get(i);
                        errInfos.append(iOperateInfo.getMessage()).append("\r\n");
                    }
                    throw new KDBizException("生成ERP客户【保存】报错：" + message + ":\n" + errInfos.toString());
                }
            }
        }
        e.getSelectedRows().clear();
        if (passDataEntitys.isEmpty()) {
            e.cancel = true;     // 没有单据通过了校验，取消后续操作
        } else {
            e.getSelectedRows().addAll(passDataEntitys);
        }
    }

    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);
            return false;
        }
        return true;
    }

    private String generateXml(DynamicObject billObj) {
        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>" + billObj.getString("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");
        return xml.toString();
    }

    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);
    }
}
