package com.yem.em.bd.etcmanual.dynamic;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.yem.em.utils.BaseDataFilterUtils;
import com.yem.em.utils.BigDecimalUtils;
import com.yem.em.utils.CarShopUtils;
import com.yem.em.utils.EmptyUtils;
import kd.bos.bill.BillShowParameter;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.Label;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.HyperLinkClickEvent;
import kd.bos.form.events.HyperLinkClickListener;
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.bos.servicehelper.user.UserServiceHelper;

/**
 * @author 夜子
 * @ClassName ReplacepartviewEdit
 * @description: 设备详情表单插件
 * @date 2023年07月26日
 * @version: 1.0
 */
public class ReplacepartviewEdit extends AbstractFormPlugin implements HyperLinkClickListener {

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> cusMap = showParameter.getCustomParams();
        if (null != cusMap && cusMap.size() > 0 && cusMap.containsKey("ecatalogId")) {
            Map<String, Object> ecatalogIded = (Map<String, Object>) cusMap.get("ecatalogId");
            Object ecatalogId = ecatalogIded.get("ecatalogId");
            DynamicObject ecatalog = BusinessDataServiceHelper.loadSingle(ecatalogId, "yem_em_ecatalog");
            if (null != ecatalog) {
//                DynamicObject material = ecatalog.getDynamicObject("yem_materiel");
//                material = BusinessDataServiceHelper.loadSingle(material.getPkValue(), "bd_material");
//                long materialid = Long.valueOf(material.getPkValue().toString());
                IDataModel model = this.getModel();
                model.setValue("yem_picture", ecatalog.get("yem_picture"));
                model.setValue("yem_defaults", ecatalog.getString("yem_partno"));
                model.setValue("yem_defaults1", ecatalog.getString("name"));
                model.setValue("yem_partcode", ecatalog.getString("yem_partno"));// 零件编码
                model.setValue("yem_partname", ecatalog.getString("name"));// 零件名称
                model.setValue("yem_specificationmodel", ecatalog.getString("yem_materielmodel"));// 规格型号
//                BigDecimal netweight = BigDecimalUtils.toBigDecimal(material.getBigDecimal("netweight"));
//                BigDecimal length = BigDecimalUtils.toBigDecimal(material.getBigDecimal("length"));
//                BigDecimal width = BigDecimalUtils.toBigDecimal(material.getBigDecimal("width"));
//                BigDecimal height = BigDecimalUtils.toBigDecimal(material.getBigDecimal("height"));
//                model.setValue("yem_kg", netweight.compareTo(BigDecimal.ZERO) == 0 ? "" : netweight);// 重量
//                model.setValue("yem_long", length.compareTo(BigDecimal.ZERO) == 0 ? "" : length);// 长
//                model.setValue("yem_width", width.compareTo(BigDecimal.ZERO) == 0 ? "" : width);// 宽
//                model.setValue("yem_high", height.compareTo(BigDecimal.ZERO) == 0 ? "" : height);// 高
                model.setValue("yem_unit", ecatalog.getDynamicObject("yem_unit"));// 单位
                model.setValue("yem_minpackage", ecatalog.getBigDecimal("yem_qty"));// 最小包装数
                model.setValue("yem_price", ecatalog.getBigDecimal("yem_price"));// 价格
                Map<String, List<String>> cxMap = new HashMap<String, List<String>>();
                // 适用性
                List<Long> list = new ArrayList<Long>();
                if (EmptyUtils.isNotEmpty(ecatalog.getString("yem_partno"))) {
                    QFilter qFilter = new QFilter("yem_partno", QCP.like, ecatalog.getString("yem_partno"));
                    QFilter qFilter1 = BaseDataFilterUtils.getBaseDataFilter("yem_em_ecatalog",
                            RequestContext.get().getOrgId());
                    DynamicObject[] ecatalogs = BusinessDataServiceHelper.load("yem_em_ecatalog", "id,number,name",
                            new QFilter[] { qFilter, qFilter1 });
                    if (ecatalogs.length > 0) {
                        for (DynamicObject dy : ecatalogs) {
                            dy = BusinessDataServiceHelper.loadSingle(ecatalog.getPkValue(), "yem_em_ecatalog");
                            if (list.contains(Long.valueOf(dy.getPkValue().toString()))) {
                                continue;
                            } else {
                                list.add(Long.valueOf(dy.getPkValue().toString()));
                            }
                            int rowIndex = this.getModel().createNewEntryRow("yem_entryentity");
                            DynamicObject ecataloggroup = dy.getDynamicObject("group");
                            if (ecataloggroup != null) {
                                ecataloggroup = BusinessDataServiceHelper.loadSingle(ecataloggroup.getPkValue(),
                                        "yem_em_ecataloggroup");
                                this.getModel().setValue("yem_partno", ecataloggroup.getString("yem_partno"), rowIndex);
                                this.getModel().setValue("yem_partsname", ecataloggroup.getString("name"), rowIndex);
                            }
                            String etcmanualid = dy.getString("yem_etcmanualid");
                            if (EmptyUtils.isNotEmpty(etcmanualid)) {
                                DynamicObject etcmanual = BusinessDataServiceHelper.loadSingle(etcmanualid,
                                        "yem_em_etcmanual");
                                if (etcmanual != null) {
                                    this.getModel().setValue("yem_modelno", etcmanual.getString("number"), rowIndex);
                                    this.getModel().setValue("yem_modelname", etcmanual.getString("name"), rowIndex);
                                    DynamicObject brand = etcmanual.getDynamicObject("yem_brand");
                                    if (brand != null) {
                                        this.getModel().setValue("yem_applicablebrand", brand.getString("name"),
                                                rowIndex);
                                        if (!cxMap.containsKey(brand.getString("name"))) {
                                            List<String> cxlist = new ArrayList<String>();
                                            if (!cxlist.contains(etcmanual.getString("name"))) {
                                                cxlist.add(etcmanual.getString("name"));
                                            }
                                            cxMap.put(brand.getString("name"), cxlist);
                                        } else {
                                            List<String> cxlist = cxMap.get(brand.getString("name"));
                                            if (!cxlist.contains(etcmanual.getString("name"))) {
                                                cxlist.add(etcmanual.getString("name"));
                                            }
                                            cxMap.remove(brand.getString("name"));
                                            cxMap.put(brand.getString("name"), cxlist);
                                        }
                                    }
                                }
                            }
                            this.getModel().setValue("yem_qty", dy.getBigDecimal("yem_qty").toString(), rowIndex);
                            this.getModel().setValue("yem_remark", dy.getString("yem_remark"), rowIndex);
                        }
                    }
                    if (cxMap.size() > 0) {
                        int index = 0;
                        for (String cxStr : cxMap.keySet()) {
                            if (index == 0) {
                                model.setValue("yem_brand", cxStr);
                                String cxStrs = String.join(";", cxMap.get(cxStr));
                                model.setValue("yem_model", cxStrs);
                            } else if (index == 1) {
                                model.setValue("yem_brand1", cxStr);
                                String cxStrs = String.join(";", cxMap.get(cxStr));
                                model.setValue("yem_model1", cxStrs);
                            } else {
                                continue;
                            }
                            index++;
                        }
                    }
                }

//                QFilter qFilter = new QFilter("yem_originalsystemcode", QCP.equals, ecatalog.getPkValue());
//                QFilter qFilter1 = BaseDataFilterUtils.getBaseDataFilter("yem_em_replaceparts",
//                        RequestContext.get().getOrgId());
//                DynamicObject[] replaceparts = BusinessDataServiceHelper.load("yem_em_replaceparts",
//                        "id,yem_originalsystemcode,yem_replacesystemcode,createtime",
//                        new QFilter[] { qFilter, qFilter1 });
//                if (null != replaceparts && replaceparts.length > 0) {
//                    for (int i = 0; i < replaceparts.length; i++) {
//                        DynamicObject replacepart = replaceparts[i];
//                        DynamicObject tp_oldecatalog = replacepart.getDynamicObject("yem_originalsystemcode");
//                        String old_name = tp_oldecatalog == null ? "" : tp_oldecatalog.getString("name");
//                        String old_number = tp_oldecatalog == null ? "" : tp_oldecatalog.getString("yem_partno");
//                        DynamicObject tp_newecatalog = replacepart.getDynamicObject("yem_replacesystemcode");
//                        String new_name = tp_newecatalog == null ? "" : tp_newecatalog.getString("name");
//                        String new_number = tp_newecatalog == null ? "" : tp_newecatalog.getString("yem_partno");
//                        Date createtime = replacepart.getDate("createtime");
//
//                        int rowIndex = model.createNewEntryRow("yem_entryentity1");
//                        model.setValue("yem_replacementpartcode", new_number, rowIndex);
//                        model.setValue("yem_replacementpartname", new_name, rowIndex);
//                        model.setValue("yem_oldpartcode", old_number, rowIndex);
//                        model.setValue("yem_oldpartname", old_name, rowIndex);
//                        model.setValue("yem_replacementdate", createtime, rowIndex);
//                    }
//                }
//
//                QFilter qFilter7 = new QFilter("materialentry.material.id", QCP.in, materialid);
//                QFilter qFilter8 = new QFilter("billstatus", QCP.in, "C");
//                DynamicObject[] applys = BusinessDataServiceHelper.load("pur_apply",
//                        "id,billno,billdate,yem_reapplyorg,purperson,materialentry,materialentry.material,materialentry.qty,materialentry.unit,materialentry.taxprice,materialentry.note",
//                        new QFilter[] { qFilter7, qFilter8 });
//                if (null != applys && applys.length > 0) {
//                    for (int i = 0; i < applys.length; i++) {
//                        DynamicObject apply = applys[i];
//                        String billno = apply.getString("billno");
//                        Date billdate = apply.getDate("billdate");
//                        DynamicObject tp_applydept = apply.getDynamicObject("yem_reapplyorg");
//                        String tp_applydept_name = tp_applydept == null ? "" : tp_applydept.getString("name");
//                        DynamicObject purperson = apply.getDynamicObject("purperson");
//                        String purperson_name = purperson == null ? "" : purperson.getString("name");
//                        // 采购数量
//                        DynamicObjectCollection materialentrys = apply.getDynamicObjectCollection("materialentry");
//                        for (int j = 0; j < materialentrys.size(); j++) {
//                            DynamicObject materialentry = materialentrys.get(j);
//                            DynamicObject purmaterial = materialentry.getDynamicObject("material");
//                            long purmaterialid = purmaterial.getLong("id");
//                            if (purmaterialid == materialid) {
//                                BigDecimal qty = BigDecimalUtils.toBigDecimal(materialentry.get("qty"));
//                                DynamicObject unit = materialentry.getDynamicObject("unit");
//                                String unit_name = unit == null ? "" : unit.getString("name");
//                                BigDecimal taxprice = materialentry.getBigDecimal("taxprice");
//                                String note = materialentry.getString("note");
//
//                                int rowIndex = model.createNewEntryRow("tp_entryentity2");
//                                model.setValue("tp_textfield14", billno, rowIndex);
//                                model.setValue("yem_replacementdate1", billdate, rowIndex);
//                                model.setValue("tp_textfield16", tp_applydept_name, rowIndex);
//                                model.setValue("tp_textfield17", purperson_name, rowIndex);
//                                model.setValue("tp_textfield18", qty, rowIndex);
//                                model.setValue("tp_textfield19", unit_name, rowIndex);
//                                model.setValue("yem_partcode0", taxprice, rowIndex);
//                                model.setValue("yem_partcode1", note, rowIndex);
//                            }
//                        }
//                    }
//                }
            }
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("yem_mycartflex", "yem_oftenbuyflex");
        EntryGrid grid = (EntryGrid) this.getControl("yem_entryentity1");
        grid.addHyperClickListener(this);
    }

    @Override
    public void click(EventObject evt) {

        final Control c = (Control) evt.getSource();
        String key = c.getKey().toLowerCase();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> cusMap = showParameter.getCustomParams();
        if (null != cusMap && cusMap.size() > 0 && cusMap.containsKey("ecatalogId")) {
            Map<String, Object> ecatalogIded = (Map<String, Object>) cusMap.get("ecatalogId");
            Object orgid = ecatalogIded.get("orgid");
            switch (key) {
                case "yem_mycartflex":// 加入购物车
                case "yem_oftenbuyflex":// 加入我的常买

//                    addGoods(evt, key, orgid.toString());
                    break;

                default:
                    break;
            }
        }
    }

    /**
     * 添加到购物车 添加到我的常买
     *
     * @param evt
     * @param key
     */
    private void addGoods(EventObject evt, String key, String orgid) {
        // 添加到我的购物车
        if (key.equals("yem_mycartflex") || key.equals("showcart")) {
            FormShowParameter showParameter = this.getView().getFormShowParameter();
            Map<String, Object> cusMap = showParameter.getCustomParams();
            if (null != cusMap && cusMap.size() > 0 && cusMap.containsKey("ecatalogId")) {
                String ecatalogId = cusMap.get("ecatalogId").toString();
                DynamicObject ecatalog = BusinessDataServiceHelper.loadSingle(ecatalogId, "yem_em_ecatalog");
                if (null != ecatalog) {
                    int count = CarShopUtils.insertCarShop(ecatalog, BigDecimal.ONE,
                            UserServiceHelper.getCurrentUserId(), orgid);
                    if (count > 0) {
                        // this.getView().showSuccessNotification("加入购物车成功！");
                        this.getView().showSuccessNotification(
                                ResManager.loadKDString("加入购物车成功！", "ReplacepartviewEdit_0", "bfcl_equipment"));
                        int count2 = CarShopUtils.SelectCarShop(UserServiceHelper.getCurrentUserId(), orgid);
                        String parentpageid = this.getPageCache().get("parentpageid");
                        if (parentpageid != null) {
                            IFormView childView = this.getView().getView(parentpageid);
                            Label lab = childView.getControl("yem_kg:");
                            lab.setText(count2 + "");
                            this.getView().sendFormAction(childView);
                        }

                    } else {
                        // this.getView().showErrorNotification("加入购物车失败！");
                        this.getView().showErrorNotification(
                                ResManager.loadKDString("加入购物车失败！", "ReplacepartviewEdit_1", "bfcl_equipment"));
                    }
                } else {
                    // this.getView().showErrorNotification("商品未维护");
                    this.getView().showErrorNotification(
                            ResManager.loadKDString("商品未维护", "ReplacepartviewEdit_2", "bfcl_equipment"));

                }
            }
        }

        // 添加到我的常买
        if (key.equals("yem_oftenbuyflex") || key.equals("oftenbuy")) {
            FormShowParameter showParameter = this.getView().getFormShowParameter();
            Map<String, Object> cusMap = showParameter.getCustomParams();
            if (null != cusMap && cusMap.size() > 0 && cusMap.containsKey("ecatalogId")) {
                String ecatalogId = cusMap.get("ecatalogId").toString();
                List<Map<String, Object>> pklist = new ArrayList<>();
                Map<String, Object> map = new HashMap<>();
                long orgId = RequestContext.getOrCreate().getOrgId();
                if (ecatalogId != null) {
                    map.put("goodsId", ecatalogId);
                    map.put("orgId", String.valueOf(orgId));
                    pklist.add(map);
                }
                long currentUserId = UserServiceHelper.getCurrentUserId();

                int result = CarShopUtils.myOftenBuy(pklist, currentUserId);
                if (result > 0) {
                    this.getView().showTipNotification(
                            ResManager.loadKDString("已成功添加到您的常买中！", "ReplacepartviewEdit_3", "bfcl_equipment"));
                } else {
                    this.getView().showTipNotification(
                            ResManager.loadKDString("您的常买中已存在选中商品！", "ReplacepartviewEdit_4", "bfcl_equipment"));
                }
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> cusMap = showParameter.getCustomParams();
        if (null != cusMap && cusMap.size() > 0 && cusMap.containsKey("ecatalogId")) {
            Map<String, Object> ecatalogIded = (Map<String, Object>) cusMap.get("ecatalogId");
            Object orgid = ecatalogIded.get("orgid");
            switch (operateKey) {
                case "showcart":// 加入购物车图标操作
                case "oftenbuy":// 加入我的常买图标操作
//                    addGoods(e, operateKey, orgid.toString());
                    break;

                default:
                    break;
            }

        }
    }

    @Override
    public void hyperLinkClick(HyperLinkClickEvent hyclick) {
        String name = hyclick.getFieldName();
        if (name.equals("yem_replacementpartcode")) {
            String billno = (String) this.getView().getModel().getValue("yem_replacementpartcode",
                    hyclick.getRowIndex());
            BillShowParameter billShowParameter = new BillShowParameter();
            billShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
            QFilter qFilter = new QFilter("newpartitem.yem_partno", QCP.equals, billno);
            DynamicObject apply = BusinessDataServiceHelper.loadSingle("yem_em_replaceparts", "id,number,newpartitem",
                    new QFilter[] { qFilter });
            billShowParameter.setPkId(apply.getPkValue());
            billShowParameter.setFormId("yem_em_replaceparts");
            this.getView().showForm(billShowParameter);
        }
    }

}
