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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.eipoa.MesAccountService;
import  com.weaver.seconddev.interfaces.eipoa.SI_HTPortalFuncSync_OUTServiceStub.UserSyncInfo;
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.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;

@org.springframework.stereotype.Service("workflow_action_OperateMesAccountAction")
public class OperateMesAccountAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired

    private  MesAccountService service;

    private static final Logger logger_4057422d = LoggerFactory.getLogger(OperateMesAccountAction.class);

    public OperateMesAccountAction() {
    }

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_4057422d.error("OperateMesAccountAction 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 request = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            String requestId = request.getRequestid();
            String wfid = request.getWorkflowid();
            BillFieldUtil util = new BillFieldUtil();
//            String tablename = util.getTablename(wfid);
            String tablename = request.getRequestManager().getBillTableName();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            String stat = "";
            String message = "";
            try {
                String gh = "";
                String sysid = "";
                String operation = "";
                String str = "";
                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("YHGH")) {
                        gh = value;
                        logger_4057422d.error(String.valueOf("工号:" + gh));
                    }
                    if (name.equals("XTID")) {
                        sysid = value;
                        logger_4057422d.error(String.valueOf("系统ID:" + sysid));
                    }
                    if (name.equals("YWLX")) {
                        if ("0".equals(value)) {
                            operation = "insert";
                            str = "开户";
                        } else if ("1".equals(value)) {
                            operation = "disable";
                            str = "销户";
                        }
                        logger_4057422d.error(String.valueOf("业务类型:" + operation));
                    }
                }
                String sta = "";
                String getStatus = "select id,status from e10_core_business.dbo." + tablename + " where id=" + requestId;
                logger_4057422d.error("getStatus" + getStatus);
                String poolname_me = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(getStatus, poolname_me);
                logger_4057422d.error("b--" + b);
                if (rs.next()) {
                    sta = Util.null2String(rs.getString("status"));
                }
                if (!"".equals(operation) && !"S".equals(sta)) {
                    UserSyncInfo[] param = new UserSyncInfo[1];
                    UserSyncInfo paramInfo = new UserSyncInfo();
                    paramInfo.setMail("");
                    paramInfo.setOperation(operation);
                    paramInfo.setSystemid(sysid);
                    paramInfo.setUserid(gh);
                    param[0] = paramInfo;
//                    MesAccountService service = new MesAccountService();
                    String[] array = service.account(param);
                    if ("E".equals(array[0])) {
                        stat = "E";
                        message = array[1];
                        logger_4057422d.error(String.valueOf(requestId + "----" + gh + "调用门户金思维MES批量开户销户接口出错：" + array[1]));
                    } else {
                        JSONObject jsonObject = JSONObject.parseObject(array[1]);
                        JSONArray jsonArray = jsonObject.getJSONArray("returnMsg");
                        JSONObject jsonObjectone = jsonArray.getJSONObject(0);
                        stat = jsonObjectone.getString("stat");
                        message = jsonObjectone.getString("result");
                        if ("0".equals(stat)) {
                            stat = "E";
                            logger_4057422d.error(String.valueOf(requestId + "----" + gh + str + "失败:" + message));
                        } else {
                            stat = "S";
                            logger_4057422d.error(String.valueOf(requestId + "----" + gh + str + "成功"));
                        }
                    }
                    String sql = "update e10_core_business.dbo." + tablename + " set status='" + stat + "',message='" + message + "' where id=" + requestId;
                    logger_4057422d.error("sql" + sql);
                    String poolname_cc = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b1 = rs.executeSql(sql, poolname_cc);
                    logger_4057422d.error("b1--" + b1);
                }
            } catch (Exception e) {
                stat = "E";
                message = e.toString();
                String errorLog = "update e10_core_business.dbo." + tablename + " set status='" + stat + "',message='" + message + "' where id=" + requestId;
                logger_4057422d.error("errorLog" + errorLog);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(errorLog, poolname);
                logger_4057422d.error("b--" + b);
                logger_4057422d.error(String.valueOf(requestId + "开户销户失败：" + e.toString()));
                return  WeaResult.fail(500, "OperateMesAccountAction开户销户失败"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_4057422d.error("OperateMesAccountAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "OperateMesAccountAction 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;
    }
}
