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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.oames.ReturnMesWLPS_SYService;
import  com.weaver.seconddev.interfaces.oames.SI_OA_HTOAApproFlowSync_OUTServiceStub;
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.conn.RecordSet;
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.*;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

/**
 * GJB-SW04-国际产业集团发货联系单审批流程
 */
@org.springframework.stereotype.Service("workflow_action_GJB_DeliveryApproveAction")
public class GJB_DeliveryApproveAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;
    private static final Logger logger_8ffb7f70 = LoggerFactory.getLogger(GJB_DeliveryApproveAction.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_8ffb7f70.error(String.valueOf("GJB_DeliveryApproveAction-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();
                // 联系单编号
                mJson.put("RELATION_NO", mMap.get("LXDBM"));
                // 版本号
                mJson.put("VERSIONS_NO", mMap.get("BBH"));
                String spjg = mMap.get("SPJG");
                String spjgname = unit.getselectNameByCol("spjg", workFlowId, spjg);
                // 审核结果
                mJson.put("AUDIT_STATUS", spjgname);
                mJson.put("YS_MONEY_AUDITOR", "");
                mJson.put("YS_MONEY_OPINION", "");
                mJson.put("XB_ATTACHE_AUDITOR", "");
                mJson.put("XB_ATTACHE_MONEY_OPINION", "");
                mJson.put("LOGISTICS_AUDITOR", "");
                mJson.put("LOGISTICS_MONEY_OPINION", "");
                mJson.put("BUSINESS_AUDITOR", "");
                mJson.put("BUSINESS_MONEY_OPINION", "");
                // String czjd = mMap.get("CZJD");//操作节点
                // RecordSet rs = new RecordSet();
                // //应收款审批人
                // String sql = "select operatedate,operatetime,remark,b.lastname from workflow_requestLog a "
                // + "INNER JOIN HrmResource b on a.operator = b.id "
                // + "where requestid = " + requestID + " and nodeid = 20475";//应收款审批人 测试环境-20475 正式环境-
                // rs.executeSql(sql);
                // String yskspr = "";
                // String yskspyj = "";
                // while (rs.next()) {
                // String date = Util.null2String(rs.getString("operatedate"));
                // String time = Util.null2String(rs.getString("operatetime"));
                // String name = Util.null2String(rs.getString("lastname"));
                // String remark = Util.null2String(rs.getString("remark"));
                // yskspr = yskspr + name.replaceAll("</?[^>]+>", "")+";";//StringEscapeUtils.unescapeHtml(name)+";";
                // yskspyj = yskspyj + remark.replaceAll("</?[^>]+>", "")+";";//
                // }
                // 
                // if(yskspr.endsWith(";")){
                // yskspr = yskspr.substring(0,yskspr.lastIndexOf(";"));
                // yskspyj = yskspyj.substring(0,yskspyj.lastIndexOf(";"));
                // }
                // 
                // 
                // 
                // //信保专员审批人
                // String sql_xb = "select operatedate,operatetime,remark,b.lastname from workflow_requestLog a "
                // + "INNER JOIN HrmResource b on a.operator = b.id "
                // + "where requestid = " + requestID + " and nodeid = 20476";//应收款审批人 测试环境-20476 正式环境-
                // rs.executeSql(sql_xb);
                // String xbspr = "";
                // String xbkspyj = "";
                // while (rs.next()) {
                // String date = Util.null2String(rs.getString("operatedate"));
                // String time = Util.null2String(rs.getString("operatetime"));
                // String name = Util.null2String(rs.getString("lastname"));
                // String remark = Util.null2String(rs.getString("remark"));
                // xbspr = xbspr + getNohtmlData(name)+";";
                // xbkspyj = xbkspyj + getNohtmlData(remark)+";";
                // }
                // 
                // if(xbspr.endsWith(";")){
                // xbspr = xbspr.substring(0,xbspr.lastIndexOf(";"));
                // xbkspyj = xbkspyj.substring(0,xbkspyj.lastIndexOf(";"));
                // }
                // 
                // 
                // //物流组审核人
                // String sql_wl = "select operatedate,operatetime,remark,b.lastname from workflow_requestLog a "
                // + "INNER JOIN HrmResource b on a.operator = b.id "
                // + "where requestid = " + requestID + " and nodeid = 20477";//应收款审批人 测试环境-20477 正式环境-
                // rs.executeSql(sql_wl);
                // String wlspr = "";
                // String wlkspyj = "";
                // while (rs.next()) {
                // String date = Util.null2String(rs.getString("operatedate"));
                // String time = Util.null2String(rs.getString("operatetime"));
                // String name = Util.null2String(rs.getString("lastname"));
                // String remark = Util.null2String(rs.getString("remark"));
                // wlspr = wlspr + getNohtmlData(name)+";";
                // wlkspyj = wlkspyj + getNohtmlData(remark)+";";
                // }
                // 
                // if(wlspr.endsWith(";")){
                // wlspr = wlspr.substring(0,wlspr.lastIndexOf(";"));
                // wlkspyj = wlkspyj.substring(0,wlkspyj.lastIndexOf(";"));
                // }
                // 
                // 
                // //商务部审核人
                // String sql_sw = "select operatedate,operatetime,remark,b.lastname from workflow_requestLog a "
                // + "INNER JOIN HrmResource b on a.operator = b.id "
                // + "where requestid = " + requestID + " and nodeid = 20478";//应收款审批人 测试环境-20478 正式环境-
                // rs.executeSql(sql_sw);
                // String swspr = "";
                // String swkspyj = "";
                // while (rs.next()) {
                // String date = Util.null2String(rs.getString("operatedate"));
                // String time = Util.null2String(rs.getString("operatetime"));
                // String name = Util.null2String(rs.getString("lastname"));
                // String remark = Util.null2String(rs.getString("remark"));
                // swspr = swspr + getNohtmlData(name)+";";
                // swkspyj = swkspyj + getNohtmlData(remark)+";";
                // }
                // 
                // if(swspr.endsWith(";")){
                // swspr = swspr.substring(0,swspr.lastIndexOf(";"));
                // swkspyj = swkspyj.substring(0,swkspyj.lastIndexOf(";"));
                // }
                // 
                // 
                // 
                // String lastoperatorid = requestInfo.getLastoperator();
                // String lastoperator = hr.getResourcename(lastoperatorid);
                // String remark = requestInfo.getRequestManager().getRemark();
                // remark = getNohtmlData(remark);
                // 
                // writeLog("remark：" + remark);
                // 
                // if("0".equals(czjd)){//应收
                // mJson.put("YS_MONEY_AUDITOR",lastoperator);
                // mJson.put("YS_MONEY_OPINION",remark);
                // mJson.put("XB_ATTACHE_AUDITOR","");
                // mJson.put("XB_ATTACHE_MONEY_OPINION","");
                // mJson.put("LOGISTICS_AUDITOR","");
                // mJson.put("LOGISTICS_MONEY_OPINION","");
                // mJson.put("BUSINESS_AUDITOR","");
                // mJson.put("BUSINESS_MONEY_OPINION","");
                // }else if("1".equals(czjd)){
                // mJson.put("YS_MONEY_AUDITOR",yskspr);
                // mJson.put("YS_MONEY_OPINION",yskspyj);
                // mJson.put("XB_ATTACHE_AUDITOR",lastoperator);
                // mJson.put("XB_ATTACHE_MONEY_OPINION",remark);
                // mJson.put("LOGISTICS_AUDITOR","");
                // mJson.put("LOGISTICS_MONEY_OPINION","");
                // mJson.put("BUSINESS_AUDITOR","");
                // mJson.put("BUSINESS_MONEY_OPINION","");
                // }else if("2".equals(czjd)){ //物流审批
                // mJson.put("YS_MONEY_AUDITOR",yskspr);
                // mJson.put("YS_MONEY_OPINION",yskspyj);
                // mJson.put("XB_ATTACHE_AUDITOR",xbspr);
                // mJson.put("XB_ATTACHE_MONEY_OPINION",xbkspyj);
                // mJson.put("LOGISTICS_AUDITOR",lastoperator);
                // mJson.put("LOGISTICS_MONEY_OPINION",remark);
                // mJson.put("BUSINESS_AUDITOR","");
                // mJson.put("BUSINESS_MONEY_OPINION","");
                // }else{
                // mJson.put("YS_MONEY_AUDITOR",yskspr);
                // mJson.put("YS_MONEY_OPINION",yskspyj);
                // mJson.put("XB_ATTACHE_AUDITOR",xbspr);
                // mJson.put("XB_ATTACHE_MONEY_OPINION",xbkspyj);
                // mJson.put("LOGISTICS_AUDITOR",wlspr);
                // mJson.put("LOGISTICS_MONEY_OPINION",wlkspyj);
                // mJson.put("BUSINESS_AUDITOR",lastoperator);
                // mJson.put("BUSINESS_MONEY_OPINION",remark);
                // }
                logger_8ffb7f70.error("调用CMS接口请求数据：=====" + mJson.toString());
                // 调用接口
//                String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htcmsoasync.oaapproveresulturl")).trim();
//                String appKey = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htcmsoasync.appKey")).trim();
                String url = configProp.getHtcmsoasync_oaapproveresulturl();
                String appKey = configProp.getHtcmsoasync_appKey();
                logger_8ffb7f70.error("调用CMS接口请求数据：url=====" + url.toString());
                logger_8ffb7f70.error("调用CMS接口请求数据：appKey=====" + appKey.toString());

                // ZZ_SendPostRequest  mGetResult = new ZZ_SendPostRequest();
                SendPostRequest_API mGetResult = new SendPostRequest_API();
                String result = mGetResult.getResult(mJson, url, appKey);
                logger_8ffb7f70.error(String.valueOf("调用CMS接口请求数据：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    // String code = jsonObject.getString("Code");//接口处理状态 1-成功，0-失败
                    // 处理消息
                    String message = jsonObject.getString("Message");
                    boolean success = jsonObject.getBoolean("Success");
                    logger_8ffb7f70.error("CMS返回数据：" + jsonObject.toString());
                    if (!success) {
                        // 失败
                        logger_8ffb7f70.error(String.valueOf("CMS返回错误信息：" + message));
                        // requestInfo.getRequestManager().setMessageid("ERROR");
                        requestInfo.getRequestManager().setMessagecontent("CMS返回错误信息：" + message);
                        return WeaResult.fail(500, "执行失败：" + message, getResultMapForAction(weaverResultMap, "result", Action.FAILURE_AND_CONTINUE, requestInfo.getRequestManager()));
                    }
                } else {
                    logger_8ffb7f70.error(String.valueOf("调用CMS接口返回失败，请联系CMS管理员！"));
                    // requestInfo.getRequestManager().setMessageid("ERROR");
                    requestInfo.getRequestManager().setMessagecontent("调用CMS接口返回失败，请联系CMS管理员！");
                    return WeaResult.fail(500, "执行失败", getResultMapForAction(weaverResultMap, "result", Action.FAILURE_AND_CONTINUE, requestInfo.getRequestManager()));
                }
            } catch (Exception exception) {
                logger_8ffb7f70.error(String.valueOf(requestID + "-GJB_DeliveryApproveAction error:" + exception.getMessage()));
                // requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
                return  WeaResult.fail(500, "GJB_DeliveryApproveAction " + exception, getResultMapForAction(weaverResultMap, "result", exception.getMessage(), requestInfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_8ffb7f70.error("GJB_DeliveryApproveAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "GJB_DeliveryApproveAction " + e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), requestInfo.getRequestManager()));
        }
    }

    /**
     * 去除字符串中html格式
     * @param origin
     * @return
     */
    private String getNohtmlData(String origin) {
        String nowStr = "";
        nowStr = origin.replaceAll("</?[^>]+>", "");
        nowStr = nowStr.replace("来自Web手机版", "").replace("来自iPhone客户端", "").replace("来自android客户端", "").replace("来自企业微信", "").replace("来自门户-流程待办", "");
        return nowStr;
    }

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