package com.customization.yll.liuzhoucitycollege.integration;

import cn.hutool.core.date.DateUtil;
import com.customization.yll.common.util.ModeUtil;
import com.customization.yll.liuzhoucitycollege.integration.bean.PushRecord;
import weaver.conn.RecordSet;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * @author yaolilin
 * @desc 金智流程推送记录
 * @date 2024/12/5
 **/
public class RequestPushLogRecorder {
    /**
     * 流程推送处理状态：待办
     */
    public static final int TODO_STATUS = 0;
    /**
     * 流程推送处理状态：已办
     */
    public static final int DONE_STATUS = 1;
    /**
     * 流程推送处理状态：删除
     */
    public static final int DELETE_STATUS = 2;
    private static final String TABLE_NAME = "uf_request_push_log";
    private final RecordSet recordSet = new RecordSet();

    /**
     * 记录推送记录到建模
     * @param pushRecord 推送记录，其中 status 为 0:待办，1:已办，2:删除
     */
    public void recordPush(PushRecord pushRecord) {
        Map<String, Object> data = new HashMap<>(5);
        data.put("workflow", pushRecord.getRequestId());
        data.put("processor", pushRecord.getProcessor());
        data.put("status", pushRecord.getStatus());
        data.put("pushed_time", getNowTime());
        Optional<Integer> dataId = getRecordId(pushRecord.getRequestId(), pushRecord.getProcessor());
        if (dataId.isPresent()) {
            ModeUtil.updateMode(data, dataId.get(), TABLE_NAME, recordSet);
        }else {
            ModeUtil.insertToMode(data, TABLE_NAME, recordSet);
        }
    }

    /**
     * 获取流程推送状态
     * @param requestId 流程请求id
     * @param processor 流程处理人id
     * @return 流程推送处理状态，0:待办，1:已办，2:删除
     */
    public Optional<Integer> getRequestStatus(int requestId, int processor) {
        recordSet.executeQuery("select status from " + TABLE_NAME + " where workflow=? and processor=?",
                requestId,processor);
        if (recordSet.next()) {
            return Optional.of(recordSet.getInt("status"));
        }
        return Optional.empty();
    }

    /**
     * 获取推送记录建模的数据id，有可能找不到记录
     * @param requestId 流程请求id
     * @param processor 流程处理人id
     * @return 数据id
     */
    public Optional<Integer> getRecordId(int requestId, int processor) {
        recordSet.executeQuery("select id from " + TABLE_NAME + " where workflow=? and processor=?",
                requestId, processor);
        if (recordSet.next()) {
            return Optional.of(recordSet.getInt("id"));
        }
        return Optional.empty();
    }

    private String getNowTime() {
        return DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss");
    }
}
