package shkd.repc.rebm.formplugin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.entity.LocaleString;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.AppInfo;
import kd.bos.entity.AppMenuInfo;
import kd.bos.entity.AppMetadataCache;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.exception.KDException;
import kd.bos.form.*;
import kd.bos.form.container.Tab;
import kd.bos.form.container.TabPage;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Toolbar;
import kd.bos.form.control.events.CellClickEvent;
import kd.bos.form.control.events.CellClickListener;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.field.AmountEdit;
import kd.bos.form.field.DecimalEdit;
import kd.bos.form.field.TextEdit;
import kd.bos.portal.util.OpenPageUtils;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.sdk.plugin.Plugin;
import kd.svc.control.events.AppNavigationMenuEvent;

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

/**
 * 单据界面插件
 */
public class DecisionJumpToConPlanPlugin extends AbstractBillPlugIn implements CellClickListener {

    /*
     * 定标
     * 1.点击‘变更合约规划’按钮跳转到成本管理的 目标成本调整
     * 2.将采购明细中的规划金额 < 供应商信息的最终价 所对应的采购项目带到目标成本调整中
     * */

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        EntryGrid entryGrid = this.getControl("bottomsection");
        entryGrid.addCellClickListener(this);
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IDataModel model = this.getModel();
        String conPlanAdjust = (String) model.getValue("qeug_conplan_adjust");// 关联合约规划调整
        String changeSection = (String) model.getValue("qeug_change_section");// 参与变更标段
        if (!conPlanAdjust.isEmpty() && changeSection.contains("1")) {
            IFormView view = this.getView();
            view.setVisible(true, "qeug_planamount");
            view.setVisible(true, "qeug_botcontrolamount");

            DecimalEdit planAmount = getControl("planamount");// 规划金额(含税)
            AmountEdit controlAmount = getControl("botcontrolamount");// 采购控制金额(含税)

            planAmount.setCaption(new LocaleString("规划金额(变更后)"));
            controlAmount.setCaption(new LocaleString("采购控制金额(变更后)"));

            Map<String, IDataEntityProperty> allFields = this.getModel().getDataEntityType().getAllFields();
            IDataEntityProperty field1 = allFields.get("planamount");
            IDataEntityProperty field2 = allFields.get("botcontrolamount");
            field1.getDisplayName().setLocaleValue("规划金额(变更后)");
            field2.getDisplayName().setLocaleValue("采购控制金额(变更后)");
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs eventArgs) {
        String operateKey = eventArgs.getOperateKey();
        if ("changeplan".equals(operateKey)) {
            IFormView mainView = this.getView().getMainView();
            IDataModel model = this.getModel();
            DynamicObjectCollection bidSections = model.getEntryEntity("bidsection");// 标段
            DynamicObjectCollection bottomSections = model.getEntryEntity("bottomsection");// 标底标段

            if (bidSections != null && bottomSections != null) {
                for (DynamicObject bidSection : bidSections) {
                    BigDecimal finalPriceSum = new BigDecimal(0);
                    int seq = bidSection.getInt("seq");
                    DynamicObjectCollection supplierEntries = bidSection.getDynamicObjectCollection("supplierentry");// 定标供应商
                    if (supplierEntries == null) continue;
                    for (DynamicObject supplierEntry : supplierEntries) {
                        if (supplierEntry.getBoolean("isrecommended")) {// 是否中标单位
                            BigDecimal finalPrice = supplierEntry.getBigDecimal("finalprice");
                            finalPriceSum = finalPriceSum.add(finalPrice);
                        }
                    }

                    if (finalPriceSum.equals(new BigDecimal(0))) continue;

                    DynamicObject project = null;
                    BigDecimal controlAmountSum = new BigDecimal(0);
                    for (DynamicObject bottomSection : bottomSections) {
                        int bottomSeq = bottomSection.getInt("seq");
                        if (seq == bottomSeq) {
                            DynamicObjectCollection bottomEntries = bottomSection.getDynamicObjectCollection("bottomentry");// 采购明细
                            if (bottomEntries != null) {
                                if (!bottomEntries.isEmpty())
                                    project = bottomEntries.get(0).getDynamicObject("botpurentryproject");

                                for (DynamicObject bottomEntry : bottomEntries) {
                                    BigDecimal controlAmount = bottomEntry.getBigDecimal("botcontrolamount");// 采购控制金额(含税)
                                    controlAmountSum = controlAmountSum.add(controlAmount);
                                }
                            }
                        }
                    }

                    if (finalPriceSum.compareTo(controlAmountSum) >= 1) {
                        jumpRECOS();
                        if (project != null) {
                            generateAimAdjustBill(mainView, model.getDataEntity().getLong("id"), project.getString("number"), seq);
                        }
                    }
                }
            }
        }
    }

    private void jumpRECOS() {
        IFormView mainView = this.getView().getMainView();
        Tab tab = mainView.getControl("tabap");

        boolean result = false;
        String key = "";
        List<Control> items = tab.getItems();
        for (Control item : items) {
            TabPage tabPage = (TabPage) item;
            if (tabPage.getKey().contains("recos")) {
                result = true;
                key= tabPage.getKey();
            }
        }

        if (!result) {
            FormShowParameter formShowParameter = new FormShowParameter();
            formShowParameter.setAppId("recos");
            formShowParameter.getOpenStyle().setShowType(ShowType.NewTabPage);
            formShowParameter.getOpenStyle().setTargetKey("tabap");
            formShowParameter.setCustomParam("formId", "recos_conplan");
            formShowParameter.setCustomParam("appImageUrl", "icons/pc/application/fdc_cbgl_48_48.png");
            formShowParameter.setCustomParam("appid", "recos");
            formShowParameter.setFormId("recos_apphome");
            formShowParameter.setCaption("成本管理");
            formShowParameter.setPageId("recos" + mainView.getPageId());
            mainView.showForm(formShowParameter);
            getView().sendFormAction(mainView);
        } else {
            tab.activeTab(key);
        }
    }

    private void generateAimAdjustBill(IFormView mainView,Long id, String purProjectNum, int seqNum) {
        String appPageID = "recos" + mainView.getPageId();
        IFormView appPageView = mainView.getViewNoPlugin(appPageID);

        BillShowParameter billShowParameter = new BillShowParameter();
        billShowParameter.setFormId("recos_aimadjust");
        billShowParameter.setBillStatusValue(0);
        billShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
        billShowParameter.getOpenStyle().setTargetKey("_submaintab_");

        billShowParameter.setCustomParam("decision_id", id);
        billShowParameter.setCustomParam("purproject_number", purProjectNum);
        billShowParameter.setCustomParam("seqNum", seqNum);

        appPageView.showForm(billShowParameter);
        getView().sendFormAction(appPageView);
    }

    @Override
    public void cellClick(CellClickEvent cellClickEvent) {
        String fieldKey = cellClickEvent.getFieldKey();
        if ("botsectionname".equals(fieldKey)) {
            int rowIndex = this.getModel().getEntryCurrentRowIndex("bottomsection");
            String changeSection = (String) this.getModel().getValue("qeug_change_section");// 参与变更标段
            if (!changeSection.contains(String.valueOf(rowIndex + 1))) {
                IFormView view = this.getView();
                view.setVisible(false, "qeug_planamount");
                view.setVisible(false, "qeug_botcontrolamount");

                DecimalEdit planAmount = getControl("planamount");// 规划金额(含税)
                AmountEdit controlAmount = getControl("botcontrolamount");// 采购控制金额(含税)

                planAmount.setCaption(new LocaleString("规划金额(含税)"));
                controlAmount.setCaption(new LocaleString("采购控制金额(含税)"));

                Map<String, IDataEntityProperty> allFields = this.getModel().getDataEntityType().getAllFields();
                IDataEntityProperty field1 = allFields.get("planamount");
                IDataEntityProperty field2 = allFields.get("botcontrolamount");
                field1.getDisplayName().setLocaleValue("规划金额(含税)");
                field2.getDisplayName().setLocaleValue("采购控制金额(含税)");
            } else {
                IFormView view = this.getView();
                view.setVisible(true, "qeug_planamount");
                view.setVisible(true, "qeug_botcontrolamount");

                DecimalEdit planAmount = getControl("planamount");// 规划金额(含税)
                AmountEdit controlAmount = getControl("botcontrolamount");// 采购控制金额(含税)

                planAmount.setCaption(new LocaleString("规划金额(变更后)"));
                controlAmount.setCaption(new LocaleString("采购控制金额(变更后)"));

                Map<String, IDataEntityProperty> allFields = this.getModel().getDataEntityType().getAllFields();
                IDataEntityProperty field1 = allFields.get("planamount");
                IDataEntityProperty field2 = allFields.get("botcontrolamount");
                field1.getDisplayName().setLocaleValue("规划金额(变更后)");
                field2.getDisplayName().setLocaleValue("采购控制金额(变更后)");
            }
        }
    }

    @Override
    public void cellDoubleClick(CellClickEvent cellClickEvent) {

    }
}