package com.weaver.seconddev.interfaces.workflow.action;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import org.springframework.core.env.Environment;
import java.lang.*;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import com.weaver.verupgrade.general.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.hrm.resource.ResourceComInfo;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * EAS007机器人制单限额流程
 */
@org.springframework.stereotype.Service("workflow_action_EASRobotAction")
public class EASRobotAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;
    private static final Logger logger_c5564c68 = LoggerFactory.getLogger(EASRobotAction.class);

    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestID = "";
            try {
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                // 工作流ID
                String workFlowId = requestInfo.getWorkflowid();
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                logger_c5564c68.error(String.valueOf("EASRobotAction-start-" + requestID));
                logger_c5564c68.error("requestIdTemp == " +requestIdTemp);
                logger_c5564c68.error("userIdTemp == " +userIdTemp);
                Map<String, String> mMap = new HashMap<String, String>();
                for (int i = 0; i < properties.length; i++) {
                    String name = properties[i].getName().toUpperCase();
                    String value = Util.null2String(properties[i].getValue());
                    mMap.put(name, value);
                }
                // requestId String
                // companyName String
                // companyCode StringOaSrmVendorCheckAction
                // limitedAmount bigdecimal
                // ifExecute String
                JSONObject mJson = new JSONObject();
                mJson.put("requestId", requestID);
                // 申请公司
                String sqgs = mMap.get("SQGSMC");
                String sqgsname = unit.getSubcompanyname(sqgs);
                // 申请单位名称
                mJson.put("companyName", sqgsname);
                // 申请公司编码
                mJson.put("companyCode", mMap.get("SQGSBM"));
                // 制单金额
                mJson.put("limitedAmount", mMap.get("XEZDJE"));
                String iszd = mMap.get("SFZXXEZD");
                if ("0".equals(iszd)) {
                    mJson.put("ifExecute", "Y");
                } else {
                    mJson.put("ifExecute", "N");
                }
                mJson.put("acceptTime", getCurrentDate());

                JSONArray array = new JSONArray();
                array.add(mJson);
                logger_c5564c68.error(requestID + "调用EAS接口请求数据：=====" + array.toString());
                // 调用接口
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("hteasoasync.rpaLimitPay")).trim();
                String url = configProp.getRpaLimitPay();
                // String appKey = Util.null2String(getPropValue("hteasoasync", "easappkey")).trim();
                SendPostRequest_Custom mGetResult = new SendPostRequest_Custom();
                String result = mGetResult.getResult(array.toString(), url);
                logger_c5564c68.error(String.valueOf(requestID + "调用EAS接口请求数据：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 处理消息
                    String message = jsonObject.getString("msg");
                    String state = jsonObject.getString("state");
                    logger_c5564c68.error("EAS返回数据：" + jsonObject.toString());
                    if (!"S".equals(state)) {
                        // 失败
                        logger_c5564c68.error(String.valueOf("EAS返回错误信息：" + message));
                        // requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("EAS返回错误信息：" + message);
                        return  WeaResult.fail(500, "EAS返回错误信息：" + message, getResultMapForAction(weaverResultMap, "result", "EAS返回错误信息：" + message, requestInfo.getRequestManager()));
                    }
                } else {
                    logger_c5564c68.error(String.valueOf("调用EAS接口返回失败，请联系EAS管理员！"));
                    // requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("调用EAS接口返回失败，请联系EAS管理员！");
                    return WeaResult.fail(500, "执行失败", getResultMapForAction(weaverResultMap, "result", Action.FAILURE_AND_CONTINUE, requestInfo.getRequestManager()));
                }
            } catch (Exception exception) {
                logger_c5564c68.error(String.valueOf(requestID + "-EASRobotAction error:" + exception.getMessage()));
                // requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
                return  WeaResult.fail(500, requestID + "-EASRobotAction error:" + exception.getMessage(), getResultMapForAction(weaverResultMap, "result", requestID + "-EASRobotAction error:" + exception.getMessage(), requestInfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_c5564c68.error("EASRobotAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "EASRobotAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
        }
    }

    public String getCurrentDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }
}

