package com.yem.wm.es.storagetrans.dynamic;

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.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
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.*;

/**
 * 动态表单
 */
public class BackCustomsCodeEdit extends AbstractFormPlugin implements BeforeF7SelectListener, Plugin {
    @Override
    public void afterCreateNewData(EventObject e)
    {
        super.afterCreateNewData(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        //过滤出当前单据的所有报关分类去重后的值
        DynamicObjectCollection entryRows = parentModel.getEntryEntity("yem_es_materialinfo");//商品明细
        Set<Student> yem_customclass = new HashSet<>();//报关分类 海关编码 申请要素去重
        for (DynamicObject entryRow : entryRows) {
            String businesssort = entryRow.getString("yem_businesssort");
            if ("P".equals(businesssort) && entryRow.getDynamicObject("yem_customclass") != null) {
                yem_customclass.add(new Student(entryRow.getDynamicObject("yem_customclass"), entryRow.getDynamicObject("yem_hscode")));
            }
        }
        for (Student yem_customclass_s : yem_customclass) {
            DynamicObject customclass = yem_customclass_s.getCustomclass();
            DynamicObject hscode = yem_customclass_s.getHscode();
//            DynamicObject declarationele = yem_customclass_s.getDeclarationele();
            ArrayList<Integer> seqList = new ArrayList<>();
            for (DynamicObject entryRow : entryRows) {
                String businesssort = entryRow.getString("yem_businesssort");
                if ("P".equals(businesssort) &&
                        entryRow.getDynamicObject("yem_customclass") == customclass &&
                        entryRow.getDynamicObject("yem_hscode") == hscode) {
                    seqList.add(entryRow.getInt("seq"));
                }
            }
            String seqListstring = seqList.toString();
            int entryRow_S = model.createNewEntryRow("yem_creditentry");
            model.setValue("yem_customclass", customclass, entryRow_S);
            model.setValue("yem_hscode", hscode, entryRow_S);
//            model.setValue("yem_declarationele", declarationele, entryRow_S);

//            if (declarationele != null) {
//                model.setValue("yem_actualfilingele", declarationele.getString("name"), entryRow_S);
//            }


            model.setValue("yem_seqliststring", seqListstring, entryRow_S);
            DynamicObject dynamicObject = entryRows.get(seqList.get(0) - 1);
            model.setValue("yem_actualfilingele", dynamicObject.getString("yem_actualfilingele"), entryRow_S);
            model.setValue("yem_piecesnum", dynamicObject.getBigDecimal("yem_piece"), entryRow_S);
            model.setValue("yem_netweightsum", dynamicObject.getBigDecimal("yem_netweightsum"), entryRow_S);
            model.setValue("yem_grossweightsum", dynamicObject.getBigDecimal("yem_grossweightsum"), entryRow_S);
            model.setValue("yem_volume", dynamicObject.getBigDecimal("yem_volm3sum"), entryRow_S);

            DynamicObject parentDataEntity = parentModel.getDataEntity(true);

            if ("yem_es_storagetrans".equals(parentDataEntity.getDataEntityType().getName())) {
                model.setValue("yem_sumwholenum", parentModel.getValue("yem_sumwholenum"));
                model.setValue("yem_sumwholew", parentModel.getValue("yem_sumwholew"));
                model.setValue("yem_sumwholecube", parentModel.getValue("yem_sumwholecube"));
                model.setValue("yem_sumparts", parentModel.getValue("yem_sumparts"));
                model.setValue("yem_summountingweight", parentModel.getValue("yem_summountingweight"));
                model.setValue("yem_summountingcube", parentModel.getValue("yem_summountingcube"));
                model.setValue("yem_sumunits", parentModel.getValue("yem_sumunits"));
                model.setValue("yem_sumweight", parentModel.getValue("yem_sumweight"));
                model.setValue("yem_sumcube", parentModel.getValue("yem_sumcube"));
            } else {
                view.setVisible(false, "yem_basicinformation");
                view.setVisible(false ,"yem_piecesnum");
                view.setVisible(false, "yem_grossweightsum");
                view.setVisible(false, "yem_netweightsum");
                view.setVisible(false, "yem_volume");
            }
        }
    }


    @Override
    public void registerListener(EventObject e) {
        this.addClickListeners("btnok");
        BasedataEdit customClass = this.getControl("yem_hscode");
        customClass.addBeforeF7SelectListener(this);
        BasedataEdit declarationele = this.getControl("yem_declarationele");
        declarationele.addBeforeF7SelectListener(this);
    }

    public void propertyChanged(PropertyChangedArgs e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        ChangeData changeData = e.getChangeSet()[0];
        String name = e.getProperty().getName();
        int rowIndex = changeData.getRowIndex();
        switch (name) {
            case "yem_hscode" ://海关编码
                DynamicObject yem_customclass = (DynamicObject)model.getValue("yem_customclass", rowIndex);
                DynamicObject yem_hscode = (DynamicObject)model.getValue("yem_hscode", rowIndex);
                if(yem_hscode!=null)
                {
                    DynamicObject[] declarationEles = BusinessDataServiceHelper.load("yem_bd_declarationele", "yem_year,id",
                            new QFilter[]{new QFilter("yem_customclass", QCP.equals, yem_customclass.getPkValue()),
                                    new QFilter("yem_hscodebase", QCP.equals, yem_hscode.getPkValue())},"yem_year desc");
                    if(declarationEles.length>0)
                    {
                        //于当前年份相等则赋值
                        Date yemYear = declarationEles[0].getDate("yem_year");
                        Calendar nowCalendar = Calendar.getInstance();
                        nowCalendar.setTime(new Date());
                        int nowYear = nowCalendar.get(Calendar.YEAR);
                        Calendar tempCalendar = Calendar.getInstance();
                        if (yemYear!=null){
                            tempCalendar.setTime(yemYear);
                            int tempYear = tempCalendar.get(Calendar.YEAR);
                            if(nowYear == tempYear){
                                model.setValue("yem_declarationele",declarationEles[0],rowIndex);
                            }else {
                                model.setValue("yem_declarationele",null,rowIndex);
                            }
                        }
                    }

                }
                else {
                    this.getModel().setValue("yem_declarationele",null,rowIndex);
                }
                break;
            case "yem_declarationele"://申报要素
                DynamicObject declarationele = (DynamicObject) this.getModel().getValue("yem_declarationele", rowIndex);
                if(declarationele != null && YEM.isNotEmpty(this.getModel().getValue("yem_actualfilingele"))){
                    String string = declarationele.getString("name");
                    this.getModel().setValue("yem_actualfilingele",string,rowIndex);
                }else {
                    this.getModel().setValue("yem_actualfilingele",null,rowIndex);
                }

        }
    }



    @Override
    public void click(EventObject e) {
        super.click(e);
        Control control = (Control) e.getSource();
        String key = control.getKey();
        if ("btnok".equals(key)) {
            IFormView view = this.getView();
            IDataModel model = this.getModel();
            IFormView parentView = view.getParentView();
            IDataModel parentmodel = parentView.getModel();
            int creditEntryRowCount = model.getEntryRowCount("yem_creditentry");//获取动态表单明细
            for (int i = 0; i < creditEntryRowCount; i++) {
                DynamicObject yem_customclass = (DynamicObject) model.getValue("yem_customclass", i);//报关分类
                DynamicObject yem_hscode = (DynamicObject) model.getValue("yem_hscode", i);//海关编码
                DynamicObject yem_declarationele = (DynamicObject) model.getValue("yem_declarationele", i);//申请要素
                String yem_seqliststring = (String) model.getValue("yem_seqliststring", i);//申请要素
                Object yem_actualfilingele = model.getValue("yem_actualfilingele", i);//实现申请要素
                BigDecimal piecesnum = (BigDecimal) model.getValue("yem_piecesnum", i);
                BigDecimal netweightsum = (BigDecimal) model.getValue("yem_netweightsum", i);
                BigDecimal grossweightsum = (BigDecimal) model.getValue("yem_grossweightsum", i);
                BigDecimal volume = (BigDecimal) model.getValue("yem_volume", i);
                String[] split = yem_seqliststring.replace(" ", "").replace("[", "").replace("]", "").split(",");
                for (String splits : split) {
                    parentmodel.setValue("yem_pieceqty", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_piece", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_grossweight", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_grossweightsum", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_netweight", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_netweightsum", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_long", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_high", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_wide", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_vol", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_volm3", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_volm3sum", null, Integer.parseInt(splits) - 1);
                    parentmodel.setValue("yem_piece", null, Integer.parseInt(splits) - 1);
                }


                String billType = parentmodel.getDataEntityType().getName();

                for (String index : split) {

                    int idx = Integer.parseInt(index) - 1;

                    parentmodel.setValue("yem_hscode", yem_hscode, idx);
                    parentmodel.setValue("yem_declareunit", YEM.isNotEmpty(yem_hscode)?yem_hscode.get("yem_legalfirst"):null, idx);
                    parentmodel.setValue("yem_declarationele", yem_declarationele, idx);
                    parentmodel.setValue("yem_actualfilingele",yem_actualfilingele, idx);
                    parentmodel.setValue("yem_customclass", yem_customclass, idx);

                    if ("yem_es_salesorder".equals(billType) || "yem_shippingdetails".equals(billType)) {

                        parentmodel.setValue("yem_piece", piecesnum, idx);
                        parentmodel.setValue("yem_netweightsum", netweightsum, idx);
                        parentmodel.setValue("yem_grossweightsum", grossweightsum, idx);
                        parentmodel.setValue("yem_volm3sum", volume, idx);
                    }
                }

                if ("yem_es_storagetrans".equals(billType)) {

                    int rowIndex = Integer.parseInt(split[0]) - 1;

                    parentmodel.setValue("yem_piece", piecesnum, rowIndex);
                    parentmodel.setValue("yem_netweightsum", netweightsum, rowIndex);
                    parentmodel.setValue("yem_grossweightsum", grossweightsum, rowIndex);
                    parentmodel.setValue("yem_volm3sum", volume, rowIndex);
                }
            }
            OperationResult a = parentView.invokeOperation("save");
            view.sendFormAction(parentView);
            view.close();
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        int row = e.getRow();
        if (name.equals("yem_hscode")) {
            selectF7hscode(e);
        }
        if (name.equals("yem_declarationele")) {
            selectF7declarationele(e);
        }
    }

    public void selectF7hscode(BeforeF7SelectEvent e) {
        int row = e.getRow();
        List<Long> ids = new ArrayList();
        IDataModel model = this.getModel();
        DynamicObject yem_customclass = (DynamicObject) model.getValue("yem_customclass", row);
        if (YEM.isNotEmpty(yem_customclass)) {
            DynamicObject[] declarationEles = BusinessDataServiceHelper.load("yem_bd_declarationele", "id,yem_hscodebase",
                    new QFilter[]{new QFilter("yem_customclass", QCP.equals, yem_customclass.getPkValue())});
            for (DynamicObject declarationEle : declarationEles) {
                DynamicObject hsCodebase = declarationEle.getDynamicObject("yem_hscodebase");
                if (YEM.isNotEmpty(hsCodebase)) {
                    ids.add(hsCodebase.getLong("id"));
                }
            }
        }
        e.addCustomQFilter(new QFilter("id", QCP.in, ids));
    }

    public void selectF7declarationele(BeforeF7SelectEvent e) {
        int row = e.getRow();
        List<Long> ids = new ArrayList();
        IDataModel model = this.getModel();
        DynamicObject yem_hscode = (DynamicObject)model.getValue("yem_hscode", row);
        if(YEM.isNotEmpty(yem_hscode)){
            e.addCustomQFilter(new QFilter("yem_hscodebase", QCP.equals,yem_hscode.getPkValue()));
        }
        DynamicObject yem_customclass = (DynamicObject)model.getValue("yem_customclass", row);
        if(YEM.isNotEmpty(yem_customclass)){
            e.addCustomQFilter(new QFilter("yem_customclass", QCP.equals,yem_customclass.getPkValue()));
        }
    }

}

class Student {
    DynamicObject customclass;//报关分类
    DynamicObject hscode;//海关编码
//    DynamicObject declarationele;//申报要素
    ArrayList seqList = new ArrayList();//序号

    public Student(DynamicObject customclass, DynamicObject hscode) {
        this.customclass = customclass;
        this.hscode = hscode;
//        this.declarationele = declarationele;
    }

    public Student(DynamicObject customclass, DynamicObject hscode, ArrayList seqList) {
        this.customclass = customclass;
        this.hscode = hscode;
//        this.declarationele = declarationele;
        this.seqList = seqList;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Student)) return false;
        Student student = (Student) o;
        return Objects.equals(getCustomclass(), student.getCustomclass()) && Objects.equals(getHscode(), student.getHscode());
    }

    @Override
    public int hashCode() {
        return Objects.hash(getCustomclass(), getHscode());
    }

    public DynamicObject getCustomclass() {
        return customclass;
    }

    public void setCustomclass(DynamicObject customclass) {
        this.customclass = customclass;
    }

    public DynamicObject getHscode() {
        return hscode;
    }

    public void setHscode(DynamicObject hscode) {
        this.hscode = hscode;
    }

//    public DynamicObject getDeclarationele() {
//        return declarationele;
//    }
//
//    public void setDeclarationele(DynamicObject declarationele) {
//        this.declarationele = declarationele;
//    }

    public ArrayList getSeqList() {
        return seqList;
    }

    public void setSeqList(ArrayList seqList) {
        this.seqList = seqList;
    }
}


