package weaver.formmode.recruit.modeexpand.position;

import com.alibaba.fastjson.JSON;
import com.engine.recruit.entity.position.PositionSdkInstance;
import com.weaver.rpa.sdk.clients.application.resume.ERPAResumeSDKClient;
import com.weaver.rpa.sdk.clients.application.resume.entity.ResumeJobV2Dto;
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.customjavacode.AbstractModeExpandJavaCodeNew;
import weaver.formmode.recruit.modeexpand.util.RecruitPositionUtil;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.User;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

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

/**
 * 新版职位发布调用接口分渠道发布，该页面拓展已废弃
 *
 * @author:dxfeng
 * @createTime: 2023/10/07
 * @version: 1.0
 */
@Deprecated
public class ReleasePositionModeExpand extends AbstractModeExpandJavaCodeNew {

    @Override
    public Map<String, String> doModeExpand(Map<String, Object> param) {
        String tableName = "uf_jcl_zp_zpzw";

        Map<String, String> resultMap = new HashMap<>(16);
        BaseBean baseBean = new BaseBean();
        try {
            User user = (User) param.get("user");
            int billId;
            int modeId;
            RequestInfo requestInfo = (RequestInfo) param.get("RequestInfo");
            if (requestInfo != null) {
                billId = Util.getIntValue(requestInfo.getRequestid());
                modeId = Util.getIntValue(requestInfo.getWorkflowid());
                if (billId > 0 && modeId > 0) {
                    RecordSet rs = new RecordSet();
                    boolean enableSdkClient = PositionSdkInstance.enableSdkClient();
                    if (enableSdkClient) {
                        long jobId = -1;
                        rs.executeQuery("select qllgwid from " + tableName + " where id = ?", billId);
                        if (rs.next()) {
                            String qllgwid = rs.getString("qllgwid");
                            if (StringUtils.isNotBlank(qllgwid)) {
                                jobId = Long.parseLong(qllgwid);
                            }
                        }
                        ERPAResumeSDKClient client = PositionSdkInstance.getPositionSdkInstance().getResumeSDKClient();
                        Map<String, Object> map = new HashMap<>(16);
                        MainTableInfo mainTableInfo = requestInfo.getMainTableInfo();
                        Property[] properties = mainTableInfo.getProperty();
                        for (Property property : properties) {
                            map.put(property.getName(), property.getValue());
                        }
                        ResumeJobV2Dto resumeJobDto = RecruitPositionUtil.convertMap2ResumeJobV2Dto(user, map);
                        String userId = String.valueOf(user.getUID());
                        // 未创建职位，则先创建职位
                        if (jobId == -1) {
                            baseBean.writeLog("【创建职位】,[id=" + billId + "],resumeJobDto=" + JSON.toJSONString(resumeJobDto));
                            // 创建千里聆职位
                            jobId = client.addResumeJobV2(userId, resumeJobDto);
                            // 更新千里聆ID到建模表单
                            rs.executeUpdate("update " + tableName + " set qllgwid = ? where id = ?", jobId, billId);
                        } else {
                            baseBean.writeLog("【更新职位】,[id=" + billId + "],[qllgwid=" + jobId + "],resumeJobDto=" + JSON.toJSONString(resumeJobDto));
                            // 已发布的职位，更新职位信息
                            client.editResumeJobV2(userId, jobId, jobDto -> {
                                new BaseBean().writeLog("职位更新前：" + JSON.toJSONString(jobDto));
                                BeanUtils.copyProperties(resumeJobDto, jobDto);
                                new BaseBean().writeLog("职位更新后：" + JSON.toJSONString(jobDto));
                            });
                        }

                        List<Integer> platformIds;
                        platformIds = resumeJobDto.getPlatformList();
                        String errorMsg = "";
                        for (Integer platformId : platformIds) {
                            ResumeTaskResult result = client.releaseResumeJob(userId, jobId, platformId);
                            // 直接查看结果，正在执行中会返回PENGING，成功后会返回SUCCEED，失败后会返回FAILED
                            TaskResult current = result.getResult();
                            baseBean.writeLog(current);
                            // 使用回调函数获取成功或者失败时的消息
                            result.onResult(() -> {
                                baseBean.writeLog("执行成功回调");
                            }, (reason) -> {
                                baseBean.writeLog("执行失败回调，原因：" + reason);
                            });

                            // 等待直到状态不再是PENDING
                            TaskResult taskResult = result.waitResult();
                            baseBean.writeLog(taskResult);
                            if (taskResult == TaskResult.SUCCEED) {
                                baseBean.writeLog("执行成功");
                            } else {
                                errorMsg = "执行失败，原因：" + result.getFailReason();
                                baseBean.writeLog(errorMsg);
                                break;
                            }
                        }
                        if (StringUtils.isNotBlank(errorMsg)) {
                            // 发布失败，下架职位
                            client.closeResumeJob(userId, jobId);
                            // 更新状态为发布失败
                            rs.executeUpdate("update " + tableName + " set qdfbzt = ? where id = ?", 3, billId);
                            resultMap.put("errmsg", errorMsg);
                            resultMap.put("flag", "false");
                            return resultMap;

                        }
                    } else {
                        resultMap.put("errmsg", "未配置发布插件，第三方平台请至各招聘网站自行发布");
                    }
                    // 更新状态为已发布
                    rs.executeUpdate("update " + tableName + " set qdfbzt = ? where id = ?", 2, billId);
                }
            }
        } catch (Exception e) {
            baseBean.writeLog(e);
            resultMap.put("errmsg", e.getMessage());
            resultMap.put("flag", "false");
        }
        return resultMap;
    }

}