package com.yem.wm.es.exportinvoice.validator;

import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.validate.AbstractValidator;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.math.BigDecimal;

/**
 * @author xwudd
 * @Description
 * @date 16:50
 **/
public class ExportInvoiceSubmitValidator extends AbstractValidator {
    @Override
    public void validate() {
        ExtendedDataEntity[] dataEntities = this.getDataEntities();
        for(ExtendedDataEntity dataEntitie : dataEntities){
            DynamicObject dataEntity = dataEntitie.getDataEntity();
            long sourceBillId = dataEntity.getLong("yem_sourcebillid");
            String sourceBillType = dataEntity.getString("yem_sourcebilltype");
            QFilter qFilter = new QFilter("yem_sourcebilltype", QCP.equals, sourceBillType);
            qFilter.and(new QFilter("yem_sourcebillid",QCP.equals,sourceBillId));
            BigDecimal sumAmt = BigDecimal.ZERO;
            DynamicObject declareDocx = null;
            if(YEM.isNotEmpty(sourceBillType)){
                declareDocx = BusinessDataServiceHelper.loadSingle(sourceBillId, sourceBillType);
            }
            DynamicObject[] exportInvoices = BusinessDataServiceHelper.load("yem_exportinvoice", "id,yem_seatransfee", qFilter.toArray());
            for (DynamicObject exportInvoice : exportInvoices){
                sumAmt = sumAmt.add(exportInvoice.getBigDecimal("yem_seatransfee"));
            }
            if(declareDocx != null){
                BigDecimal reightAmt = declareDocx.getBigDecimal("yem_reightamt");
                if(sumAmt.compareTo(reightAmt) > 0){
                    this.addErrorMessage(dataEntitie,"同一报关单下推生成的多张出口发票海运费金额合计值不允许超出上游报关单的海运费金额,请检查数据！");
                }
            }
            setOutForm(dataEntitie);
            checkCount(dataEntitie);

        }
    }


    /**
     * @author power
     * @Description 分摊金额 汇总校验
     * @date 11/20
     **/
    private void setOutForm(ExtendedDataEntity dataEntitie) {
        DynamicObject dataEntity = dataEntitie.getDataEntity();
        DynamicObjectCollection entry = dataEntity.getDynamicObjectCollection("yem_exportinvoice_c");
        BigDecimal seabase = dataEntity.getBigDecimal("yem_seabase");
        BigDecimal insurefeecurrba = dataEntity.getBigDecimal("yem_insurefeecurrba");
        BigDecimal commission = dataEntity.getBigDecimal("yem_commission");
        BigDecimal sum =seabase.add(insurefeecurrba.add(commission));
        BigDecimal sumshareamt = BigDecimal.ZERO;
        for (DynamicObject dynamicObject : entry) {
            BigDecimal shareamt = dynamicObject.getBigDecimal("yem_shareamtc");
            sumshareamt =sumshareamt.add(shareamt);
        }
        if (sum.compareTo(sumshareamt) != 0) {
            this.addErrorMessage(dataEntitie,"出口发票分摊金额合计 不等于 海运费（结算币别），保费（结算币别），佣金（结算币别）合计");
        }
    }

    /**
     *   口发票提交时增加校验：该出口发票上游出口报关单已下推的所有出口发票的海运费（原币）合计值不允许超出上游报关单的海运费（原币），
     * 如果超出，增加提示信息:"出口发票 单号 海运费金额：***元  +   出口发票 单号 海运费金额：***元，汇总值为**元，超出上游报关单海运费金额***元，请核实！"
     *  @author ZLP
     * */

    private  void checkCount(ExtendedDataEntity dt) {
        DynamicObject dataEntity = dt.getDataEntity();
        //确定本次为 最后一次生成出口发票
        //储运托单 海运费
        BigDecimal decimal = BigDecimal.ZERO;
        long aLong = dataEntity.getLong("yem_sourcebillid");
        if(YEM.isNotEmpty(aLong)) {
            DynamicObject object2 = BusinessDataServiceHelper.loadSingle(aLong, "yem_es_declaredocx");
            if (object2 != null) {
                DynamicObject object = BusinessDataServiceHelper.loadSingle(object2.getPkValue(), object2.getDynamicObjectType().getName());
                if (object != null) {
                    decimal = object.getBigDecimal("yem_reightamt");
                }
            }
        }

        DynamicObject[] load = BusinessDataServiceHelper.load("yem_exportinvoice", "billno,yem_seatransfee",
                new QFilter[]{
                        //new QFilter("billstatus", QCP.equals, "C"),
                        new QFilter("yem_sourcebillid", QCP.equals, aLong)
                });
        if(load != null){
            BigDecimal count = BigDecimal.ZERO;
            for(DynamicObject dc:load){
                BigDecimal yemReightamt = dc.getBigDecimal("yem_seatransfee");
                count = count.add(yemReightamt);
            }
            if(count.compareTo(decimal) > 0){
                StringBuffer info = new StringBuffer();
                for(DynamicObject dc:load){
                    info.append("出口发票 【单号】:"+dc.getString("billno") +
                            "   【海运费金额】:"+dc.getBigDecimal("yem_seatransfee").setScale(6,BigDecimal.ROUND_HALF_UP)+"元\n");
                }
                info.append("超出上游报关单【海运费金额】:"+decimal.setScale(6,BigDecimal.ROUND_HALF_UP)+"元,请核实!");
                this.addWarningMessage(dt,info.toString());
            }
        }
    }
}
