package com.kingdee.shr.recuritment.service.offer;

import com.kingdee.bos.BOSException;
import com.kingdee.bos.Context;
import com.kingdee.bos.dao.ormapping.ObjectUuidPK;
import com.kingdee.bos.metadata.data.SortType;
import com.kingdee.bos.metadata.entity.*;
import com.kingdee.bos.metadata.query.util.CompareType;
import com.kingdee.eas.base.attachment.AttachmentInfo;
import com.kingdee.eas.common.EASBizException;
import com.kingdee.eas.custom.beisen.utils.HRAttachmentUploadUtil;
import com.kingdee.eas.custom.recuritment.utils.AttachmentUtils;
import com.kingdee.shr.attachment.ISHRAttachmentExt;
import com.kingdee.shr.attachment.SHRAttachmentExtCollection;
import com.kingdee.shr.attachment.SHRAttachmentExtFactory;
import com.kingdee.shr.attachment.SHRAttachmentExtInfo;
import com.kingdee.shr.base.syssetting.exception.SHRWebException;
import com.kingdee.shr.preentry.*;
import com.kingdee.shr.recuritment.*;
import com.kingdee.shr.recuritment.app.util.ParamUtil;
import com.kingdee.shr.recuritment.service.recRegister.RecRegisterService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * @Description 同步简历到预入职
 * @Date 2025/9/18 10:28
 * @Created by 59279
 */
public class SyncResumeToPreServiceEx extends SyncResumeToPreService {
    private Logger logger = Logger.getLogger(SyncResumeToPreServiceEx.class);

    /**
     * 根据简历信息添加新的预入职记录。
     * <p>
     * 该方法首先根据简历基础信息查询最新的招聘登记记录，如果不存在则创建一个新的招聘登记记录。
     * 然后基于招聘登记记录或简历信息生成预入职信息，并更新相关状态。
     * 同时将对应的招聘登记记录及简历标记为无效。
     *
     * @param ctx   上下文对象，用于获取业务服务实例
     * @param offer 包含简历和预入职相关信息的 Offer 信息对象
     * @param isSSC 是否为共享服务中心操作标识
     * @return 返回创建的预入职信息对象
     * @throws EASBizException 业务异常
     * @throws BOSException    BOS框架异常
     * @throws SHRWebException SHR Web服务异常
     */
    public PreEntryInfo addNewPreEntryByResume(Context ctx, OfferInfo offer, boolean isSSC) throws EASBizException, BOSException, SHRWebException {
        // 构建查询条件：根据简历基础记录ID查找招聘登记记录
        EntityViewInfo view = new EntityViewInfo();
        FilterInfo filter = new FilterInfo();
        filter.getFilterItems().add(new FilterItemInfo("resumeBaseRec", offer.getResumeBaseRec().getId().toString(), CompareType.EQUALS));
        view.setFilter(filter);

        // 设置查询字段选择器，包含所有字段、人才信息和简历基础信息
        SelectorItemCollection selector = new SelectorItemCollection();
        selector.add("*");
        selector.add("talent.*");
        selector.add("resumeBaseRec.*");
        view.setSelector(selector);

        // 设置排序规则：按创建时间降序排列
        SorterItemCollection sorterColl = new SorterItemCollection();
        SorterItemInfo sorterItemInfo = new SorterItemInfo("createTime");
        sorterItemInfo.setSortType(SortType.DESCEND);
        sorterColl.add(sorterItemInfo);
        view.setSorter(sorterColl);
        IRecRegister iRecRegister = RecRegisterFactory.getLocalInstance(ctx);
        //删除招聘登记记录
        iRecRegister.delete(filter);
        // 查询招聘登记记录集合
        //RecRegisterCollection coll = iRecRegister.getRecRegisterCollection(view);
        RecRegisterCollection coll = null;
        //todo 从招聘登记表创建预入职单,有区号为空的bug
        // 如果未查到记录，则尝试通过简历创建新的招聘登记记录并重新查询
        //if (RecDBUtils.isEmpty(coll)) {
//        ResumeBaseRecInfo resumeBaseRecInfo = ResumeBaseRecFactory.getLocalInstance(ctx).getResumeBaseRecInfo("select * where id='" + offer.getResumeBaseRec().getId().toString() + "'");
//        ResumeConvertUtilEx.addRecRegisterByResume(ctx, resumeBaseRecInfo);
//        RecRegisterCollection coll = iRecRegister.getRecRegisterCollection("select *,talent.*,resumeBaseRec.* where resumeBaseRec = '" + offer.getResumeBaseRec().getId().toString() + "' order by createTime desc");
        //}
        PreEntryInfo preEntryInfo = null;
        // 处理查询到的招聘登记记录
        if (coll != null && coll.size() > 0) {
            RecRegisterInfo recRegisterInfo = coll.get(0);

            // 判断是否有关联的人才信息
            if (recRegisterInfo.getTalent() != null) {
                // 若 Offer 中已有预入职信息且已设置报到状态，则直接使用
                if (offer.getPreEntry() != null && offer.getPreEntry().getCheckInState() != null) {
                    preEntryInfo = offer.getPreEntry();
                } else {
                    // 否则基于招聘登记信息创建新的预入职信息
                    preEntryInfo = this.addNewPreEntryByRecRegister(ctx, recRegisterInfo, offer.getPreEntryDate(), isSSC);
                    offer.setPreEntry(preEntryInfo);
                    OfferFactory.getLocalInstance(ctx).update(new ObjectUuidPK(offer.getId()), offer);
                }
            } else {
                // 没有关联人才信息时，基于简历创建预入职信息
                preEntryInfo = this.addNewPreEntryByResume(ctx, offer, isSSC, preEntryInfo);
            }

            // 将当前招聘登记记录及其关联的简历标记为无效
            boolean result = RecRegisterService.getInstance().invalidRegister(ctx, recRegisterInfo);
            if (result) {
                recRegisterInfo.setRecRegisterState(RecRegisterStateEnum.INVALID);
                iRecRegister.update(new ObjectUuidPK(recRegisterInfo.getId()), recRegisterInfo);
                ResumeBaseRecInfo resumeInfo = recRegisterInfo.getResumeBaseRec();
                resumeInfo.setRecRegisterState(RecRegisterStateEnum.INVALID);
                ResumeBaseRecFactory.getLocalInstance(ctx).update(new ObjectUuidPK(resumeInfo.getId()), resumeInfo);

                // 根据配置决定是否更新文件状态
                Integer registerEditWay = ParamUtil.getInstance().getRecRegisterEditWay(ctx);
                if (registerEditWay == 2) {
                    this.updateFileStateForSubmit(ctx, recRegisterInfo.getResumeBaseRec().getId().toString());
                }
            }
        } else {
            // 无招聘登记记录时，基于简历创建预入职信息
            preEntryInfo = this.addNewPreEntryByResume(ctx, offer, isSSC, preEntryInfo);
        }

        // 标记简历为无效状态
        RecRegisterService.getInstance().invalidResume(ctx, offer.getResumeBaseRec().getId().toString());

        // 执行预入职后的后续处理逻辑
        this.afterPreEntry(ctx, offer);

        return preEntryInfo;
    }


    /**
     * 同步简历信息到预入职人员信息
     * <p>
     * 该方法用于将简历中的各项信息同步到预入职人员对象中，包括基本信息、头像、联系方式、工作经历、学历、
     * 项目经验、语言能力、证书等，并最终调用扩展服务完成简历与预入职人员的关联。
     * </p>
     *
     * @param ctx    上下文对象，用于获取服务实例和传递上下文信息
     * @param person 预入职人员信息对象，作为信息同步的目标对象
     * @param resume 简历基础信息对象，作为信息同步的来源对象
     */
    public void syncResumeToPEPerson(Context ctx, PreEntryPersonInfo person, ResumeBaseRecInfo resume) {
        super.syncResumeToPEPerson(ctx, person, resume);
        //简历id
        try {
            String resumeId = resume.getId().toString();
            IRecApproval iRecApproval = RecApprovalFactory.getLocalInstance(ctx);
            RecApprovalCollection recApprovalCollection =
                    iRecApproval.getRecApprovalCollection("where resumeBaseRec = '" + resumeId + "'");
            if (!recApprovalCollection.isEmpty()) {
                //获取招聘审批信息
                RecApprovalInfo recApprovalInfo = recApprovalCollection.get(0);
                //获取背调信息
                String personalScreening = recApprovalInfo.getPersonalScreening();
                if (StringUtils.isNotBlank(personalScreening)) {
                    person.put("personalScreening", personalScreening);
                    SelectorItemCollection updateSic = new SelectorItemCollection();
                    updateSic.add("personalScreening");
                    //更新背调信息
                    PreEntryPersonFactory.getLocalInstance(ctx).updatePartial(person, updateSic);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        if (person != null) {
            logger.error("***************************同步简历附件到预入职开始***************************");
            //预入职id
            String id = person.getId().toString();
            //简历id
            String resumeId = resume.getId().toString();
            try {
                //删除简历附件
                String filter = "where boid = '" + id + "' and (attachment.name like '%标准简历%' or attachment.name like '%面试评价%' or attachment.name like '%原始简历%' or attachment.name like '%背景调查审批表%' )";
                AttachmentUtils.deleteAttachment(ctx, filter);
                ISHRAttachmentExt ishrAttachmentExt = SHRAttachmentExtFactory.getLocalInstance(ctx);
                SHRAttachmentExtCollection shrAttachmentExtCollection =
                        ishrAttachmentExt.getSHRAttachmentExtCollection("select attachment.* where boID = '" + resumeId + "'");
                String uipk = "hr.preentry.resume.base";//预入职人员_基本信息
                for (int i = 0; i < shrAttachmentExtCollection.size(); i++) {
                    SHRAttachmentExtInfo shrAttachmentExtInfo = shrAttachmentExtCollection.get(i);
                    AttachmentInfo attachmentInfo = shrAttachmentExtInfo.getAttachment();
                    if (attachmentInfo == null || attachmentInfo.getFile() == null) {
                        continue;
                    }
                    String type = attachmentInfo.getSimpleName();
                    String fileName = attachmentInfo.getName();
                    byte[] file = attachmentInfo.getFile();
                    //上传附件
                    HRAttachmentUploadUtil.uploadAttachment(ctx, file, type, fileName, id, uipk, "null0");
                }
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
            logger.error("***************************同步简历附件到预入职结束***************************");
        }
    }


    /**
     * 同步人员基本信息
     *
     * @param person 人员信息对象
     * @param resume 简历基本信息对象
     * @param ctx    上下文环境
     * @return 同步后的人员信息对象
     */
    public PreEntryPersonInfo syncPersonBaseInfo(PreEntryPersonInfo person, ResumeBaseRecInfo resume, Context ctx) {
        super.syncPersonBaseInfo(person, resume, ctx);
        //简历id
        try {
            String resumeId = resume.getId().toString();
            IRecApproval iRecApproval = RecApprovalFactory.getLocalInstance(ctx);
            RecApprovalCollection recApprovalCollection =
                    iRecApproval.getRecApprovalCollection("where resumeBaseRec = '" + resumeId + "'");
            if (!recApprovalCollection.isEmpty()) {
                //获取招聘审批信息
                RecApprovalInfo recApprovalInfo = recApprovalCollection.get(0);
                //获取背调信息
                String personalScreening = recApprovalInfo.getPersonalScreening();
                if (StringUtils.isNotBlank(personalScreening)) {
                    person.put("personalScreening", personalScreening);
                }
            }
        } catch (BOSException e) {
            logger.error(e.getMessage(), e);
        }
        return person;
    }
}
