//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package nc.bs.arap.actions;

import nc.bs.arap.bill.ArapBillPubUtil;
import nc.bs.arap.util.ArapBillVOUtils;
import nc.bs.arap.util.BillAccountCalendarUtils;
import nc.bs.arap.util.BillDateUtils;
import nc.bs.arap.util.BillMoneyVUtils;
import nc.bs.arap.validator.CrossRuleCheckValidator;
import nc.bs.dao.BaseDAO;
import nc.bs.dao.DAOException;
import nc.bs.trade.business.HYSuperDMO;
import nc.jdbc.framework.processor.MapListProcessor;
import nc.jdbc.framework.processor.MapProcessor;
import nc.vo.arap.basebill.BaseBillVO;
import nc.vo.arap.gathering.GatheringBillItemVO;
import nc.vo.arap.utils.StringUtil;
import nc.vo.bd.defdoc.DefdocVO;
import nc.vo.pub.AggregatedValueObject;
import nc.vo.pub.BusinessException;
import nc.vo.pub.lang.UFDouble;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GatheringbillSaveBatchBSAction extends BillInsertBatchBSAction {
    public GatheringbillSaveBatchBSAction() {
        this.validatorCode.add(5);
        this.validatorCode.add(15);
        this.validatorCode.add(29);
        this.validatorCode.add(19);
        this.validatorCode.add(8);
        this.validatorCode.add(24);
        this.validatorCode.add(28);
//        this.validatorCode.add(44);
        this.validatorCode.add(46);
        this.validatorCode.add(31);
        this.validatorCode.add(36);
        this.validatorCode.add(23);
        this.validatorCode.add(49);
        this.validatorCode.add(57);
        this.validatorCode.add(59);
        this.validatorCode.add(62);
        this.validatorCode.add(93);
        this.validatorCode.add(94);
        this.validatorCode.add(100);
    }

    protected void doBeforeInsert(AggregatedValueObject[] bills) throws BusinessException {
        ArapBillPubUtil.fillTradeTypeInfo(bills);
        BillDateUtils.setBillDateByNow(bills);
        ArapBillPubUtil.resetBasedocVid(bills);
        BillAccountCalendarUtils.setAccperiodYearMonth(bills);
        ArapBillVOUtils.prepareDefaultInfo(bills);
        BillMoneyVUtils.sumAllVoBodyToHead(bills);
        (new CrossRuleCheckValidator()).validate(bills);
        ArapBillPubUtil.resetDestVODoc(bills);
        ArapBillVOUtils.setMaterialInfo(bills);
        ArapBillVOUtils.setDefaultSagaFrozen(bills);
        ArapBillVOUtils.setDefaultFeeundertaker(bills);
        ArapBillVOUtils.setDefaultSettleFlag(bills);

        /**
         * 收款单保存校验关联的销售订单实际收款金额是否超过价税合计
         */

        for(AggregatedValueObject bill : bills) {
            BaseBillVO billVO = (BaseBillVO) bill.getParentVO(); //修改的收款单
            UFDouble money = billVO.getMoney(); //金额
            String pk_tradetype = billVO.getPk_tradetype();
//            if(!"F2-Cxx-02".equals(pk_tradetype)){
//                continue;
//            }
            String srcBilltype = ((GatheringBillItemVO)bill.getChildrenVO()[0]).getSrc_billtype();
            if(!"30".equals(srcBilltype)){
                continue;
            }
            List<String> def3List = new ArrayList<>();
            for (int i=0;i<bill.getChildrenVO().length;i++){
                def3List.add(((GatheringBillItemVO)bill.getChildrenVO()[i]).getSrc_billid());
            }
            String result = "";
            StringBuilder sb = new StringBuilder();
            if (def3List.size() > 1) {
                for (int i = 0; i < def3List.size(); i++) {
                    sb.append("'").append(def3List.get(i)).append("'");
                    if (i < def3List.size() - 1) {
                        sb.append(",");
                    }
                }

                result = sb.toString();
            } else {
                result = "'" + (String) def3List.get(0) + "'";
            }
            String def3 = ((GatheringBillItemVO)bill.getChildrenVO()[0]).getSrc_billid(); // 收款单对应的销售订单id
            if(StringUtil.isEmpty(def3) || "N".equals(def3) || "~".equals(def3)){
                //无绑定的销售订单则下一次循环
                continue;
            }

            //根据销售订单id去查询销售订单
            BaseDAO dao = new BaseDAO();
            String sql = "select vbillcode,nreceivedmny,ntotalorigmny from so_saleorder where dr = 0 and csaleorderid = '" +def3+"'";



//            List<String> defMap = checkOrgCtrl();
//            if (defMap.isEmpty() ) {
//                return ;
//            }
//            String sql1="SELECT org_salesorg.CODE ,so_saleorder.dbilldate, so_saleorder.pk_org, so_saleorder.vbillcode,so_saleorder.nreceivedmny,so_saleorder.ntotalorigmny FROM  so_saleorder LEFT JOIN org_salesorg ON org_salesorg.PK_SALESORG = so_saleorder.PK_ORG  where so_saleorder.dr = 0 and so_saleorder.csaleorderid = '" +def3+"'";
            String sql1="SELECT org_salesorg.CODE ,so_saleorder.dbilldate, so_saleorder.pk_org, so_saleorder.vbillcode,so_saleorder.nreceivedmny,so_saleorder.ntotalorigmny FROM  so_saleorder LEFT JOIN org_salesorg ON org_salesorg.PK_SALESORG = so_saleorder.PK_ORG  where so_saleorder.dr = 0 and so_saleorder.csaleorderid in  (" + result + ") ";
            ArrayList<HashMap<String, Object>> saleMap = (ArrayList<HashMap<String, Object>>)dao.executeQuery(sql1, new MapListProcessor());

//            List<Map> saleMap = (List<Map>)dao.executeQuery(sql1, new MapProcessor());
//            String code = saleMap.get("code").toString();
//            LocalDateTime dbilldate = LocalDateTime.parse(saleMap.get("dbilldate").toString(),
//                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//            LocalDateTime targetDate = LocalDateTime.parse("2025-06-27 00:00:00",
//                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//
//            if (!defMap.isEmpty()&& defMap.contains(code) && dbilldate.isBefore(targetDate)) {
//                return;
//            }
//            Map saleMap = (Map)dao.executeQuery(sql, new MapProcessor());
            //销售订单价税合计
            UFDouble ntotalorigmny = UFDouble.ZERO_DBL;
            //销售订单实际收款金额
            UFDouble nreceivedmny = UFDouble.ZERO_DBL;
            StringBuilder vbillcodeBuilder = new StringBuilder();
            if(saleMap != null) {
                for (Map<String, Object> map : saleMap) {
                    // 累加 nreceivedmny
                    String nreceivedmnyStr = map.get("nreceivedmny") == null ? "0" : map.get("nreceivedmny").toString();
                    nreceivedmny.add(new UFDouble(nreceivedmnyStr)) ;

                    // 累加 ntotalorigmny
                    BigDecimal ntotalorigmnyStr = map.get("ntotalorigmny") == null ? BigDecimal.ZERO : (BigDecimal) map.get("ntotalorigmny");
                    UFDouble ufd=    new UFDouble(ntotalorigmnyStr);
                    ntotalorigmny=  ntotalorigmny.add(ufd);
                    // 拼接 vbillcode
                    String vbillcodeStr = map.get("vbillcode") == null ? "" : map.get("vbillcode").toString();
                    if (!vbillcodeStr.isEmpty()) {
                        if (vbillcodeBuilder.length() > 0) {
                            vbillcodeBuilder.append(", ");
                        }
                        vbillcodeBuilder.append(vbillcodeStr);
                    }
                }
            }
            if (money.compareTo(ntotalorigmny) > 0) {
                UFDouble moreMoney = money.sub(ntotalorigmny);
                throw new BusinessException("【该笔收款税收合计" + money + "已超销售订单 [" + vbillcodeBuilder + "] " + moreMoney + "元，无法传输！请检查订单累计收款金额！】");
            }
        }
    }
    private List<String> checkOrgCtrl() {
        List<String> list = new ArrayList<>();
        String strWhere = " pk_defdoclist in (select pk_defdoclist from bd_defdoclist where code='org-ctrl' and dr=0 )  and dr=0";
        try {
            DefdocVO[] defdocVOs = (DefdocVO[]) new HYSuperDMO().queryByWhereClause(DefdocVO.class, strWhere);
            if (defdocVOs != null && defdocVOs.length > 0) {
                for (DefdocVO defdocVO : defdocVOs) {
                    list.add(defdocVO.getCode());
                }
            }
        } catch (DAOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
