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

import java.net.Socket;
import com.alibaba.fastjson.JSONObject;
import com.weaver.seconddev.interfaces.prop.ConfigProp;
import tebie.applib.api.APIContext;
import tebie.applib.api.IClient;
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 org.springframework.core.env.Environment;
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_CheckEmailAction")
public class CheckEmailAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_48219209 = LoggerFactory.getLogger(CheckEmailAction.class);

    public CheckEmailAction() {
    }
    @Autowired
    private ConfigProp configProp;

    @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_48219209.error("CheckEmailAction start ");
        try {
            Socket socket = null;
            IClient client = null;
            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 = "";
                // 邮箱账号
                String yxzh = "";
                // 邮箱类型
                String yxlx = "";
                // 邮箱地址
                String emailIP = "";
                // 邮箱端口
                String port = "";
                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;
                    }
                    if (name.equals("YXZH")) {
                        yxzh = value.trim();
                    }
                    if (name.equals("YXLX")) {
                        if ("0".equals(value)) {
                            yxlx = "@hengtonggroup.com.cn";
                            sysid = "SYS025";
//                            emailIP = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htemail.htgroup")).trim();
//                            port = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htemail.htgroupport")).trim();
                            emailIP = configProp.getHtgroup();
                            port = configProp.getHtgroupport();
                        } else if ("1".equals(value)) {
                            yxlx = "@htgd.com.cn";
                            sysid = "SYS026";
//                            emailIP = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htemail.htgd")).trim();
//                            port = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htemail.htgdport")).trim();
                            emailIP = configProp.getHtgd();
                            port = configProp.getHtgdport();
                        } else if ("2".equals(value)) {
                            yxlx = "@jsalpha.com";
                            sysid = "SYS035";
//                            emailIP = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htemail.guangdao")).trim();
//                            port = Util.null2String(I18nContextUtilcus.getBean(Environment.class).getProperty("htemail.guangdaoport")).trim();
                            emailIP = configProp.getGuangdao();
                            port = configProp.getGuangdaoport();
                        }
                    }
                    if (name.equals("YWLX")) {
                        ywlx = value;
                    }
                }
                int num = 0;
                String sql = "select count(id) as count from e10_core_business.dbo." + tablename + " where yhgh='" + yhgh + "' and lczt='1'";
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(sql, poolname);
                logger_48219209.error("b--"+b);
                if (rs.next()) {
                    num = rs.getInt("count");
                }
                if (num > 0) {
                    logger_48219209.error(String.valueOf("工号:" + yhgh + "，此流程已有未归档的申请，待归档后才能再次申请。"));
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("此流程已有未归档的申请，待归档后才能再次申请。");
                }
//                GetSystemList sys = new GetSystemList();
                String result = sys.getList(yhgh);
                logger_48219209.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_48219209.error(String.valueOf("index:" + i));
                        if ("0".equals(ywlx)) {
                            if (i >= 0) {
                                logger_48219209.error(String.valueOf("工号:" + yhgh + "，系统已开户，请不要重复开户！"));
                                request.getRequestManager().setMessageid("ERROR");
                                request.getRequestManager().setMessagecontent("系统已开户，请不要重复开户！");
                            }
                        } else if ("1".equals(ywlx) || "2".equals(ywlx)) {
                            if (i > 0) {
                                socket = new Socket(emailIP, Integer.parseInt(port));
                                client = APIContext.getClient(socket);
                                APIContext ret = client.getAttrs(yxzh + yxlx, "homepage");
                                if (ret.getRetCode() == 0) {
                                    String workcode = ret.getResult();
                                    if (workcode.length() > 9) {
                                        workcode = workcode.substring(9);
                                    }
                                    if (!workcode.trim().equals(yhgh)) {
                                        logger_48219209.error(String.valueOf("工号:" + yhgh + "，输入的邮箱账号不正确！"));
                                        request.getRequestManager().setMessageid("ERROR");
                                        request.getRequestManager().setMessagecontent("邮箱账号不正确，请输入正确的账号！");
                                        return  WeaResult.fail(500, "工号:" + yhgh + "，输入的邮箱账号不正确！", getResultMapForAction(weaverResultMap, "result", "工号:" + yhgh + "，输入的邮箱账号不正确！", request.getRequestManager()));

                                    }
                                } else {
                                    logger_48219209.error("工号:" + yhgh + ret.getErrorInfo());
                                    request.getRequestManager().setMessageid("ERROR");
                                    request.getRequestManager().setMessagecontent("邮箱账号不正确，请输入正确的账号！");
                                    return  WeaResult.fail(500, "邮箱账号不正确，请输入正确的账号！", getResultMapForAction(weaverResultMap, "result", "邮箱账号不正确，请输入正确的账号！", request.getRequestManager()));

                                }
                            } else {
                                logger_48219209.error(String.valueOf("工号:" + yhgh + "，系统未开户，不能申请该业务类型！"));
                                request.getRequestManager().setMessageid("ERROR");
                                request.getRequestManager().setMessagecontent("系统未开户，不能申请该业务类型！");
                                return  WeaResult.fail(500, "系统未开户，不能申请该业务类型！", getResultMapForAction(weaverResultMap, "result", "系统未开户，不能申请该业务类型！", request.getRequestManager()));

                            }
                        }
                    } else {
                        String message = jsonObject.getString("message");
                        logger_48219209.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_48219209.error(String.valueOf("调用门户查询已开户系统接口失败，请联系门户系统管理员"));
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("调用门户查询已开户系统接口失败，请联系门户系统管理员");
                    return  WeaResult.fail(500, "调用门户查询已开户系统接口失败，请联系门户系统管理员", getResultMapForAction(weaverResultMap, "result", "调用门户查询已开户系统接口失败，请联系门户系统管理员", request.getRequestManager()));

                }
            } catch (Exception e) {
                logger_48219209.error(String.valueOf("调用接口出错：" + e.toString()));
                request.getRequestManager().setMessageid("ERROR");
                request.getRequestManager().setMessagecontent("调用接口出错：" + e.toString());
                return  WeaResult.fail(500, "调用接口出错：" + e.toString(), getResultMapForAction(weaverResultMap, "result", "调用接口出错：" + e.toString(), request.getRequestManager()));

            } finally {
                if (client != null) {
                    client.close();
                }
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_48219209.error("CheckEmailAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "CheckEmailAction 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;
    }
}
