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

import java.io.IOException;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.alibaba.fastjson.JSONArray;
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.AccountService;
import  com.weaver.seconddev.interfaces.eipoa.SI_HTPortalUAMGMT2_OUTServiceStub;
import  com.weaver.seconddev.interfaces.eipoa.SI_HTPortalUAMGMT2_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 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_OperateEmailAccountAction")
public class OperateEmailAccountAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private ConfigProp configProp;
    // public static void main(String[] args) {
    // Socket socket = null;
    // try {
    // socket = new Socket("10.6.2.2", Integer.parseInt("6195"));
    // IClient client = APIContext.getClient(socket);
    // APIContext ret = client.userExist("zhangbk@hengtonggroup.com.cn");
    // int code = ret.getRetCode();
    // System.out.println(code);
    // } catch (IOException e) {
    // e.printStackTrace();
    // }
    // 
    // }

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

    public OperateEmailAccountAction() {
    }

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_7c6670cc.error("OperateEmailAccountAction 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 bill = new BillFieldUtil();
//            String tablename = bill.getTablename(wfid);
            String tablename = request.getRequestManager().getBillTableName();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            String sql = "";
            // 工号
            String yhgh = "";
            // 邮箱账号
            String yxzh = "";
            // 邮箱类型
            String yxlx = "";
            // 系统id
            String sysid = "";
            // 业务类型
            String ywlx = "";
            // 邮箱账号
            String emailaccount = "";
            // 邮箱地址
            String emailIP = "";
            // 邮箱端口
            String port = "";
            String[] res = new String[2];
            Socket socket = null;
            IClient client = null;
            APIContext ret = null;
            try {
                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());
                    logger_7c6670cc.error(String.valueOf("属性:" + name + "--" + value));
                    if (name.equals("YHGH")) {
                        yhgh = value;
                    }
                    if (name.equals("YXZH")) {
                        yxzh = value.trim();
                    }
                    if (name.equals("YXLX")) {
                        logger_7c6670cc.error("value--" + value);
                        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();
                        }
                        logger_7c6670cc.error("port--" + port);
                    }
                    if (name.equals("YWLX")) {
                        ywlx = value;
                    }
                }
                emailaccount = yxzh + yxlx;
                logger_7c6670cc.error(String.valueOf("邮箱账号：" + emailaccount + "--" + sysid));
                String state = "";
                socket = new Socket(emailIP, Integer.parseInt(port));
                client = APIContext.getClient(socket);
                if ("0".equals(ywlx)) {
                    state = "insert";
                    ret = client.userExist(emailaccount);
                    int code = ret.getRetCode();
                    if (code != 19) {
                        if (code == 0 || code == 8) {
                            res[0] = "E";
                            res[1] = "邮箱账号已存在！";
                            logger_7c6670cc.error(String.valueOf(requestId + "--" + res[0] + "--" + res[1]));
                        } else {
                            res[0] = "E";
                            res[1] = "网络异常，请稍后重试！";
                            logger_7c6670cc.error(String.valueOf(requestId + "--" + res[0] + "--" + res[1]));
                        }
                    } else {
                        res = operate(requestId, yhgh, sysid, emailaccount, state);
                    }
                } else if ("1".equals(ywlx)) {
                    state = "disable";
                    ret = client.userExist(emailaccount);
                    int code = ret.getRetCode();
                    if (code != 19) {
                        res = operate(requestId, yhgh, sysid, emailaccount, state);
                    } else {
                        res[0] = "E";
                        res[1] = "邮箱账号不存在！";
                        logger_7c6670cc.error(String.valueOf(requestId + "--" + res[0] + "--" + res[1]));
                    }
                } else if ("2".equals(ywlx)) {
                    // password=p3as5wo9rd (password=password@123)
                    ret = client.changeAttrs(emailaccount, "password=p3as5wo9rd&password_expiry_time=" + getCurrentDate());
                    if (ret.getRetCode() != 0) {
                        res[0] = "E";
                        res[1] = "重置密码失败：" + ret.getErrorInfo();
                        logger_7c6670cc.error(String.valueOf(requestId + "--" + res[0] + "--" + res[1]));
                    } else {
                        res[0] = "S";
                        res[1] = "success";
                        logger_7c6670cc.error(String.valueOf(requestId + "--" + res[0] + "--" + res[1]));
                    }
                }
                sql = "update e10_core_business.dbo." + tablename + " set status='" + res[0] + "',message='" + res[1] + "' where id=" + requestId;
                logger_7c6670cc.error("sql--" + sql);
                String poolname_46 = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(sql, poolname_46);
                logger_7c6670cc.error("b--" + b);
                if ("E".equals(res[0])) {
                    request.getRequestManager().setMessageid("ERROR");
                    request.getRequestManager().setMessagecontent("处理邮箱账号失败：" + res[1]);
                    return WeaResult.fail(500, "执行异常:" + res[1]);
                }
            } catch (Exception e) {
                sql = "update e10_core_business.dbo." + tablename + " set status='E',message='" + e.toString() + "' where id =" + requestId;
                logger_7c6670cc.error("sql--" + sql);
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeSql(sql, poolname);
                logger_7c6670cc.error("b--" + b);
                logger_7c6670cc.error(requestId + "处理邮箱账号失败：" , e);
                request.getRequestManager().setMessageid("ERROR");
                request.getRequestManager().setMessagecontent("处理邮箱账号失败：" + e.toString());
                return WeaResult.fail(500, "OperateEmailAccountAction err", e);
            } finally {
                client.close();
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_7c6670cc.error("OperateEmailAccountAction e: {}", e);
            return WeaResult.fail(500, "OperateEmailAccountAction e: {}", e);
        }
    }

    public String[] operate(String requestId, String yhgh, String sysid, String emailaccount, String state) {
        String[] str = new String[2];
        SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo[] param = new SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo[1];
        SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo paramInfo = new SI_HTPortalUAMGMT2_OUTServiceStub.UserSyncInfo();
        paramInfo.setUserid(yhgh);
        paramInfo.setSystemid(sysid);
        paramInfo.setMail(emailaccount);
        paramInfo.setOperation(state);
        param[0] = paramInfo;
//        AccountService service = new AccountService();
        str = service.account("HT01EIP006", param);
        if ("E".equals(str[0])) {
            logger_7c6670cc.error(String.valueOf(requestId + "---" + yhgh + "调用邮箱接口出错：" + str[1]));
        } else {
            JSONObject jsonObject = JSONObject.parseObject(str[1]);
            JSONArray jsonArray = jsonObject.getJSONArray("returnMsg");
            JSONObject jsonObjectone = jsonArray.getJSONObject(0);
            str[1] = jsonObjectone.getString("result");
            String stat = jsonObjectone.getString("stat");
            if ("1".equals(stat)) {
                str[0] = "S";
                logger_7c6670cc.error(String.valueOf(requestId + "---" + yhgh + "处理邮箱账号成功"));
            } else {
                str[0] = "E";
                logger_7c6670cc.error(String.valueOf(requestId + "---" + yhgh + "处理邮箱账号失败：" + str[1]));
            }
        }
        return str;
    }

    public String getCurrentDate() {
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String dateString = formatter.format(currentTime);
        return dateString;
    }

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