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

import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.exception.KDBizException;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.events.AfterDoOperationEventArgs;
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.servicehelper.operation.SaveServiceHelper;
import kd.bos.util.StringUtils;

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

/**
 * 交易明细指定
 * @author wanghaiwu_kd
 * @date 2026/01/05
 */
public class AssingDetailFormPlugin extends AbstractBillPlugIn implements BeforeF7SelectListener {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);

        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        Long companyId = (Long) customParams.get("companyId");

        QFilter qFilter = new QFilter("id", QCP.equals, companyId);
        DynamicObject company = BusinessDataServiceHelper.loadSingle("bos_org", qFilter.toArray());

        this.getModel().setValue("nckd_org", company);

        List<Long> billIds = (List<Long>) customParams.get("billIds");
        String entityName = (String) customParams.get("entityName");

        DynamicObjectType type = EntityMetadataCache.getDataEntityType(entityName);
        //根据pkid找到完整的对象
        DynamicObject[] billArray = BusinessDataServiceHelper.load(billIds.toArray(), type);
        DynamicObject bill = billArray[0];

        this.getModel().setValue("nckd_paybillno", bill.getString("billno"));
        this.getModel().setValue("nckd_currency", bill.getDynamicObject("currency"));
    }

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

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

    @Override
    public void beforeF7Select(BeforeF7SelectEvent evt) {
        String property = evt.getProperty().getName();

        ListShowParameter showParameter = (ListShowParameter) evt.getFormShowParameter();
        ListFilterParameter filterParam = showParameter.getListFilterParameter();
        List<QFilter> qFilters = filterParam.getQFilters();

        if("nckd_detail".equals(property)){
            DynamicObject company = (DynamicObject)this.getModel().getValue("nckd_org");
            if(company == null){
                throw new KDBizException(ResManager.loadKDString("请先维护所属组织！", "VehicleEditPlugin_12", "em-formplugin", new Object[0]));
            }
            Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
            List<Long> billIds = (List<Long>) customParams.get("billIds");
            String entityName = (String) customParams.get("entityName");

            DynamicObjectType type = EntityMetadataCache.getDataEntityType(entityName);
            //根据pkid找到完整的对象
            DynamicObject[] billArray = BusinessDataServiceHelper.load(billIds.toArray(), type);
            DynamicObject bill = billArray[0];

            DynamicObject currency = bill.getDynamicObject("currency");

            QFilter filter = new QFilter("nckd_company.id", QCP.not_in, company.getLong("id"));
            if("CNY".equals(currency.getString("number"))){
                BigDecimal actpayamt = bill.getBigDecimal("actpayamt");
                filter.and((new QFilter("nckd_debitamount", QCP.equals, actpayamt)).or(new QFilter("nckd_creditamount", QCP.equals, actpayamt)));
            }
//            filter.and(new QFilter("status", QCP.equals, "D"));//已付款
//            filter.and(new QFilter("bfj2_sourcebilltype", QCP.equals, " "));//手工单据

            qFilters.add(filter);
        }
    }


    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);

        IDataModel model = this.getView().getModel();
        String key = e.getProperty().getName();

        switch (key) {
            case "nckd_company":
                //凭证类型
//                model.setValue("bfj2_paybill", null);

                break;
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args) {
        super.afterDoOperation(args);

        String operateKey = args.getOperateKey();
        if (args.getOperationResult() != null && args.getOperationResult().isSuccess() && "nckd_assigndetail".equals(operateKey)) {
            //同步CBS交易明细 --------------------------
            //message 返回的提示信息
            String message = assignDetail();
            if (StringUtils.isNotEmpty(message)) {
                this.getView().showConfirm(message, MessageBoxOptions.OK);
                return;
            }

            Map<String, String> returnData = new HashMap(4);
            returnData.put("message", "success");
            this.getView().returnDataToParent(returnData);
            this.getView().close();
        }
    }

    public Long getTransdetailID(String payBillId){
        Long billId = Long.parseLong(payBillId);
        QFilter qf = new QFilter("id", QCP.equals, billId);
        DynamicObject billDyn = BusinessDataServiceHelper.loadSingle("cas_paybill", new QFilter[]{qf});
        String transdetailId = billDyn.getString("detailseqid");
        QFilter qf1 = new QFilter("billno", QCP.equals, transdetailId);
        DynamicObject transdetailDyn = BusinessDataServiceHelper.loadSingle("bei_transdetail", new QFilter[]{qf1});
        return transdetailDyn.getLong("id");
    }

    /**
     * 流水指定
     * @return
     */
    private String assignDetail(){
        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();

        List<Long> billIds = (List<Long>) customParams.get("billIds");
        String entityName = (String) customParams.get("entityName");

        DynamicObjectType type = EntityMetadataCache.getDataEntityType(entityName);
        //根据pkid找到完整的对象
        DynamicObject[] billArray = BusinessDataServiceHelper.load(billIds.toArray(), type);
        DynamicObject bill = billArray[0];

        boolean isassigndetail = bill.getBoolean("nckd_isassigndetail");
        if(isassigndetail){
            return "已手工指定过交易流水，请先撤销指定后再重新指定";
        }

        String detailno = bill.getString("detailseqid");
        if(StringUtils.isNotEmpty(detailno)){
            return "已存在关联的交易流水(" + detailno + ")，不允许手工指定";
        }

        if(this.getModel().getValue("nckd_detail") == null){
            return "交易流水不能为空";
        }

        DynamicObject detail = (DynamicObject)this.getModel().getValue("nckd_detail");
        String detailNO = detail.getString("number");

        QFilter qFilter = new QFilter("detailseqid", QCP.equals, detailNO);
        DynamicObject paybillInfo = BusinessDataServiceHelper.loadSingle("cas_paybill", new QFilter[]{qFilter});
        if(paybillInfo != null){
            return "交易流水(" + detailNO + ")与付款单(" + paybillInfo.getString("billno") + ")已匹配，不能指定";
        }
        //1、先校验付款单是否已存在下游凭证
        qFilter = new QFilter("id", QCP.equals, bill.getPkValue());
        bill = BusinessDataServiceHelper.loadSingle("cas_paybill", new QFilter[]{qFilter});

        //更新付款单字段
        bill.set("detailseqid", detailNO);
        bill.set("nckd_isassigndetail", true);

        SaveServiceHelper.update(new DynamicObject[]{bill});

        return null;
    }
}
