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 java.util.UUID;
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;

/**
 * SRM供应商绩效处罚确认
 */
@org.springframework.stereotype.Service("workflow_action_OaSrmVendorPunishConfirmAction")
public class OaSrmVendorPunishConfirmAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;

    private static final Logger logger_9131997c = LoggerFactory.getLogger(OaSrmVendorPunishConfirmAction.class);

    private String SENDID = "";

    private String ITFID = "HT01BDS001";

    private String SYSID = "SYS004";
    @Autowired
    private ConfigProp configProp;

    @Autowired
    SendPostRequest_PO mGetResult;
    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_9131997c.error("OaSrmVendorPunishConfirmAction start");
        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 {
            /**
             * 请求ID*
             */
            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_9131997c.error(String.valueOf("OaSrmVendorPunishConfirmAction--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);
                }
                // 是否强制执行0-是；1-否
                String sfqzzx = mMap.get("SFQZZX");
                if (sfqzzx.equals("0")) {
                    // 强制执行就不需要调用接口
                    return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
                }
                String uuid = UUID.randomUUID().toString();
                JSONObject mReqJson = new JSONObject();
                mReqJson.put("SENDID", uuid);
                mReqJson.put("ITFID", ITFID);
                mReqJson.put("SYSID", SYSID);
                JSONObject mJson = new JSONObject();
                mJson.put("workflowId", workFlowId);
                mJson.put("requestId", requestID);
                mJson.put("lcbh", mMap.get("LCBH"));
                String sqdw = mMap.get("SQDW");
                String sqdwname = unit.getSubcompanyname(sqdw);
                // 公司编码
                mJson.put("companyCode", mMap.get("GSBM"));
                // 公司名称
                mJson.put("companyName", mMap.get("GSMC"));
                String sqbm = mMap.get("SQBM");
                String sqbmname = unit.getDepartmentname(sqbm);
                // 申请部门
                mJson.put("departmentName", sqbmname);
                // 申请人
                String sqr = mMap.get("SQR");
                String sqrcode = mMap.get("GH");
                ;
                String sqrname = "";
                if (!sqr.equals("")) {
                    // 申请人姓名
                    sqrname = hr.getResourcename(sqr);
                }
                // 申请人
                mJson.put("applyName", sqrname);
                // 工号
                mJson.put("applyEmpNo", sqrcode);
                // 供应商编码
                mJson.put("vendorCode", mMap.get("GYSBM"));
                // 供应商名称
                mJson.put("vendorName", mMap.get("GYSMC"));
                // 物料描述
                mJson.put("materialDesc", mMap.get("WLMS"));
                // 请求类型
                mJson.put("requestType", "1");
                String placecode = mMap.get("FSDD");
                String placename = unit.getselectNameByCol("fsdd", workFlowId, placecode);
                // 发生地址
                mJson.put("happenPlace", placename);
                // 发生日期
                mJson.put("happenDate", mMap.get("FSRQ"));
                // 问题描述
                mJson.put("qcDesc", mMap.get("ZLWTMS"));
                // 材料损失
                mJson.put("materialLoss", mMap.get("CLSS"));
                // 绩效罚款
                mJson.put("achievementsFines", mMap.get("JXFK"));
                // 其他损失
                mJson.put("otherLossesAndFines", mMap.get("QTFK"));
                // 合计
                mJson.put("totalAmount", mMap.get("SPHJ"));
                mReqJson.put("DATAS", mJson);
                logger_9131997c.error("调用SRM供应商绩效处罚信息同步接口请求数据：=====" + mReqJson.toString());
                // 调用接口
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htsrmoasync.OaSrmVendorPunish")).trim();
                String url = configProp.getOaSrmVendorPunish();
//                SendPostRequest_PO mGetResult = new SendPostRequest_PO();
                String result = mGetResult.getResult(mReqJson, url);
                logger_9131997c.error(String.valueOf("调用SRM供应商绩效处罚信息同步接口请求数据：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    JSONObject returnJson = jsonObject.getJSONObject("RETURN");
                    // 接口处理状态 1-成功，0-失败
                    String isTat = returnJson.getString("istat");
                    // 处理消息
                    String srMessage = returnJson.getString("message");
                    logger_9131997c.error("SRM系统返回数据：" + jsonObject.toString());
                    if (!"S".equals(isTat)) {
                        // 失败
                        logger_9131997c.error(String.valueOf("SRM返回错误信息：" + srMessage));
                        // requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("SRM返回错误信息：" + srMessage);
                        return  WeaResult.fail(500, "SRM返回错误信息：" + srMessage, getResultMapForAction(weaverResultMap, "result","SRM返回错误信息：" + srMessage, requestInfo.getRequestManager()));
                    }
                } else {
                    logger_9131997c.error(String.valueOf("调用SRM系统接口返回失败，请联系SRM系统管理员！"));
                    // requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("调用SRM接口返回失败，请联系SRM系统管理员！");
                    return  WeaResult.fail(500, "调用SRM接口返回失败，请联系SRM系统管理员！", getResultMapForAction(weaverResultMap, "result","调用SRM接口返回失败，请联系SRM系统管理员！", requestInfo.getRequestManager()));
                }
            } catch (Exception e) {
                logger_9131997c.error(String.valueOf("提交失败！"));
                logger_9131997c.error(String.valueOf("Error======" + e.getMessage()));
                // requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
                return  WeaResult.fail(500, "OaSrmVendorPunishConfirmAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestInfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_9131997c.error("OaSrmVendorPunishConfirmAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "OaSrmVendorPunishConfirmAction 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;
    }
}
