package com.yem.wm.syn.eas.delivernotice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.RequestEAS;
import kd.bos.dataentity.entity.DynamicObject;
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.logging.Log;
import kd.bos.logging.LogFactory;
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.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author zhouc
 * @date 2024/4/15 15:21
 * @className DelivernoticeUnSynEAS
 * @description 销售出库单反审核删除其他领料申请单
 */
public class DelivernoticeUnSynEAS extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(DelivernoticeUnSynEAS.class);

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            String yem_billtype = dataEntitie.getString("yem_billtype.number");
            boolean yemIseas = dataEntitie.getBoolean("yem_iseas");
            if (yem_billtype.equals("yem_es_delivernotice_o") && yemIseas) {
                JSONArray jsonArray = getJSON(dataEntitie);
                if (jsonArray.size() == 0) {
                    return;
                }
                List<String> list = setWebService(dataEntitie, jsonArray, "10004");
                if (list.size() > 0) {
                    JSONObject jsonObject = JSON.parseObject(list.get(0));
                    String status = jsonObject.getString("status");
                    String msg = jsonObject.getString("msg");
                    if (!"0".equals(status)) {
                        JSONArray billErrors = jsonObject.getJSONArray("billErrors");
                        for (Object billError : billErrors) {
                            JSONObject js = (JSONObject) billError;
                            String number = js.getString("number");
                            list.add(number);
                            JSONArray errorMsgs = js.getJSONArray("errorMsgs");
                            StringBuilder s = new StringBuilder();
                            for (Object errorMsg : errorMsgs) {
                                s.append(errorMsg + ";");
                            }
                            String msgE = number + "删除EAS失败:" + s;
                            DynamicObject dynamicObject =
                                    BusinessDataServiceHelper.loadSingle("yem_es_delivernotice", new QFilter[]{new QFilter("billno", QCP.equals, number)});

                            addErrorInfo(msgE, dynamicObject.getPkValue());
                            e.setCancel(true);
                        }
                    } else {
                        dataEntitie.set("yem_iseas", false);
                        dataEntitie.set("yem_synfalt", null);
                        SaveServiceHelper.update(dataEntitie);
                    }
                }
            }
        }
    }

    private JSONArray getJSON(DynamicObject dataEntitie) {
        JSONArray jsonArray = new JSONArray();
        dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
        JSONObject json = new JSONObject();
        //单据编号
        json.put("number", dataEntitie.getString("billno"));
        //供应方库存组织
        //2024-08-08传库存组织改为传发货组织
        DynamicObject yem_reqstorageorgunit = dataEntitie.getDynamicObject("yem_deliverorg");
        if (yem_reqstorageorgunit != null) {
            json.put("ReqStorageOrgUnit", setJson("number", yem_reqstorageorgunit.getString("number")));
        }
        jsonArray.add(json);
        log.debug(dataEntitie.getString("billno") + "销售出库单删除EAS" + jsonArray.toJSONString());
        return jsonArray;
    }


    private List setWebService(DynamicObject dataEntitie, JSONArray json, String type) {
        String service = null;
        ArrayList<String> list = new ArrayList<>();
        try {
            service = RequestEAS.getServiceUnAudit(json.toJSONString(), type);
        } catch (Exception e) {
            log.error("删除EAS异常,请联系管理员" + e.getMessage());
            String msgE = "删除EAS异常,请联系管理员" + e.getMessage();
            addErrorInfo(msgE, dataEntitie.getPkValue());
            return list;
        }

        JSONObject jsonObject = JSON.parseObject(service);
        list.add(jsonObject.toString());
        return list;
    }


    private JSONObject setJson(String key, String value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject;
    }

    private void addErrorInfo(String message, Object pk) {
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(pk, "yem_es_delivernotice");
        if (dynamicObject != null) {
            dynamicObject.set("yem_synfalt", message);
            SaveServiceHelper.update(dynamicObject);
        }
        this.operationResult.addErrorInfo(
                new ValidationErrorInfo(
                        "", pk, 0, 0, "err", "删除EAS失败", message, ErrorLevel.Error));

    }
}
