package com.yem.wm.im.priceLibrary.form;

import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;

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

/**
 * @Description 替换动态表单插件
 */
public class ReplaceFormPlugIn extends AbstractFormPlugin implements Plugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        FormShowParameter fsp = view.getFormShowParameter();
        Map<String, Object> customParams = fsp.getCustomParams();
        String type = (String) customParams.get("type");
        if ("A".equals(type)) {
            priceLibraryFunction(customParams);
        }
        if ("B".equals(type)) {
            billFunction(customParams);
        }

    }

    public void priceLibraryFunction(Map<String, Object> customParams) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        view.setVisible(false, "yem_productmodel", "yem_basemodel", "yem_typeconfiguration");
        JSONObject modelObj = (JSONObject) customParams.get("modelObj");
        List<Long> ids = (List<Long>) customParams.get("ids");
        QFilter qFilter = new QFilter("yem_bd_products.id", QCP.equals, modelObj.getLong("id"));
        qFilter.and(new QFilter("status",QCP.equals,"C"));
        qFilter.and(new QFilter("enable",QCP.equals,"1"));
        DynamicObject[] productsgroup = BusinessDataServiceHelper.load("yem_bd_mechanical",
                "id", new QFilter[]{qFilter}, null);
        if (productsgroup.length > 0) {
            DynamicObject load = BusinessDataServiceHelper.loadSingle(productsgroup[0].getLong("id"), "yem_bd_mechanical");
            DynamicObjectCollection mechanical_c = load.getDynamicObjectCollection("yem_bd_mechanical_r");
            for (DynamicObject mechanical : mechanical_c) {
                Long id = mechanical.getLong("id");
                if (ids.contains(id)) {
                    continue;
                }
                String status = mechanical.getString("yem_entrystatus_r");
                if (!"A".equals(status)) {
                    continue;
                }
                int createRow = model.createNewEntryRow("yem_replaceentry");
                model.setValue("yem_profilenamea", mechanical.getString("yem_profilenamer"), createRow);
                model.setValue("yem_configure", mechanical.getString("yem_configurename"), createRow);
                model.setValue("yem_specification", mechanical.getString("yem_specification_r"), createRow);
                model.setValue("yem_remarke", mechanical.getString("yem_remarkr"), createRow);
                model.setValue("yem_entryid", mechanical.getPkValue(), createRow);
            }
        }
    }

    public void billFunction(Map<String, Object> customParams) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        List<QFilter> qFilters = new ArrayList<>();
        JSONObject productModel = (JSONObject)customParams.get("productModel");
        Long products = (Long) customParams.get("products");
        List<Long> ids = (List<Long>) customParams.get("ids");
        qFilters.add(new QFilter("yem_bd_products", QCP.equals, products));
        qFilters.add(new QFilter("status", QCP.equals, "C"));
        DynamicObject mechanical = BusinessDataServiceHelper.loadSingle("yem_bd_mechanical", "id", qFilters.toArray(new QFilter[qFilters.size()]));
        if (mechanical != null) {
            mechanical = BusinessDataServiceHelper.loadSingle(mechanical.getPkValue(), mechanical.getDynamicObjectType().getName());
            DynamicObjectCollection replaceables = mechanical.getDynamicObjectCollection("yem_bd_mechanical_r");
            for (DynamicObject replaceable : replaceables) {
                Long id = replaceable.getLong("id");
                if (ids.contains(id)) {
                    continue;
                }
                String status = replaceable.getString("yem_entrystatus_r");
                if (!"A".equals(status)) {
                    continue;
                }
                int entryRow = model.createNewEntryRow("yem_replaceentry");
                model.setValue("yem_basemodel", productModel.getLong("id"), entryRow);
                model.setValue("yem_productmodel", productModel.getJSONObject("yem_products").getLong("id"), entryRow);
                model.setValue("yem_profilenamea", replaceable.getString("yem_profilenamer"), entryRow);
                model.setValue("yem_configure", replaceable.getString("yem_configurename"), entryRow);
                model.setValue("yem_unitsetnumber", replaceable.getBigDecimal("yem_unitsetnumber_r"), entryRow);
                model.setValue("yem_specification", replaceable.getString("yem_specification_r"), entryRow);
//                        model.setValue("yem_marketraiseprice", replaceable.getBigDecimal("yem_salesmarkup_re"), entryRow);
                model.setValue("yem_remarke", replaceable.getString("yem_remarkr"), entryRow);
                model.setValue("yem_entryid", replaceable.getPkValue(), entryRow);
                model.setValue("yem_ruconfigure_c",replaceable.getString("yem_ruconfigure_r"),entryRow);

                model.setValue("yem_model_config_r", replaceable.getDynamicObject("yem_model_config_r"), entryRow);

            }
        }

    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("btnok");
    }

    @Override
    public void click(EventObject e) {
        Control source = (Control) e.getSource();
        String key = source.getKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        FormShowParameter fsp = view.getFormShowParameter();
        Map<String, Object> customParams = fsp.getCustomParams();
        String type = (String) customParams.get("type");
        if ("btnok".equals(key)) {
            if ("A".equals(type)) {
                EntryGrid optionalEntry = view.getControl("yem_replaceentry");
                int[] selectRows = optionalEntry.getSelectRows();
                for (int selectRow : selectRows) {
                    int optionalRow = parentModel.createNewEntryRow("yem_replaceable");
                    parentModel.setValue("yem_profilename_re", model.getValue("yem_profilenamea", selectRow), optionalRow);
                    parentModel.setValue("yem_englishname", model.getValue("yem_configure", selectRow), optionalRow);
                    parentModel.setValue("yem_remark_re", model.getValue("yem_remarke", selectRow), optionalRow);
                    parentModel.setValue("yem_specification_re", model.getValue("yem_specification", selectRow), optionalRow);
                    parentModel.setValue("yem_entryid_re", model.getValue("yem_entryid", selectRow), optionalRow);
                }
            }
            if ("B".equals(type)) {
//                Object exrateTable = parentModel.getValue("yem_exratetable");
//                Object sourceCurrency = null;
//                Object targetCurrency = parentModel.getValue("yem_currency");
//                Date exrateDate = (Date) parentModel.getValue("yem_exratedate");
//                String marketPriceCurrName = FunctionalCommon.getAmountFieldCurrencyKey(parentView, "yem_marketprice");
//                sourceCurrency = YEM.isNotEmpty(marketPriceCurrName)?parentModel.getValue(marketPriceCurrName):targetCurrency;
//                BigDecimal marketPriceExchangeRate = YEM.getExchangeRate(exrateTable, sourceCurrency, targetCurrency, exrateDate);
//                String marketRaisePriceCurrName = FunctionalCommon.getAmountFieldCurrencyKey(parentView, "yem_marketprice");
//                sourceCurrency = YEM.isNotEmpty(marketRaisePriceCurrName)?parentModel.getValue(marketRaisePriceCurrName):targetCurrency;
//                BigDecimal marketRaisePriceExchangeRate = YEM.getExchangeRate(exrateTable, sourceCurrency, targetCurrency, exrateDate);
                EntryGrid optionalEntry = view.getControl("yem_replaceentry");
                int[] selectRows = optionalEntry.getSelectRows();
                for (int selectRow : selectRows) {
                    int optionalRow = parentModel.createNewEntryRow("yem_multiconfig");
//                    BigDecimal marketPrice = (BigDecimal) model.getValue("yem_marketprice", selectRow);
//                    BigDecimal marketRaisePrice = (BigDecimal) model.getValue("yem_marketraiseprice", selectRow);
//                    marketPrice = marketPriceExchangeRate.compareTo(BigDecimal.ZERO) > 0 ? marketPrice.multiply(marketPriceExchangeRate) : marketPrice;
//                    marketRaisePrice = marketRaisePriceExchangeRate.compareTo(BigDecimal.ZERO) > 0 ? marketRaisePrice.multiply(marketRaisePriceExchangeRate) : marketRaisePrice;
                    parentModel.setValue("yem_configurtype", "B", optionalRow);
                    parentModel.setValue("yem_configurname", model.getValue("yem_profilenamea", selectRow), optionalRow);
                    parentModel.setValue("yem_configurtypeen", model.getValue("yem_configure", selectRow), optionalRow);
                    parentModel.setValue("yem_configurtyperu",model.getValue("yem_ruconfigure_c",selectRow),optionalRow);
                    parentModel.setValue("yem_specification_o", model.getValue("yem_specification", selectRow), optionalRow);
//                    parentModel.setValue("yem_marketprice", marketPrice, optionalRow);
//                    parentModel.setValue("yem_marketraiseprice", marketRaisePrice, optionalRow);
                    parentModel.setValue("yem_unitsetnumber", model.getValue("yem_unitsetnumber", selectRow), optionalRow);
                    parentModel.setValue("yem_remarkss", model.getValue("yem_remarke", selectRow), optionalRow);
                    parentModel.setValue("yem_configentryid", model.getValue("yem_entryid", selectRow), optionalRow);
                    DynamicObject modelConfigR = (DynamicObject) model.getValue("yem_model_config_r", selectRow);
                    DynamicObject parentDataEntity = parentModel.getDataEntity(true);
                    if (YEM.isNotEmpty(modelConfigR)) {
                        parentModel.setValue("yem_cname_config", modelConfigR.getString("yem_standard_cname"), optionalRow);
                        parentModel.setValue("yem_ename_config", modelConfigR.getString("yem_standard_ename"), optionalRow);
                        parentModel.setValue("yem_runame_config", modelConfigR.getString("yem_standard_runame"), optionalRow);
                    }
                }
            }

        }
        view.sendFormAction(parentView);
        view.close();
    }
}