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

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.xml.namespace.QName;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
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 java.util.Map;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

@org.springframework.stereotype.Service("workflow_action_NeiBuDiaoDongAction")
public class NeiBuDiaoDongAction implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_1103b3f3 = LoggerFactory.getLogger(NeiBuDiaoDongAction.class);

    private Log log = LogFactory.getLog(NeiBuDiaoDongAction.class.getName());

    public Log getLog() {
        return log;
    }

    public void setLog(Log log) {
        this.log = log;
    }

    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 request = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        // RecordSetDataSource rsds = new RecordSetDataSource("eHR_test");
        // rsds.executeSql("select ???GUID AS YGID from ht_psnaccount where ??????? ="+lastoperator);
        // rsds.next();
        // DealerID =  Util.null2String(rsds.getString("YGID"));
        // String createsqlString = "select d.id,h.loginid,h.lastname,d.departmentmark from workflow_requestbase t,hrmresource h,hrmdepartment d where  h.id = t.creater and h.departmentid=d.id and t.requestid = "+requestid;
        // rs2.execute(createsqlString);
        // rs2.next();
        // String createrNameId = rs2.getString("loginid");
        // int departmentId = Util.getIntValue(rs2.getString("id"));
        try {
            log.error("do action on request:" + request.getRequestid());
            String requestid = request.getRequestid();
            String lastoperator = request.getLastoperator();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            // RecordSet rs2 = new RecordSet();
            String workflowid = request.getWorkflowid();
            String maintable = "";
            // String DealerID = "";
//            String sql = "select b.tablename from wfp_base a,form b where a.formid = b.id and a.id = " + workflowid;
//            String poolname = CONN_TYPE.workflow.getType();
            // RecordSetDataSource rsds = new RecordSetDataSource("eHR_test");
            // rsds.executeSql("select ???GUID AS YGID from ht_psnaccount where ??????? ="+lastoperator);
            // rsds.next();
            // DealerID =  Util.null2String(rsds.getString("YGID"));
            // String createsqlString = "select d.id,h.loginid,h.lastname,d.departmentmark from workflow_requestbase t,hrmresource h,hrmdepartment d where  h.id = t.creater and h.departmentid=d.id and t.requestid = "+requestid;
            // rs2.execute(createsqlString);
            // rs2.next();
            // String createrNameId = rs2.getString("loginid");
            // int departmentId = Util.getIntValue(rs2.getString("id"));
            /*        String creater = rs2.getString("departmentmark") + "_" + rs2.getString("lastname");
 TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//            boolean b = rs.executeSql(sql, poolname);
//            logger_1103b3f3.error("b--" + b);
//            while (rs.next()) {
//                maintable = rs.getString("tablename");
//            }
            // ?????????
            String KDCRQ = "";
            // ????
            String GH = "";
            // ????????
            String SQSJ = "";
            // ????????
            String DCBM = "";
            // ?????????λ/???
            String NDCGW2 = "";
            // ???λ????
            String RGWRQ = "";
            // ???????
            String DRBM = "";
            // ???????λ/???
            String ZW2 = "";
            // ????????
            String DGRQ = "";
            String OutDept = "";
            String OutPosition = "";
            String InDept = "";
            String InPosition = "";
            String strPar = "";
            // ?????????????
            Property[] properties = request.getMainTableInfo().getProperty();
            for (int i = 0; i < properties.length; i++) {
                // ????????
                // ?????
                String name = properties[i].getName().toUpperCase();
                // ?
                String value = Util.null2String(properties[i].getValue());
                if (name.equals("GH")) {
                    GH = value;
                    // rsds.executeSql("select ???GUID AS YGID from ht_psnaccount where ??????? ="+GH);
                    // rsds.next();
                    // DealerID =  Util.null2String(rsds.getString("YGID"));
                } else if (name.equals("SQSJ")) {
                    SQSJ = value;
                    SQSJ = SQSJ.substring(0, 10);
                } else if (name.equals("DCBM")) {
                    DCBM = value;
                    String poolname_a1 = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b1 = rs.executeSql("select code from eteams.dbo.department as  HrmDepartment where id =" + DCBM, poolname_a1);
                    logger_1103b3f3.error("b1--" + b1);
                    rs.next();
                    OutDept = Util.null2String(rs.getString("departmentcode"));
                } else if (name.equals("NDCGW2")) {
                    NDCGW2 = value;
                    String poolname_el = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b1 = rs.executeSql("select code from e10_common.dbo.position as  HrmJobTitles where id =" + NDCGW2, poolname_el);
                    logger_1103b3f3.error("b1--" + b1);
                    rs.next();
                    OutPosition = Util.null2String(rs.getString("jobtitlecode"));
                } else if (name.equals("RGWRQ")) {
                    RGWRQ = value;
                    RGWRQ.substring(0, 10);
                } else if (name.equals("DRBM")) {
                    DRBM = value;
                    String poolname_up = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b1 = rs.executeSql("select code from eteams.dbo.department as  HrmDepartment where id =" + DRBM, poolname_up);
                    logger_1103b3f3.error("b1--" + b1);
                    rs.next();
                    InDept = Util.null2String(rs.getString("departmentcode"));
                } else if (name.equals("DRGW")) {
                    ZW2 = value;
                    String poolname_9p = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b1 = rs.executeSql("select code from e10_common.dbo.position as  HrmJobTitles where id =" + ZW2, poolname_9p);
                    logger_1103b3f3.error("b1--" + b1);
                    rs.next();
                    InPosition = Util.null2String(rs.getString("jobtitlecode"));
                } else if (name.equals("DGRQ")) {
                    DGRQ = value;
                    DGRQ.substring(0, 10);
                } else if (name.equals("KDCRQ")) {
                    KDCRQ = value;
                    KDCRQ.substring(0, 10);
                } else if (name.equals("YDLX")) {
                    strPar = value;
                }
                log.error("main:" + requestid + "	" + name + "	" + value);
            }
            try {
                String endPoint = "http://10.6.2.12/hengtongws/HengtongWebService.asmx";
                String soapaction = "http://tempuri.org/";
                Service service = new Service();
                Call call1 = (Call) service.createCall();
                call1.setTargetEndpointAddress(new java.net.URL(endPoint));
                call1.setOperationName(new QName(soapaction, "PsnAdjustFormWS"));
                call1.addParameter(new QName(soapaction, "PersonID"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "ApplyDate"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "OutDept"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "OutPosition"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "InPositionDate"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "InDept"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "InPosition"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "InDate"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "DealerID"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.addParameter(new QName(soapaction, "strPar"), org.apache.axis.encoding.XMLType.XSD_STRING, javax.xml.rpc.ParameterMode.INOUT);
                call1.setReturnType(new QName(soapaction, "PsnAdjustFormWS"), String.class);
                call1.setUseSOAPAction(true);
                call1.setSOAPActionURI(soapaction + "PsnAdjustFormWS");
                // call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
                // call2.setTargetEndpointAddress(new java.net.URL(endPoint));
                log.error("GH:   " + GH + "SQRQ:   " + SQSJ + "OutDept:  " + OutDept + "OutPosition :  " + OutPosition + "RGWRQ:  " + RGWRQ + "InDept:" + InDept + "InPosition:" + InPosition + "DGRQ:  " + DGRQ + "lastoperator:  " + lastoperator + "strPar:" + strPar);
                String str = (String) call1.invoke(new Object[] { GH, SQSJ, OutDept, OutPosition, KDCRQ, InDept, InPosition, DGRQ, lastoperator, strPar });
                System.out.println(str);
                log.error(str);
                if (!str.equals("SUCCESS")) {
                    request.getRequestManager().setMessageid("100003");
                    request.getRequestManager().setMessagecontent(str);
                    return  WeaResult.fail(500, "NeiBuDiaoDongAction str"+ str, getResultMapForAction(weaverResultMap, "result",str, request.getRequestManager()));

                }
            } catch (Exception e) {
                System.err.println(e.toString());
                return  WeaResult.fail(500, "NeiBuDiaoDongAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));

            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_1103b3f3.error("NeiBuDiaoDongAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "NeiBuDiaoDongAction e: {}"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.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;
    }
}
