package nckd.jimin.jyyy.hr.tsrsc.plugin.workflow;

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.workflow.api.AgentExecution;
import kd.bos.workflow.engine.extitf.IWorkflowPlugin;
import nckd.jimin.jyyy.hr.tsrsc.plugin.util.MokaApiUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Map;

/**
 * 年度招聘申请审批流程-工作流插件
 * 流程编码：Proc_nckd_yearapply_audit_1
 * 审批通过的年度招聘申请同步给 Moka 的招聘需求
 * @author ：Tyx
 * @since ：2025-05-28
 */
public class YearCrApplyMokaWorkFlowPlugin implements IWorkflowPlugin {
    private static Log log = LogFactory.getLog(YearCrApplyMokaWorkFlowPlugin.class);

    @Override
    public void notify(AgentExecution execution) {
        // 单据的BusinessKey(业务ID)
        String businessKey = execution.getBusinessKey();
        // 目标单据
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(
                businessKey,
                execution.getEntityNumber()
        );
        // 申请人数为零
        if (dynamicObject == null || dynamicObject.getInt("nckd_applynum") <= 0) {
            return;
        }
        // 错误列表
        ArrayList<String> errList = new ArrayList<>();

        // 对外招聘组织 的 对外招聘组织编码（number）
        Map<String, String> recruitOrgMap = CasRecrApplyMokaWorkFlowPlugin.getRecruitOrgMap();

        DynamicObjectCollection entryEntity = dynamicObject.getDynamicObjectCollection("entryentity");
        for (DynamicObject entry : entryEntity) {
            // 招聘人数为零，跳过
            // 原单编号
            String billNo = ((DynamicObject) entry.getParent()).getString("billno");
            // 排序号
            int seq = entry.getInt("seq");

            // 需求人数
            String name = ((DynamicObject) entry.getParent()).getDynamicObjectType().getName();
            int needNumber = 0;
            try {
                needNumber = "nckd_yearcasreplan".equals(name) ? entry.getInt("nckd_approvednum") : entry.getInt("nckd_recruitnum");
            } catch (NullPointerException e) {
                String msg = String.format("单据编号为【%s】的第%s条数据：%s",
                        billNo, seq, "需求人数或公司核定人数未填写"
                );
                errList.add(msg);
                continue;
            }

            if (needNumber > 0) {
                // 生产请求json
                JSONObject body = CasRecrApplyMokaWorkFlowPlugin.getRequestBody(dynamicObject, entry, needNumber, recruitOrgMap);

                // 新建 招聘需求
                // 招聘类型
                String recruitTypeFlag;
                switch (entry.getString("nckd_recruittype.number")) {
                    case "1010_S":
                        // 校园招聘
                        recruitTypeFlag = "2";
                        break;
                    case "1020_S":
                        // 社会招聘
                        recruitTypeFlag = "1";
                        break;
                    default:
                        continue;
                }

                // 发送新建招聘需求请求
                JSONObject responseObj = null;
                try {
                    responseObj = MokaApiUtil.addMokaCurrentHire(recruitTypeFlag, body);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
                // 记录调用日志
                MokaApiUtil.newApiLog(
                        "nckd_yearcasreplan",
                        "年度招聘计划",
                        "ndzp",
                        MokaApiUtil.getParamValue("moka_url")
                                + "/api-platform/v1/headcount"
                                + "?currentHireMode=" + recruitTypeFlag,
                        body.toString(),
                        responseObj.toString()
                );

                if (responseObj.getInteger("code") != 0) {
                    String msg = String.format("第%s条数据：%s",
                            seq, responseObj.getString("msg")
                    );
                    errList.add(msg);
                }
            }
        }

        if (!errList.isEmpty()) {
            throw new KDException("该年度招聘计划新建Moka招聘需求时，发生以下错误:\r\n" + String.join("\r\n", errList));
        }
    }
}












