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.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.events.BizDataEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.BasedataProp;
import kd.bos.exception.KDBizException;
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 nckd.base.helper.CommonHelperUtils;

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

/**
 * 单据标识：对公报销单(nckd_er_publicreimbur_ext)
 * @author wanghaiwu_kd
 * @date 2025/04/28
 */
public class PublicReimburseBillFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener {
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);

        if(this.getModel().getProperty("expenseitem") != null) {
            BasedataEdit expenseitemF7 = (BasedataEdit) this.getControl("expenseitem");
            expenseitemF7.addBeforeF7SelectListener(this);
        }

        if(this.getModel().getProperty("nckd_expenseitem") != null) {
            BasedataEdit expenseitemF7ext = (BasedataEdit) this.getControl("nckd_expenseitem");
            expenseitemF7ext.addBeforeF7SelectListener(this);
        }

        if(this.getModel().getProperty("nckd_project") != null) {
            BasedataEdit projectF7ext = (BasedataEdit) this.getControl("nckd_project");
            projectF7ext.addBeforeF7SelectListener(this);
        }

        if(this.getModel().getProperty("nckd_acctitem") != null) {
            BasedataEdit acctitemF7ext = (BasedataEdit) this.getControl("nckd_acctitem");
            acctitemF7ext.addBeforeF7SelectListener(this);
        }
    }

    /*
     * 已代扣代缴设置，刘志华编写代码
     * */
    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);

        String fieldKey = e.getProperty().getName();

        if("nckd_expenseitem".equals(fieldKey)){
            DynamicObject newValue = (DynamicObject)e.getChangeSet()[0].getNewValue();
            if(EmptyUtils.isNotEmpty(newValue)){
                QFilter qFilter = new QFilter("nckd_expenseitem", QCP.in, newValue.getLong("id"));
                qFilter.and(new QFilter("status", QCP.equals, "C"));
                qFilter.and(new QFilter("enable", QCP.equals, "1"));
                if(this.getModel().getValue("costcompany") != null){
                    DynamicObject company = (DynamicObject) this.getModel().getValue("costcompany");
                    qFilter.and(new QFilter("nckd_org.id", QCP.equals, company.getLong("id")));
                }

                DynamicObject expenseitemInfo =BusinessDataServiceHelper.loadSingle("nckd_proxytax", qFilter.toArray());
                //已代扣代缴赋值
                if(this.getModel().getProperty("nckd_jywithhold") != null ){
                    if(EmptyUtils.isNotEmpty(expenseitemInfo)){
                        this.getModel().setValue("nckd_jywithhold",true);
                    } else {
                        this.getModel().setValue("nckd_jywithhold",false);
                    }
                }

                //是否分摊处理
                setIsShareValue();
            } else {
                this.getModel().setValue("nckd_jywithhold",false);
            }
        } else if("org".equals(fieldKey)){
            setIsShareValue();
        }
    }

    /**
     * 设置是否分摊     *
     */
    private void setIsShareValue(){
        DynamicObject dept = (DynamicObject) this.getModel().getValue("org");
        DynamicObject item = (DynamicObject) this.getModel().getValue("nckd_expenseitem");
        boolean isShare = false;
        if(dept != null && item != null){
            Long deptId = dept.getLong("id");
            item = BusinessDataServiceHelper.loadSingle(item.getPkValue(), item.getDynamicObjectType().getName(), "id,nckd_sharedep");
            DynamicObjectCollection sharedepts = item.getDynamicObjectCollection("nckd_sharedep");

            if(sharedepts != null && sharedepts.size() > 0){
                for(DynamicObject sharedept : sharedepts){
                    if(deptId.compareTo(sharedept.getLong("fbasedataid_id")) == 0){
                        isShare = true;
                        break;
                    }
                }
            }
        }

        this.getModel().setValue("isbeforeshare", isShare);
    }

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

        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        ListShowParameter showParameter = (ListShowParameter) evt.getFormShowParameter();
        ListFilterParameter filterParam = showParameter.getListFilterParameter();
        List<QFilter> qFilters = filterParam.getQFilters();

        DynamicObject expenseItem = (DynamicObject)this.getModel().getValue("nckd_expenseitem");

        if("expenseitem".equals(property) || "nckd_expenseitem".equals(property)) {
            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);
            }
        } else if("nckd_project".equals(property)){//项目
            if(expenseItem == null){
                throw new KDBizException(ResManager.loadKDString("请先维护费用类型！", "PublicReimburseBillFormPlugin_12", "em-formplugin", new Object[0]));
            }

            expenseItem = BusinessDataServiceHelper.loadSingle(expenseItem.getPkValue(), expenseItem.getDynamicObjectType().getName());
            DynamicObjectCollection projectKinds = expenseItem.getDynamicObjectCollection("nckd_projectkind");
            List<Long> idList = (List)projectKinds.stream().mapToLong((x) -> {
                return x.getLong("fbasedataid_id");
            }).boxed().collect(Collectors.toList());

            QFilter filter = new QFilter("group.id", QCP.in, idList);

            qFilters.add(filter);
        } else if("nckd_acctitem".equals(property)){//核算项目
            if(expenseItem == null){
                throw new KDBizException(ResManager.loadKDString("请先维护费用类型！", "PublicReimburseBillFormPlugin_12", "em-formplugin", new Object[0]));
            }

            expenseItem = BusinessDataServiceHelper.loadSingle(expenseItem.getPkValue(), expenseItem.getDynamicObjectType().getName());

            //取消，不找一级费用类型
//            expenseItem = getLevelExpenseItemInfo(expenseItem);

            QFilter filter = new QFilter("nckd_expenseitem.id", QCP.in, expenseItem.getLong("id"));

            qFilters.add(filter);
        }
    }

    /**
     * 查找一级费用项目
     * @param expenseItem
     * @return
     */
    private DynamicObject getLevelExpenseItemInfo(DynamicObject expenseItem){
        if(expenseItem.getDynamicObject("parent") != null){
            DynamicObject parentInfo = BusinessDataServiceHelper.loadSingle(expenseItem.getDynamicObject("parent").getPkValue(), expenseItem.getDynamicObjectType().getName());

            expenseItem = getLevelExpenseItemInfo(parentInfo);
        }

        return expenseItem;
    }

    @Override
    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);
            if(StringUtils.isNotEmpty(formId)) {
                this.getModel().setValue("nckd_pageid", formId);

                //【单据类型】字段，根据页面类型自动默认赋值
                Boolean haveBillType = this.getModel().getDataEntityType().getProperties().containsKey("nckd_billtypefield");
                if(haveBillType) {
                    //处理单据类型
                    QFilter f = new QFilter("number", "=", formId);
                    DynamicObject layoutInfo = BusinessDataServiceHelper.loadSingle("bos_formmeta", "id, number,name, basedatafield", f.toArray());

                    if (layoutInfo != null) {
                        DynamicObject billTypeInfo = CommonHelperUtils.queryBaseDynamicObject("bos_billtype", "layoutsolution", layoutInfo.getString("id"));
                        this.getModel().setValue("nckd_billtypefield", billTypeInfo);
                    }
                }
            }
        }

        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, masterid,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");
                    }
                }

                //根据页面类型找到费用类型,专项费用和培训申请时候自动填充费用类型   刘志华增加
                String viewtNumber = viewTypeCols[0].getString("number");
                if(viewtNumber.equals("1004")||viewtNumber.equals("1009")){
                    //根据页面类型查找费用类型
                    QFilter numberFilter = new QFilter("number", QCP.equals, viewtNumber);
                    DynamicObject payViewType = BusinessDataServiceHelper.loadSingle("nckd_payviewtype", numberFilter.toArray());
                    if(payViewType != null && payViewType.getDynamicObject("nckd_expenseitem") != null){
                        //费用项目赋值
                        this.getModel().setValue("nckd_expenseitem", payViewType.getDynamicObject("nckd_expenseitem"));


                        //费用明细中的费用项目
                        DynamicObjectCollection expenseentryentity = this.getModel().getEntryEntity("expenseentryentity");
                        if(expenseentryentity != null && expenseentryentity.size() > 0) {
                            this.getModel().setValue("expenseitem", payViewType.getDynamicObject("nckd_expenseitem"), 0);
                        }
                    }
                }
            }
        }
    }

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

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

        kd.bos.form.container.Container container = this.getView().getControl("advconap_contract");

        container.setCollapse(false);
    }
}