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

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.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 付款处理，指定交易明细
 * @author wanghaiwu_kd
 * @date 2026/01/05
 */
public class PaymentAssignDetailListPlugin extends AbstractListPlugin {
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);

        Object source = args.getSource();

        String opKey = ((AbstractOperate)source).getOperateKey();
        Set<Long> selectedDatas = (Set)args.getListSelectedData().stream().map((data) -> {
            return (Long)data.getPrimaryKeyValue();
        }).collect(Collectors.toSet());

        switch (opKey) {
            case "nckd_assigndetail":
                if (selectedDatas.size() == 0) {
                    this.getView().showTipNotification(ResManager.loadKDString("请选择要指定交易明细的单据。", "PaymentAssignDetailListPlugin_7", "fi-cas-formplugin", new Object[0]));
                    args.setCancel(true);
                    return;
                } else if (selectedDatas.size() > 1) {
                    this.getView().showTipNotification(ResManager.loadKDString("只能选择一张单据指定交易明细。", "PaymentAssignDetailListPlugin_7", "fi-cas-formplugin", new Object[0]));
                    args.setCancel(true);
                    return;
                } else {
                    QFilter qFilter = new QFilter("id", QCP.in, selectedDatas);
                    qFilter.and(new QFilter("billstatus", QCP.not_equals2, getAssginBillStatus()));

                    boolean exists = QueryServiceHelper.exists(getEntityName(), qFilter.toArray());
                    if (exists) {
                        this.getView().showTipNotification(ResManager.loadKDString("选择的单据中存在不是" + getAssginBillStatusName() + "状态的单据，不允许指定交易明细。", "PaymentAssignDetailListPlugin_7", "fi-cas-formplugin", new Object[0]));
                        args.setCancel(true);
                        return;
                    }

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

                    boolean isassigndetail = bill.getBoolean("nckd_isassigndetail");
                    if(isassigndetail){
                        this.getView().showTipNotification(ResManager.loadKDString("已手工指定过交易流水，请先撤销指定后再重新指定", "PaymentAssignDetailListPlugin_7", "fi-cas-formplugin", new Object[0]));
                        args.setCancel(true);
                        return;
                    }

                    String detailno = bill.getString("detailseqid");
                    if(StringUtils.isNotEmpty(detailno)){
                        this.getView().showTipNotification(ResManager.loadKDString("已存在关联的交易流水(" + detailno + ")，不允许手工指定", "PaymentAssignDetailListPlugin_7", "fi-cas-formplugin", new Object[0]));
                        args.setCancel(true);
                        return;
                    }
                }
                break;
            case "nckd_unassigndetail":

                break;
        }
    }

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

        String opKey = args.getOperateKey();

        if("nckd_assigndetail".equalsIgnoreCase(opKey)) {
            ListSelectedRowCollection selectedRows = this.getSelectedRows();
            List<Long> idList = new ArrayList<>();
            for(ListSelectedRow row : selectedRows){
                idList.add((Long)row.getPrimaryKeyValue());
            }
            QFilter qFilter = new QFilter("id", QCP.in, idList);

            DynamicObject[] billInfos = BusinessDataServiceHelper.load(getEntityName(), "id, org", qFilter.toArray());

            List<Long> companyIds = new ArrayList<>();
            for(DynamicObject bill : billInfos){
                if(!companyIds.contains(bill.getDynamicObject("org").getLong("id"))){
                    companyIds.add(bill.getDynamicObject("org").getLong("id"));
                }
            }

            if(companyIds.size() > 1){
                this.getView().showTipNotification(ResManager.loadKDString("选择的单据中存在多个资金组织，不允许指定。", "PaymentAssignDetailListPlugin_7", "fi-cas-formplugin", new Object[0]));
            } else {

                OperationResult operationResult = args.getOperationResult();
                if (operationResult.isSuccess()) {
                    FormShowParameter showForm = new FormShowParameter();
                    showForm.setFormId("nckd_assigndetail");
                    showForm.getOpenStyle().setShowType(ShowType.Modal);

                    showForm.setCustomParam("entityName", getEntityName());
                    showForm.setCustomParam("companyId", billInfos[0].getDynamicObject("org").getLong("id"));
                    showForm.setCustomParam("billIds", idList);

                    showForm.setCloseCallBack(new CloseCallBack(this, "nckd_assigndetail"));
                    this.getView().showForm(showForm);
                }
            }
        } else if("nckd_unassigndetail".equalsIgnoreCase(opKey)) {
            OperationResult operationResult = args.getOperationResult();
            operationResult.setShowMessage(false);
            String message = operationResult.getMessage();

            List<IOperateInfo> errorInfos = operationResult.getAllErrorOrValidateInfo();
            boolean isSuccess = operationResult.isSuccess();
            if(errorInfos.size()> 0){
                operationResult.setSuccess(false);
                StringBuffer msg = new StringBuffer();
                for (IOperateInfo errInfo: errorInfos) {
                    msg.append(errInfo.getMessage()).append("\r\n");
                }
                message = message + "\r\n" + msg.toString();
            }

            if(StringUtils.isEmpty(message)){
                this.getView().showSuccessNotification("取消成功！");
            } else {
                this.getView().showErrorNotification(message);
            }

            this.getView().invokeOperation("refresh");
        }
    }

    public void closedCallBack(ClosedCallBackEvent event) {
        super.closedCallBack(event);
        Map returnData;
        if ("nckd_assigndetail".equals(event.getActionId())) {
            returnData = (Map) event.getReturnData();
            if (returnData != null && returnData.get("message") != null) {
                this.getView().showSuccessNotification(ResManager.loadKDString("交易流水指定成功。", "PaymentAssignDetailListPlugin_7", "fi-cas-formplugin", new Object[0]));
                this.getView().invokeOperation("refresh");
            }
        }
    }

    public String getEntityName(){
        return "cas_paybill";
    }

    public String getAssginBillStatus(){
        return "D";
    }

    public String getAssginBillStatusName(){
        return "已付款";
    }
}
