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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.eipoa.AccountService;
import  com.weaver.seconddev.interfaces.eipoa.SI_HTPortalUAMGMT2_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.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_OperateAccountAction")
public class OperateAccountAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private  AccountService service;
    private static final Logger logger_9c33175e = LoggerFactory.getLogger(OperateAccountAction.class);

    public OperateAccountAction() {
    }

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_9c33175e.error("OperateAccountAction 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_9c33175e.error(String.valueOf("工号:" + gh));
                    }
                    if (name.equals("XTID")) {
                        sysid = value;
                        logger_9c33175e.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_9c33175e.error(String.valueOf("业务类型:" + operation));
                    }
                }
                String sta = "";
                String getStatus = "select id ,status sta from e10_core_business.dbo." + tablename + " where id='" + requestId+"'";
                logger_9c33175e.error("getStatus--" + getStatus);
                String poolname_2x = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(getStatus, poolname_2x);
                logger_9c33175e.error("b1--" + b);

                if (rs.next()) {
                    sta = Util.null2String(rs.getString("sta"));
                    logger_9c33175e.error("status== " + sta );
                }
                logger_9c33175e.error("operation--" + operation);
                if (!"".equals(operation) && !"S".equals(sta)) {
                    SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo[] param = new SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo[1];
                    SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo paramInfo = new SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo();
                    paramInfo.setMail("");
                    paramInfo.setOperation(operation);
                    paramInfo.setSystemid(sysid);
                    paramInfo.setUserid(gh);
                    param[0] = paramInfo;
//                    AccountService service = new AccountService();
                    String[] array = service.account("HT01EIP006", param);
                    if ("E".equals(array[0])) {
                        stat = "E";
                        message = array[1];
                        logger_9c33175e.error(String.valueOf(requestId + "----" + gh + "调用批量开户销户接口出错：" + 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_9c33175e.error(String.valueOf(requestId + "----" + gh + str + "失败:" + message));
                        } else {
                            stat = "S";
                            logger_9c33175e.error(String.valueOf(requestId + "----" + gh + str + "成功"));
                        }
                    }
                    String sql = "update e10_core_business.dbo." + tablename + " set status='" + stat + "',message='" + message + "' where id=" + requestId;
                    logger_9c33175e.error("sql--" + sql);
                    String poolname_y8 = CONN_TYPE.workflow.getType();
                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                    boolean b1 = rs.executeSql(sql, poolname_y8);
                    logger_9c33175e.error("b2222--" + b1);
                    if (b1) {
                        logger_9c33175e.error(String.valueOf(requestId + "----" + gh + "更新状态成功"));
                    } else {
                        logger_9c33175e.error(String.valueOf(requestId + "----" + gh + "更新状态失败"));
                    }
                }
            } 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_9c33175e.error("errorLog--" + errorLog);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(errorLog, poolname);
                logger_9c33175e.error("Exception b--" + b);
                logger_9c33175e.error(requestId + "开户销户失败：" , e);
                return WeaResult.fail(500, "OperateAccountAction err", e);
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_9c33175e.error("OperateAccountAction e: {}", e);
            return WeaResult.fail(500, "OperateAccountAction e: {}", e);
        }
    }

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