package weaver.interfaces.shuzhi.cronjob;

import com.engine.shuzhi.entity.po.ModeStaffPO;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.*;

/**
 * 编制数据同步服务
 *
 * @author:dxfeng
 * @createTime: 2023/06/01
 * @version: 1.0
 */
public class SyncModeStaffJob extends BaseCronJob {
    private static String SPECIAL_JOB_NAME = "培训生";

    @Override
    public void execute() {
        new BaseBean().writeLog("######编制数据同步服务,任务开始######");
        RecordSet rs = new RecordSet();
        String sql;
        // 查询培训生的岗位ID
        sql = "select id from hrmjobtitles where jobtitlename = ? ";
        Set<String> specialJobIds = new HashSet<>();
        rs.executeQuery(sql, SPECIAL_JOB_NAME);
        while (rs.next()) {
            specialJobIds.add(rs.getString("id"));
        }
        // 查询各个岗位下对应的人员
        sql = "select count(id) as num, departmentid, jobtitle from hrmresource where status < 4 group by departmentid, jobtitle";
        rs.executeQuery(sql);
        List<ModeStaffPO> modeStaffList = new ArrayList<>();
        while (rs.next()) {
            modeStaffList.add(ModeStaffPO.builder().num(rs.getString("num")).departmentid(rs.getString("departmentid")).jobtitle(rs.getString("jobtitle")).build());
        }

        // 根据部门+岗位查询最新一个月的记录
        if ("sqlserver".equals(rs.getDBType())) {
            sql = "select top 1 id, bzrs from uf_bzxxbd where bm = ? and gw = ? order by yf desc";
        } else if ("oracle".equals(rs.getDBType())) {
            sql = "select id, bzrs from uf_bzxxbd where bm = ? and gw = ?  and rownum = 1 order by yf desc";
        } else {
            sql = "select id, bzrs from uf_bzxxbd where bm = ? and gw = ? order by yf desc limit 1";
        }
        for (ModeStaffPO modeStaff : modeStaffList) {
            rs.executeQuery(sql, modeStaff.getDepartmentid(), modeStaff.getJobtitle());
            if (rs.next()) {
                String staffId = rs.getString("id");
                String staffNum = rs.getString("bzrs");
                // 岗位为培训生编制人数等于在岗人数
                modeStaff.setStaffNum(specialJobIds.contains(modeStaff.getJobtitle()) ? modeStaff.getNum().toString() : staffNum);
                rs.executeUpdate("update uf_bzxxbd set zgrs = ? ,bzrs = ? ,kbrs = ? where id = ?", modeStaff.getNum(), modeStaff.getStaffNum(), modeStaff.getLackNum(), staffId);
            }
        }

        sql = "update uf_bzxxbd set zgrs = 0, kbrs = bzrs where zgrs is null or zgrs = 0";
        rs.execute(sql);
        new BaseBean().writeLog("######编制数据同步服务,任务结束######");
    }
}
