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.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author 涛
 * @date 2023/11/30
 * 礼品领用申请单-服务插件-反审核后删除EAS
 */
public class ImGiftApplyUnAudit extends AbstractOperationServicePlugIn {
    private final static String TYPE = "10004";
    private final static Log log = LogFactory.getLog(ImGiftApplyUnAudit.class);
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_billtype");
        fieldKeys.add("org");
        fieldKeys.add("yem_proposer");
        fieldKeys.add("yem_department");
        fieldKeys.add("yem_generalasstacttype");
        fieldKeys.add("yem_provideunit");
        fieldKeys.add("yem_isacross");
        fieldKeys.add("yem_costitem");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_im_entryentity");
        fieldKeys.add("yem_materialnum");
        fieldKeys.add("yem_qty");
        fieldKeys.add("yem_iseas");
        fieldKeys.add("yem_reqstorageorgunit");
        fieldKeys.add("yem_synfalt");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        List<ExtendedDataEntity> selectedRows = e.getSelectedRows();
        //过滤单据类型
        List<ExtendedDataEntity> datas = isbillType(selectedRows);
        if (datas.size()==0){
            return;
        }
        JSONArray jsonArray = getJSON(datas);
        if (jsonArray.size()==0) {
            return;
        }
        List<ExtendedDataEntity> data = setData(datas, jsonArray, TYPE);
        List<ExtendedDataEntity> noBillType = isNoBillType(selectedRows);

        for (ExtendedDataEntity dataEntity: data) {
            DynamicObject dynamicObject = dataEntity.getDataEntity();
            dynamicObject.set("yem_iseas",false);
            dynamicObject.set("yem_synfalt",null);
            SaveServiceHelper.update(dynamicObject);
        }
        data.addAll(noBillType);
        //获取通过对象
        e.getSelectedRows().clear();
        if (data.size()==0){
            e.setCancel(true);
        }else {
            e.getSelectedRows().addAll(data);
        }
    }
    private DynamicObject[] setEntite(DynamicObject[] typeZJBill, DynamicObject[] data){
        DynamicObject[] dataEntites = new DynamicObject[typeZJBill.length+ data.length];
        System.arraycopy(data,0,dataEntites,0,data.length);
        System.arraycopy(typeZJBill,0,dataEntites,data.length,typeZJBill.length);
        return dataEntites;
    }

    private JSONArray getJSON(List<ExtendedDataEntity> selectedRows) {
        JSONArray jsonArray = new JSONArray();
        for (ExtendedDataEntity selectedRow: selectedRows) {
            DynamicObject dataEntitie = selectedRow.getDataEntity();
            boolean yemIseas = dataEntitie.getBoolean("yem_iseas");
            if (!yemIseas){
                continue;
            }
            JSONObject json = new JSONObject();
            //单据编号
            json.put("number",dataEntitie.getString("billno"));
            //供应方库存组织
            DynamicObject yem_reqstorageorgunit = dataEntitie.getDynamicObject("yem_reqstorageorgunit");
            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(JSONArray json, List<ExtendedDataEntity> selectedRows, 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();
            for (ExtendedDataEntity selectedRow: selectedRows) {
                DynamicObject data = selectedRow.getDataEntity();
                list.add(data.getString("billno"));
                addErrorInfo(msgE,data.getPkValue());
            }
            return list;
        }

        JSONObject jsonObject = JSON.parseObject(service);
        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_im_giftapply", new QFilter[]{new QFilter("billno", QCP.equals, number)});
                addErrorInfo(msgE,dynamicObject.getPkValue());
            }
            if (list.size()==0){
                String msgE = "删除EAS失败:"+msg;
                for (ExtendedDataEntity selectedRow: selectedRows) {
                    DynamicObject data = selectedRow.getDataEntity();
                    list.add(data.getString("billno"));
                    addErrorInfo(msgE,data.getPkValue());
                }
                return list;
            }
        }

        return list;
    }

    /**
     *
     * @param selectedRows 实体
     * @param jsonArray
     * @return 过滤同步失败的数据
     */
    private List<ExtendedDataEntity> setData(List<ExtendedDataEntity> selectedRows,JSONArray jsonArray, String type){
        List<String> list = setWebService(jsonArray,selectedRows,type);
        List<ExtendedDataEntity> arrayList = new ArrayList<>();
        for (ExtendedDataEntity selectedRow: selectedRows) {
            arrayList.add(selectedRow);
        }

        for (String number: list) {
            Predicate<ExtendedDataEntity> predicate = selectedRow -> !StringUtils.equals(selectedRow.getDataEntity().getString("billno"),number);
            arrayList = arrayList.stream().filter(predicate).collect(Collectors.toList());
        }

        return arrayList;
    }

    private List<ExtendedDataEntity> isbillType(List<ExtendedDataEntity> selectedRows){

        List<ExtendedDataEntity> list = new ArrayList<>();
        for (ExtendedDataEntity selectedRow: selectedRows) {
            DynamicObject dataEntity = selectedRow.getDataEntity();
            DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");

            //如果单据类型等于礼品领用申请单
            if ("yem_im_giftapply_LY".equals(yemBilltype.getString("number"))){
                list.add(selectedRow);
            }
        }

        return list;
    }


    private List<ExtendedDataEntity> isNoBillType(List<ExtendedDataEntity> selectedRows){


        List<ExtendedDataEntity> list = new ArrayList<>();
        for (ExtendedDataEntity selectedRow: selectedRows) {
            DynamicObject dataEntity = selectedRow.getDataEntity();
            DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");

            //如果单据类型等于礼品领用申请单
            if (!"yem_im_giftapply_LY".equals(yemBilltype.getString("number"))){
                list.add(selectedRow);
            }
        }

        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_im_giftapply");
        if (dynamicObject != null) {
            dynamicObject.set("yem_synfalt",message);
            SaveServiceHelper.update(dynamicObject);
        }
        this.operationResult.addErrorInfo(
                new ValidationErrorInfo(
                        "",pk, 0,0,"err","删除EAS失败",message, ErrorLevel.Error));

    }
}
