package com.yem.wm.im.inquirylist.op;

import com.yem.wm.utils.DynamicObjectUtil;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
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.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class InquirylistAudit extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        e.getFieldKeys().addAll(this.billEntityType.getAllFields().keySet());

    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
        if (!"audit".equals(operationKey)) {
            return;
        }
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            Boolean billtype = billtype(dataEntitie);
            if (!billtype) continue;
            DynamicObjectCollection imDetailedinforColl = dataEntitie.getDynamicObjectCollection("yem_im_detailedinfor");
            //多功能配置
            for (DynamicObject imDetailedinfor : imDetailedinforColl) {
                DynamicObjectCollection yemMulticonfigColl = imDetailedinfor.getDynamicObjectCollection("yem_multiconfig");
                for (DynamicObject dynamicObject : yemMulticonfigColl) {
                    String yemConfigurtype = dynamicObject.getString("yem_configurtype");
                    if ("A".equals(yemConfigurtype)) {
                        optional(dataEntitie, dynamicObject);
                    }
                    if ("B".equals(yemConfigurtype)) {
                        replace(dataEntitie, dynamicObject);
                    }
                    if ("C".equals(yemConfigurtype)) {
                        retrofitting(dataEntitie, dynamicObject);
                    }
                }
            }
            DynamicObjectCollection yemImDetailedinfor = dataEntitie.getDynamicObjectCollection("yem_im_detailedinfor");
            for (DynamicObject dynamicObject : yemImDetailedinfor) {
                DynamicObject yemProductmodel = dynamicObject.getDynamicObject("yem_productmodel");
                BigDecimal yemQingdaounitprice = dynamicObject.getBigDecimal("yem_qingdaounitprice");
                BigDecimal yemUnitprice = dynamicObject.getBigDecimal("yem_unitprice");
                BigDecimal yemForeigntradeprice = dynamicObject.getBigDecimal("yem_foreigntradeprice");
                if (yemProductmodel != null) {
                    DynamicObject yemProducts = yemProductmodel.getDynamicObject("yem_products");
                    if (yemProducts != null) {
                        long aLong = yemProducts.getLong("id");
                        String selectfield = DynamicObjectUtil.getSelectfields("yem_pricelibrary", false);
                        String selectfields = DynamicObjectUtil.getEntrySelectfields(selectfield, "yem_pricelibrary", "yem_basicmodel", false);
                        DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", selectfields
                                , new QFilter[]{new QFilter("yem_bd_products.id", QCP.equals, aLong)});
                        if (loadSingle != null) {
                            DynamicObjectCollection yemBasicmodel = loadSingle.getDynamicObjectCollection("yem_basicmodel");
                            for (DynamicObject Basic : yemBasicmodel) {
                                DynamicObject yemModel = Basic.getDynamicObject("yem_model");
                                if (yemModel != null) {
                                    long yemModelLong = yemModel.getLong("id");
                                    long yemProductmodelLong = yemProductmodel.getLong("id");
                                    if (yemModelLong == yemProductmodelLong) {
                                        if (yemQingdaounitprice.compareTo(BigDecimal.ZERO) > 0) {
                                            Basic.set("yem_pricefob", yemQingdaounitprice);
                                        }
                                        if (yemUnitprice.compareTo(BigDecimal.ZERO) > 0) {
                                            Basic.set("yem_fcafactoryprice", yemUnitprice);
                                        }
                                        if (yemForeigntradeprice.compareTo(BigDecimal.ZERO) > 0) {
                                            Basic.set("yem_foreigntradeprice", yemForeigntradeprice);
                                        }
                                    }
                                }
                            }
                        }
                        SaveServiceHelper.update(loadSingle);
                    }
                }
            }
//            productmodel(dataEntitie);
        }
    }

    private void productmodel(DynamicObject dataEntitie) {
        DynamicObjectCollection yemImDetailedinfor = dataEntitie.getDynamicObjectCollection("yem_im_detailedinfor");
        for (DynamicObject dynamicObject : yemImDetailedinfor) {
            DynamicObjectCollection yemMulticonfig = dynamicObject.getDynamicObjectCollection("yem_multiconfig");
            DynamicObject yemProductmodel = dynamicObject.getDynamicObject("yem_productmodel");
            if (yemProductmodel != null) {
                DynamicObject yemProducts = yemProductmodel.getDynamicObject("yem_products");
                if (yemProducts != null) {
                    long yemProductsLong = yemProducts.getLong("id");
                    DynamicObject loadSingle = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", "id,billno,yem_cancelstatus,yem_bd_products" +
                                    ",yem_optional,yem_optional.yem_disabledstate,yem_optional.yem_entryid_o,yem_optional.yem_salesprice_o,yem_optional.yem_salesmarkup_o" +
                                    ",yem_replaceable,yem_replaceable.yem_disabledstate1,yem_replaceable.yem_entryid_re,yem_replaceable.yem_salesprice_re,yem_replaceable.yem_salesmarkup_re" +
                                    ",yem_retrofitting,yem_retrofitting.yem_disabledstate2,yem_retrofitting.yem_entryid_rt,yem_retrofitting.yem_salesprice_rt,yem_retrofitting.yem_salesmarkup_rt"
                            , new QFilter[]{new QFilter("yem_bd_products.id", QCP.equals, yemProductsLong)});
                    if (loadSingle != null) {
                        loadSingle.set("yem_cancelstatus", "0");
                        DynamicObjectCollection yemOptional = loadSingle.getDynamicObjectCollection("yem_optional");
                        DynamicObjectCollection yem_replaceable = loadSingle.getDynamicObjectCollection("yem_replaceable");
                        DynamicObjectCollection yem_retrofitting = loadSingle.getDynamicObjectCollection("yem_retrofitting");
                        for (DynamicObject yemMulticonfigs : yemMulticonfig) {
                            long yemMulticonfigsLong = yemMulticonfigs.getLong("id");
                            BigDecimal yemMarketprice = yemMulticonfigs.getBigDecimal("yem_marketprice");
                            BigDecimal yem_marketraiseprice = yemMulticonfigs.getBigDecimal("yem_marketraiseprice");

                            for (DynamicObject yem_optionals : yemOptional) {
                                yem_optionals.set("yem_disabledstate", "0");
                                long aLong = yem_optionals.getLong("yem_entryid_o");
                                if (aLong == yemMulticonfigsLong) {
                                    yem_optionals.set("yem_salesprice_o", yem_marketraiseprice);
                                    yem_optionals.set("yem_salesmarkup_o", yemMarketprice);
                                }
                            }
                            for (DynamicObject yem_replaceables : yem_replaceable) {
                                yem_replaceables.set("yem_disabledstate1", "0");
                                long aLong = yem_replaceables.getLong("yem_entryid_re");
                                if (aLong == yemMulticonfigsLong) {
                                    yem_replaceables.set("yem_salesprice_re", yem_marketraiseprice);
                                    yem_replaceables.set("yem_salesmarkup_re", yemMarketprice);
                                }
                            }
                            for (DynamicObject yem_retrofittings : yem_retrofitting) {
                                yem_retrofittings.set("yem_disabledstate2", "0");
                                long aLong = yem_retrofittings.getLong("yem_entryid_rt");
                                if (aLong == yemMulticonfigsLong) {
                                    yem_retrofittings.set("yem_salesprice_rt", yem_marketraiseprice);
                                    yem_retrofittings.set("yem_salesmarkup_rt", yemMarketprice);
                                }
                            }
                        }
                    }
                    SaveServiceHelper.update(loadSingle);
                }
            }
        }
    }

    public Boolean billtype(DynamicObject dataEntitie) {
        DynamicObject yemBilltype = dataEntitie.getDynamicObject("yem_billtype");
        String number = yemBilltype.getString("number");
        if ("yem_im_inquirylist_ZJ".equals(number)) {
            return true;
        }
        return false;
    }


    /**
     * 可加装
     *
     * @param dataEntitie
     * @param yemMulticonfig
     */
    public void optional(DynamicObject dataEntitie, DynamicObject yemMulticonfig) {

        //产品机型
        DynamicObject bdProducts = yemMulticonfig.getDynamicObject("yem_productstree");
        String bdProductNumber = bdProducts.getString("number");
        //配置分录内码
        Long configentryid = yemMulticonfig.getLong("yem_configentryid");
        //标准销售定价
        BigDecimal marketprice = yemMulticonfig.getBigDecimal("yem_marketprice");
        //标准销售加价
        BigDecimal marketraiseprice = yemMulticonfig.getBigDecimal("yem_marketraiseprice");
        //配置名称
        String configurname = yemMulticonfig.getString("yem_configurname");
        //配置英文名称
        String configurtypeen = yemMulticonfig.getString("yem_configurtypeen");
        //规格型号
        String specification_o = yemMulticonfig.getString("yem_specification_o");
        //参数（mm）
        String arguments = yemMulticonfig.getString("yem_arguments");
        //备注
        String remarkss = yemMulticonfig.getString("yem_remarkss");


        //价格库
        DynamicObject pricelibrary = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", new QFilter[]{new QFilter("yem_bd_products.number"
                , QCP.equals, bdProductNumber), new QFilter("billstatus", "=", "C")});
        if (pricelibrary == null) {
            return;
        }
        pricelibrary.set("yem_cancelstatus","0");
        DynamicObjectCollection optionalColl = pricelibrary.getDynamicObjectCollection("yem_optional");
        Predicate<DynamicObject> filter = dynamicObject -> dynamicObject.getLong("yem_entryid_o") == configentryid;
        List<DynamicObject> collects = optionalColl.stream().filter(filter).collect(Collectors.toList());
        if (collects.size() > 0) {
            //更新
            DynamicObject dynamicObject = collects.get(0);
            dynamicObject.set("yem_disabledstate", "A");
            if (marketprice.compareTo(BigDecimal.ZERO) > 0) {
                dynamicObject.set("yem_salesprice_o", marketprice);
            }
            if (marketraiseprice.compareTo(BigDecimal.ZERO) > 0) {
                dynamicObject.set("yem_salesmarkup_o", marketraiseprice);
            }
            SaveServiceHelper.update(pricelibrary);
        } else {
            DynamicObject dynamicObject = new DynamicObject(optionalColl.getDynamicObjectType());
            dynamicObject.set("yem_disabledstate", "A");
            dynamicObject.set("yem_profilename_o", configurname);
            dynamicObject.set("yem_english", configurtypeen);
            dynamicObject.set("yem_specification_o", specification_o);
            dynamicObject.set("yem_salesprice_o", marketprice);
            dynamicObject.set("yem_salesmarkup_o", marketraiseprice);
            dynamicObject.set("yem_parameter_o", arguments);
            dynamicObject.set("yem_remark_o", remarkss);
            dynamicObject.set("yem_entryid_o", configentryid);
            optionalColl.add(dynamicObject);
            SaveServiceHelper.save(new DynamicObject[]{pricelibrary});
        }
    }


    /**
     * 可替换
     *
     * @param dataEntitie
     * @param yemMulticonfig
     */
    public void replace(DynamicObject dataEntitie, DynamicObject yemMulticonfig) {
        //产品机型
        DynamicObject bdProducts = yemMulticonfig.getDynamicObject("yem_productstree");
        String bdProductNumber = bdProducts.getString("number");
        //配置分录内码
        Long configentryid = yemMulticonfig.getLong("yem_configentryid");
        //标准销售定价
        BigDecimal marketprice = yemMulticonfig.getBigDecimal("yem_marketprice");
        //标准销售加价
        BigDecimal marketraiseprice = yemMulticonfig.getBigDecimal("yem_marketraiseprice");
        //配置名称
        String configurname = yemMulticonfig.getString("yem_configurname");
        //配置英文名称
        String configurtypeen = yemMulticonfig.getString("yem_configurtypeen");
        //规格型号
        String specification_o = yemMulticonfig.getString("yem_specification_o");
        //参数（mm）
        String arguments = yemMulticonfig.getString("yem_arguments");
        //备注
        String remarkss = yemMulticonfig.getString("yem_remarkss");


        //价格库
        DynamicObject pricelibrary = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", new QFilter[]{new QFilter("yem_bd_products.number"
                , QCP.equals, bdProductNumber), new QFilter("billstatus", "=", "C")});
        if (pricelibrary == null) {
            return;
        }
        pricelibrary.set("yem_cancelstatus","0");
        DynamicObjectCollection optionalColl = pricelibrary.getDynamicObjectCollection("yem_replaceable");
        Predicate<DynamicObject> filter = dynamicObject -> dynamicObject.getLong("yem_entryid_re") == configentryid;
        List<DynamicObject> collects = optionalColl.stream().filter(filter).collect(Collectors.toList());
        if (collects.size() > 0) {
            //更新
            DynamicObject dynamicObject = collects.get(0);
            dynamicObject.set("yem_disabledstate1", "A");

            if (marketprice.compareTo(BigDecimal.ZERO) > 0) {
                dynamicObject.set("yem_salesprice_re", marketprice);
            }
            if (marketraiseprice.compareTo(BigDecimal.ZERO) > 0) {
                dynamicObject.set("yem_salesmarkup_re", marketraiseprice);
            }
            SaveServiceHelper.update(pricelibrary);
        } else {
            DynamicObject dynamicObject = new DynamicObject(optionalColl.getDynamicObjectType());
            dynamicObject.set("yem_disabledstate1", "A");
            dynamicObject.set("yem_profilename_re", configurname);
            dynamicObject.set("yem_englishname", configurtypeen);
            dynamicObject.set("yem_specification_re", specification_o);
            dynamicObject.set("yem_salesprice_re", marketprice);
            dynamicObject.set("yem_salesmarkup_re", marketraiseprice);
            dynamicObject.set("yem_remark_re", remarkss);
            dynamicObject.set("yem_entryid_re", configentryid);
            optionalColl.add(dynamicObject);
            SaveServiceHelper.save(new DynamicObject[]{pricelibrary});

        }
    }

    /**
     * 可选装
     *
     * @param dataEntitie
     * @param yemMulticonfig
     */
    public void retrofitting(DynamicObject dataEntitie, DynamicObject yemMulticonfig) {
        //产品机型
        DynamicObject bdProducts = yemMulticonfig.getDynamicObject("yem_productstree");
        String bdProductNumber = bdProducts.getString("number");
        //配置分录内码
        Long configentryid = yemMulticonfig.getLong("yem_configentryid");
        //标准销售定价
        BigDecimal marketprice = yemMulticonfig.getBigDecimal("yem_marketprice");
        //标准销售加价
        BigDecimal marketraiseprice = yemMulticonfig.getBigDecimal("yem_marketraiseprice");
        //配置名称
        String configurname = yemMulticonfig.getString("yem_configurname");
        //配置英文名称
        String configurtypeen = yemMulticonfig.getString("yem_configurtypeen");
        //规格型号
        String specification_o = yemMulticonfig.getString("yem_specification_o");
        //参数（mm）
        String arguments = yemMulticonfig.getString("yem_arguments");
        //备注
        String remarkss = yemMulticonfig.getString("yem_remarkss");


        //价格库
        DynamicObject pricelibrary = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", new QFilter[]{new QFilter("yem_bd_products.number"
                , QCP.equals, bdProductNumber), new QFilter("billstatus", "=", "C")});
        if (pricelibrary == null) {
            return;
        }
        pricelibrary.set("yem_cancelstatus","0");
        DynamicObjectCollection optionalColl = pricelibrary.getDynamicObjectCollection("yem_retrofitting");
        Predicate<DynamicObject> filter = dynamicObject -> dynamicObject.getLong("yem_entryid_rt") == configentryid;
        List<DynamicObject> collects = optionalColl.stream().filter(filter).collect(Collectors.toList());
        if (collects.size() > 0) {
            //更新
            DynamicObject dynamicObject = collects.get(0);
            dynamicObject.set("yem_disabledstate2", "A");
            if (marketprice.compareTo(BigDecimal.ZERO) > 0) {
                dynamicObject.set("yem_salesprice_rt", marketprice);
            }
            if (marketraiseprice.compareTo(BigDecimal.ZERO) > 0) {
                dynamicObject.set("yem_salesmarkup_rt", marketraiseprice);
            }
            SaveServiceHelper.update(pricelibrary);
        } else {
            DynamicObject dynamicObject = new DynamicObject(optionalColl.getDynamicObjectType());
            dynamicObject.set("yem_disabledstate2", "A");
            dynamicObject.set("yem_profilename_rt", configurname);
            dynamicObject.set("yem_englishnames", configurtypeen);
            dynamicObject.set("yem_specification_rt", specification_o);
            dynamicObject.set("yem_salesprice_rt", marketprice);
            dynamicObject.set("yem_salesmarkup_rt", marketraiseprice);
            dynamicObject.set("yem_remark_rt", remarkss);
            dynamicObject.set("yem_entryid_rt", configentryid);
            optionalColl.add(dynamicObject);
            SaveServiceHelper.save(new DynamicObject[]{pricelibrary});

        }
    }

}
