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

import com.weaver.seconddev.interfaces.prop.ConfigProp;
import org.apache.axiom.om.OMAbstractFactory;
import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.OMFactory;
import org.apache.axiom.om.OMNamespace;
import org.apache.axiom.soap.SOAP11Constants;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis2.AxisFault;
import org.apache.axis2.Constants;
import org.apache.axis2.addressing.EndpointReference;
import org.apache.axis2.client.Options;
import org.apache.axis2.client.ServiceClient;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import javax.xml.namespace.QName;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import org.apache.axis2.kernel.http.HTTPConstants;
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;

/**
 * ISO_文件作废流程返回接口
 */
@org.springframework.stereotype.Service("workflow_action_ISO_FileToVoidAction")
public class ISO_FileToVoidAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;
    @Autowired
    private ConfigProp configProp;
    private static final Logger logger_ee6301ba = LoggerFactory.getLogger(ISO_FileToVoidAction.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 {
            /**
             * 请求ID*
             */
            String requestID = "";
            try {
                ResourceComInfo hr = I18nContextUtil.getBean(ResourceComInfo.class);
                BillFieldUtil unit = new BillFieldUtil();
                Property[] properties = requestInfo.getMainTableInfo().getProperty();
                requestID = requestInfo.getRequestid();
                logger_ee6301ba.error(String.valueOf("ISO_FileToVoidAction--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);
                }
                // 审批状态
                String state = mMap.get("STATE");
                logger_ee6301ba.error(String.valueOf("审批状态：" + state));
                // int approvestate = -1;
                // if(state!=null&&!state.equals("")){
                // approvestate = Integer.parseInt(state);
                // }
                // Object[] obj = new Object[]{requestID,approvestate};
                String[] result = callInternalFileToVoid(requestID, state);
                if (!"0".equals(result[0])) {
                    logger_ee6301ba.error(String.valueOf("ISO_FileToVoidAction---同步文件作废流程返回失败-" + result));
                    // requestInfo.getRequestManager().setMessageid("ERROR");
                    if (result[1] != null && !result[1].equals("")) {
                        requestInfo.getRequestManager().setMessagecontent(result[1]);
                    } else {
                        requestInfo.getRequestManager().setMessagecontent("同步失败，请联系系统管理员！");
                    }
                    return  WeaResult.fail(500, "ISO_FileToVoidAction---同步文件作废流程返回失败-" + result, getResultMapForAction(weaverResultMap, "result","ISO_FileToVoidAction---同步文件作废流程返回失败-" + result, requestInfo.getRequestManager()));
                }
            } catch (Exception e) {
                logger_ee6301ba.error(String.valueOf("提交失败！"));
                logger_ee6301ba.error(String.valueOf("Error======" + e.getMessage()));
                // requestInfo.getRequestManager().setMessageid("ERROR");
                requestInfo.getRequestManager().setMessagecontent("提交失败！");
                return  WeaResult.fail(500, "ISO_FileToVoidAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestInfo.getRequestManager()));
            }
            logger_ee6301ba.error(String.valueOf("ISO_FileToVoidAction--end--" + requestID));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, requestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_ee6301ba.error("ISO_FileToVoidAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "ISO_FileToVoidAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), requestInfo.getRequestManager()));
        }
    }

    /**
     * 文件作废
     * @param bb
     * @param requestid
     * @param obj
     * @return
     */
    public String[] callInternalFileToVoid(String requestid, String status) throws AxisFault {
        String[] resultArr = new String[2];
        ServiceClient serviceClient = null;
        try {
            serviceClient = new ServiceClient();
            Options option = new Options();
            option.setSoapVersionURI(SOAP11Constants.SOAP_ENVELOPE_NAMESPACE_URI);
            option.setTransportInProtocol(Constants.TRANSPORT_HTTP);
            option.setTimeOutInMilliSeconds(30000);
            option.setAction("http://tempuri.org/InternalFileToVoid");
            // https://testecmapi.hengtonggroup.com.cn:8012/workflow.asmx
//            String url = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htecmoasync.isoresulturl")).trim();
            String url = configProp.getIsoresulturl();
            // 值为targetNamespace+methodName
            EndpointReference epfs = new EndpointReference(url);
            option.setTo(epfs);
            option.setManageSession(true);
            option.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, true);
            serviceClient.setOptions(option);
            OMFactory fac = OMAbstractFactory.getOMFactory();
            OMNamespace namespace = fac.createOMNamespace("http://tempuri.org/", "");
            OMElement element = fac.createOMElement("InternalFileToVoid", namespace);
            OMElement incidentId = fac.createOMElement("incidentId", namespace);
            incidentId.setText(requestid);
            element.addChild(incidentId);
            OMElement approvalStatus = fac.createOMElement("approvalStatus", namespace);
            approvalStatus.setText(status);
            element.addChild(approvalStatus);
            OMElement result = null;
            result = serviceClient.sendReceive(element);
            serviceClient.cleanupTransport();
            logger_ee6301ba.error("result=" + result);
            logger_ee6301ba.error(String.valueOf("****************************************************************************************************************"));
            Iterator in = result.getChildrenWithLocalName("InternalFileToVoidResult");
            while (in.hasNext()) {
                OMElement om = (OMElement) in.next();
                Iterator in2 = om.getChildElements();
                while (in2.hasNext()) {
                    OMElement subom = (OMElement) in2.next();
                    String name = subom.getLocalName();
                    String text = subom.getText();
                    if ("STATUS".equals(name)) {
                        resultArr[0] = text;
                    } else {
                        resultArr[1] = text;
                    }
                    logger_ee6301ba.error(String.valueOf(name + "=" + text));
                }
            }
        } catch (Exception e) {
            if (serviceClient != null) {
                serviceClient.cleanupTransport();
            }
            resultArr[0] = "1";
            resultArr[1] = e.getMessage();
            logger_ee6301ba.error(String.valueOf("error--" + e.getMessage()));
        }
        return resultArr;
    }

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