package com.engine.recruit.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.engine.core.impl.Service;
import com.engine.recruit.conn.ApplicantCommonInfo;
import com.engine.recruit.conn.RecruitRecordSet;
import com.engine.recruit.entity.position.PositionRelease;
import com.engine.recruit.entity.position.PositionSdkInstance;
import com.engine.recruit.entity.position.PositionSelectItem;
import com.engine.recruit.enums.PositionReleaseStatusEnum;
import com.engine.recruit.enums.PositionThirdChannelEnum;
import com.engine.recruit.exception.CustomizeRunTimeException;
import com.engine.recruit.service.RecruitPositionService;
import com.weaver.formmodel.data.model.Formfield;
import com.weaver.rpa.sdk.clients.application.resume.ERPAResumeSDKClient;
import com.weaver.rpa.sdk.clients.application.resume.common.ResumeJobStatus;
import com.weaver.rpa.sdk.clients.application.resume.entity.ResumeJobDynamicField;
import com.weaver.rpa.sdk.clients.application.resume.entity.ResumeJobV2Dto;
import com.weaver.rpa.sdk.exception.RpaSdkException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import weaver.conn.RecordSet;
import weaver.erpa.apps.entity.application.resume.dto.ResumeTaskResult;
import weaver.erpa.apps.entity.application.resume.enums.TaskResult;
import weaver.formmode.recruit.modeexpand.util.RecruitModeUtil;
import weaver.formmode.recruit.modeexpand.util.RecruitPositionUtil;
import weaver.general.BaseBean;
import weaver.general.Util;

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

/**
 * @author:dxfeng
 * @createTime: 2023/10/09
 * @version: 1.0
 */
public class RecruitPositionServiceImpl extends Service implements RecruitPositionService {

    @Override
    public Map<String, Object> updatePostInfo(Map<String, Object> param) {
        Map<String, Object> returnMap = new HashMap<>();
        String zpzwfzr = Util.null2String(param.get("zpzwfzr"));
        String zpxzr = Util.null2String(param.get("zpxzr"));
        String ids = Util.null2String(param.get("ids"));
        if (StringUtils.isBlank(ids)) {
            throw new CustomizeRunTimeException("数据有误，请重试");
        }
        RecordSet rs = new RecordSet();
        if (StringUtils.isNotBlank(zpzwfzr)) {
            rs.executeUpdate(" update uf_jcl_zp_zpzw set zpzwfzr = ? where id in (" + ids + ")", zpzwfzr);
        }
        if (StringUtils.isNotBlank(zpxzr)) {
            rs.executeUpdate(" update uf_jcl_zp_zpzw set zpxzr = ? where id in (" + ids + ")", zpxzr);
        }
        return returnMap;
    }

    @Override
    public Map<String, Object> getFormCondition(Map<String, Object> param) {
        Map<String, Object> apidatas = new HashMap<>();
        apidatas.put("hasRight", true);
        String conditionType = Util.null2String(param.get("conditionType"));
        String selectValue = Util.null2String(param.get("selectValue"));

        boolean enableSdkClient = PositionSdkInstance.enableSdkClient();
        if (!enableSdkClient) {
            throw new CustomizeRunTimeException("千里聆SDK校验失败，无法获取职位动态字段，请检查千里聆非标配置");
        }
        PositionSdkInstance positionSdkInstance = PositionSdkInstance.getPositionSdkInstance();

        // 获取职位类别表单
        if ("positionType".equals(conditionType)) {
            String dsfqd = Util.null2String(param.get("dsfqd"));
            getPositionType(dsfqd, selectValue, apidatas, positionSdkInstance);
        }

        // 前程无忧-发布城市
        if ("job51City".equals(conditionType)) {
            getCityType(selectValue, apidatas, positionSdkInstance);
        }

        // 前程无忧-所属行业
        if ("industryType".equals(conditionType)) {
            getIndustryType(selectValue, apidatas, positionSdkInstance);
        }

        // BOSS直聘-驻外语言要求
        if ("residentLanguage".equals(conditionType)) {
            getResidentLanguage(selectValue, apidatas, positionSdkInstance);
        }

        // BOSS直聘-驻外国家或地区
        if ("residentCountry".equals(conditionType)) {
            getResidentCountry(selectValue, apidatas, positionSdkInstance);
        }

        // BOSS直聘-是否驻外
        if ("multiSelect".equals(conditionType)) {
            getMultiSelect(apidatas, positionSdkInstance);
        }
        return apidatas;
    }

    @Override
    public Map<String, Object> releaseResumeJob(Map<String, Object> param) {
        try {
            String billId = Util.null2String(param.get("billId"));
            String platformIds = Util.null2String(param.get("platformIds"));
            if (StringUtils.isBlank(platformIds)) {
                throw new CustomizeRunTimeException("请选择要发布的平台");
            }
            RecordSet rs = new RecordSet();
            rs.executeQuery("select * from uf_jcl_zp_zpzw where id = ?", billId);
            Map<String, Object> map = RecruitRecordSet.getSingleRecordMap(rs);
            String msg = "发布操作完成";
            boolean enableSdkClient = PositionSdkInstance.enableSdkClient();
            if (enableSdkClient) {
                long jobId = -1;
                String qllgwid = Util.null2String(map.get("qllgwid"));
                if (StringUtils.isNotBlank(qllgwid)) {
                    jobId = Long.parseLong(qllgwid);
                }

                ERPAResumeSDKClient client = PositionSdkInstance.getPositionSdkInstance().getResumeSDKClient();

                ResumeJobV2Dto resumeJobDto = RecruitPositionUtil.convertMap2ResumeJobV2Dto(user, map);
                RecruitPositionUtil.checkRequiredFields(resumeJobDto);
                String userId = String.valueOf(user.getUID());
                // 未创建职位，则先创建职位
                if (jobId == -1) {
                    rs.writeLog("【创建职位】,[id=" + billId + "],resumeJobDto=" + JSON.toJSONString(resumeJobDto));
                    // 创建千里聆职位
                    jobId = client.addResumeJobV2(userId, resumeJobDto);
                    // 更新千里聆ID到建模表单
                    rs.executeUpdate("update uf_jcl_zp_zpzw set qllgwid = ? where id = ?", jobId, billId);
                } else {
                    rs.writeLog("【更新职位】,[id=" + billId + "],[qllgwid=" + jobId + "],resumeJobDto=" + JSON.toJSONString(resumeJobDto));
                    // 已发布的职位，更新职位信息
                    client.editResumeJobV2(userId, jobId, jobDto -> {
                        BeanUtils.copyProperties(resumeJobDto, jobDto);
                    });
                }

                String[] split = platformIds.split(",");
                for (String platformId : split) {
                    PositionThirdChannelEnum positionThirdChannelEnum = PositionThirdChannelEnum.getEnumByValue(platformId);

                    ResumeTaskResult result = client.releaseResumeJob(userId, jobId, positionThirdChannelEnum.getResumePlatformId());
                    // 直接查看结果，正在执行中会返回PENGING，成功后会返回SUCCEED，失败后会返回FAILED
                    TaskResult current = result.getResult();
                    rs.writeLog(current);
                    // 使用回调函数获取成功或者失败时的消息
                    result.onResult(() -> {
                        rs.writeLog("发布成功回调");
                    }, (reason) -> {
                        rs.writeLog("发布失败回调，原因：" + reason);
                    });

                    // 等待直到状态不再是PENDING
                    TaskResult taskResult = result.waitResult();
                    rs.writeLog(taskResult);
                    Integer status;
                    if (taskResult == TaskResult.SUCCEED) {
                        status = PositionReleaseStatusEnum.PUBLISHED.getValue();
                    } else {
                        msg = "发布操作完成，" + result.getFailReason();
                        status = PositionReleaseStatusEnum.PUBLISHING_FAILED.getValue();
                    }
                    recordPublishingStatus(billId, platformId, status, result.getFailReason());
                }
            } else {
                msg = "未配置发布插件，第三方平台请至各招聘网站自行发布";
                String[] splits = platformIds.split(",");
                for (String platformId : splits) {
                    recordPublishingStatus(billId, platformId, PositionReleaseStatusEnum.PUBLISHED.getValue(), msg);
                }
            }
            Map<String, Object> reportList = getReportList(param);
            reportList.put("msg", msg);
            return reportList;
        } catch (InterruptedException | RpaSdkException e) {
            throw new CustomizeRunTimeException(e.getMessage(), e);
        }
    }

    @Override
    public Map<String, Object> closeResumeJob(Map<String, Object> param) {
        try {
            String billId = Util.null2String(param.get("billId"));
            // 当前仅支持所有渠道一键下架
            //String platformIds = Util.null2String(param.get("platformIds"));
            //if (StringUtils.isBlank(platformIds)) {
            //    throw new CustomizeRunTimeException("请选择要发布的平台");
            //}
            RecordSet rs = new RecordSet();

            // 查询已发布渠道的信息
            String platformIds = Util.null2String(param.get("platformIds"));
            List<String> platformList = new ArrayList<>();
            rs.executeQuery("select inner_channel from uf_jcl_qdfb where position = ? and status = ? ", billId, PositionReleaseStatusEnum.PUBLISHED.getValue());
            while (rs.next()) {
                platformList.add(rs.getString("inner_channel"));
            }

            // 判断是否配置千里聆，若未配置千里聆信息，则不执行下架职位操作，只更新状态
            boolean enableSdkClient = PositionSdkInstance.enableSdkClient();
            String msg = "";
            if (enableSdkClient) {
                rs.executeQuery("select qllgwid from uf_jcl_zp_zpzw where id = ?", billId);
                if (rs.next()) {
                    String qllgwid = rs.getString("qllgwid");
                    // 第三方渠道未发布，不调用千里聆执行职位下架操作
                    if (StringUtils.isBlank(qllgwid)) {
                        throw new CustomizeRunTimeException("billId=" + billId + ",当前职位暂未同步至千里聆发布,无需进行下架操作");
                    }

                    if (CollectionUtils.isEmpty(platformList)) {
                        throw new CustomizeRunTimeException("当前职位暂未发布,无需进行下架操作");
                    }

                    long jobId = Long.parseLong(qllgwid);
                    ERPAResumeSDKClient client = PositionSdkInstance.getPositionSdkInstance().getResumeSDKClient();
                    String userId = String.valueOf(user.getUID());
                    ResumeTaskResult result = client.closeResumeJob(userId, jobId);

                    TaskResult current = result.getResult();
                    rs.writeLog(current);

                    // 使用回调函数获取成功或者失败时的消息
                    result.onResult(() -> {
                        rs.writeLog("下架成功回调");
                    }, (reason) -> {
                        rs.writeLog("下架失败回调，原因：" + reason);
                    });

                    // 等待直到状态不再是PENDING
                    TaskResult taskResult = result.waitResult();
                    rs.writeLog(taskResult);
                    if (taskResult == TaskResult.SUCCEED) {
                        msg = "下架操作完成";
                    } else {
                        msg = result.getFailReason();
                    }
                    syncResumePlatformStatus(billId, jobId, client);
                }
            } else {
                msg = "未配置下架插件，第三方平台请至各招聘网站自行下架";
                for (String platformId : platformList) {
                    recordPublishingStatus(billId, platformId, PositionReleaseStatusEnum.CLOSED.getValue(), msg);
                }
            }
            Map<String, Object> reportList = getReportList(param);
            reportList.put("msg", msg);
            return reportList;
        } catch (InterruptedException | RpaSdkException e) {
            throw new CustomizeRunTimeException(e.getMessage(), e);
        }
    }

    @Override
    public Map<String, Object> refreshResumeJob(Map<String, Object> param) {
        String billId = Util.null2String(param.get("billId"));
        RecordSet rs = new RecordSet();
        try {
            long jobId = -1;
            rs.executeQuery("select qllgwid from uf_jcl_zp_zpzw where id = ?", billId);
            if (rs.next()) {
                String qllgwid = rs.getString("qllgwid");
                // 第三方渠道未发布，不调用千里聆执行职位下架操作
                if (StringUtils.isBlank(qllgwid)) {
                    throw new CustomizeRunTimeException("当前职位未同步至千里聆发布,无需进行刷新操作,职位ID【" + billId + "】");
                }
                jobId = Long.parseLong(qllgwid);
            }
            ERPAResumeSDKClient client = PositionSdkInstance.getPositionSdkInstance().getResumeSDKClient();
            ResumeTaskResult result = client.refreshResumeJob(String.valueOf(user.getUID()), jobId);
            String msg = "";

            TaskResult current = result.getResult();
            rs.writeLog(current);

            // 使用回调函数获取成功或者失败时的消息
            result.onResult(() -> {
                rs.writeLog("刷新成功回调");
            }, (reason) -> {
                rs.writeLog("刷新失败回调，原因：" + reason);
            });

            // 等待直到状态不再是PENDING
            TaskResult taskResult = result.waitResult();
            rs.writeLog(taskResult);
            if (taskResult == TaskResult.SUCCEED) {
                msg = "刷新操作完成";
                syncResumePlatformStatus(billId, jobId, client);
            } else {
                msg = "刷新操作完成，" + result.getFailReason();
            }
            Map<String, Object> reportList = getReportList(param);
            reportList.put("msg", msg);
            return reportList;
        } catch (InterruptedException | RpaSdkException e) {
            throw new CustomizeRunTimeException(e.getMessage(), e);
        }
    }


    @Override
    public Map<String, Object> getReportList(Map<String, Object> param) {
        String billId = Util.null2String(param.get("billId"));
        RecordSet rs = new RecordSet();
        rs.executeQuery("select * from uf_jcl_qdfb where position = ?", billId);
        List<PositionRelease> list = new ArrayList<>();
        Map<String, Object> returnMap = new HashMap<>();
        while (rs.next()) {
            Integer status = Convert.toInt(rs.getString("status"), 0);
            PositionReleaseStatusEnum releaseStatusEnum = PositionReleaseStatusEnum.getEnumByValue(status);
            PositionRelease positionRelease = new PositionRelease();
            positionRelease.setId(rs.getInt("inner_channel"));
            positionRelease.setStatus(releaseStatusEnum.getLabel());
            String tips = rs.getString("tips");
            if (StringUtils.isNotBlank(tips)) {
                positionRelease.setTips(tips);
            }
            list.add(positionRelease);
        }
        returnMap.put("list", list);
        return returnMap;
    }

    @Override
    public Map<String, Object> setStepMsgConfig(Map<String, Object> param) {
        Map<String, Object> resultMap = new HashMap<>();
        RecordSet rs = new RecordSet();
        String checked = Util.null2String(param.get("checked"));
        String zpzw = Util.null2String(param.get("cardid"));
        if (StringUtils.isBlank(zpzw)) {
            zpzw = "-1";
        }
        if (StringUtils.isNotBlank(checked)) {
            checked = "true".equals(checked) ? "1" : "0";
            rs.executeQuery("select qyzt from uf_jcl_step_config where zpzw = ? ", zpzw);
            if (rs.next()) {
                // 更新数据
                rs.executeUpdate("update uf_jcl_step_config set qyzt = ? where zpzw = ?", checked, zpzw);
            } else {
                // 插入数据
                rs.executeUpdate("insert into uf_jcl_step_config (zpzw, qyzt) values (?, ?)", zpzw, checked);
            }
        }
        rs.executeQuery("select qyzt from uf_jcl_step_config where zpzw = ?", zpzw);
        if (rs.next()) {
            resultMap.put("enable", "1".equals(rs.getString("qyzt")));
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> saveAndReleaseResumeJob(Map<String, Object> param) {
        String billId = Util.null2String(param.get("billId"));
        String submitDataStr = Util.null2String(param.get("submitData"));
        if (StringUtils.isAnyBlank(billId, submitDataStr)) {
            throw new CustomizeRunTimeException("职位发布失败，接口传参有误");
        }
        JSONObject submitData = JSONObject.parseObject(submitDataStr);
        List<Formfield> fieldList = RecruitModeUtil.getFieldList("uf_jcl_zp_zpzw");
        Map<String, Formfield> fieldIdMap = fieldList.stream().collect(Collectors.toMap(item -> "field" + item.getId()
                , item -> item, (k1, k2) -> k1));
        Map<String, Object> mainDataMap = new HashMap<>();
        Map<String, Object> innerMap = submitData.getInnerMap();
        BaseBean baseBean = new BaseBean();
        for (Map.Entry<String, Object> entry : innerMap.entrySet()) {
            String key = entry.getKey();
            String value = Util.null2String(entry.getValue());
            Formfield formfield = fieldIdMap.get(key);
            if (null != formfield) {
                String fieldName = formfield.getFieldname();
                if (StringUtils.isNotBlank(value)) {
                    mainDataMap.put(fieldName, value);
                } else {
                    mainDataMap.put(fieldName, null);
                    if ("text".equals(formfield.getFielddbtype())) {
                        mainDataMap.put(fieldName, "");
                    }
                }
            } else {
                baseBean.writeLog("未匹配到对应字段,key==" + key);
            }
        }
        mainDataMap.put("id", billId);

        RecruitRecordSet.updateDataById(mainDataMap, "uf_jcl_zp_zpzw");
        return releaseResumeJob(param);
    }

    /**
     * 获取职位类别
     *
     * @param dsfqd
     * @param selectValue
     * @param apidatas
     * @param positionSdkInstance
     */
    private void getPositionType(String dsfqd, String selectValue, Map<String, Object> apidatas, PositionSdkInstance positionSdkInstance) {
        String[] split = selectValue.split("#");
        Map<String, String> selectValueMap = new HashMap<>();
        for (String s : split) {
            String[] split1 = s.split(":");
            if (split1.length == 2) {
                selectValueMap.put(split1[0], split1[1]);
            }
        }
        String boss_value = selectValueMap.get("BOSS直聘");
        apidatas.put("boss_value", StringUtils.isBlank(boss_value) ? null : Arrays.asList(boss_value.split("-")));
        String liepin_value = selectValueMap.get("猎聘");
        apidatas.put("liepin_value", StringUtils.isBlank(liepin_value) ? null : Arrays.asList(liepin_value.split("-")));
        String lagou_value = selectValueMap.get("拉勾");
        apidatas.put("lagou_value", StringUtils.isBlank(lagou_value) ? null : Arrays.asList(lagou_value.split("-")));
        String job51_value = selectValueMap.get("前程无忧");
        apidatas.put("job51_value", StringUtils.isBlank(job51_value) ? null : Arrays.asList(job51_value.split("-")));
        String zhilian_value = selectValueMap.get("智联");
        apidatas.put("zhilian_value", StringUtils.isBlank(zhilian_value) ? null : Arrays.asList(zhilian_value.split("-")));

        boolean bossShow = false;
        boolean liepinShow = false;
        boolean lagouShow = false;
        boolean job51Show = false;
        boolean zhilianShow = false;
        if (dsfqd.contains("0")) {
            List<ResumeJobDynamicField.Item> boss_type = positionSdkInstance.getBoss_type();
            apidatas.put("boss", boss_type);
            bossShow = true;
        }

        if (dsfqd.contains("4")) {
            List<ResumeJobDynamicField.Item> liepin_type = positionSdkInstance.getLiepin_type();
            apidatas.put("liepin", liepin_type);
            liepinShow = true;
        }
        if (dsfqd.contains("3")) {
            List<ResumeJobDynamicField.Item> lagou_type = positionSdkInstance.getLagou_type();
            apidatas.put("lagou", lagou_type);
            lagouShow = true;
        }

        if (dsfqd.contains("2")) {
            List<ResumeJobDynamicField.Item> job51_type = positionSdkInstance.getJob51_type();
            apidatas.put("job51", job51_type);
            job51Show = true;
        }

        if (dsfqd.contains("1")) {
            List<ResumeJobDynamicField.Item> zhilian_type = positionSdkInstance.getZhilian_type();
            apidatas.put("zhilian", zhilian_type);
            zhilianShow = true;
        }
        apidatas.put("bossShow", bossShow);
        apidatas.put("liepinShow", liepinShow);
        apidatas.put("lagouShow", lagouShow);
        apidatas.put("job51Show", job51Show);
        apidatas.put("zhilianShow", zhilianShow);
    }

    /**
     * 获取发布城市
     *
     * @param selectValue
     * @param apidatas
     * @param positionSdkInstance
     */
    private void getCityType(String selectValue, Map<String, Object> apidatas, PositionSdkInstance positionSdkInstance) {
        List<String> valueList = new ArrayList<>();
        if (StringUtils.isNotBlank(selectValue)) {
            String[] split = selectValue.split(",");
            valueList = Arrays.asList(split);
        }

        List<ResumeJobDynamicField.Item> job51_city = positionSdkInstance.getJob51_city();
        if (CollectionUtils.isNotEmpty(job51_city)) {
            job51_city = job51_city.parallelStream().filter(item -> !item.getLabel().contains("省")).collect(Collectors.toList());
        }
        apidatas.put("job51_city", job51_city);
        apidatas.put("job51CityValue", valueList);
    }

    /**
     * 获取所属行业
     *
     * @param selectValue
     * @param apidatas
     * @param positionSdkInstance
     */
    private void getIndustryType(String selectValue, Map<String, Object> apidatas, PositionSdkInstance positionSdkInstance) {
        List<List<String>> valueList = new ArrayList<>();
        if (StringUtils.isNotBlank(selectValue)) {
            String[] split = selectValue.split("#");
            for (String s : split) {
                String[] split1 = s.split("-");
                valueList.add(Arrays.asList(split1));
            }
        }

        List<ResumeJobDynamicField.Item> job51_industry = positionSdkInstance.getJob51_industry();
        apidatas.put("job51_industry", job51_industry);
        apidatas.put("job51IndustryValue", valueList);
    }


    /**
     * 驻外语言要求
     *
     * @param selectValue
     * @param apidatas
     * @param positionSdkInstance
     */
    private void getResidentLanguage(String selectValue, Map<String, Object> apidatas, PositionSdkInstance positionSdkInstance) {
        List<String> valueList = new ArrayList<>();
        if (StringUtils.isNotBlank(selectValue)) {
            String[] split = selectValue.split(",");
            valueList = Arrays.asList(split);
        }

        List<ResumeJobDynamicField.Item> boss_resident_language = positionSdkInstance.getBoss_resident_language();
        apidatas.put("boss_resident_language", boss_resident_language);
        apidatas.put("bossResidentLanguage", valueList);
    }

    /**
     * 驻外国家或地区
     *
     * @param selectValue
     * @param apidatas
     * @param positionSdkInstance
     */
    private void getResidentCountry(String selectValue, Map<String, Object> apidatas, PositionSdkInstance positionSdkInstance) {
        List<String> valueList = new ArrayList<>();
        if (StringUtils.isNotBlank(selectValue)) {
            String[] split = selectValue.split(",");
            valueList = Arrays.asList(split);
        }

        List<ResumeJobDynamicField.Item> boss_resident_country = positionSdkInstance.getBoss_resident_country();
        apidatas.put("boss_resident_country", boss_resident_country);
        apidatas.put("bossResidentCountry", valueList);
    }


    /**
     * 获取招聘职位，多线下拉框字段信息
     *
     * @param apidatas
     * @param positionSdkInstance
     */
    private void getMultiSelect(Map<String, Object> apidatas, PositionSdkInstance positionSdkInstance) {
        apidatas.put("boss_resident", PositionSelectItem.convertDynamicFieldItem(positionSdkInstance.getBoss_resident()));
        //apidatas.put("boss_resident_country", PositionSelectItem.convertDynamicFieldItem(positionSdkInstance.getBoss_resident_country()));
        //apidatas.put("boss_resident_language", PositionSelectItem.convertDynamicFieldItem(positionSdkInstance.getBoss_resident_language()));
        apidatas.put("boss_resident_time", PositionSelectItem.convertDynamicFieldItem(positionSdkInstance.getBoss_resident_time()));
        apidatas.put("boss_resident_time_2", PositionSelectItem.convertDynamicFieldItem(positionSdkInstance.getBoss_resident_time_2()));
        //apidatas.put("job51_city", PositionSelectItem.convertDynamicFieldItem(positionSdkInstance.getJob51_city()));
    }


    /**
     * 记录发布状态
     *
     * @param position
     * @param innerChannel
     * @param status
     * @param tips
     */
    private void recordPublishingStatus(String position, String innerChannel, Integer status, String tips) {
        String tableName = "uf_jcl_qdfb";
        Map<String, Object> insertMap = new HashMap<>();
        String uuid = UUID.randomUUID().toString();
        insertMap.put("modeuuid", uuid);
        int formModeId = ApplicantCommonInfo.getModeIdByTableName(tableName);
        insertMap.put("formmodeid", formModeId);
        RecruitRecordSet.buildModeInsertFields(insertMap, user.getUID());
        insertMap.put("position", position);
        insertMap.put("inner_channel", innerChannel);
        insertMap.put("status", status);
        if (StringUtils.isNotBlank(tips)) {
            insertMap.put("tips", tips);
        }
        RecruitRecordSet.insertData(insertMap, tableName);
        int id = RecruitRecordSet.refreshRight(uuid, tableName, formModeId, user.getUID());

        // 删除原来该职位下，该渠道的数据
        String deleteSql = "delete from uf_jcl_qdfb where position = '" + position + "' and inner_channel = " + innerChannel + " and id != " + id;
        RecruitRecordSet.deleteData(deleteSql);
    }


    private void syncResumePlatformStatus(String billId, long jobId, ERPAResumeSDKClient client) {
        Map<Integer, ResumeJobStatus> integerResumeJobStatusMap = client.syncResumePlatformStatus(String.valueOf(user.getUID()), jobId);
        for (Map.Entry<Integer, ResumeJobStatus> entry : integerResumeJobStatusMap.entrySet()) {
            Integer key = entry.getKey();
            ResumeJobStatus value = entry.getValue();
            Integer status = PositionReleaseStatusEnum.UNPUBLISHED.getValue();
            if (null == value) {
                status = PositionReleaseStatusEnum.CLOSED.getValue();
            } else if (value.equals(ResumeJobStatus.RELEASED)) {
                status = PositionReleaseStatusEnum.PUBLISHED.getValue();
            } else if (value.equals(ResumeJobStatus.UNRELEASED)) {
                status = PositionReleaseStatusEnum.UNPUBLISHED.getValue();
            }
            PositionThirdChannelEnum positionThirdChannelEnum = PositionThirdChannelEnum.getEnumByPlatformId(key);
            recordPublishingStatus(billId, positionThirdChannelEnum.getValue(), status, null);
        }
    }
}
