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.syn.eas.YemTransferorderService;
import com.yem.wm.utils.RequestEAS;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.operate.result.OperateErrorInfo;
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.exception.KDBizException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.operation.SaveServiceHelper;

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

/**
 * @author 涛
 * @date 2023/11/07
 * 调拨订单反审核插件
 */
public class YemTransferorderUnAudit extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(YemTransferorderUnAudit.class);

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

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();

        if ("unsyneas".equals(operationKey)){
            List<ExtendedDataEntity> selectedRows = e.getSelectedRows();

            ArrayList<ExtendedDataEntity> arrayList = new ArrayList<>();
            for (ExtendedDataEntity selectedRow: selectedRows) {
                DynamicObject dataEntitie = selectedRow.getDataEntity();
                boolean yemIseas = dataEntitie.getBoolean("yem_iseas");
                if (!yemIseas){
                    arrayList.add(selectedRow);
                    continue;
                }
                JSONArray array = new JSONArray();
                JSONObject jsonObject = new JSONObject();
                String billno = dataEntitie.getString("billno");
                jsonObject.put("number",billno);
                DynamicObject yem_supfinorg = dataEntitie.getDynamicObject("yem_supfinorg");
                jsonObject.put("issueCompanyOrgUnit",setJson("number",yem_supfinorg.getString("number")));
                array.add(jsonObject);
                try{
                    String s = setWebService(array, dataEntitie);
                    if (s.length()>0){
                        this.operationResult.addErrorInfo(
                                new ValidationErrorInfo(
                                        "",dataEntitie.getPkValue(), 0,0,"err","反审核",dataEntitie.getString("billno")+"反审核失败:"+s, ErrorLevel.Error));
                    }else {
                        dataEntitie.set("yem_iseas",false);
                        dataEntitie.set("yem_synfalt",null);
                        SaveServiceHelper.update(dataEntitie);
                        arrayList.add(selectedRow);
                    }
                }catch (Exception ex){
                    log.error("反审核EAS异常请联系管理员:"+ex.getMessage());
                    dataEntitie.set("yem_synfalt",ex.getMessage());
                    SaveServiceHelper.update(dataEntitie);
                    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);
            }

        }
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);


    }


    private String setWebService(JSONArray json, DynamicObject dataEntitie){
        String service = RequestEAS.getServiceUnAudit(json.toJSONString(), "004");
        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");
            for (Object billError: billErrors) {
                JSONObject js = (JSONObject) billError;
                JSONArray errorMsg = js.getJSONArray("errorMsgs");
                errorMsgs = errorMsg.getString(0);
            }
            if (msg!=null){
                errorMsgs = msg + 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;
    }
}
