package nckd.jimin.jyyy.fi.plugin.form;

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.events.BizDataEventArgs;
import kd.bos.entity.property.BasedataProp;
import kd.bos.ext.fi.plugin.ArApConvert.util.EmptyUtils;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.list.ListFilterParameter;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.util.StringUtils;

import java.util.Arrays;
import java.util.EventObject;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 单据标识：公共单据插件，处理费用项目过滤问题。
 * @author wanghaiwu_kd
 * @date 2025/05/06
 */
public class ExpenseItemFilterFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener {
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);

        Boolean havaExpenseItem = this.getModel().getDataEntityType().getProperties().containsKey("nckd_expenseitem");
        if(havaExpenseItem) {
            BasedataEdit expenseitemF7ext = (BasedataEdit) this.getControl("nckd_expenseitem");
            expenseitemF7ext.addBeforeF7SelectListener(this);
        }

        BasedataEdit expenseitemF7 = (BasedataEdit) this.getControl("expenseitem");
        expenseitemF7.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent evt) {
        String property = evt.getProperty().getName();
        String entityId = ((BasedataProp) evt.getProperty()).getBaseEntityId();
        int curRowIndex = evt.getRow();

        if ("expenseitem".equals(property) || "nckd_expenseitem".equals(property)) {
            ListShowParameter showParameter = (ListShowParameter) evt.getFormShowParameter();
            ListFilterParameter filterParam = showParameter.getListFilterParameter();
            List<QFilter> qFilters = filterParam.getQFilters();

            Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
            if (customParams.get("nckd_viewTypeFilter") != null) {
                QFilter viewTypeFilter = QFilter.fromSerializedString(customParams.get("nckd_viewTypeFilter").toString());

                qFilters.add(viewTypeFilter);
            } else if(this.getModel().getValue("nckd_payviewtypemul") != null){
                DynamicObjectCollection collection = (DynamicObjectCollection)this.getModel().getValue("nckd_payviewtypemul");
                List<Long> idList = (List)collection.stream().mapToLong((x) -> {
                    return x.getLong("fbasedataid_id");
                }).boxed().collect(Collectors.toList());

                QFilter viewTypeFilter = new QFilter("nckd_payviewtype.id", QCP.in, idList);

                qFilters.add(viewTypeFilter);
            }
        }
    }

    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);

        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        BillShowParameter parameter = new BillShowParameter();
        String formId = "";
        if(EmptyUtils.isNotEmpty(customParams.get("formId"))){
            formId =customParams.get("formId").toString();
            parameter.setFormId(formId);

            Boolean isExists = this.getModel().getDataEntityType().getProperties().containsKey("nckd_pageid");
            if(isExists) {
                this.getModel().setValue("nckd_pageid", formId);
            }
        }

        if(customParams.get("viewType") != null){
            String[] typeStrings = customParams.get("viewType").toString().split(",");

            QFilter qFilter = new QFilter("number", QCP.in, typeStrings);

            DynamicObject[] viewTypeCols = BusinessDataServiceHelper.load("nckd_payviewtype", "id, number, name", qFilter.toArray());
            if(viewTypeCols != null && viewTypeCols.length > 0){
                //页面类型赋值
                this.getModel().setValue("nckd_payviewtype", viewTypeCols[0]);

                List<Long> idList = Arrays.stream(viewTypeCols)
                        .map(type ->  type.getLong("id"))
                        .collect(Collectors.toList());
                Object[] basedataIds = idList.toArray();
                //页面类型多选赋值
                this.getModel().setValue("nckd_payviewtypemul", basedataIds);

                /***
                 * 当页面类型为 资金类时，往来类型为  内部公司
                 * turborao 2025/05/15
                 */
                for(DynamicObject viewType : viewTypeCols){
                    if("资金类".equals(viewType.getString("name"))) {
                        this.getModel().setValue("billpayertype", "bos_org");
                    }
                }
            }
        }
    }

    @Override
    public void createNewData(BizDataEventArgs e) {
        super.createNewData(e);
    }
}
