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

import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
import kd.bos.exception.KDException;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jimin.jyyy.hr.tsrsc.plugin.util.MokaApiUtil;
import nckd.jimin.jyyy.hr.tsrsc.plugin.workflow.CasRecrApplyMokaWorkFlowPlugin;

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

/**
 * 提交生效插件
 */
public class ApplySubmitEffectOpPlugin extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] bills = e.getDataEntities();
        for (DynamicObject dynamicObject : bills) {
            // 目标单据
            // DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(bill.getPkValue(), bill.getDynamicObjectType().getName());
            // 申请人数为零
            if (dynamicObject == null || dynamicObject.getInt("nckd_applynum") <= 0) {
                throw new KDException("申请人数为零！");
            }
            // 错误列表
            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 e1) {
                    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 e2) {
                        throw new RuntimeException(e2);
                    }
                    // 记录调用日志
                    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));
            }
            else {
                dynamicObject.set("billstatus", "C");
                dynamicObject.set("auditor", UserServiceHelper.getCurrentUserId());
                dynamicObject.set("auditdate",new Date());
                SaveServiceHelper.save(new DynamicObject[]{dynamicObject});
            }

        }
    }
}