package com.engine.recruit.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.engine.core.impl.Service;
import com.engine.recruit.conn.ApplicantCommonInfo;
import com.engine.recruit.conn.RecruitDataMap;
import com.engine.recruit.conn.RecruitRecordSet;
import com.engine.recruit.constant.ModeSearchCodeConstant;
import com.engine.recruit.constant.ModeTreeCodeConstant;
import com.engine.recruit.constant.RecruitConstant;
import com.engine.recruit.entity.init.po.*;
import com.engine.recruit.exception.CustomizeRunTimeException;
import com.engine.recruit.service.InitRecruitDataService;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.recruit.modeexpand.process.StageDataInsert;
import weaver.formmode.service.CustomPageService;
import weaver.general.BaseBean;
import weaver.general.Util;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author:dxfeng
 * @createTime: 2023/11/22
 * @version: 1.0
 */
public class InitRecruitDataServiceImpl extends Service implements InitRecruitDataService {
    @Override
    public Map<String, Object> checkInitStatus() {

        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from uf_jcl_zplc");
        if (rs.next()) {
            updateRecruitData();
        } else {
            initRecruitData();
        }
        return null;
    }

    @Override
    public Map<String, Object> initRecruitData() {
        RecordSet rs = new RecordSet();
        rs.executeUpdate("delete from uf_jcl_zplc");
        rs.executeUpdate("delete from uf_jcl_zpjdsz");
        rs.executeUpdate("delete from uf_jcl_zpjdsz_dt1");
        rs.executeUpdate("delete from uf_jcl_zpjdsz_dt2");
        rs.executeUpdate("delete from uf_jcl_lcczan");
        // 刷新页面菜单
        rs.executeQuery("select * from hp_nonstandard_function_info where num='163' and name ='招聘管理'");
        if (rs.next()) {
            refreshMenuUrl();
        }

        // 插入操作按钮数据，
        int buttonModeId = ApplicantCommonInfo.getModeIdByTableName("uf_jcl_lcczan");
        Map<String, Object> baseMap = new RecruitDataMap<>();
        RecruitRecordSet.buildModeInsertFields(baseMap, 1);
        List<OperateButtonPo> operateButtonList = insertButtonData(baseMap, buttonModeId);
        Map<String, OperateButtonPo> operateButtonMap = operateButtonList.stream().collect(Collectors.toMap(OperateButtonPo::getButtonName, item -> item, (k1, k2) -> k1));

        // 插入招聘阶段数据
        int stageModeId = ApplicantCommonInfo.getModeIdByTableName("uf_jcl_zpjdsz");
        insertStageData(baseMap, stageModeId, operateButtonMap);

        // 创建内置流程
        int flowModeId = ApplicantCommonInfo.getModeIdByTableName("uf_jcl_zplc");
        insertFlowData(baseMap, flowModeId);

        return null;
    }

    @Override
    public Map<String, Object> updateRecruitData() {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from hp_nonstandard_function_info where num='163' and name ='招聘管理'");
        if (rs.next()) {
            // 更新菜单地址
            refreshMenuUrl();
        }
        return null;
    }


    /**
     * 更新招聘管理相关菜单地址
     */
    private void refreshMenuUrl() {

        List<String> menuSqlList = new ArrayList<>();
        // 招聘需求
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.RECRUITMENT_DEMAND_MANAGEMENT) + "' where id = " + 100189);
        // 招聘职位
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.RECRUITMENT_POSITIONS) + "' where id = " + 100190);
        // 应聘者
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.APPLICANTS) + "' where id = " + 100192);
        // 部门筛选
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.SCREENING_FEEDBACK) + "' where id = " + 100193);
        // 笔试
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.WRITTEN_RESULTS) + "' where id = " + 100194);
        // 面试
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.INTERVIEW) + "' where id = " + 100195);
        // 薪酬谈判
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.SALARY_NEGOTIATION) + "' where id = " + 100196);
        // 背调
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.BACK_TONE) + "' where id = " + 100197);
        // offer
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.OFFER) + "' where id = " + 100198);
        //// 人才库
        //menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.TALENT_POOL) + "' where id = " + 100200);
        // 简历库
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.RESUME_LIBRARY) + "' where id = " + 100201);
        // 工作地点
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.WORK_LOCATION) + "' where id = " + 100203);
        // 字段类型名称
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.DATA_DICTIONARY_TYPE_NAME) + "' where id = " + 100205);
        // 邮件通知模板
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.EMAIL_NOTIFICATION_TEMPLATE) + "' where id = " + 100206);
        // 千里聆邮箱配置
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.QLL_EMAIL_CONFIG) + "' where id = " + 100207);
        // 我的招聘需求
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.MY_RECRUITMENT_NEEDS) + "' where id = " + 100209);
        // 我的筛选
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.MY_FILTERING) + "' where id = " + 100210);
        // 我的面试
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.PARTICIPATE_IN_INTERVIEWS) + "' where id = " + 100211);
        // 招聘流程
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.RECRUITMENT_PROCESS_LIST) + "' where id = " + 100213);
        // 招聘阶段
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.RECRUITMENT_STAGE_LIST) + "' where id = " + 100214);
        // 操作按钮
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.LIST_OF_OPERATION_BUTTONS) + "' where id = " + 100215);
        //// 入职管理
        //menuSqlList.add("update LeftMenuInfo set fullrouteurl= '/spa/cube/index.html#/main/cube/viewCustomPage?id=" + getCustomPageId("入职管理", ModeSearchCodeConstant.ENTRY_MANAGEMENT) + "&noTitleShow=1' where id = " + 100199);
        // 数据字典
        menuSqlList.add("update LeftMenuInfo set fullrouteurl= '/spa/cube/index.html#/main/cube/tree?id=" + getCustomTreeId(ModeTreeCodeConstant.DATA_DICTIONARY_TREE) + "&noTitleShow=1' where id = " + 100204);
        // 简历订阅
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/search?customid=" + getCustomSearchId(ModeSearchCodeConstant.RESUME_SUBSCRIPTION) + "' where id = " + 100218);


        // 处理自定义页面
        CustomPageService customPageService = new CustomPageService();
        customPageService.setUser(user);
        int appId = getAppIdByName(RecruitConstant.MODE_APP_NAME);
        List<Map<String, Object>> customPageByModeIds = customPageService.getCustomPageByModeIds(appId);
        new BaseBean().writeLog("MODE_APP_NAME：==" + RecruitConstant.MODE_APP_NAME);
        new BaseBean().writeLog("appId：==" + appId);
        new BaseBean().writeLog("customPageByModeIds：==" + JSON.toJSONString(customPageByModeIds));
        String rzglId = "";
        String rckId = "";
        for (Map<String, Object> map : customPageByModeIds) {
            String name = Util.formatMultiLang(Util.null2String(map.get("customname")), "7");
            String id = Util.null2String(map.get("id"));
            // 入职管理
            if ("入职管理".equals(name)) {
                rzglId = id;
            } else if ("人才库".equals(name)) {
                rckId = id;
            }
        }
        if (StringUtils.isBlank(rzglId)) {
            throw new CustomizeRunTimeException("招聘管理菜单初始化失败，请检查建模引擎自定义页面[入职管理]是否存在");
        }
        if (StringUtils.isBlank(rckId)) {
            throw new CustomizeRunTimeException("招聘管理菜单初始化失败，请检查建模引擎自定义页面[人才库]是否存在");
        }
        // 入职管理
        menuSqlList.add("update LeftMenuInfo set fullrouteurl= '/spa/cube/index.html#/main/cube/viewCustomPage?id=" + rzglId + "&noTitleShow=1' where id = " + 100199);

        // 人才库
        menuSqlList.add("update LeftMenuInfo set fullrouteurl = '/spa/cube/index.html#/main/cube/viewCustomPage?id=" + rckId + "&noTitleShow=1' where id = " + 100200);


        RecordSet rs = new RecordSet();
        for (String sql : menuSqlList) {
            new BaseBean().writeLog("招聘目录初始化SQL：==" + sql);
            rs.executeUpdate(sql);
        }
    }

    /**
     * 获取名称获取APPID
     *
     * @param appName
     * @return
     */
    private int getAppIdByName(String appName) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select ID from modeTreeField where treefieldname like '%" + appName + "%'");
        String id = "";
        if (rs.next()) {
            id = rs.getString("id");
        }
        if (StringUtils.isNotBlank(id)) {
            return Convert.toInt(id);
        }
        throw new CustomizeRunTimeException("招聘管理菜单初始化失败，请检查该名称建模应用是否存在[" + appName + "]");
    }

    /**
     * 获取建模查询列表ID
     *
     * @param customSearchCode
     * @return
     */
    private String getCustomSearchId(String customSearchCode) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from mode_customsearch where customsearchcode = ? ", customSearchCode);
        if (rs.next()) {
            return rs.getString("id");
        }
        throw new CustomizeRunTimeException("招聘管理菜单初始化失败，请检查建模引擎查询列表配置[" + customSearchCode + "]");
    }

    /**
     * 获取建模自定义页面ID
     *
     * @param customPageName   自定义页面名称
     * @param customSearchCode
     * @return
     */
    private String getCustomPageId(String customPageName, String customSearchCode) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select appid from mode_customsearch where customsearchcode = ? ", customSearchCode);
        if (rs.next()) {
            String appId = rs.getString("appid");
            rs.executeQuery("select id from mode_custompage where appid = ?  and customname = ?", appId, customPageName);
            if (rs.next()) {
                return rs.getString("id");
            }
        }
        throw new CustomizeRunTimeException("招聘管理菜单初始化失败，请检查建模引擎自定义页面配置[" + customPageName + "," + customSearchCode + "]");
    }

    /**
     * 获取建模树ID
     *
     * @param treeCode
     * @return
     */
    private String getCustomTreeId(String treeCode) {
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from mode_customtree where treecode =? ", treeCode);
        if (rs.next()) {
            return rs.getString("id");
        }
        throw new CustomizeRunTimeException("招聘管理菜单初始化失败，请检查建模引擎树配置[" + treeCode + "]");
    }


    /**
     * 插入初始化流程数据
     *
     * @param baseMap
     * @param modeId
     */
    private void insertFlowData(Map<String, Object> baseMap, int modeId) {
        OperateFlowPo flowPo = OperateFlowPo.builder()
                .lcmc("默认流程")
                .lczt(0)
                .ksjd(getStageIdByName("筛选"))
                .gcjd(getStageIdByName("面试"))
                .jsjd(getStageIdByName("offer"))
                .build();

        RecruitDataMap<Object> flowDataMap = new RecruitDataMap<>();
        flowDataMap.putAll(baseMap);
        String uuid = UUID.randomUUID().toString();
        flowDataMap.put("modeuuid", uuid);
        flowDataMap.put("formmodeid", modeId);
        flowDataMap.put("lcmc", flowPo.getLcmc());
        flowDataMap.put("lczt", flowPo.getLczt());
        flowDataMap.put("ksjd", flowPo.getKsjd());
        flowDataMap.put("gcjd", flowPo.getGcjd());
        flowDataMap.put("jsjd", flowPo.getJsjd());

        RecruitRecordSet.insertData(flowDataMap, "uf_jcl_zplc");
        int billId = RecruitRecordSet.refreshRight(uuid, "uf_jcl_zplc", modeId, 1);
        // 流程关联招聘阶段
        StageDataInsert.relatedStageData(1, String.valueOf(billId), "zplc", flowPo.getKsjd(), flowPo.getGcjd(), flowPo.getJsjd());

    }


    /**
     * 插入招聘阶段设置数据
     *
     * @param baseMap
     * @param modeId
     * @param operateButtonMap
     */
    private void insertStageData(Map<String, Object> baseMap, int modeId, Map<String, OperateButtonPo> operateButtonMap) {
        List<OperateStagePo> stageList = buildOperateStageList(operateButtonMap);
        List<OperateStageDt2> dt2List = buildStageDt2Data();
        for (OperateStagePo stage : stageList) {
            RecruitDataMap<Object> stageDataMap = new RecruitDataMap<>();
            stageDataMap.putAll(baseMap);
            String uuid = UUID.randomUUID().toString();
            stageDataMap.put("modeuuid", uuid);
            stageDataMap.put("formmodeid", modeId);
            stageDataMap.put("jdmc", stage.getJdmc());
            stageDataMap.put("jdms", stage.getJdms());
            stageDataMap.put("jdlx", stage.getJdlx());
            stageDataMap.put("hj", stage.getHj());
            stageDataMap.put("sfqy", 0);
            stageDataMap.put("zplc", -1);
            RecruitRecordSet.insertData(stageDataMap, "uf_jcl_zpjdsz");
            int id = RecruitRecordSet.refreshRight(uuid, "uf_jcl_zpjdsz", modeId, 1);
            stage.setId(id);

            // 插入明细表1
            List<OperateStageDt1> dt1 = stage.getDt1();
            for (OperateStageDt1 stageDt1 : dt1) {
                Map<String, Object> dt1Map = new RecruitDataMap<>();
                dt1Map.put("mainid", id);
                dt1Map.put("czan", stageDt1.getCzan());
                dt1Map.put("zdyxsmc", stageDt1.getZdyxsmc());
                dt1Map.put("tzymdz", stageDt1.getTzymdz());
                dt1Map.put("sfqy", 0);
                dt1Map.put("zssx", stageDt1.getZssx());
                RecruitRecordSet.insertData(dt1Map, "uf_jcl_zpjdsz_dt1");
            }

            // 插入明细表2
            for (OperateStageDt2 stageDt2 : dt2List) {
                Map<String, Object> dt2Map = new RecruitDataMap<>();
                dt2Map.put("mainid", id);
                dt2Map.put("ymbt", stageDt2.getYmbt());
                dt2Map.put("ymdz", stageDt2.getYmdz());
                dt2Map.put("zssx", stageDt2.getZssx());
                RecruitRecordSet.insertData(dt2Map, "uf_jcl_zpjdsz_dt2");
            }

        }
    }

    /**
     * 构建招聘阶段设置，明细表2数据集合
     *
     * @return
     */
    private List<OperateStageDt2> buildStageDt2Data() {
        List<OperateStageDt2> dt2List = new ArrayList<>();
        dt2List.add(OperateStageDt2.builder()
                .ymbt("原始简历")
                .ymdz("/spa/document/index.jsp?id=$ysjl$&isRecruitCard=true")
                .zssx(0)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("基本信息")
                .ymdz(getModeLink("/spa/cube/index.html#/main/cube/card?type=0&modeId={modeId}&formId={formId}&billid=$parentid$&opentype=0&isRecruitCard=true", "uf_jcl_yppc", "", ""))
                .zssx(10)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("部门筛选反馈")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&isRecruitCard=true&customid={customid}", "uf_jcl_bmsxfk", "筛选反馈-简历卡片"))
                .zssx(20)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("笔试")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&isRecruitCard=true&customid={customid}", "uf_jcl_bs", "笔试-简历卡片"))
                .zssx(30)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("面试")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&isRecruitCard=true&customid={customid}", "uf_jcl_ms", "面试-简历卡片"))
                .zssx(40)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("背调")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&isRecruitCard=true&customid={customid}", "uf_jcl_bd", "背调-简历卡片"))
                .zssx(50)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("薪酬谈判")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&isRecruitCard=true&customid={customid}", "uf_jcl_xctp", "薪酬谈判-简历卡片"))
                .zssx(60)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("历史投递记录")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&xm=$xm$&sjhm=$sjhm$&isRecruitCard=true&customid={customid}", "uf_jcl_yppc", "相关历史投递记录"))
                .zssx(70)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("备注")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&isRecruitCard=true&customid={customid}", "uf_jcl_bz", "备注-简历卡片"))
                .zssx(80)
                .build());

        dt2List.add(OperateStageDt2.builder()
                .ymbt("应聘过程")
                .ymdz(getModeSearchUrl("/spa/cube/index.html#/main/cube/search?pcid=$parentid$&isRecruitCard=true&customid={customid}", "uf_jcl_ypgc", "应聘过程-简历卡片"))
                .zssx(90)
                .build());

        return dt2List;

    }


    private List<OperateStagePo> buildOperateStageList(Map<String, OperateButtonPo> operateButtonMap) {
        List<OperateStagePo> stageList = new ArrayList<>();
        stageList.add(buildStagePo(OperateStagePo.builder().jdmc("筛选").jdms("筛选").jdlx(0).hj(0).build(),
                operateButtonMap,
                "进入下一阶段", "部门筛选", "淘汰", "转移阶段", "转推其他职位", "归档人才库", "添加备注", "加入黑名单"));

        stageList.add(buildStagePo(OperateStagePo.builder().jdmc("笔试").jdms("笔试").jdlx(1).hj(1).build(),
                operateButtonMap,
                "进入下一阶段", "安排笔试", "转移阶段", "淘汰", "转推其他职位", "归档人才库", "添加备注", "加入黑名单"));

        stageList.add(buildStagePo(OperateStagePo.builder().jdmc("面试").jdms("面试").jdlx(2).hj(1).build(),
                operateButtonMap,
                "进入下一阶段", "安排面试", "淘汰", "转移阶段", "转推其他职位", "归档人才库", "添加备注", "加入黑名单"));

        stageList.add(buildStagePo(OperateStagePo.builder().jdmc("背调").jdms("背调").jdlx(5).hj(1).build(),
                operateButtonMap,
                "进入下一阶段", "背调结果登记", "淘汰", "转移阶段", "转推其他职位", "归档人才库", "添加备注", "加入黑名单"));

        stageList.add(buildStagePo(OperateStagePo.builder().jdmc("薪酬谈判").jdms("薪酬谈判").jdlx(4).hj(1).build(),
                operateButtonMap,
                "进入下一阶段", "谈判记录登记", "淘汰", "转移阶段", "转推其他职位", "归档人才库", "添加备注", "加入黑名单"));

        stageList.add(buildStagePo(OperateStagePo.builder().jdmc("offer").jdms("offer").jdlx(6).hj(2).build(),
                operateButtonMap,
                "创建offer", "转为待入职", "转移阶段", "淘汰", "转推其他职位", "归档人才库", "添加备注", "加入黑名单"));
        return stageList;
    }

    private OperateStagePo buildStagePo(OperateStagePo stagePo, Map<String, OperateButtonPo> operateButtonMap, String... buttonNames) {
        List<OperateStageDt1> dt1 = new ArrayList<>();
        int index = 10;
        for (String buttonName : buttonNames) {
            OperateButtonPo operateButtonPo = operateButtonMap.get(buttonName);
            dt1.add(OperateStageDt1.builder()
                    .czan(operateButtonPo.getId())
                    .zdyxsmc(operateButtonPo.getButtonName())
                    .tzymdz(operateButtonPo.getLinkUrl())
                    .zssx(index)
                    .build());
            index += 10;
        }
        stagePo.setDt1(dt1);
        return stagePo;
    }


    /**
     * 插入操作按钮数据
     *
     * @param baseMap
     * @param modeId
     * @return
     */
    private List<OperateButtonPo> insertButtonData(Map<String, Object> baseMap, int modeId) {
        List<OperateButtonPo> buttonList = buildButtonList();
        for (OperateButtonPo button : buttonList) {
            RecruitDataMap<Object> buttonDataMap = new RecruitDataMap<>();
            buttonDataMap.putAll(baseMap);
            String uuid = UUID.randomUUID().toString();
            buttonDataMap.put("modeuuid", uuid);
            buttonDataMap.put("formmodeid", modeId);
            buttonDataMap.put("anmc", button.getButtonName());
            buttonDataMap.put("sfqy", "0");
            buttonDataMap.put("anbs", button.getButtonKey());
            buttonDataMap.put("andz", button.getButtonAction());

            RecruitRecordSet.insertData(buttonDataMap, "uf_jcl_lcczan");
            int id = RecruitRecordSet.refreshRight(uuid, "uf_jcl_lcczan", modeId, 1);
            button.setId(id);
        }
        return buttonList;
    }

    /**
     * 构建操作按钮基础信息
     *
     * @return
     */
    private List<OperateButtonPo> buildButtonList() {
        List<OperateButtonPo> buttonList = new ArrayList<>();
        buttonList.add(OperateButtonPo.builder().buttonName("进入下一阶段").buttonAction("postAndReload")
                .buttonKey("com.engine.recruit.service.impl.NextStageServiceImpl")
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("部门筛选").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&{ypz}=$parentid$", "uf_jcl_bmsx", "", "ypz"))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("淘汰").buttonAction("confirmAndReload")
                .buttonKey("com.engine.recruit.service.impl.EliminateServiceImpl")
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("转推其他职位").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&layoutid={layoutid}&guid=card&sourceId=$parentid$", "uf_jcl_yppc", "转推其他职位-新建一个投递", ""))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("归档人才库").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&layoutid={layoutid}&guid=card&ids=$parentid$", "uf_jcl_yppc", "归档人才库-新建模板", ""))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("加入黑名单").buttonAction("confirmAndReload")
                .buttonKey("com.engine.recruit.service.impl.JoinBlacklistServiceImpl")
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("安排笔试").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?modeId={modeId}&formId={formId}&type=1&layoutid={layoutid}&{ypz}=$parentid$", "uf_jcl_bs", "笔试安排-新建模板", "ypz"))
                .build());

        //buttonList.add(OperateButtonPo.builder().buttonName("笔试结果登记").buttonAction("openDialog")
        //        .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?modeId={modeId}&formId={formId}&type=1&layoutid={layoutid}&{ypz}=$parentid$", "uf_jcl_bs", "笔试结果-编辑模板", "ypz"))
        //        .build());

        buttonList.add(OperateButtonPo.builder().buttonName("安排面试").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&{ypz}=$parentid$", "uf_jcl_ms", "", "ypz"))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("背调结果登记").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&{ypz}=$parentid$&recordType=addBackTone", "uf_jcl_bd", "", "ypz"))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("谈判记录登记").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&{ypz}=$parentid$&recordType=addSalaryNegotiation", "uf_jcl_xctp", "", "ypz"))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("创建offer").buttonAction("openDialog")
                .linkUrl(getWorkFlowLink("/spa/workflow/index_form.jsp#/main/workflow/req?iscreate=1&workflowid={workflowid}&{xm}=$parentid$", "jcl_offer审批", "xm"))
                .build());


        buttonList.add(OperateButtonPo.builder().buttonName("转为待入职").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&pcid=$parentid$&recordType=pendingEmployment", "uf_jcl_rzgl", "", ""))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("转移阶段").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?billid=$parentid$&type=2&modeId={modeId}&formId={formId}&layoutid={layoutid}&guid=card&id=$parentid$", "uf_jcl_yppc", "转移阶段", ""))
                .build());

        buttonList.add(OperateButtonPo.builder().buttonName("添加备注").buttonAction("openDialog")
                .linkUrl(getModeLink("/spa/cube/index.html#/main/cube/card?type=1&modeId={modeId}&formId={formId}&{ypz}=$parentid$", "uf_jcl_bz", "", "ypz"))
                .build());

        return buttonList;
    }


    /**
     * 获取阶段ID
     *
     * @param stageName
     * @return
     */
    private String getStageIdByName(String stageName) {
        String stageId = null;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id from uf_jcl_zpjdsz where zplc =-1 and jdmc = ?  ", stageName);
        if (rs.next()) {
            stageId = rs.getString("id");
        }
        return stageId;
    }

    /**
     * 完善查询相关URL
     *
     * @param url
     * @param tableName
     * @param customName
     * @return
     */
    private String getModeSearchUrl(String url, String tableName, String customName) {
        String searchUrl = url;
        int modeId = ApplicantCommonInfo.getModeIdByTableName(tableName);
        int customId = ApplicantCommonInfo.getCustomId(modeId, customName);

        searchUrl = searchUrl.replace("{customid}", String.valueOf(customId));

        return searchUrl;
    }

    /**
     * 动态完善建模相关URL
     *
     * @param url
     * @param tableName
     * @param layoutName
     * @param fieldName
     * @return
     */
    private String getModeLink(String url, String tableName, String layoutName, String fieldName) {
        String modeLink = url;
        int modeId = ApplicantCommonInfo.getModeIdByTableName(tableName);
        int formId = ApplicantCommonInfo.getFormIdByTableName(tableName);
        modeLink = modeLink.replace("{modeId}", String.valueOf(modeId));
        modeLink = modeLink.replace("{formId}", String.valueOf(formId));

        if (StringUtils.isNotBlank(layoutName)) {
            int layoutId = ApplicantCommonInfo.getLayoutId(modeId, layoutName);
            modeLink = modeLink.replace("{layoutid}", String.valueOf(layoutId));
        }

        if (StringUtils.isNotBlank(fieldName)) {
            int fieldId = ApplicantCommonInfo.getFieldId(formId, fieldName);
            modeLink = modeLink.replace("{" + fieldName + "}", "field" + fieldId);
        }
        return modeLink;
    }

    /**
     * 动态完善流程相关URL
     *
     * @param url
     * @param workflowName
     * @param fieldName
     * @return
     */
    private String getWorkFlowLink(String url, String workflowName, String fieldName) {
        String workFlowLink = url;
        String workflowId = "";
        int formId = -1;
        RecordSet rs = new RecordSet();
        rs.executeQuery("select id,formid  from workflow_base where workflowname like '" + workflowName + "%'");
        if (rs.next()) {
            workflowId = rs.getString("id");
            formId = rs.getInt("formid");
        }
        workFlowLink = workFlowLink.replace("{workflowid}", workflowId);
        if (StringUtils.isNotBlank(fieldName)) {
            int fieldId = ApplicantCommonInfo.getFieldId(formId, fieldName);
            workFlowLink = workFlowLink.replace("{" + fieldName + "}", "field" + fieldId);
        }
        return workFlowLink;
    }

}
