package weaver.interfaces.htsc.wpscenter.utils;

import net.sf.json.JSONObject;
import weaver.hrm.User;
import weaver.systeminfo.SystemEnv;
import weaver.workflow.logging.Logger;
import weaver.workflow.logging.LoggerFactory;

import java.util.UUID;

public class TaskUtil {

    private Logger log = LoggerFactory.getLogger(TaskUtil.class);
    private String task_id = "";

    private User user;

    /**
     * 任务状态，执行中
     */
    public static final String TASK_STATUS_RUNNIND = "running";

    /**
     * 任务状态，执行中
     */
    public static final String TASK_STATUS_WAITING = "waiting";

    /**
     * 任务状态，成功
     */
    public static final String TASK_STATUS_SUCCESS = "success";


    public TaskUtil(){
        initTask();
    }

    /**
     * 初始化taskid
     */
    public void initTask(){
        task_id = UUID.randomUUID().toString();
    }

    public String getTask_id() {
        return task_id;
    }

    public void setTask_id(String task_id) {
        this.task_id = task_id;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Logger getLog() {
        return log;
    }

    public TaskUtil setLog(Logger log) {
        this.log = log;
        return this;
    }

    public JSONObject queryTaskResult(){
        JSONObject result = new JSONObject();

        String apiUrl = Config.getCpsV1TaskQuery();

        TokenUtil tokenUtil = new TokenUtil();
        String appToken = tokenUtil.getFileFormatToken(user);
        apiUrl = apiUrl + "?app_token=" + appToken;

        JSONObject requestParams = new JSONObject();
        requestParams.put("task_id", getTask_id());

        HttpUtil httpUtil = new HttpUtil(user);
        try{
            // 请求接口转换文档
            JSONObject response = httpUtil.post(apiUrl, requestParams, null);

            return response;
        }catch (Exception e){
            log.error(e);
            result.put("result", "-1");
            // 文档转换失败
            result.put("message", SystemEnv.getHtmlLabelName(390468, Tools.getUserLanguageid(user)));
            result.put("messageid", "390468");
        }


        return result;
    }

    public JSONObject waitForTaskResult(){
        JSONObject result = new JSONObject();

        // 等待周期及次数
        long taskWaitIntvalTime = (long) Config.getTaskWaitIntvalTime();
        int taskMaxWaitCount = Config.getTaskMaxWaitCount();

        for(int i = 0; i < taskMaxWaitCount; i++){
            JSONObject currentResult = queryTaskResult();
            String resultString = Tools.getJsonData(currentResult,"result");
            if(i == 0) {
                log.info("waitForTaskResult first : " + currentResult.toString());
            }
            if(!"0".equals(resultString)){
                String message = Tools.getJsonData(currentResult, "msg");
                message = null == message || message.isEmpty() ? SystemEnv.getHtmlLabelName(129710, Tools.getUserLanguageid(user)) : message;
                result.put("response", currentResult.toString());
                result.put("result", resultString);
                result.put("status", resultString);
                result.put("message", message);
                result.put("messageid", resultString);
                break;
            }
            String status = Tools.getJsonData(currentResult,"status").toLowerCase();
            if(TASK_STATUS_SUCCESS.equals(status)){
                log.info("waitForTaskResult end : " + currentResult.toString());
                return currentResult;
            } else if(TASK_STATUS_RUNNIND.equals(status) || TASK_STATUS_WAITING.equals(status)) {
                try{
                    Thread.sleep(taskWaitIntvalTime);
                }catch (InterruptedException e){}
            } else {
                String message = Tools.getJsonData(currentResult, "msg");
                // 129710 未知错误
                message = null == message || message.isEmpty() ? SystemEnv.getHtmlLabelName(129710, Tools.getUserLanguageid(user)) : message;
                result.put("response", currentResult.toString());
                result.put("result", resultString);
                result.put("message", message);
                result.put("messageid", resultString);

                try{
                    Thread.sleep(taskWaitIntvalTime);
                }catch (InterruptedException e){}
            }
            if(i + 1 > taskMaxWaitCount) {
                log.info("waitForTaskResult end : " + currentResult.toString());
            }
        }

        return result;
    }
}
