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

import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
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;

/**
 * 车辆维保同步到报账系统
 */
@org.springframework.stereotype.Service("workflow_action_EASCarRepairAction")
public class EASCarRepairAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;
    private static final Logger logger_d8323d3f = LoggerFactory.getLogger(EASCarRepairAction.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_d8323d3f.error(String.valueOf("EASCarRepairAction-start-" + requestID));
                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);
                }
                JSONObject mJson = new JSONObject();
                // 1.车辆维保；2.住宿；3.就餐
                mJson.put("oaType", "1");
                // OA流程号
                mJson.put("OAnum", mMap.get("LCBH"));
                // 申请人
                String sqr = mMap.get("SQR");
                String sqrcode = "";
                String sqrname = "";
                if (!sqr.equals("")) {
                    // 申请人工号
                    sqrcode = unit.getWorkcode(sqr);
                    // 申请人姓名
                    sqrname = hr.getResourcename(sqr);
                }
                // 申请人工号
                mJson.put("sqrgh", sqrcode);
                // 申请人名称
                mJson.put("sqrmc", sqrname);
                // 费用结算人
                String fyjsr = mMap.get("FYJSR");
                String fyjsrcode = "";
                String fyjsrname = "";
                if (!fyjsr.equals("")) {
                    // 费用结算人工号
                    fyjsrcode = unit.getWorkcode(fyjsr);
                    // 费用结算人姓名
                    fyjsrname = hr.getResourcename(fyjsr);
                }
                // 费用结算人工号
                mJson.put("fyjsrgh", fyjsrcode);
                // 费用结算人名称
                mJson.put("fyjsrmc", fyjsrname);
                // 申请日期
                mJson.put("sqrq", mMap.get("SQRQ"));
                String sqdw = mMap.get("SQDW");
                String sqdwname = unit.getSubcompanyname(sqdw);
                // 申请单位名称
                mJson.put("sqdwmc", sqdwname);
                String fyjsdw = mMap.get("CLSZDW");
                String fyjsdwname = unit.getSubcompanyname(fyjsdw);
                // 费用结算单位名称
                mJson.put("fyjsdwmc", fyjsdwname);
                // 金额 实际维保费用
                mJson.put("amount", mMap.get("SJWBFY"));
                // 日期 Type=1时为空，type=2时，入住日期；type=3时，就餐日期
                mJson.put("rq", "");
                String type = mMap.get("SQLX");
                logger_d8323d3f.error(String.valueOf("EASCarRepairAction-type-" + type));
                String sqlxname = unit.getselectNameByCol("sqlx", workFlowId, type);
                logger_d8323d3f.error(String.valueOf("EASCarRepairAction-sqlxname-" + sqlxname));
                // 申请类型,1保养，2维修，3保养和维修
                mJson.put("sqlx", sqlxname.substring(1, 2));
                // 车牌号 Type=1时有值
                mJson.put("cph", mMap.get("CPH"));
                // 本次维保厂家名称
                mJson.put("wbcj", mMap.get("BCWBCJQT"));
                mJson.put("by1", "");
                mJson.put("by2", "");
                mJson.put("by3", "");
                logger_d8323d3f.error("调用EAS接口请求数据：=====" + mJson.toString());
                // 调用接口
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("hteasoasync.syncOaApplyForm")).trim();
//                String appKey = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("hteasoasync.easappkey")).trim();
                String url = configProp.getSyncOaApplyForm();
                String appKey = configProp.getEasappkey();
                SendPostRequest_API mGetResult = new SendPostRequest_API();
                String result = mGetResult.getResult(mJson, url, appKey);
                logger_d8323d3f.error(String.valueOf("调用EAS接口请求数据：" + result));
                // {"msg":"车牌号为空","state":"E"}
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // 处理消息
                    String message = jsonObject.getString("msg");
                    String state = jsonObject.getString("state");
                    logger_d8323d3f.error("EAS返回数据：" + jsonObject.toString());
                    if (!"S".equals(state)) {
                        // 失败
                        logger_d8323d3f.error(String.valueOf("EAS返回错误信息：" + message));
                        // requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("EAS返回错误信息：" + message);
                        return WeaResult.fail(500, "执行失败", getResultMapForAction(weaverResultMap, "result", Action.FAILURE_AND_CONTINUE, requestInfo.getRequestManager()));
                    }
                } else {
                    logger_d8323d3f.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_d8323d3f.error(String.valueOf(requestID + "-EASCarRepairAction error:" + exception.getMessage()));
                // requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
                return  WeaResult.fail(500, requestID + "-EASCarRepairAction error:" + exception.getMessage(), getResultMapForAction(weaverResultMap, "result", requestID + "-EASCarRepairAction error:" + exception.getMessage(), requestInfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_d8323d3f.error("EASCarRepairAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "EASCarRepairAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
        }
    }

    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;
    }
}
