package com.kingdee.shr.recuritment.web.handler;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.ctrl.reportone.r1.form.engine.x.util.StringUtil;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.recuritment.task.BeisenTransferPhaseFacadeFactory;
import com.kingdee.eas.custom.recuritment.task.IBeisenTransferPhaseFacade;
import com.kingdee.shr.base.syssetting.api.bean.BatchMessageTipsBody;
import com.kingdee.shr.base.syssetting.api.bean.BatchMessageTipsHeader;
import com.kingdee.shr.base.syssetting.context.SHRContext;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.base.syssetting.exception.ShrWebBizException;
import com.kingdee.shr.recuritment.*;
import com.kingdee.shr.recuritment.service.offer.SyncResumeToPreServiceEx;
import com.kingdee.util.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description offer列表
 * @Date 2025/7/8 19:42
 * @Created by Heyuan
 */
public class OfferListHandlerEx extends OfferListHandler {
    private static final Logger logger = Logger.getLogger(OfferListHandlerEx.class);
    private Context ctx = SHRContext.getInstance().getContext();

    /**
     * 终止入职
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    public void executeSyncBeisenAction(
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap
    ) throws SHRWebException {
        String billIds = this.getBillId(request);
        if (org.apache.commons.lang3.StringUtils.isEmpty(billIds)) {
            throw new ShrWebBizException("单据id不能为空!");
        } else if (billIds.split(",").length > 1) {
            throw new ShrWebBizException("只能选中单行!");
        }
        try {
            if (!StringUtils.isEmpty(billIds)) {
                //同步录用报批状态至北森
                IBeisenTransferPhaseFacade iBeisenTransferPhaseFacade =
                        BeisenTransferPhaseFacadeFactory.getLocalInstance(ctx);
                iBeisenTransferPhaseFacade.syncOfferToBeisen(billIds, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 终止入职
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    @Override
    public void stopOfferAction(
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap
    ) throws SHRWebException {
        super.stopOfferAction(request, response, modelMap);
        String billIds = request.getParameter("billId");
        try {
            if (!StringUtils.isEmpty(billIds)) {
                //同步录用报批状态至北森
                IBeisenTransferPhaseFacade iBeisenTransferPhaseFacade =
                        BeisenTransferPhaseFacadeFactory.getLocalInstance(ctx);
                iBeisenTransferPhaseFacade.syncOfferToBeisen(billIds, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 将指定的录用单据转为标准预备入职状态。
     * <p>
     * 该方法会根据传入的 billId 参数，批量处理多个录用单据。对每个单据执行以下操作：
     * 1. 验证单据是否满足转预备入职条件；
     * 2. 若验证通过且未放弃入职，则调用服务将简历同步至标准预备入职；
     * 3. 记录每条数据的处理结果（成功或失败）；
     * 4. 最后尝试将录用状态同步到北森系统。
     * </p>
     *
     * @param request  HTTP 请求对象，用于获取请求参数（如 billId）
     * @param response HTTP 响应对象，用于输出响应内容
     * @param modelMap Spring MVC 的模型映射对象，可用于传递数据到视图层（本方法未使用）
     * @throws SHRWebException 当业务处理过程中发生异常时抛出
     */
    @Override
    public void toPrePersonAction(
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap
    ) throws SHRWebException {
        // 获取请求中的 billId 参数
        String billIds = request.getParameter("billId");
        Context ctx = getContext();
        IOffer iOffer;
        try {
            // 获取 Offer 服务实例
            iOffer = OfferFactory.getLocalInstance(ctx);
        } catch (BOSException e) {
            logger.error(e.getMessage(), e);
            throw new SHRWebException("系统错误，请联系管理员");
        }
        int success = 0;
        int failure = 0;
        BatchMessageTipsHeader batchMessageTipsHeader = new BatchMessageTipsHeader();

        // 如果 billIds 不为空，则按逗号分割并逐个处理
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(billIds)) {
            String[] ids = billIds.split(",");
            for (int i = 0; i < ids.length; ++i) {
                BatchMessageTipsBody body = new BatchMessageTipsBody();
                body.setId(ids[i]);
                Map<String, Object> map = new HashMap();

                try {
                    // 执行校验逻辑
                    this.checkPass(ids[i], map);
                    String error = (String) map.get("errorMsg");

                    // 如果没有错误信息，则继续处理
                    if (org.apache.commons.lang3.StringUtils.isEmpty(error)) {
                        // 查询 Offer 信息
                        OfferInfo offer = iOffer.getOfferInfo("select resumeBaseRec,preEntry.*,preEntry.talent.*,preEntryDate where id = '" + ids[i] + "' ");

                        // 如果该 Offer 没有被放弃入职
                        if (!offer.isGiveUpEntry()) {
                            SyncResumeToPreServiceEx syncResumeToPreServiceEx = new SyncResumeToPreServiceEx();
                            // 添加标准预备入职记录
                            syncResumeToPreServiceEx.addNewPreEntryByResume(ctx, offer, false);
                        }

                        ++success;
                        body.setMuitTipsState(Boolean.TRUE);
                        body.setMuitTipsMessage("操作成功！");
                        batchMessageTipsHeader.addResult(body);
                    } else {
                        // 校验失败，记录失败原因
                        ++failure;
                        body.setMuitTipsState(Boolean.FALSE);
                        body.setMuitTipsMessage(error);
                        batchMessageTipsHeader.addResult(body);
                    }
                } catch (EASBizException e) {
                    logger.error(e.getMessage(), e);
                    ++failure;
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage("预入职失败！" + e.getMessage());
                    batchMessageTipsHeader.addResult(body);
                } catch (BOSException e) {
                    logger.error(e.getMessage(), e);
                    ++failure;
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage("预入职失败！" + e.getMessage());
                    batchMessageTipsHeader.addResult(body);
                } catch (SHRWebException e) {
                    logger.error(e.getMessage(), e);
                    ++failure;
                    body.setMuitTipsState(Boolean.FALSE);
                    body.setMuitTipsMessage("预入职失败！" + e.getMessage());
                    batchMessageTipsHeader.addResult(body);
                }
            }
        }

        // 设置批量处理结果统计信息
        batchMessageTipsHeader.setBillId(billIds);
        batchMessageTipsHeader.setFailureCount(failure);
        batchMessageTipsHeader.setSuccessCount(success);

        // 输出处理结果
        this.writeSuccessData(batchMessageTipsHeader);

        // 同步录用报批状态至北森系统
        try {
            if (!StringUtils.isEmpty(billIds)) {
                IBeisenTransferPhaseFacade iBeisenTransferPhaseFacade =
                        BeisenTransferPhaseFacadeFactory.getLocalInstance(ctx);
                iBeisenTransferPhaseFacade.syncOfferToBeisen(billIds, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }


    /**
     * 检查候选人是否可以进入下一步流程（如简历投递等），主要判断该候选人是否正在被其他职位流程占用。
     * 如果候选人当前处于“简历筛选”或其他招聘环节，则不允许重复使用，并提示相关信息。
     *
     * @param billId 候选人简历的唯一标识ID
     * @param map    用于返回错误信息的Map对象，若检查不通过会填充state和errorMsg字段
     * @return true表示可以通过，false表示已被占用或存在冲突
     * @throws SHRWebException 当业务逻辑异常或系统异常时抛出
     */
    private boolean checkPass(String billId, Map<String, Object> map) throws SHRWebException {
        StringBuffer msgBuffer = new StringBuffer("");
        try {
            // 获取当前简历在途的应聘记录集合
            ResumeBaseRecCollection resumeColl = this.getOnWayResume(billId);
            if (resumeColl != null && resumeColl.size() > 0) {
                ResumeBaseRecInfo resumeBaseRec = resumeColl.get(0);
                // 判断当前简历所处的状态是否为“简历筛选”
                if ("简历筛选".equals(resumeBaseRec.getResumeState().getResumeStateType().getName())) {
                    msgBuffer.append("当前候选人已被：");
                    String positionName = "";
                    // 获取职位名称（优先取recuritPosition，其次hrJob）
                    if (resumeBaseRec.getRecuritPosition() != null) {
                        positionName = resumeBaseRec.getRecuritPosition().getName();
                    } else if (resumeBaseRec.getHrJob() != null) {
                        positionName = resumeBaseRec.getHrJob().getName();
                    }
                    msgBuffer.append(positionName);
                    msgBuffer.append("职位(");
                    msgBuffer.append(resumeBaseRec.getDepartment().getName());
                    msgBuffer.append("部门)");
                    msgBuffer.append("的简历筛选环节所抢,可联系操作人");

                    // 添加操作人信息
                    if (resumeBaseRec.getProposer() != null) {
                        msgBuffer.append(resumeBaseRec.getProposer().getName() + "解锁！");
                    } else {
                        msgBuffer.append("解锁！");
                    }
                } else {
                    // 当前简历处于其他招聘环节
                    msgBuffer.append("当前候选人正在：");
                    String positionName = "";

                    // 获取职位名称（优先取recuritPosition，其次hrJob）
                    if (resumeBaseRec.getRecuritPosition() != null) {
                        positionName = resumeBaseRec.getRecuritPosition().getName();
                    } else if (resumeBaseRec.getHrJob() != null) {
                        positionName = resumeBaseRec.getHrJob().getName();
                    }
                    msgBuffer.append(positionName);
                    msgBuffer.append("职位(");
                    msgBuffer.append(resumeBaseRec.getDepartment().getName());
                    msgBuffer.append("部门)的");
                    msgBuffer.append(resumeBaseRec.getResumeState().getResumeStateType().getName());
                    msgBuffer.append("环节应聘！当在该职位上应聘不通过，才可释放使用！");
                    // 查询最近处理人信息
                    ApplyRecordCollection applyRecordCollection = ApplyRecordFactory.getRemoteInstance().getApplyRecordCollection("select creator.name where resumeBaseRec ='" + resumeBaseRec.getId() + "' order by createTime desc");
                    if (null != applyRecordCollection && applyRecordCollection.size() > 0) {
                        msgBuffer.append("可联系简历当前或者上一处理人：”" + applyRecordCollection.get(0).getCreator().getName() + "“释放");
                    }
                }
                // 将错误信息放入map中返回
                map.put("state", "error");
                map.put("errorMsg", msgBuffer.toString());
                return false;
            } else {
                // 无在途应聘记录，允许继续操作
                return true;
            }
        } catch (EASBizException e) {
            logger.error(e.getMessage(), e);
            throw new ShrWebBizException(e.getMessage(), e);
        } catch (BOSException e) {
            logger.error(e.getMessage(), e);
            throw new ShrWebBizException(e.getMessage(), e);
        }
    }


    /**
     * 获取在途简历信息
     *
     * @param offerId 申请单ID
     * @return 简历基础信息集合
     * @throws BOSException    业务对象服务异常
     * @throws EASBizException EAS业务异常
     */
    private ResumeBaseRecCollection getOnWayResume(String offerId) throws BOSException, EASBizException {
        ResumeBaseRecCollection resumeColl = null;
        SelectorItemCollection sel = new SelectorItemCollection();
        sel.add(new SelectorItemInfo("*"));
        sel.add(new SelectorItemInfo("resumeBaseRec.*"));
        // 根据offerId获取申请单信息
        OfferInfo offer = OfferFactory.getRemoteInstance().getOfferInfo(new ObjectUuidPK(offerId), sel);
        String ifSimplePerson = offer.getResumeBaseRec().getIfSimplePerson();
        if (!StringUtil.isEmpty(ifSimplePerson)) {
            // 构造查询条件：相同简单人员标识、已处理状态、排除当前记录
            EntityViewInfo evi = new EntityViewInfo();
            FilterInfo filter = new FilterInfo();
            filter.getFilterItems().add(new FilterItemInfo("ifSimplePerson", ifSimplePerson, CompareType.EQUALS));
            filter.getFilterItems().add(new FilterItemInfo("TransactionState", TransactionStateEnum.PROCESSED.getValue(), CompareType.EQUALS));
            filter.getFilterItems().add(new FilterItemInfo("id", offer.getResumeBaseRec().getId().toString(), CompareType.NOTEQUALS));
            // 设置需要查询的字段
            SelectorItemCollection sic = evi.getSelector();
            sic.add(new SelectorItemInfo("department.name"));
            sic.add(new SelectorItemInfo("recuritPosition.name"));
            sic.add(new SelectorItemInfo("hrJob.name"));
            sic.add(new SelectorItemInfo("resumeState.resumeStateType.name"));
            sic.add(new SelectorItemInfo("proposer.name"));
            evi.setFilter(filter);
            evi.setSelector(sic);
            // 执行查询获取在途简历集合
            IResumeBaseRec iResumeBaseRec = ResumeBaseRecFactory.getRemoteInstance();
            resumeColl = iResumeBaseRec.getResumeBaseRecCollection(evi);
        }
        return resumeColl;
    }


    /**
     * 反终止
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    @Override
    public void noStopOfferAction(
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap
    ) throws SHRWebException {
        super.noStopOfferAction(request, response, modelMap);
        String billIds = request.getParameter("billId");
        try {
            if (!StringUtils.isEmpty(billIds)) {
                //同步录用报批状态至北森
                IBeisenTransferPhaseFacade iBeisenTransferPhaseFacade =
                        BeisenTransferPhaseFacadeFactory.getLocalInstance(ctx);
                iBeisenTransferPhaseFacade.syncOfferToBeisen(billIds, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }

    /**
     * 放弃入职
     *
     * @param request
     * @param response
     * @param modelMap
     * @throws SHRWebException
     */
    @Override
    public void abondonEntryAction(
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap modelMap
    ) throws SHRWebException {
        super.abondonEntryAction(request, response, modelMap);
        String billIds = request.getParameter("billId");
        try {
            if (!StringUtils.isEmpty(billIds)) {
                //同步录用报批状态至北森
                IBeisenTransferPhaseFacade iBeisenTransferPhaseFacade =
                        BeisenTransferPhaseFacadeFactory.getLocalInstance(ctx);
                iBeisenTransferPhaseFacade.syncOfferToBeisen(billIds, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ShrWebBizException(e);
        }
    }
}
