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

import com.alibaba.fastjson.JSONObject;
import  com.weaver.seconddev.interfaces.eipoa.GetSystemList;
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_CheckSystemAction")
public class CheckSystemAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_b4155f0e = LoggerFactory.getLogger(CheckSystemAction.class);

    public CheckSystemAction() {
    }
    @Autowired
    private GetSystemList sys;

    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_b4155f0e.error("CheckSystemAction start");
        try {
            try {
                BillFieldUtil unit = new BillFieldUtil();
                String wfid = request.getWorkflowid();
//                String tablename = unit.getTablename(wfid);
                String tablename = request.getRequestManager().getBillTableName();
                // 用户工号
                String yhgh = "";
                // 系统ID
                String sysid = "";
                // 业务类型
                String ywlx = "";
                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")) {
                        yhgh = value;
                        logger_b4155f0e.error(String.valueOf("工号:" + yhgh));
                    }
                    if (name.equals("XTID")) {
                        sysid = value;
                        logger_b4155f0e.error(String.valueOf("系统ID:" + sysid));
                    }
                    if (name.equals("YWLX")) {
                        ywlx = value;
                        logger_b4155f0e.error(String.valueOf("业务类型:" + ywlx));
                    }
                }
                int num = 0;
                String sql = "select count(id) as count from e10_core_business.dbo." + tablename + " where yhgh='" + yhgh + "' and lczt='1' and xtid='" + sysid + "'";
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(sql, poolname);
                logger_b4155f0e.error("b--"+b);
                if (rs.next()) {
                    num = rs.getInt("count");
                }
                if (num > 0) {
                    logger_b4155f0e.error(String.valueOf("工号:" + yhgh + "，此流程已有未归档的申请，待归档后才能再次申请。"));
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("此流程已有未归档的申请，待归档后才能再次申请。");
                    return  WeaResult.fail(500, "此流程已有未归档的申请，待归档后才能再次申请。" , getResultMapForAction(weaverResultMap, "result", "返回错误信息" , request.getRequestManager()));

                }
//                GetSystemList sys = new GetSystemList();
                String result = sys.getList(yhgh);
                logger_b4155f0e.error(String.valueOf("调用门户查询已开户系统接口返回值：" + result));
                if (!"E".equals(result)) {
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    String flag = jsonObject.getString("success");
                    if (flag.equals("true")) {
                        int i = result.indexOf(sysid);
                        logger_b4155f0e.error(String.valueOf("index:" + i));
                        if ("0".equals(ywlx)) {
                            if (i >= 0) {
                                logger_b4155f0e.error(String.valueOf("工号:" + yhgh + "，系统已开户，请不要重复开户！"));
                                request.getRequestManager().setMessageid("ERROR");
                                request.getRequestManager().setMessagecontent("系统已开户，请不要重复开户！");
                                return  WeaResult.fail(500, "工号:" + yhgh + "，系统已开户，请不要重复开户！" , getResultMapForAction(weaverResultMap, "result", "返回错误信息" , request.getRequestManager()));

                            }
                        } else {
                            if (i < 0) {
                                logger_b4155f0e.error(String.valueOf("工号:" + yhgh + "，系统未开户，无法申请此业务类型！"));
                                request.getRequestManager().setMessageid("ERROR");
                                request.getRequestManager().setMessagecontent("系统未开户，无法申请此业务类型！");
                                return  WeaResult.fail(500, "工号:" + yhgh + "，系统未开户，无法申请此业务类型！" , getResultMapForAction(weaverResultMap, "result", "返回错误信息" , request.getRequestManager()));

                            }
                        }
                        /*    				else if("1".equals(ywlx)){
    					if(i<0){
    						writeLog("工号:"+yhgh+"，系统未开户，请不要申请销户！");
    						request.getRequestManager().setMessageid("ERROR");
                        	request.getRequestManager().setMessagecontent("系统未开户，请不要申请销户！");
    					}
    				}else if("2".equals(ywlx)){
    					if(i<0){
    						writeLog("工号:"+yhgh+"，系统未开户，无法申请权限变更！");
    						request.getRequestManager().setMessageid("ERROR");
                        	request.getRequestManager().setMessagecontent("系统未开户，无法申请权限变更！");
    					}
    				}*/
                    } else {
                        String message = jsonObject.getString("message");
                        logger_b4155f0e.error(String.valueOf("门户返回错误信息：" + message));
                        request.getRequestManager().setMessageid("ERROR");
                        request.getRequestManager().setMessagecontent("门户返回错误信息：" + message);
                        return  WeaResult.fail(500, "门户返回错误信息：" + message, getResultMapForAction(weaverResultMap, "result", "门户返回错误信息：" + message, request.getRequestManager()));

                    }
                } else {
                    logger_b4155f0e.error(String.valueOf("调用门户查询已开户系统接口失败，请联系门户系统管理员"));
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("调用门户查询已开户系统接口失败，请联系门户系统管理员");
                    return  WeaResult.fail(500, "调用门户查询已开户系统接口失败，请联系门户系统管理员", getResultMapForAction(weaverResultMap, "result", "调用门户查询已开户系统接口失败，请联系门户系统管理员", request.getRequestManager()));

                }
            } catch (Exception e) {
                logger_b4155f0e.error(String.valueOf("调用门户查询已开户系统接口出错：" + e.toString()));
                request.getRequestManager().setMessageid("ERROR");
                request.getRequestManager().setMessagecontent("门户返回错误信息：" + e.toString());
                return  WeaResult.fail(500, "调用门户查询已开户系统接口出错"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));

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