package com.yem.wm.syn.eas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.syn.eas.submit.utils.FilterUtils;
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.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/22
 * 付款申请单-服务插件-提交同步EAS
 */
public class PayapplyService extends AbstractOperationServicePlugIn {
    private final static String TYPE = "10000";
    private final static Log log = LogFactory.getLog(PayapplyService.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("org");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("creator");
        fieldKeys.add("yem_appdepartment");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_amount");
        fieldKeys.add("yem_approvalamount");
        fieldKeys.add("yem_fktype");
        fieldKeys.add("yem_expensetype");
        fieldKeys.add("yem_plantype");
        fieldKeys.add("yem_applycause");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_applaydetail");
        fieldKeys.add("yem_e_asstacttype");
        fieldKeys.add("yem_e_asstact");
        fieldKeys.add("yem_e_assacct");
        fieldKeys.add("yem_e_bebank");
        fieldKeys.add("yem_borrowcompany");
        fieldKeys.add("yem_appdepartment");
        fieldKeys.add("yem_e_settlementtype");
        fieldKeys.add("yem_e_applyamount");
        fieldKeys.add("yem_auditamountloc");
        fieldKeys.add("yem_e_remark");
        fieldKeys.add("yem_iseas");
        fieldKeys.add("yem_financialorg");
        fieldKeys.add("yem_synfalt");
        fieldKeys.add("yem_account");
        fieldKeys.add("yem_applyorg");
        fieldKeys.add("yem_synceas");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        List<ExtendedDataEntity> selectedRows = e.getSelectedRows();

        List<ExtendedDataEntity> sync = new ArrayList<>();
        for (ExtendedDataEntity selectedRow : selectedRows) {
            if ("A".equals(selectedRow.getDataEntity().getString("yem_synceas"))) {
                sync.add(selectedRow);
            }
        }

        if (!sync.isEmpty()) {
            JSONArray jsonArray = getJSON(sync);
            String operationKey = e.getOperationKey();
            List<ExtendedDataEntity> list = setData(sync, jsonArray, TYPE, operationKey);
        }
        //获取通过对象

//        e.getSelectedRows().clear();
//        if (list.size() == 0) {
//            e.setCancel(true);
//        } else {
//            e.getSelectedRows().addAll(list);
//        }

    }


   /* @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        JSONArray jsonArray = getJSON(dataEntities);
        DynamicObject[] data = setData(dataEntities, jsonArray, TYPE);
        //获取通过对象
        e.setDataEntities(data);
    }*/

    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 org = dataEntitie.getDynamicObject("yem_financialorg");
            if (org != null) {
                json.put("currentCompany", setJson("number", org.getString("number")));
                json.put("CU", setJson("number", org.getString("number")));
            }
            //公司
            DynamicObject yem_applyorg = dataEntitie.getDynamicObject("yem_applyorg");
            if (yem_applyorg != null) {
                json.put("CU", setJson("number", yem_applyorg.getString("number")));
            }

            //单据状态a
            json.put("BillStatus", 1);

            //单据日期
            SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat fmtTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String yemBizdate = fmtDate.format(dataEntitie.getDate("yem_bizdate"));
            json.put("bizDate", yemBizdate);
            //申请人  creator
            DynamicObject creators = dataEntitie.getDynamicObject("creator");
            if (creators != null) {
                json.put("applyer", setJson("number", FilterUtils.getUserNumber(creators.getString("number"))));
                //借款人
                json.put("borrowPerson", setJson("number", FilterUtils.getUserNumber(creators.getString("number"))));
                //创建者
                json.put("creator", setJson("number", FilterUtils.getUserNumber(creators.getString("number"))));
            }
            // 部门
            DynamicObject appdepartment = dataEntitie.getDynamicObject("yem_appdepartment");
            if (appdepartment != null) {
                json.put("department", setJson("number", appdepartment.getString("number")));
            }

            // 币别
            DynamicObject currency = dataEntitie.getDynamicObject("yem_currency");
            if (currency != null) {
//                json.put("currency", setJson("number", currency.getString("number")));
                //end by zhouc  2024-03-13
                json.put("currency",setJson("number",currency.getString("description")));
            }
            //汇率
            json.put("exchange_rate", dataEntitie.getBigDecimal("yem_exrate"));

            // 申请金额
            json.put("requestAmount", dataEntitie.getBigDecimal("yem_amount"));
            //审批金额
            json.put("auditAmount", dataEntitie.getBigDecimal("yem_approvalamount"));
            //付款类型
            json.put("FKType", dataEntitie.getString("yem_fktype"));
            //费用类型
            json.put("expenseType", dataEntitie.getString("yem_expensetype"));
            //计划内外情况
            json.put("planType", dataEntitie.getString("yem_plantype"));
            //请款事由
            json.put("requestReason", dataEntitie.getString("yem_applycause"));

            //创建日期
            String createtime = fmtTime.format(dataEntitie.getDate("createtime"));
            json.put("createTime", createtime);

            //明细信息分录
            //商品明细
            DynamicObjectCollection yem_applaydetailcoll = dataEntitie.getDynamicObjectCollection("yem_applaydetail");
            JSONArray entry = getEntry(yem_applaydetailcoll, dataEntitie);
            json.put("entrys", entry);
            jsonArray.add(json);
            log.debug(dataEntitie.getString("billno") + "配件询价单同步EASjson" + jsonArray.toJSONString());

        }

        return jsonArray;
    }

    private JSONArray getEntry(DynamicObjectCollection yem_applaydetailcoll, DynamicObject dataEntitie) {
        JSONArray jsonArray = new JSONArray();

        for (DynamicObject applaydetail : yem_applaydetailcoll) {
            JSONObject json = new JSONObject();
            //往来户类型
            String name = applaydetail.getString("yem_e_asstacttype");
            if (name != null) {
                //往来户
                DynamicObject yemEAsstact = applaydetail.getDynamicObject("yem_e_asstact");
                //供应商
                if ("bd_supplier".equals(name)) {
                    json.put("payeeType", 1);
                    //往来户编码
                    json.put("payeeID", yemEAsstact.getString("number"));
                    json.put("payee", yemEAsstact.getString("name"));
                } else if ("bd_customer".equals(name)) { //客户
                    json.put("payeeType", 2);
                    json.put("payeeID", yemEAsstact.getString("number"));
                    json.put("payee", yemEAsstact.getString("name"));
                } else if ("bos_user".equals(name)) { //其他
                    json.put("payeeType", 3);
                    json.put("payee", yemEAsstact.getString("name"));
                }
            }
            //收款账户
            json.put("payeeAccountBank", applaydetail.getString("yem_account"));
            //收款银行
            DynamicObject yemEBebank = applaydetail.getDynamicObject("yem_e_bebank");
            if (yemEBebank != null) {
                json.put("payeeBank", yemEBebank.getString("name"));
            }
            //借款单位
            DynamicObject borrowcompany = applaydetail.getDynamicObject("yem_borrowcompany");
            if (borrowcompany != null) {
                json.put("borrowCompany", setJson("number", borrowcompany.getString("number")));
            }

            //借款部门
            DynamicObject yem_appdepartment = dataEntitie.getDynamicObject("yem_appdepartment");
            if (yem_appdepartment != null) {
                json.put("jkdepartment", setJson("number", yem_appdepartment.getString("number")));
            }
            //结算方式
            DynamicObject yem_e_settlementtype = applaydetail.getDynamicObject("yem_e_settlementtype");
            if (yem_e_settlementtype != null) {
                json.put("banlanceType", setJson("number", yem_e_settlementtype.getString("number")));
            }

            //申请付款金额
            json.put("reqPayAmount", applaydetail.getBigDecimal("yem_e_applyamount"));
            //未付款金额
            json.put("unpayAmount", applaydetail.getBigDecimal("yem_e_applyamount"));
            //本次实际付款金额
            json.put("realPayAmount", applaydetail.getBigDecimal("yem_e_applyamount"));
            //未还款金额
            json.put("unbackAmount", applaydetail.getBigDecimal("yem_e_applyamount"));
            //申请付款金额本位币
            json.put("auditAmountLoc", applaydetail.getBigDecimal("yem_auditamountloc"));
            //备注
            json.put("remark", applaydetail.getString("yem_e_remark"));

            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.getService(json.toJSONString(), type);
        } catch (Exception e) {
            log.error("同步EAS异常,请联系管理员" + e.getMessage());
            String msgE = "同步EAS异常,请联系管理员" + e.getMessage();
            for (ExtendedDataEntity selectedRow : selectedRows) {
                DynamicObject data = selectedRow.getDataEntity();
                data.set("yem_synfalt", "同步失败,失败原因:" + e.getMessage());
                SaveServiceHelper.update(data);
                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_payapply", new QFilter[]{new QFilter("billno", QCP.equals, number)});
                dynamicObject.set("yem_synfalt", "同步失败,失败原因:" + s);
                SaveServiceHelper.update(dynamicObject);
                addErrorInfo(msgE, dynamicObject.getPkValue());
            }
            if (list.size() == 0) {
                String msgE = "同步EAS失败:" + msg;
                for (ExtendedDataEntity selectedRow : selectedRows) {
                    DynamicObject data = selectedRow.getDataEntity();
                    data.set("yem_synfalt", "同步失败,失败原因:" + msg);
                    SaveServiceHelper.update(data);
                    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, String operationKey) {
        List<String> list = setWebService(jsonArray, selectedRows, type);
        List<ExtendedDataEntity> arrayList = new ArrayList<>();
        for (ExtendedDataEntity selectedRow : selectedRows) {
            DynamicObject dataEntitie = selectedRow.getDataEntity();
            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());
        }

        List<ExtendedDataEntity> arrayLists = new ArrayList<>();
//        if ("syn_eas".equals(operationKey)){
        for (ExtendedDataEntity selectedRow : arrayList) {
            DynamicObject dataEntity = selectedRow.getDataEntity();
            dataEntity.set("yem_iseas", true);
            dataEntity.set("yem_synfalt", "同步成功");
            SaveServiceHelper.update(dataEntity);
            arrayLists.add(selectedRow);
        }
//        }else{
//            for (ExtendedDataEntity selectedRow:arrayList) {
//                DynamicObject dataEntity = selectedRow.getDataEntity();
//                dataEntity.set("yem_iseas",true);
//                dataEntity.set("yem_synfalt","同步成功");
//                SaveServiceHelper.update(dataEntity);
//                arrayLists.add(selectedRow);
//            }
//        }
        return arrayLists;
    }

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


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

    }
}
