package shkd.repc.iwork;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.api.WorkflowElement;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;

import java.util.List;

/**
 * 设置流程参与人插件
 */
public class IWorkParticipantPlugin implements IWorkflowPlugin {

    private static final Log logger = LogFactory.getLog(IWorkParticipantPlugin.class);

    /**
     * recon_contractbill(合同)-印章管理员
     * recon_payreqbill(付款申请)-资金出纳和园区会计
     * recon_designchgbill(涉及变更)  供应商:designunit(设计单位)
     * recon_chgauditorderbill(工程指令) 供应商:construnit(施工单位)
     * recon_rewarddeductbill(奖励扣款) 供应商存在分录:rewarddeductentry(奖惩单分录) 供应商:entry_supplier(供应商)
     */
    @Override
    public List<Long> calcUserIds(AgentExecution execution) {
        List<Long> currentApprover = execution.getCurrentApprover(); // 获取当前节点的审批人

        String businessKey = execution.getBusinessKey(); // 单据的BusinessKey(业务ID)
        String entityNumber = execution.getEntityNumber(); // 单据实体编码
        DynamicObject entity = BusinessDataServiceHelper.loadSingle(businessKey, entityNumber);

        if (entity != null) {
            switch (entityNumber) {
                case "recon_designchgbill":
                    getApprover(entity, currentApprover, "designunit");
                    break;
                case "recon_chgauditorderbill":
                    getApprover(entity, currentApprover, "construnit");
                    break;
                case "recon_rewarddeductbill":
                    getApprovers(entity, currentApprover, "rewarddeductentry", "entry_supplier");
                    break;
                case "recon_contractbill":
                    handleContractBill(entity, currentApprover);
                    break;
                case "recon_payreqbill":
                    handlePayReqBill(entity, currentApprover);
                    break;
                default:
                    // 处理未定义的实体编码的情况(可选)
                    break;
            }
        }

        return currentApprover;
    }

    /**
     * 根据供应商名称获取联系人,并添加到传阅人中
     * @param entity 当前单据
     * @param currentApprover 当前审批人
     * @param supplierTitle 供应商标识
     * @return
     */
    public static List<Long> getApprover(DynamicObject entity, List<Long> currentApprover, String supplierTitle) {
        if (entity != null) {
            DynamicObject preSupplier = entity.getDynamicObject(supplierTitle);
            if (preSupplier != null) {
                preSupplier = BusinessDataServiceHelper.loadSingle(preSupplier.getPkValue(), "resm_official_supplier"); // 正式供应商
                DynamicObjectCollection entryLinkmans = preSupplier.getDynamicObjectCollection("entry_linkman"); // 联系人

                for (DynamicObject entryLinkman : entryLinkmans) {
                    if (entryLinkman.getBoolean("isopenaccount")) {
                        String contactPerson = entryLinkman.getString("contactperson"); // 名字
                        addUserToApprover(contactPerson, currentApprover);
                    }
                }
            }
        }
        return currentApprover;
    }

    /**
     * 根据供应商名称获取联系人,并添加到传阅人中
     * @param entity 当前单据
     * @param currentApprover 当前审批人
     * @param supplierEntry 供应商分录标识
     * @param supplierTitle 供应商标识
     * @return
     */
    public static List<Long> getApprovers(DynamicObject entity, List<Long> currentApprover, String supplierEntry, String supplierTitle) {
        if (entity != null) {
            DynamicObjectCollection collections = entity.getDynamicObjectCollection(supplierEntry);
            for (DynamicObject collection : collections) {
                DynamicObject preSupplier = collection.getDynamicObject(supplierTitle);
                if (preSupplier != null) {
                    preSupplier = BusinessDataServiceHelper.loadSingle(preSupplier.getPkValue(), "resm_official_supplier"); // 正式供应商
                    DynamicObjectCollection entryLinkmans = preSupplier.getDynamicObjectCollection("entry_linkman"); // 联系人

                    for (DynamicObject entryLinkman : entryLinkmans) {
                        if (entryLinkman.getBoolean("isopenaccount")) {
                            String contactPerson = entryLinkman.getString("contactperson"); // 名字
                            addUserToApprover(contactPerson, currentApprover);
                        }
                    }
                }
            }
        }
        return currentApprover;
    }

    /**
     * 将用户添加到当前审批人列表中
     * @param contactPerson 联系人姓名
     * @param currentApprover 当前审批人列表
     */
    private static void addUserToApprover(String contactPerson, List<Long> currentApprover) {
        if (contactPerson != null && !contactPerson.isEmpty()) {
            QFilter qFilter = new QFilter("name", QCP.equals, contactPerson);
            DynamicObject bosUser = BusinessDataServiceHelper.loadSingle("bos_user", new QFilter[]{qFilter});
            if (bosUser != null) {
                currentApprover.add(bosUser.getLong("id"));
            }
        }
    }

    private void handleContractBill(DynamicObject entity, List<Long> currentApprover) {
        String partyatype = entity.getString("partyatype"); // 甲方类别
        if ("qeug_recon_developer".equals(partyatype)) {
            DynamicObject dynamicObject = entity.getDynamicObject("multitypepartya"); // 甲方
            addApprover(currentApprover, dynamicObject, "qeug_userfield2", "印章管理员");
        }
    }

    private void handlePayReqBill(DynamicObject entity, List<Long> currentApprover) {
        DynamicObject contractbill = entity.getDynamicObject("contractbill"); // 付款申请_获取选择的合同
        if (contractbill != null) {
            contractbill = BusinessDataServiceHelper.loadSingle(contractbill.getPkValue(), "recon_contractbill");
            String partyatype1 = contractbill.getString("partyatype"); // 甲方类别
            if ("qeug_recon_developer".equals(partyatype1)) {
                DynamicObject dynamicObject = contractbill.getDynamicObject("multitypepartya"); // 甲方
                addApprover(currentApprover, dynamicObject, "qeug_userfield", "园区会计");
                addApprover(currentApprover, dynamicObject, "qeug_userfield1", "资金出纳");

            }
        }
    }

    private void addApprover(List<Long> currentApprover, DynamicObject dynamicObject, String field, String role) {
        if (dynamicObject != null) {
            dynamicObject = BusinessDataServiceHelper.loadSingle(dynamicObject.getPkValue(), "qeug_recon_developer");
            DynamicObject approver = dynamicObject.getDynamicObject(field);
            if (approver != null) {
                Long id = approver.getLong("id");
                currentApprover.add(id);
                logger.info("添加参与人(" + role + "):" + id + " " + approver.getString("name"));
            }
        }
    }


}