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

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.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
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.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 涛
 * @date 2023/11/08
 * 发货通知单反审核插件
 */
public class YemEsDelivernoticeUnAudit extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(YemEsDelivernoticeUnAudit.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_org");
        fieldKeys.add("yem_synfalt");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        if ("unaudit".equals(operationKey)) {
//            List<ExtendedDataEntity> selectedRows = e.getSelectedRows();
//            ArrayList<ExtendedDataEntity> arrayList = new ArrayList<>();
            for (DynamicObject selectedRow : dataEntities) {
//                    DynamicObject dataEntitie = selectedRow.getDataEntity();
                DynamicObject dataEntitie = BusinessDataServiceHelper.loadSingle(selectedRow.getPkValue(), selectedRow.getDynamicObjectType().getName());
                DynamicObject yem_billtype = dataEntitie.getDynamicObject("yem_billtype");
                if (yem_billtype != null) {
                    String number = yem_billtype.getString("number");
                    if (number.equals("yem_es_delivernotice_zj") || number.equals("yem_es_delivernotice_pj")) {
                        JSONObject jsonObject = new JSONObject();
                        JSONArray array = new JSONArray();
                        String billno = dataEntitie.getString("billno");
                        jsonObject.put("number", billno);
                        DynamicObject yem_org = dataEntitie.getDynamicObject("yem_org");
                        jsonObject.put("storageOrgUnit", setJson("number", yem_org.getString("number")));
                        array.add(jsonObject);
                        try {
                            String s = setWebService(array, dataEntitie);
                            if (s.length() > 0) {
                                dataEntitie.set("yem_synfalt", s);
                                SaveServiceHelper.update(dataEntitie);
                                this.operationResult.addErrorInfo(
                                        new ValidationErrorInfo(
                                                "", dataEntitie.getPkValue(), 0, 0, "err", "反审核", dataEntitie.getString("billno") + "反审核失败:" + s, ErrorLevel.Error));
                                e.setCancel(true);
                            } else {
//                                    arrayList.add(selectedRow);
                                dataEntitie.set("yem_iseas", false);
                                dataEntitie.set("yem_synfalt", null);
                                dataEntitie.set("yem_synfalt_tag", null);
                                SaveServiceHelper.update(dataEntitie);
                            }
                        } catch (Exception ex) {
                            log.error("反审核EAS异常请联系管理员:" + ex.getMessage());
                            this.operationResult.addErrorInfo(
                                    new ValidationErrorInfo(
                                            "", dataEntitie.getPkValue(), 0, 0, "err", "反审核", dataEntitie.getString("billno") + "反审核EAS异常请联系管理员", ErrorLevel.Error));
                            continue;
                        }
//                            //获取通过对象
//                            e.getSelectedRows().clear();
//                            if (arrayList.size() == 0) {
//                                e.setCancel(true);
//                            } else {
//                                e.getSelectedRows().addAll(arrayList);
//                            }
                    }
                }
            }

        }
    }


    private String setWebService(JSONArray json, DynamicObject dataEntitie) {
        String service = RequestEAS.getServiceUnAudit(json.toJSONString(), "007");
        JSONObject jsonObject = JSON.parseObject(service);
        String status = jsonObject.getString("status");
        String msg = jsonObject.getString("msg");
        String errorMsgs = "";
        if (!"0".equals(status)) {
            JSONArray billErrors = jsonObject.getJSONArray("billErrors");
            int i = 1;
            for (Object billError : billErrors) {
                JSONObject js = (JSONObject) billError;
                JSONArray errorMsg = js.getJSONArray("errorMsgs");
                if (errorMsgs.length() > 0) {
                    errorMsgs = errorMsgs + "\n" + i + "、" + errorMsg.getString(0);
                } else {
                    errorMsgs = i + "、" + errorMsg.getString(0);
                }
                i++;
            }
            if (msg != null) {
                errorMsgs = msg + "\n" + errorMsgs;
            }

            //throw new KDBizException(dataEntitie.getString("billno")+errorMsgs);
        }

        return errorMsgs;
    }

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