package com.engine.recruit.service.impl;

import com.engine.core.impl.Service;
import com.engine.recruit.conn.StepMsgCommonInfo;
import com.engine.recruit.entity.recruitflow.po.RecruitStepPo;
import com.engine.recruit.exception.CustomizeRunTimeException;
import com.engine.recruit.service.RecruitButtonService;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.general.Util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>聚才林招聘</p>
 * "进入下一阶段"按钮实现类
 *
 * @author:dxfeng
 * @createTime: 2023/09/18
 * @version: 1.0
 */
public class NextStageServiceImpl extends Service implements RecruitButtonService {
    @Override
    public Map<String, Object> execute(Map<String, Object> params) {
        Map<String, Object> returnMap = new HashMap<>();
        String billId = Util.null2String(params.get("billId"));
        // 招聘阶段ID
        String stageId = null;
        String ypzw = "";
        // 招聘流程ID
        int recruitFlowId = -1;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select ypzw,zplc,zpjd from uf_jcl_yppc where id = ?", billId);
        if (rs.next()) {
            recruitFlowId = rs.getInt("zplc");
            stageId = rs.getString("zpjd");
            ypzw = rs.getString("ypzw");
        }
        if (-1 == recruitFlowId) {
            throw new CustomizeRunTimeException("未设置对应招聘流程");
        }
        rs.executeQuery("select id,jdmc,hj from uf_jcl_zpjdsz where sfqy = 0 and zplc = ? order by hj,zssx", recruitFlowId);
        List<RecruitStepPo> stepList = new ArrayList<>();
        while (rs.next()) {
            stepList.add(RecruitStepPo.builder().key(rs.getInt("id")).description(rs.getString("jdmc")).type(rs.getString("hj")).build());
        }
        boolean found = false;
        Integer target = null;
        if (StringUtils.isBlank(stageId)) {
            stageId = String.valueOf(stepList.get(0).getKey());
        }
        for (RecruitStepPo recruitStepPo : stepList) {
            if (found) {
                target = recruitStepPo.getKey();
                break;
            }

            if (recruitStepPo.getKey() == Integer.parseInt(stageId)) {
                found = true;
                // 结束环节
                if ("2".equals(recruitStepPo.getType())) {
                    target = -1;
                }
            }
        }
        rs.executeQuery("select jdlx from uf_jcl_zpjdsz where id = ?", target);
        if (rs.next()) {
            String jdlx = rs.getString("jdlx");
            // 更新应聘者简历为下一阶段
            rs.executeUpdate("update uf_jcl_yppc set zpjd = ?,dqypjd = ? where id = ?", target, jdlx, billId);
        }

        // 阶段提醒
        StepMsgCommonInfo.sendMsg(billId, ypzw, String.valueOf(recruitFlowId), String.valueOf(target), user);


        return returnMap;
    }
}
