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

import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.exception.KDBizException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author xwudd
 * @Description
 * @date 10:29
 **/
public class ExportInvoiceSaveOP extends AbstractOperationServicePlugIn {
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_exportinvoice_c");
        fieldKeys.add("yem_sourcebillid_ec");
        fieldKeys.add("yem_sourcebillentryid");
        fieldKeys.add("yem_cusqty");
        fieldKeys.add("billno");
        fieldKeys.add("yem_es_materialinfo");
        fieldKeys.add("yem_sourcebillid");
        fieldKeys.add("yem_seatransfee");
    }

    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        DynamicObject[] dataEntities = e.getDataEntities();
        for(DynamicObject dt:dataEntities){
          //  setOutForm(dt);
        }
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for(DynamicObject dataEntitie : dataEntities){
            Map<Long,BigDecimal> map = new HashMap<>();
            Map<Long,Integer> seqs = new HashMap<>();
            Set<Long> ids = new HashSet<>();
            DynamicObjectCollection exportInvoice_cs = dataEntitie.getDynamicObjectCollection("yem_exportinvoice_c");
            for(DynamicObject exportInvoice_c : exportInvoice_cs){
                long sourceBillId = exportInvoice_c.getLong("yem_sourcebillid_ec");
                long sourceBillEntryId = exportInvoice_c.getLong("yem_sourcebillentryid");
                BigDecimal sourceCusQty = exportInvoice_c.getBigDecimal("yem_cusqty");
                ids.add(sourceBillId);
                if(map.containsKey(sourceBillEntryId)){
                    map.put(sourceBillEntryId,map.get(sourceBillEntryId).add(sourceCusQty));
                }else{
                    map.put(sourceBillEntryId,sourceCusQty);
                }
                seqs.put(sourceBillEntryId,exportInvoice_c.getInt("seq"));
            }
            map = getQtyMap(dataEntitie, map);
            StringBuffer sb = new StringBuffer();
            DynamicObject[] declareDocxs = BusinessDataServiceHelper.load("yem_es_declaredocx", "id,billno,yem_es_declare_ec.yem_cusqty,yem_es_declare_ec.yem_billingnoticeqty",
                    new QFilter[]{new QFilter("id", QCP.in, ids)});
            Set<Long> entryIds = map.keySet();
            for(Long entryId : entryIds){
                BigDecimal sourceCusQty = map.get(entryId);
                for(DynamicObject declareDocx : declareDocxs){//源单（出口报关单）
                    DynamicObjectCollection declare_ecs = declareDocx.getDynamicObjectCollection("yem_es_declare_ec");//源单报关商品分录
                    for(int j = 0; j < declare_ecs.size(); j++){
                        DynamicObject declare_ec = declare_ecs.get(j);
                        long declare_ecId = declare_ec.getLong("id");
                        if(entryId == declare_ecId){
                            BigDecimal cusQty = declare_ec.getBigDecimal("yem_cusqty");
                            if(sourceCusQty.compareTo(cusQty) <= 0){
                                declare_ec.set("yem_billingnoticeqty",sourceCusQty);
                            }else{
                                sb.append(String.format("[出口发票单（%s），报关商品第%s行]反写[出口报关单（%s），报关商品第%s行：已开票数量大于数量，不允许超额！！！]\n",
                                        dataEntitie.getString("billno"),seqs.get(entryId),declareDocx.getString("billno"),j + 1));
                            }
                        }
                    }
                }
            }
            if(sb.length() > 0){
                throw new KDBizException(sb.toString());
            }else{
                SaveServiceHelper.save(declareDocxs);
            }
        }

    }


    public Map<Long,BigDecimal> getQtyMap(DynamicObject dataEntitie,Map<Long,BigDecimal> map){
        long id = dataEntitie.getLong("id");
        Set<Long> entryIds = map.keySet();
        String name = dataEntitie.getDynamicObjectType().getName();
        String selectFields = DynamicObjectUtil.getSelectfields(name, false);
        selectFields = DynamicObjectUtil.getEntrySelectfields(selectFields, name, "yem_exportinvoice_c", false);
        DynamicObject[] exportInvoices = BusinessDataServiceHelper.load(name, selectFields,
                new QFilter[]{new QFilter("yem_exportinvoice_c.yem_sourcebillentryid", QCP.in, entryIds),
                        new QFilter("id", QCP.not_equals, id)});
        for(DynamicObject exportInvoice : exportInvoices){
            DynamicObjectCollection exportInvoice_cs = exportInvoice.getDynamicObjectCollection("yem_exportinvoice_c");
            for(DynamicObject exportInvoice_c : exportInvoice_cs){
                long sourceBillEntryId = exportInvoice_c.getLong("yem_sourcebillentryid");
                BigDecimal sourceCusQty = exportInvoice_c.getBigDecimal("yem_cusqty");
                if(map.containsKey(sourceBillEntryId)){
                    map.put(sourceBillEntryId,map.get(sourceBillEntryId).add(sourceCusQty));
                }else{
                    map.put(sourceBillEntryId,sourceCusQty);
                }
            }
        }
        return map;
    }

    /**
     *  最后一张出口发票保存时 处理海运费（原币）尾零  (暂时废弃 11-21)
     * */
    private static void setOutForm(DynamicObject dt) {
        //确定本次为 最后一次生成出口发票
        boolean flag = true;
        //储运托单 海运费
        BigDecimal decimal = BigDecimal.ZERO;
        long aLong = dt.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");
                    DynamicObjectCollection dynamicObjectCollection1 = object.getDynamicObjectCollection("yem_es_materialinfo");
                    DynamicObjectCollection dynamicObjectCollectionNow = dt.getDynamicObjectCollection("yem_es_materialinfo");
                    int row = 0;
                    //报关单总数量
                    BigDecimal sonCount = BigDecimal.ZERO;
                    //储运未报关总数量
                    BigDecimal faCount = BigDecimal.ZERO;
                    //子父分录行数相同
                    if(dynamicObjectCollection1 != null && dynamicObjectCollectionNow != null && dynamicObjectCollectionNow.size() == dynamicObjectCollection1.size()){
                        for(DynamicObject dc:dynamicObjectCollection1){
                            BigDecimal yemQty = dc.getBigDecimal("yem_qty");
                            BigDecimal yemInvoicedqty = dc.getBigDecimal("yem_invoicedqty");
                            BigDecimal yemUnassdeclaqty = BigDecimal.ZERO;
                            if(yemQty != null){
                                yemUnassdeclaqty = yemQty.subtract(yemInvoicedqty);
                            }
                            if(BigDecimal.ZERO.compareTo(yemUnassdeclaqty) != 0){
                                if(dynamicObjectCollectionNow != null && dynamicObjectCollectionNow.size() > row){
                                    DynamicObject object1 = dynamicObjectCollectionNow.get(row);
                                    if(object1 !=null){
                                        //来源分录id等于父明细内码时
                                        Object pkValue = dc.getPkValue();
                                        long sourceentryid = object1.getLong("yem_sourceentryid");
                                        if(pkValue != null && pkValue.equals(sourceentryid)){
                                            BigDecimal yemQtys = object1.getBigDecimal("yem_qty");
                                            if(YEM.isNotEmpty(yemUnassdeclaqty) && yemUnassdeclaqty.compareTo(yemQtys) != 0){
                                                flag = false;
                                            }
                                        }
                                    }
                                }

                            }
                            row++;
                        }
                    }else {

                        int rowCount = 0;
                        for(DynamicObject dts:dynamicObjectCollection1){
                            BigDecimal yemQty = dts.getBigDecimal("yem_qty");
                            BigDecimal yemInvoicedqty = dts.getBigDecimal("yem_invoicedqty");
                            BigDecimal yemUnassdeclaqty = BigDecimal.ZERO;
                            if(yemQty != null){
                                yemUnassdeclaqty = yemQty.subtract(yemInvoicedqty);
                            }
                            if(YEM.isNotEmpty(yemUnassdeclaqty)){
                                rowCount ++;
                            }
                        }
                        //子父分录行数不同
                        //父分录 未报关数量不为0的行数要不等于子分类行数
                        if(dynamicObjectCollectionNow != null && dynamicObjectCollectionNow.size() != rowCount){
                            flag = false;
                        }else {
                            //  //父分录 未报关数量不为0的行数要等于子分类行数 且数量之和要等于父分录 未报关数量之和
                            for(DynamicObject dynamicObject:dynamicObjectCollectionNow){
                                BigDecimal yemQty = dynamicObject.getBigDecimal("yem_qty");
                                sonCount = sonCount.add(yemQty);
                            }
                            for(DynamicObject dc:dynamicObjectCollection1){
                                BigDecimal yemQty = dc.getBigDecimal("yem_qty");
                                BigDecimal yemInvoicedqty = dc.getBigDecimal("yem_invoicedqty");
                                BigDecimal yemUnassdeclaqty = BigDecimal.ZERO;
                                if(yemQty != null){
                                    yemUnassdeclaqty = yemQty.subtract(yemInvoicedqty);
                                }
                                faCount = faCount.add(yemUnassdeclaqty);
                            }
                            if(faCount.compareTo(sonCount) != 0){
                                flag = false;
                            }

                        }
                    }




                }
            }


        }
        //处理海运费尾零
        if(flag){
            DynamicObject[] load = BusinessDataServiceHelper.load("yem_exportinvoice", "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);
                }
                BigDecimal yemReightamt = dt.getBigDecimal("yem_seatransfee");
                yemReightamt = count.add(yemReightamt);
                if(yemReightamt.compareTo(decimal) != 0){
                         dt.set("yem_seatransfee",decimal.subtract(count));
                }
            }
        }
    }
}
