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

import com.yem.wm.utils.OrgFilterUtils;
import com.yem.wm.utils.RequestEAS;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.IFormView;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.operation.OperationServiceHelper;

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

public class TransFerOrderForm extends AbstractBillPlugIn implements BeforeF7SelectListener {

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String key = e.getOperateKey();
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        OperationResult operationResult = e.getOperationResult();

        if (key.equals("syneas")) {
            if (YEM.isNotEmpty(operationResult)) {
                view.invokeOperation("refresh");
            }
        }
        if (key.equals("unsyneas")) {
            if (YEM.isNotEmpty(operationResult)) {
                view.invokeOperation("refresh");
            }
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("yem_syneas");
        //监听
        BasedataEdit yem_entryoutwarehouse = this.getControl("yem_entryoutwarehouse");
        yem_entryoutwarehouse.addBeforeF7SelectListener(this);
        BasedataEdit yem_entryoutposition = this.getControl("yem_entryoutposition");
        yem_entryoutposition.addBeforeF7SelectListener(this);
        BasedataEdit yem_entryinwarehouse = this.getControl("yem_entryinwarehouse");
        yem_entryinwarehouse.addBeforeF7SelectListener(this);
        //调入库位
        BasedataEdit yem_entryinposition = this.getControl("yem_entryinposition");
        yem_entryinposition.addBeforeF7SelectListener(this);
        //供应方库存组织
        BasedataEdit yem_supstockorg = this.getControl("yem_supstockorg");
        yem_supstockorg.addBeforeF7SelectListener(this);

        //供应方财务组织
        BasedataEdit supfinorg = this.getControl("yem_supfinorg");
        //供应方库存组织
        BasedataEdit supstockorg = this.getControl("yem_supstockorg");
        //需求方财务组织
        BasedataEdit cusfinorg = this.getControl("yem_cusfinorg");
        //需求方库存组织
        BasedataEdit cusstockorg = this.getControl("yem_cusstockorg");
        //调出部门
        BasedataEdit outdept = this.getControl("yem_outdept");
        //调入部门
        BasedataEdit indept = this.getControl("yem_indept");

        supfinorg.addBeforeF7SelectListener(this);
        supstockorg.addBeforeF7SelectListener(this);
        cusfinorg.addBeforeF7SelectListener(this);
        cusstockorg.addBeforeF7SelectListener(this);
        outdept.addBeforeF7SelectListener(this);
        indept.addBeforeF7SelectListener(this);
    }

    @Override
    public void itemClick(ItemClickEvent evt) {
        super.itemClick(evt);
        String itemKey = evt.getItemKey();
//        if ("yem_syneas".equals(itemKey)) {
//            DynamicObject dataEntity = this.getModel().getDataEntity();
//            DynamicObject[] dataEntitys = new DynamicObject[]{dataEntity};
//            try {
//                OperationServiceHelper.executeOperate("syneas", "yem_transferorder", dataEntitys, OperateOption.create());
//                this.getView().updateView();
//            } catch (Exception e) {
//                this.getView().updateView();
//                this.getView().showErrorNotification(e.getMessage());
//            }
//        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate) args.getSource();
        String key = formOperate.getOperateKey();
        DynamicObject obj = this.getModel().getDataEntity(true);
        List<Integer> list = new ArrayList<>();
        if (key.equals("syneas") || "submit".equals(key) || "getprice1".equals(key)) {
            DynamicObjectCollection entrys = (DynamicObjectCollection) obj.get("yem_es_materialinfo");
            Date yemBizdate = obj.getDate("yem_bizdate");
            DynamicObject inorg = obj.getDynamicObject("yem_cusfinorg");
            if (inorg == null) {
                //提示
                this.getView().showErrorNotification("请填写【需求方财务组织】！");
                return;
            }
            String inOrgNum = inorg.getString("number");
            BigDecimal yem_exrate = obj.getBigDecimal("yem_exrate") == null ? BigDecimal.ONE : (BigDecimal) obj.getBigDecimal("yem_exrate");
            BigDecimal yem_amount = BigDecimal.ZERO;
            BigDecimal yem_amountbase = BigDecimal.ZERO;
            int i = 0;
            for (DynamicObject entry : entrys) {
                i++;
                BigDecimal fprice = BigDecimal.ZERO;

//                if ("A".equals(entry.getString("yem_impactprice"))) {
//                    continue;
//                }
                String businesssort = entry.getString("yem_businesssort");
                String impactprice = entry.getString("yem_impactprice");
                if ("Z".equals(businesssort) && "A".equals(impactprice)) {
                    fprice = new BigDecimal("0.01");
                    entry.set("yem_price", fprice);
                    entry.set("yem_pricetax", fprice);//价格获取赋值=含税单价
                    //单价=含税单价/（1+税率） 6位
                    BigDecimal yem_taxrate = entry.getBigDecimal("yem_taxrate") == null ? BigDecimal.ZERO : entry.getBigDecimal("yem_taxrate");
                    BigDecimal yem_price1 = fprice.divide(BigDecimal.ONE.add(yem_taxrate), 6, RoundingMode.HALF_UP);
                    entry.set("yem_price", yem_price1);
                    //价税合计 = 含税单价*数量
                    BigDecimal yem_qty = entry.getBigDecimal("yem_qty") == null ? BigDecimal.ZERO : entry.getBigDecimal("yem_qty");
                    BigDecimal yem_amttax = fprice.multiply(yem_qty).setScale(2, RoundingMode.HALF_UP);
                    entry.set("yem_amttax", yem_amttax);
                    //金额=单价*数量
                    BigDecimal yem_amt = yem_price1.multiply(yem_qty).setScale(2, RoundingMode.HALF_UP);
                    entry.set("yem_amt", yem_amt);
                    //税额=价税合计-金额;
                    BigDecimal yem_amounttax = yem_amttax.subtract(yem_amt);
                    entry.set("yem_amounttax", yem_amounttax);
                    //实际单价=单价
                    entry.set("yem_realityprice", yem_price1);
                    //实际含税单价=含税单价
                    entry.set("yem_realitypricetax", fprice);
                    //所有本位币字段，对应字段*汇率，金额保留6位，含税正常取，尾零不显示
                    //金额本位币yem_locamt
                    BigDecimal yem_locamt = yem_amt.multiply(yem_exrate).setScale(6, RoundingMode.HALF_UP);
                    entry.set("yem_locamt", yem_locamt);
                    //税额本位币yem_amountfield1
                    entry.set("yem_amountfield1", yem_amounttax.multiply(yem_exrate).setScale(6, RoundingMode.HALF_UP));
                    //价税合计本位币yem_baseamttax
                    entry.set("yem_baseamttax", yem_amttax.multiply(yem_exrate).setScale(6, RoundingMode.HALF_UP));
                    //金额汇总
                    yem_amount = yem_amount.add(yem_amt);
                    //金额本位币汇总
                    yem_amountbase = yem_amountbase.add(yem_locamt);
                    continue;
                }


                //如果是赠品不获取价格
                if (entry.getBoolean("yem_gift")) {
                    continue;
                }
                String materialNum = (String) entry.get("yem_materiel.number");
                DynamicObject outorg = entry.getDynamicObject("yem_shippersalesorg");
                if (outorg == null) {
                    //提示
                    int row = i;
                    this.getView().showErrorNotification("第【" + row + "】行，请填写【发货方销售组织】！");
                    continue;
                }
                String outorgNum = outorg.getString("number");
                BigDecimal yem_realitypricetax = entry.getBigDecimal("yem_realitypricetax");
                List<Map<String, Object>> transferCostPrice = RequestEAS.getTransferCostPrice(materialNum, inOrgNum, outorgNum, yemBizdate);
                if (transferCostPrice.size() == 0 && yem_realitypricetax.compareTo(BigDecimal.ZERO) == 0) {
                    list.add(i);
                }
                for (Map<String, Object> stringObjectMap : transferCostPrice) {
                    fprice = (BigDecimal) stringObjectMap.get("fprice");
                }
                if (fprice.compareTo(BigDecimal.ZERO) == 0) {
                    if ("Z".equals(businesssort)) {
                        fprice = new BigDecimal("0.01");
                    }
                }
//                if (fprice.compareTo(BigDecimal.ZERO) > 0) {
//                }
                entry.set("yem_price", fprice);
                entry.set("yem_pricetax", fprice);//价格获取赋值=含税单价
                //单价=含税单价/（1+税率） 6位
                BigDecimal yem_taxrate = entry.getBigDecimal("yem_taxrate") == null ? BigDecimal.ZERO : entry.getBigDecimal("yem_taxrate");
                BigDecimal yem_price1 = fprice.divide(BigDecimal.ONE.add(yem_taxrate), 6, RoundingMode.HALF_UP);
                entry.set("yem_price", yem_price1);
                //价税合计 = 含税单价*数量
                BigDecimal yem_qty = entry.getBigDecimal("yem_qty") == null ? BigDecimal.ZERO : entry.getBigDecimal("yem_qty");
                BigDecimal yem_amttax = fprice.multiply(yem_qty).setScale(2, RoundingMode.HALF_UP);
                entry.set("yem_amttax", yem_amttax);
                //金额=单价*数量
                BigDecimal yem_amt = yem_price1.multiply(yem_qty).setScale(2, RoundingMode.HALF_UP);
                entry.set("yem_amt", yem_amt);
                //税额=价税合计-金额;
                BigDecimal yem_amounttax = yem_amttax.subtract(yem_amt);
                entry.set("yem_amounttax", yem_amounttax);
                //实际单价=单价
                entry.set("yem_realityprice", yem_price1);
                //实际含税单价=含税单价
                entry.set("yem_realitypricetax", fprice);
                //所有本位币字段，对应字段*汇率，金额保留6位，含税正常取，尾零不显示
                //金额本位币yem_locamt
                BigDecimal yem_locamt = yem_amt.multiply(yem_exrate).setScale(6, RoundingMode.HALF_UP);
                entry.set("yem_locamt", yem_locamt);
                //税额本位币yem_amountfield1
                entry.set("yem_amountfield1", yem_amounttax.multiply(yem_exrate).setScale(6, RoundingMode.HALF_UP));
                //价税合计本位币yem_baseamttax
                entry.set("yem_baseamttax", yem_amttax.multiply(yem_exrate).setScale(6, RoundingMode.HALF_UP));
                //金额汇总
                yem_amount = yem_amount.add(yem_amt);
                //金额本位币汇总
                yem_amountbase = yem_amountbase.add(yem_locamt);
            }
            //设置是否存在调拨成本价
            boolean b = true;
            for (int j = 0; j < entrys.size(); j++) {

                if (!entrys.get(j).getBoolean("yem_gift")) {

                    if (entrys.get(j).getBigDecimal("yem_pricetax").compareTo(BigDecimal.ZERO) < 1) {
                        b = false;
                    }
                }

            }
            if (entrys.size() == 0) {
                b = false;
            }
            this.getModel().setValue("yem_isextprice", b);
            if (list.size() == 0) {
                this.getView().showSuccessNotification("获取调拨价格成功！");
                getView().updateView("yem_es_materialinfo");
            } else {
                if ("syneas".equals(key)) {
                    args.setCancel(true);
                    this.getView().showTipNotification("第" + list.toString() + "获取调拨价格失败！无法同步EAS！");
                    getView().updateView("yem_es_materialinfo");
                } else {
                    this.getView().showTipNotification("第" + list.toString() + "获取调拨价格失败！");
                    getView().updateView("yem_es_materialinfo");
                }
            }
            getView().invokeOperation("save");
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        if (name.equals("yem_impactprice")) {
            setImpactPrise();
        }
        //发货库存组织
        if ("yem_impactprice".equals(name)) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            //发货库存组织
            Object yemDeliveryinventoryorg = this.getModel().getValue("yem_deliveryinventoryorg", row);
            if (yemDeliveryinventoryorg == null) {
                this.getModel().setValue("yem_entryoutwarehouse", null, row);
                this.getModel().setValue("yem_deliverywarehouse", null, row);
                this.getModel().setValue("yem_supwarehouse", null, row);
            }
            //调出仓库
        } else if ("yem_entryoutwarehouse".equals(name)) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            Object yem_entryoutwarehouse = this.getModel().getValue("yem_entryoutwarehouse", row);
            if (yem_entryoutwarehouse == null) {
                //调出库位
                this.getModel().setValue("yem_entryoutposition", null, row);
            }
            //收货库存组织
        } else if ("yem_receinventoryorg".equals(name)) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            Object yem_receinventoryorg = this.getModel().getValue("yem_receinventoryorg", row);
            if (yem_receinventoryorg == null) {
                //调入仓库
                this.getModel().setValue("yem_entryinwarehouse", null, row);
            }
            //调入仓库
        } else if ("yem_entryinwarehouse".equals(name)) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            Object yem_entryinwarehouse = this.getModel().getValue("yem_entryinwarehouse", row);
            if (yem_entryinwarehouse == null) {
                //调入库位
                this.getModel().setValue("yem_entryinposition", null, row);
            }
        }
    }

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

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

    /**
     * 根据分录中影响调拨价汇总到单据头
     */
    private void setImpactPrise() {
        IDataModel model = this.getModel();
        DynamicObjectCollection entryEntity = model.getEntryEntity("yem_es_materialinfo");
        Set<String> set = new HashSet<>();
        for (DynamicObject dynamicObject : entryEntity) {
            String impactprice = dynamicObject.getString("yem_impactprice");
            set.add(impactprice);
        }

        if (set .contains("A")) {
            model.setValue("yem_impactprices", "A");
        } else {
            model.setValue("yem_impactprices", "B");
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        if ("yem_entryoutwarehouse".equals(name)) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
            //发货库存组织
            Object yemDeliveryinventoryorg = this.getModel().getValue("yem_deliveryinventoryorg", row);
            if (yemDeliveryinventoryorg == null) {
                this.getView().showTipNotification("请选择发货库存组织");
                e.setCancel(true);
                return;
            }
            DynamicObject deliveryinventoryorg = (DynamicObject) yemDeliveryinventoryorg;
            QFilter filter = new QFilter("useorg.number", QCP.equals, deliveryinventoryorg.getString("number"));
            ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();
            List<QFilter> qFilters = formShowParameter.getListFilterParameter().getQFilters();
            qFilters.add(filter);
        } else
            //调出库位 的 仓库等于调出仓库
            if ("yem_entryoutposition".equals(name)) {
                int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
                //调出仓库
                Object yem_entryoutwarehouse = this.getModel().getValue("yem_entryoutwarehouse", row);
                if (yem_entryoutwarehouse == null) {
                    this.getView().showTipNotification("请选择调出仓库");
                    e.setCancel(true);
                    return;
                }
                DynamicObject entryoutwarehouse = (DynamicObject) yem_entryoutwarehouse;
                QFilter filter = new QFilter("group.number", QCP.equals, entryoutwarehouse.getString("number"));
                ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();
                List<QFilter> qFilters = formShowParameter.getListFilterParameter().getQFilters();
                qFilters.add(filter);
            } else
                //调入仓库 的 库存组织 等于 收货库存组织 yem_receinventoryorg
                if ("yem_entryinwarehouse".equals(name)) {
                    int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
                    //收货库存组织
                    Object yem_receinventoryorg = this.getModel().getValue("yem_receinventoryorg", row);
                    if (yem_receinventoryorg == null) {
                        this.getView().showTipNotification("请选择收货库存组织");
                        e.setCancel(true);
                        return;
                    }
                    DynamicObject receinventoryorg = (DynamicObject) yem_receinventoryorg;
                    QFilter filter = new QFilter("useorg.number", QCP.equals, receinventoryorg.getString("number"));
                    ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();
                    List<QFilter> qFilters = formShowParameter.getListFilterParameter().getQFilters();
                    qFilters.add(filter);
                } else
                    //调入库位 的 仓库 等于 调入仓库 yem_receinventoryorg
                    if ("yem_entryinposition".equals(name)) {
                        int row = this.getModel().getEntryCurrentRowIndex("yem_es_materialinfo");
                        //收货库存组织
                        Object yem_entryinwarehouse = this.getModel().getValue("yem_entryinwarehouse", row);
                        if (yem_entryinwarehouse == null) {
                            this.getView().showTipNotification("请选择调入仓库");
                            e.setCancel(true);
                            return;
                        }
                        DynamicObject entryinwarehouse = (DynamicObject) yem_entryinwarehouse;
                        QFilter filter = new QFilter("group.number", QCP.equals, entryinwarehouse.getString("number"));
                        ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();
                        List<QFilter> qFilters = formShowParameter.getListFilterParameter().getQFilters();
                        qFilters.add(filter);
                    }/*else
            //供应方库存组织 的上级编码 等于 供应方财务组织
            if ("yem_supstockorg".equals(name)){
                //供应方财务组织
                Object yem_supfinorg = this.getModel().getValue("yem_supfinorg");
                if (yem_supfinorg == null){
                    this.getView().showTipNotification("请选择供应方财务组织");
                    e.setCancel(true);
                    return;
                }
                DynamicObject supfinorg = (DynamicObject) yem_supfinorg;
                List<Long> ids = new ArrayList<>();
                ids.add(supfinorg.getLong("id"));
                List<Long> allSubordinateOrgs = OrgUnitServiceHelper.getAllSubordinateOrgs(OrgViewType.Inventory, ids, true);
                QFilter filter = new QFilter("id", QCP.in, allSubordinateOrgs);

                ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();
                List<QFilter> qFilters = formShowParameter.getListFilterParameter().getQFilters();
                qFilters.add(filter);
        }*/

        // yem_supfinorg
        // yem_supstockorg
        // yem_cusfinorg
        // yem_cusstockorg
        // yem_outdept
        // yem_indept

        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity();
        DynamicObject org = dataEntity.getDynamicObject("org");
        // 供应方财务组织                       供应方库存组织                       需求方财务组织                     需求方库存组织                       调出部门                       调入部门
        if ("yem_supfinorg".equals(name) || "yem_supstockorg".equals(name) || "yem_cusfinorg".equals(name) || "yem_cusstockorg".equals(name) || "yem_outdept".equals(name) || "yem_indept".equals(name)) {
            e.addCustomQFilter(OrgFilterUtils.getOrgFilter(org));
        }
    }

}
