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.ImInQuirylistPJService;
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.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.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.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 ImInquiryListUnAudit extends AbstractOperationServicePlugIn {

    private final static String TYPE = "10001";
    private final static Log log = LogFactory.getLog(ImInquiryListUnAudit.class);
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_department");
        fieldKeys.add("yem_billtype");
        fieldKeys.add("yem_enquirymessage");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_iscaigou");
        fieldKeys.add("yem_remark");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_im_detailedinfor");
        fieldKeys.add("yem_material");
        fieldKeys.add("yem_marketre");
        fieldKeys.add("yem_classification");
        fieldKeys.add("yem_iseas");
        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);
        List<ExtendedDataEntity> data = setData(datas, jsonArray,TYPE);
        //获取整机
        List<ExtendedDataEntity> typeZJBill = isbillTypeZJ(selectedRows);
        data.addAll(typeZJBill);
        //获取通过对象
        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();
            JSONObject json = new JSONObject();
            //单据编号
            json.put("number",dataEntitie.getString("billno"));
            DynamicObject yemDepartment = dataEntitie.getDynamicObject("yem_department");
            json.put("Department",setJson("number",yemDepartment.getString("number")));
            jsonArray.add(json);
        }
        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_inquirylist", 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;
    }

    private JSONObject setJson(String key, String value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject;
    }
    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_inquirylist_PJ".equals(yemBilltype.getString("number"))){
                list.add(selectedRow);
            }
        }
        return list;
    }

    private List<ExtendedDataEntity> isbillTypeZJ(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_inquirylist_PJ".equals(yemBilltype.getString("number"))){
                list.add(selectedRow);
            }
        }
        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());
        }
        for (ExtendedDataEntity selectedRow:arrayList) {
            DynamicObject dataEntity = selectedRow.getDataEntity();
            dataEntity.set("yem_iseas",false);
            dataEntity.set("yem_synfalt",null);
            SaveServiceHelper.update(dataEntity);
        }
        return arrayList;
    }


    private void addErrorInfo(String message,Object pk){
        this.operationResult.addErrorInfo(
                new ValidationErrorInfo(
                        "",pk, 0,0,"err","同步EAS失败",message, ErrorLevel.Error));

    }


}
