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

import com.alibaba.fastjson.JSONObject;
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.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 RetrofittingFormPlugIn extends AbstractFormPlugin implements Plugin {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView view = this.getView();
        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_marketprice", "yem_marketraiseprice", "yem_quotecurrency");
        JSONObject modelObj = (JSONObject)customParams.get("modelObj");
        List<Long> ids = (List<Long>)customParams.get("ids");
        DynamicObject load = BusinessDataServiceHelper.loadSingle(modelObj.getLong("id"), "yem_bd_mechanical");
        DynamicObjectCollection mechanical_c = load.getDynamicObjectCollection("yem_bd_mechanical_a");
        for(DynamicObject mechanical : mechanical_c){
            Long id = mechanical.getLong("id");
            if(ids.contains(id)){
                continue;
            }
            int createRow = model.createNewEntryRow("yem_retrofittingentry");
            model.setValue("yem_profilenamea",mechanical.getString("yem_profilenamea"),createRow);
            model.setValue("yem_configure",mechanical.getString("yem_configures"),createRow);
            model.setValue("yem_remarke",mechanical.getString("yem_remarka"),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<>();
        String billTypeNumber = (String)customParams.get("billTypeNumber");
        String operationNumber = (String)customParams.get("operationNumber");
        Long productsId = (Long)customParams.get("productsId");
        Long productModelId = (Long)customParams.get("productModelId");
        List<Long> ids = (List<Long>)customParams.get("ids");
        qFilters.add(new QFilter("yem_bd_products",QCP.equals,productsId));
//        qFilters.add(new QFilter("yem_basicmodel.yem_model",QCP.equals,productModelId));
        if("yem_es_salesorder_ZJ".equals(billTypeNumber)){
            qFilters.add(new QFilter("yem_billtype.number",QCP.equals,"yem_pricelibrary_ZJ"));
        }
        if("yem_es_salesorder_PJ".equals(billTypeNumber)){
            qFilters.add(new QFilter("yem_billtype.number",QCP.equals,"yem_pricelibrary_PJ"));
        }
        qFilters.add(new QFilter("billstatus",QCP.equals,"C"));
//        String selectfields = DynamicObjectUtil.getSelectfields("yem_pricelibrary",false);
//        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_pricelibrary","yem_basicmodel",false);
//        selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_pricelibrary","yem_optional",false);
        DynamicObject priceLibrary = BusinessDataServiceHelper.loadSingle("yem_pricelibrary", "id", qFilters.toArray(new QFilter[qFilters.size()]));
        if(priceLibrary != null){
            priceLibrary = BusinessDataServiceHelper.loadSingle(priceLibrary.getPkValue(),priceLibrary.getDynamicObjectType().getName());
            model.setValue("yem_quotecurrency",priceLibrary.getDynamicObject("yem_quotecurrency"));
            DynamicObjectCollection basicModels = priceLibrary.getDynamicObjectCollection("yem_basicmodel");
            for(DynamicObject basicModel : basicModels){
                DynamicObject modelObj = basicModel.getDynamicObject("yem_model");
                Long modelId = modelObj != null?modelObj.getLong("id"):0L;
                if(productModelId.equals(modelId)){
                    DynamicObjectCollection optionals = basicModel.getDynamicObjectCollection("yem_retrofitting");
                    for(DynamicObject optional : optionals){
                        Long id = optional.getLong("id");
                        if(ids.contains(id)){
                            continue;
                        }
                        int entryRow = model.createNewEntryRow("yem_retrofittingentry");
                        model.setValue("yem_profilenamea",optional.getString("yem_profilename_rt"),entryRow);
                        model.setValue("yem_configure",optional.getString("yem_englishnames"),entryRow);
                        model.setValue("yem_marketprice",optional.getBigDecimal("yem_salesprice_rt"),entryRow);
                        model.setValue("yem_marketraiseprice",optional.getBigDecimal("yem_salesmarkup_rt"),entryRow);
                        model.setValue("yem_remarke",optional.getString("yem_remark_rt"),entryRow);
                            model.setValue("yem_entryid",optional.getPkValue(),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_retrofittingentry");
                int[] selectRows = optionalEntry.getSelectRows();
                for (int selectRow : selectRows) {
                    int optionalRow = parentModel.createNewEntryRow("yem_retrofitting");
                    parentModel.setValue("yem_profilename_rt", model.getValue("yem_profilenamea", selectRow), optionalRow);
                    parentModel.setValue("yem_englishnames", model.getValue("yem_configure", selectRow), optionalRow);
                    parentModel.setValue("yem_remark_rt", model.getValue("yem_remarke", selectRow), optionalRow);
                    parentModel.setValue("yem_entryid_rt", model.getValue("yem_entryid", selectRow), optionalRow);
                }
            }
            if("B".equals(type)){
                Object exrateTable = parentModel.getValue("yem_exratetable");
                Object sourceCurrency = model.getValue("yem_quotecurrency");
                Object targetCurrency = parentModel.getValue("yem_currency");
                Date exrateDate = (Date) parentModel.getValue("yem_exratedate");
                BigDecimal exchangeRate = YEM.getExchangeRate(exrateTable, sourceCurrency, targetCurrency, exrateDate);
                EntryGrid retrofittingEntry = view.getControl("yem_retrofittingentry");
                int[] selectRows = retrofittingEntry.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 = exchangeRate.compareTo(BigDecimal.ZERO) > 0?marketPrice.multiply(exchangeRate):marketPrice;
                    marketRaisePrice = exchangeRate.compareTo(BigDecimal.ZERO) > 0?marketRaisePrice.multiply(exchangeRate):marketRaisePrice;
                    parentModel.setValue("yem_configurtype","C",optionalRow);
                    parentModel.setValue("yem_configurname",model.getValue("yem_profilenamea",selectRow),optionalRow);
                    parentModel.setValue("yem_configurtypeen",model.getValue("yem_configure",selectRow),optionalRow);
                    parentModel.setValue("yem_marketprice",marketPrice,optionalRow);
                    parentModel.setValue("yem_marketraiseprice",marketRaisePrice,optionalRow);
                    parentModel.setValue("yem_remarkss",model.getValue("yem_remarke",selectRow),optionalRow);
                    parentModel.setValue("yem_configentryid",model.getValue("yem_entryid",selectRow),optionalRow);
                }
            }

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