package com.yem.wm.syn.cmmp.delete;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.syn.cmmp.addnew.OrderProReqBillCG;
import com.yem.wm.syn.utils.HttpClient;
import com.yem.wm.utils.RequestCmmp;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
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 涛
 * @date 2023/12/07
 * 订单产品需求单反审核删除CMMP
 */
public class OrderProReqBillDelCMMP  extends AbstractOperationServicePlugIn {


    private final static Log log = LogFactory.getLog(OrderProReqBillDelCMMP.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_billtype");
        fieldKeys.add("yem_isvmi");
        fieldKeys.add("yem_iscmmppj");
        fieldKeys.add("yem_iscmmp");
        fieldKeys.add("yem_iscmmpapply");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_calloutorg");
        fieldKeys.add("yem_depcode");
        fieldKeys.add("yem_billstatusfield");
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
        ArrayList<DynamicObject> arrayList = new ArrayList<DynamicObject>();
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntity: dataEntities) {
            String billno = dataEntity.getString("billno");
            JSONObject json = new JSONObject();
            //申请单号
            json.put("apply_code",billno);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("bill",json);
            //单据类型
            DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");
            String billTypeNum = yemBilltype.getString("number");
            //仓库类型
            String yemIsvmi = dataEntity.getString("yem_isvmi");
            String yemBillstatusfield = dataEntity.getString("yem_billstatusfield");
            if ("B".equals(yemBillstatusfield)){
                return;
            }
            //如果是配件采购计划 删除CMMP采购申请
            if ("yem_orderproreqbill_CG".equals(billTypeNum)){
                boolean yemIscmmppj = dataEntity.getBoolean("yem_iscmmppj");
                if (yemIscmmppj) {
                    json.put("need_code",billno);
                    json.remove("apply_code");
                    jsonObject.put("bill",json);
                    arrayList = setData(dataEntity, jsonObject, "purNeed", "yem_iscmmppj");
                }
            } //如果是配件调拨计划 并且 类型为正常仓库 删除CMMP  调拨申请单 dbApply
            else if ("yem_orderproreqbill_DB".equals(billTypeNum)&&"C".equals(yemIsvmi)) {
                boolean yem_iscmmp = dataEntity.getBoolean("yem_iscmmp");
                if (yem_iscmmp) {
                    arrayList = setData(dataEntity, jsonObject, "dbApply", "yem_iscmmp");
                }
            }//如果单据类型等于配件调拨计划 并且 仓库类型为VMI 删除CMMP 其他领料申请outApply
            else if ("yem_orderproreqbill_DB".equals(billTypeNum)&&"V".equals(yemIsvmi)) {
                boolean yem_iscmmpapply = dataEntity.getBoolean("yem_iscmmpapply");
                if (yem_iscmmpapply) {
                    arrayList = setData(dataEntity, jsonObject, "outApply", "yem_iscmmpapply");
                }
            }
        }
        if (arrayList.size()==0) return;
        DynamicObject[] dynamicObjects = setDataFilter(dataEntities, arrayList);
        e.setDataEntities(dynamicObjects);
    }



    private ArrayList<DynamicObject> setData(DynamicObject dataEntity, JSONObject jsonObject,String billType,String cmmp){
        ArrayList<DynamicObject> list = new ArrayList<>();
        //产品类型
        DynamicObject yem_bd_products = dataEntity.getDynamicObject("yem_bd_products");
        Long productsId = RequestCmmp.getTopCplx(yem_bd_products);
        DynamicObject cmmpconfig = QueryServiceHelper.queryOne("yem_cmmpconfig", "yem_ip,yem_port,yem_num",
                new QFilter[]{new QFilter("yem_cmmpconfigentry.yem_bd_productsgroupn.id", QCP.equals, productsId)});

        if (cmmpconfig == null){
            this.operationResult.addErrorInfo(new ValidationErrorInfo("",dataEntity.getPkValue(), 0,0,"err","同步CMMP",dataEntity.getString("billno")+"同步CMMP失败:未找到产品类型为"+yem_bd_products.getString("name")+"的CMMP配置,请联系管理员确认!", ErrorLevel.Error));
            return list;
        }
        String database = cmmpconfig.getString("yem_num");
        String ip = cmmpconfig.getString("yem_ip");
        String port = cmmpconfig.getString("yem_port");
        try {
            String url = "http://"+ip+":"+port+"/gateway/cosmic/cmmp/"+billType+"/rm/"+database;
            String data = HttpClient.post(url,jsonObject.toJSONString());
            JSONObject json = JSON.parseObject(data);
            String status = json.getString("status");
            if (!"0".equals(status)){
                String billErrors = json.getString("billErrors");
                String msg = json.getString("msg");
                if (StringUtils.isNotBlank(billErrors)){
                    msg = msg + billErrors;
                }
                list.add(dataEntity);
                this.operationResult.addErrorInfo(new ValidationErrorInfo("",dataEntity.getPkValue(), 0,0,"err","删除CMMP",dataEntity.getString("billno")+"删除CMMP失败:"+msg, ErrorLevel.Error));
                return list;
            }
            dataEntity.set(cmmp,false);
            SaveServiceHelper.update(dataEntity);

        }catch (Exception e){
            list.add(dataEntity);
            this.operationResult.addErrorInfo(new ValidationErrorInfo("",dataEntity.getPkValue(), 0,0,"err","删除CMMP",dataEntity.getString("billno")+"删除CMMP失败:"+e.getMessage(), ErrorLevel.Error));
        }
        return list;
    }


    /**
     *
     * @param datas 实体
     * @param list
     * @return 过滤同步失败的数据
     */
    private DynamicObject[] setDataFilter(DynamicObject[] datas, ArrayList<DynamicObject> list){

        List<DynamicObject> arrayList = new ArrayList<>();
        for (DynamicObject dataEntitie: datas) {
            arrayList.add(dataEntitie);
        }

        for (DynamicObject dataEntity: list) {
            String billno = dataEntity.getString("billno");
            Predicate<DynamicObject> predicate = dynamicObject -> !StringUtils.equals(dynamicObject.getString("billno"),billno);
            arrayList = arrayList.stream().filter(predicate).collect(Collectors.toList());
        }
        DynamicObject[] data = new DynamicObject[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            data[i] = arrayList.get(i);
        }
        return data;
    }

}
