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

import kd.bos.bill.BillOperationStatus;
import kd.bos.bill.BillShowParameter;
import kd.bos.dataentity.RefObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.datamodel.ListSelectedRow;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.operate.FormOperate;
import kd.bos.list.BillList;
import kd.bos.list.ListShowParameter;
import kd.bos.list.plugin.AbstractListPlugin;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.botp.BFTrackerServiceHelper;
import kd.bos.servicehelper.workflow.WorkflowServiceHelper;
import kd.fi.er.business.utils.ErEntityTypeUtils;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 外办申请，
 */
public class DailyVehicleCusListPlugin 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());

        String confirmTip;
        switch (opKey) {
            case "unaudit":
                if (!this.checkBeforeTripChange(selectedDatas)) {
                    args.setCancel(true);
                    return;
                }
                break;
            case "nckd_tripinvoke":
                if (selectedDatas.size() > 1 || selectedDatas.size() == 0) {
                    this.getView().showTipNotification(ResManager.loadKDString("仅支持对单条外办申请单进行撤销变更。", "TripReqBillList_7", "fi-er-formplugin", new Object[0]));
                    args.setCancel(true);
                } else {
                    if (selectedDatas.size() == 1) {
                        ListSelectedRow row = args.getListSelectedData().get(0);
                        confirmTip = ((ListShowParameter)this.getView().getFormShowParameter()).getBillFormId();
                        DynamicObject item = QueryServiceHelper.queryOne(confirmTip, "nckd_ischange,billstatus", new QFilter[]{new QFilter("id", "=", row.getPrimaryKeyValue())});
                        if (!item.getBoolean("nckd_ischange")) {
                            this.getView().showTipNotification(ResManager.loadKDString("不满足操作条件：只有进行过变更的单据才允许撤销变更。", "TripReqBillList_11", "fi-er-formplugin", new Object[0]));
                            args.setCancel(true);
                            return;
                        }

                        if (!item.getString("billstatus").equals("A")) {
                            this.getView().showTipNotification(ResManager.loadKDString("操作条件不满足：只有单据状态为“暂存”的单据才可撤销变更。", "TripReqBillList_12", "fi-er-formplugin", new Object[0]));
                            args.setCancel(true);
                            return;
                        }
                    }
                }
        }

    }

    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String opKey = e.getOperateKey();

        if ("unaudit".equalsIgnoreCase(opKey)) {
            ListSelectedRowCollection selectedRows = this.getSelectedRows();
            Object selectId = selectedRows.get(0).getPrimaryKeyValue();

            OperationResult operationResult = e.getOperationResult();
            if (operationResult.isSuccess()) {
                BillShowParameter formShowParameter = new BillShowParameter();
                formShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                formShowParameter.setFormId(((ListShowParameter)this.getView().getFormShowParameter()).getBillFormId());
                formShowParameter.setBillStatus(BillOperationStatus.EDIT);
                formShowParameter.setPkId(selectId);
                this.getView().showForm(formShowParameter);
            }
        } else if ("nckd_tripinvoke".equalsIgnoreCase(opKey)) {
            ListSelectedRowCollection selectedRows = this.getSelectedRows();
            Object selectId = selectedRows.get(0).getPrimaryKeyValue();
            int row = selectedRows.get(0).getRowKey();
            Long workId = WorkflowServiceHelper.getProcessInstanceIdByBusinessKey(String.valueOf(selectId));
            List<Long> approveres = WorkflowServiceHelper.getApproverByBusinessKey(String.valueOf(selectId));
            if (workId != null && !workId.equals(0L) && !approveres.isEmpty()) {
                WorkflowServiceHelper.abandon(workId);
                BillList list = (BillList)this.getControl("billlistap");
                list.refresh();
            }

            OperationResult result = e.getOperationResult();
            if (result.isSuccess()) {
                this.getView().showSuccessNotification(ResManager.loadKDString("行程已成功撤销。", "TripReqBillList_9", "fi-er-formplugin", new Object[0]));
            } else {
                this.getView().showTipNotification(ResManager.loadKDString("行程撤销失败。", "TripReqBillList_10", "fi-er-formplugin", new Object[0]));
            }

            BillList list = (BillList)this.getControl("billlistap");
            list.refresh();
        }
    }


    private boolean checkBeforeTripChange(Set<Long> selectedDatas) {
        if (selectedDatas.size() > 1 || selectedDatas.size() == 0) {
            this.getView().showTipNotification(ResManager.loadKDString("仅支持对单条外办申请单进行行程变更。", "TripReqBillList_13", "fi-er-formplugin", new Object[0]));
            return false;
        } else {
            Long selectReqBillId = (Long)selectedDatas.stream().findFirst().get();
            String entityName = ((ListShowParameter)this.getView().getFormShowParameter()).getBillFormId();
            DynamicObject reqBill = QueryServiceHelper.queryOne(entityName, "billno,billstatus", new QFilter[]{new QFilter("id", "=", selectReqBillId)});
            if (reqBill == null) {
                this.getView().showErrorNotification(ResManager.loadKDString("数据库无法查询到数据，请刷新页面后尝试。", "TripAutoOpenedListPlugin_2", "fi-er-formplugin", new Object[0]));
                return false;
            } else if (!"E".equals(reqBill.get("billstatus")) ) {
                this.getView().showTipNotification(ResManager.loadKDString("只有“审核通过”的外办申请才能进行行程变更。", "TripReqBillList_14", "fi-er-formplugin", new Object[0]));
                return false;
            } else {
                Map<String, HashSet<Long>> targetBills = BFTrackerServiceHelper.findTargetBills(entityName, (Long[]) Collections.singleton(selectReqBillId).toArray(new Long[0]));
                if (targetBills.isEmpty()) {
                    return true;
                } else {
                    HashSet<Long> targetBillIds = (HashSet)targetBills.get("er_tripreimbursebill");
                    if (targetBillIds != null && !targetBillIds.isEmpty()) {
                        this.getView().showTipNotification(ResManager.loadKDString("所选的外办申请单存在已关联的差旅报销单，不允许变更行程。", "TripReqBillList_15", "fi-er-formplugin", new Object[0]));
                        return false;
                    } else {
                        if (ErEntityTypeUtils.isTripReqBillInter(entityName)) {
                            targetBillIds = (HashSet)targetBills.get("er_tripreimburse_cardgrid");
                            if (targetBillIds != null && !targetBillIds.isEmpty()) {
                                this.getView().showTipNotification(ResManager.loadKDString("所选的外办申请单存在已关联的差旅报销单，不允许变更行程。", "TripReqBillList_15", "fi-er-formplugin", new Object[0]));
                                return false;
                            }
                        }

                        return true;
                    }
                }
            }
        }
    }
}
