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

import org.apache.axis2.kernel.http.HTTPConstants;
import org.apache.axis2.transport.http.HttpTransportProperties;
import  com.weaver.seconddev.interfaces.easoa.SI_WhitelistSync_OUTServiceStub;
import  com.weaver.seconddev.interfaces.swfa.BillFieldUtil;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
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.apache.axis2.transport.http.impl.httpclient4.HttpTransportPropertiesImpl;
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.BaseBean;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

// 白名单同步到EAS
@org.springframework.stereotype.Service("workflow_action_EasWhiteListAction")
public class EasWhiteListAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_b5430ca5 = LoggerFactory.getLogger(EasWhiteListAction.class);

    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);
        logger_b5430ca5.error("EasWhiteListAction start== ");
        logger_b5430ca5.error("requestIdTemp == " +requestIdTemp);
        logger_b5430ca5.error("userIdTemp == " +userIdTemp);
        try {
            String requestid = request.getRequestid();
            String tablename = "";
            String wfid = request.getWorkflowid();
            BillFieldUtil unit = new BillFieldUtil();
//            tablename = unit.getTablename(wfid);
            tablename = request.getRequestManager().getBillTableName();
            String id = "";
            try {
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                String sql = "select id from e10_core_business.dbo." + tablename + " where id='" + requestid + "'";
                logger_b5430ca5.error("sql == "+sql);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(sql, poolname);
                logger_b5430ca5.error("b == "+b);
                while (rs.next()) {
                    id = rs.getString("id");
                    logger_b5430ca5.error("id == "+id);
                }
            } catch (Exception e) {
                logger_b5430ca5.error(String.valueOf(e.toString()));
            }
            // 名称
            String mc = "";
            // 白名单类型
            String type = "";
            // 白名单状态
            String status = "";
            // 银行账号
            String bankAccount = "";
            // 开户行名称
            String bankName = "";
            // 身份证号或社会信用代码
            String identityNumber = "";
            // 创建日期
            String createTime = "";
            // 有效截止日期
            String endTime = "";
            // 原因
            String reason = "";
            // 日期
            String rq = "";
            // 时间
            String sj = "";
            String flowCode = "";
            String code = "";
            Property[] aproperty = request.getMainTableInfo().getProperty();
            for (int i = 0; i < aproperty.length; i++) {
                String name = aproperty[i].getName().toUpperCase();
                String value = Util.null2String(aproperty[i].getValue());
                if (name.equals("MC")) {
                    mc = value;
                    logger_b5430ca5.error("MC == "+mc);
                }
                if (name.equals("BMDLX")) {
                    type = value;
                    logger_b5430ca5.error("type == "+type);
                }
                if (name.equals("BMDZT")) {
                    status = value;
                    logger_b5430ca5.error("status == "+status);
                }
                if (name.equals("YHZH")) {
                    bankAccount = value;
                    logger_b5430ca5.error("bankAccount == "+bankAccount);
                }
                if (name.equals("YHMC")) {
                    bankName = value;
                    logger_b5430ca5.error("bankName == "+bankName);
                }
                if (name.equals("SHXYDM")) {
                    identityNumber = value;
                    logger_b5430ca5.error("identityNumber == "+identityNumber);
                }
                if (name.equals("TBSJ")) {
                    rq = value;
                    logger_b5430ca5.error("rq == "+rq);
                }
                if (name.equals("SJ")) {
                    sj = value;
                    logger_b5430ca5.error("sj == "+sj);
                }
                if (name.equals("YXJZRQ")) {
                    if (!"".equals(value) && value != null) {
                        endTime = value + " 00:00:00";
                    }
                    logger_b5430ca5.error("endTime == "+endTime);
                }
                if (name.equals("SQBMDYY")) {
                    reason = value;
                    logger_b5430ca5.error("reason == "+reason);
                }
                if (name.equals("LCBH")) {
                    flowCode = value;
                    logger_b5430ca5.error("flowCode == "+flowCode);
                }
                if (!"".equals(flowCode)) {
                    code = flowCode.trim().substring(flowCode.length() - 11, flowCode.length());
                    logger_b5430ca5.error("code == "+code);
                }
                createTime = rq + " " + sj + ":00";
            }
            SI_WhitelistSync_OUTServiceStub.SyncWhiteListService input = new SI_WhitelistSync_OUTServiceStub.SyncWhiteListService();
            SI_WhitelistSync_OUTServiceStub.SyncWhiteListInfo infos = new SI_WhitelistSync_OUTServiceStub.SyncWhiteListInfo();
            SI_WhitelistSync_OUTServiceStub.SieWhiteListInfo info = new SI_WhitelistSync_OUTServiceStub.SieWhiteListInfo();
            info.setWhiteId(id + "");
            info.setCode(code);
            info.setName(mc);
            info.setType(type);
            info.setStatus(status);
            info.setBankAccount(bankAccount);
            info.setBankName(bankName);
            info.setIdentityNumber(identityNumber);
            info.setFlowId(requestid);
            info.setFlowCode(flowCode);
            info.setCreateTime(createTime);
            info.setEndTime(endTime);
            info.setReason(reason);
            infos.addWhiteListInfos(info);
            infos.setITFID("");
            infos.setSENDID("");
            infos.setSYSID("");
            input.setSyncWhiteListInfo(infos);
            try {
                String[] result = new String[5];
                // String uri = "http://10.6.2.35:7001/easws/services/syncWhiteListService?wsdl";
                String uri = "http://sappod.hengtong.com:50000/XISOAPAdapter/MessageServlet?senderParty=&senderService=BS_OA&receiverParty=&receiverService=&interface=SI_WhitelistSync_OUT&interfaceNamespace=http://hengtong.com/OA/WhitelistSync";
                SI_WhitelistSync_OUTServiceStub stub = new SI_WhitelistSync_OUTServiceStub(uri);
                stub._getServiceClient().getOptions().setProperty("__CHUNKED__", Boolean.FALSE);
                stub._getServiceClient().getOptions().setTimeOutInMilliSeconds(300000);
                stub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT,300000);
                stub._getServiceClient().getOptions().setProperty(HTTPConstants.CONNECTION_TIMEOUT,300000);
//                HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
                HttpTransportPropertiesImpl.Authenticator auth = new HttpTransportPropertiesImpl.Authenticator();
                auth.setUsername("pouser");
                auth.setPassword("654321");
                stub._getServiceClient().getOptions().setProperty(org.apache.axis2.kernel.http.HTTPConstants.AUTHENTICATE,auth);
                SI_WhitelistSync_OUTServiceStub.SyncWhiteListServiceResponse response = stub.sI_WhitelistSync_OUT(input);
                SI_WhitelistSync_OUTServiceStub.ResultInfo resultInfo = response.get_return();
                result[0] = resultInfo.getISTAT();
                result[1] = resultInfo.getITFID();
                result[2] = resultInfo.getMESSAGE();
                result[3] = resultInfo.getSENDID();
                result[4] = resultInfo.getSYSID();
                RecordSet rs1 = I18nContextUtil.getBean(RecordSet.class);
                String sql = "update e10_core_business.dbo." + tablename + " set state='" + result[0] + "',message='" + result[2] + "' where id='" + requestid + "'";
                logger_b5430ca5.error("sql = "+sql);

                String poolname_x3 = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs1.executeSql(sql, poolname_x3);
                logger_b5430ca5.error("result = "+b);
            } catch (Exception e) {
                logger_b5430ca5.error(String.valueOf("EasWhiteListAction调用接口报错 " + e.toString()));
                return  WeaResult.fail(500, "EasWhiteListAction调用接口报错 " + e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));

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