package nckd.jimin.jyyy.fi.task;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.exception.KDException;
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.schedule.api.StopTask;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import nckd.base.helper.CommonHelperUtils;
import nckd.jimin.jyyy.fi.plugin.operate.SRMHelperUtils;
import java.math.BigDecimal;
import java.util.*;


/**
 * 付款状态回写srm调度任务类，同步付款状态至SRM的预付、付款申请
 * @author wanghaiwu_kd
 * @date 2025/05/15
 */
public class WriteBackPayResult2SRMTask extends AbstractTask implements StopTask {
    private static final Log logger = LogFactory.getLog(WriteBackPayResult2SRMTask.class);
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        //对公报销单回写
        writeBackPublicBill(requestContext, map);
        //预付单回写
        writeBackPrepayBill(requestContext, map);
    }

    private void writeBackPublicBill(RequestContext requestContext, Map<String, Object> map){
        String entityName = "er_publicreimbursebill";
        String pattern = "yyyy-MM-dd HH:mm:ss";

        //srm状态，1：SRM已推送；2：已退回SRM；3：已反写SRM；4：反写SRM失败
        List<String> srmStatusList = Arrays.asList("2", "3");

        QFilter filter = new QFilter("billstatus", QCP.equals, "G");
        filter.and(new QFilter("nckd_srmstatus", QCP.not_in, srmStatusList));
        filter.and(new QFilter("nckd_srmbillno", QCP.is_notnull, null));
        filter.and(new QFilter("nckd_srmbillno", QCP.not_equals2, " "));
        filter.and(new QFilter("nckd_srmbillno", QCP.not_equals2, ""));
//        filter.and(new QFilter("billno", QCP.equals, "BX2010202505-0130"));

        DynamicObjectType type = EntityMetadataCache.getDataEntityType(entityName);
        //先找到批量的pkid
        List<Object> list = QueryServiceHelper.queryPrimaryKeys(entityName,  filter.toArray(), null, Integer.MAX_VALUE);

        logger.info("查询到" + list.size() + "条符合条件的对公报销单：" + list.toString());

        //根据pkid找到完整的对象
        DynamicObject[] billEntities = BusinessDataServiceHelper.load(list.toArray(), type);

        List<DynamicObject> listObj = new ArrayList<>();
        for (DynamicObject payBillEntity : billEntities) {
            //srm单据号
            String billno = payBillEntity.getString("billno");
            String srmBillNo = payBillEntity.getString("nckd_srmbillno");
            String paymentDate = "";

            logger.info("处理对公报销单：" + billno + "，srm单据号：" + srmBillNo);

            if(payBillEntity.getDate("head_paydate") != null){
                paymentDate = CommonHelperUtils.getDateFormatString(payBillEntity.getDate("head_paydate"), pattern);
            }

            BigDecimal paymentAmount = payBillEntity.getBigDecimal("payedamount");//BigDecimal.ZERO;
//            DynamicObjectCollection accountEntrys = payBillEntity.getDynamicObjectCollection("accountentry");
//
//            if(accountEntrys != null && accountEntrys.size() > 0){
//                for(DynamicObject entry : accountEntrys){
//                    paymentAmount = paymentAmount.add(entry.getBigDecimal("orireceiveamount"));
//                }
//            }


            boolean isSave = false;
            StringBuffer errMessage = new StringBuffer();
            Map<String, String> returnMapApprove = SRMHelperUtils.writeApproveStatus(srmBillNo, "PAYMENT");
            logger.info("付款单审批状态回写结果：" + returnMapApprove.toString());

            if(returnMapApprove != null){
                if("1".equals(returnMapApprove.get("code"))){
                    if(errMessage.length() > 0){
                        errMessage.append(",");
                    }
                    logger.info("预付单(" + billno + ", " + srmBillNo + ")审批状态回写失败，" + returnMapApprove.get("msg"));

                    payBillEntity.set("nckd_srmstatus", "4");
                } else {
                    payBillEntity.set("nckd_srmstatus", "3");
                }
                isSave = true;
            }

            Map<String, String> returnMap = SRMHelperUtils.writeBackPayResulst(srmBillNo, paymentDate, paymentAmount);

            logger.info("付款单支付状态回写结果：" + returnMap.toString());

            if(returnMap != null){
                if("1".equals(returnMap.get("code"))){
                    if(errMessage.length() > 0){
                        errMessage.append(",");
                    }
                    logger.info("对公报销单(" + billno + ", " + srmBillNo + ")回写失败，" + returnMap.get("msg"));
                    payBillEntity.set("nckd_srmstatus", "4");
                } else {
                    payBillEntity.set("nckd_srmstatus", "3");
                }
            }

            if(isSave){
                listObj.add(payBillEntity);
                if(listObj.size() == 500) {
                    SaveServiceHelper.update(listObj.toArray(new DynamicObject[]{}));
                    listObj.clear();
                }
            }
        }
        if(listObj.size() > 0) {
            SaveServiceHelper.update(listObj.toArray(new DynamicObject[]{}));
        }
    }

    private void writeBackPrepayBill(RequestContext requestContext, Map<String, Object> map){
        String entityName = "er_prepaybill";
        String pattern = "yyyy-MM-dd HH:mm:ss";

        //srm状态，1：SRM已推送；2：已退回SRM；3：已反写SRM；4：反写SRM失败
        List<String> srmStatusList = Arrays.asList("2", "3");

        QFilter filter = new QFilter("billstatus", QCP.equals, "G");
        filter.and(new QFilter("nckd_srmstatus", QCP.not_in, srmStatusList));
        filter.and(new QFilter("nckd_srmbillno", QCP.is_notnull, null));
        filter.and(new QFilter("nckd_srmbillno", QCP.not_equals2, " "));
        filter.and(new QFilter("nckd_srmbillno", QCP.not_equals2, ""));
//        filter.and(new QFilter("billno", QCP.equals, "PV-202410-006562"));

        DynamicObjectType type = EntityMetadataCache.getDataEntityType(entityName);
        //先找到批量的pkid
        List<Object> list = QueryServiceHelper.queryPrimaryKeys(entityName,  filter.toArray(), null, Integer.MAX_VALUE);

        logger.info("查询到" + list.size() + "条符合条件的预付单：" + list.toString());

        //根据pkid找到完整的对象
        DynamicObject[] billEntities = BusinessDataServiceHelper.load(list.toArray(), type);

        List<DynamicObject> listObj = new ArrayList<>();
        for (DynamicObject payBillEntity : billEntities) {
            //srm单据号
            String billno = payBillEntity.getString("billno");
            String srmBillNo = payBillEntity.getString("nckd_srmbillno");
            String paymentDate = "";

            logger.info("处理预付单：" + billno + "，srm单据号：" + srmBillNo);

            if(payBillEntity.getDate("head_paydate") != null){
                paymentDate = CommonHelperUtils.getDateFormatString(payBillEntity.getDate("head_paydate"), pattern);
            }

            BigDecimal paymentAmount = payBillEntity.getBigDecimal("payamount");//BigDecimal.ZERO;
//            DynamicObjectCollection accountEntrys = payBillEntity.getDynamicObjectCollection("accountentry");
//
//            if(accountEntrys != null && accountEntrys.size() > 0){
//                for(DynamicObject entry : accountEntrys){
//                    paymentAmount = paymentAmount.add(entry.getBigDecimal("orireceiveamount"));
//                }
//            }

            boolean isSave = false;
            StringBuffer errMessage = new StringBuffer();
            Map<String, String> returnMapApprove = SRMHelperUtils.writeApproveStatus(srmBillNo, "PREPAYMENT");
            logger.info("预付单审批状态回写结果：" + returnMapApprove.toString());

            if(returnMapApprove != null){
                if("1".equals(returnMapApprove.get("code"))){
                    if(errMessage.length() > 0){
                        errMessage.append(",");
                    }
                    logger.info("预付单(" + billno + ", " + srmBillNo + ")审批状态回写失败，" + returnMapApprove.get("msg"));

                    payBillEntity.set("nckd_srmstatus", "4");
                } else {
                    payBillEntity.set("nckd_srmstatus", "3");
                }
                isSave = true;
            }

            Map<String, String> returnMap = SRMHelperUtils.writeBackPayResulst(srmBillNo, paymentDate, paymentAmount);

            logger.info("预付单支付状态回写结果：" + returnMap.toString());

            if(returnMap != null){
                if("1".equals(returnMap.get("code"))){
                    if(errMessage.length() > 0){
                        errMessage.append(",");
                    }
                    logger.info("预付单(" + billno + ", " + srmBillNo + ")回写失败，" + returnMap.get("msg"));

                    payBillEntity.set("nckd_srmstatus", "4");
                } else {
                    payBillEntity.set("nckd_srmstatus", "3");
                }

                isSave = true;
            }

            if(isSave) {
                listObj.add(payBillEntity);
                if (listObj.size() == 500) {
                    SaveServiceHelper.update(listObj.toArray(new DynamicObject[]{}));
                    listObj.clear();
                }
            }
        }
        if(listObj.size() > 0) {
            SaveServiceHelper.update(listObj.toArray(new DynamicObject[]{}));
        }
    }
}
