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

import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.ebuilder.form.client.ebform.data.EbFormDataDubboService;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.seconddev.interfaces.workflow.util.CommonDevUtil;
import com.weaver.teams.domain.user.SimpleEmployee;
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_KeyUserAction")
public class KeyUserAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_52370ec1 = LoggerFactory.getLogger(KeyUserAction.class);

    @Autowired
    private CommonDevUtil commonDevUtil;

    @RpcReference(group = "ebuilderform")
    private EbFormDataDubboService ebFormDataDubboService;

    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);
        try {
            logger_52370ec1.error(String.valueOf("do KeyUserAction on request:" + request.getRequestid()));
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            try {
                // 获取主表数据
                // 申请类型
                String type = "";
                // 业务模块名称
                String ywmkxz = "";
                // 原关键用户
                String ygjyh = "";
                // 新关键用户
                String xgjyh = "";
                // 对应角色ID
                String dyjsid = "";
                // 2=总部 1=分部
                String level = "2";
                // 分隔符
                char flag = Util.getSeparator();
                Property[] aproperty = request.getMainTableInfo().getProperty();
                for (int i = 0; i < aproperty.length; i++) {
                    String name = aproperty[i].getName().toUpperCase();
                    String value = Util.null2String(aproperty[i].getValue());
                    if (name.equals("SQLX")) {
                        // 申请类型
                        type = value;
                        logger_52370ec1.error(String.valueOf("得到申请类型" + type));
                    }
                    if (name.equals("YWMKXZ")) {
                        // 业务模块名称
                        ywmkxz = value;
                        logger_52370ec1.error(String.valueOf("得到业务模块名称" + ywmkxz));
                    }
                    if (name.equals("YGJYH")) {
                        // 原关键用户
                        ygjyh = value;
                        logger_52370ec1.error(String.valueOf("得到原关键用户" + ygjyh));
                    }
                    if (name.equals("XGJYH")) {
                        // 新关键用户
                        xgjyh = value;
                        logger_52370ec1.error(String.valueOf("得到新关键用户" + xgjyh));
                    }
                    if (name.equals("DYXTJS")) {
                        // 对应角色ID
                        dyjsid = value;
                        logger_52370ec1.error(String.valueOf("得到对应角色ID" + dyjsid));
                    }
                }
                if ("0".equals(type)) {
                    // 新增
                    logger_52370ec1.error(String.valueOf("系统关键用户变更申请流程======新增用户[" + xgjyh + "]"));
                    if (!"".equals(xgjyh)) {
                        String[] array = xgjyh.split(",");
                        if (array != null) {
                            for (int i = 0; i < array.length; i++) {
//                                String poolname_91 = CONN_TYPE.workflow.getType();
                                // String cmd=array[i] + flag + dyjsid + flag + level;
                                /*rs.executeProc("HrmRoleMembers_Insert", cmd);
 TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
 TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//                                long generate = IdGenerator.generate();
//                                rs.executeSql("insert into auth_user_role(roleid,resourceid,rolelevel,resourcetype) values(" + dyjsid + "," + array[i] + "," + level + ",1)", poolname_91,generate);
                                String poolname = CONN_TYPE.hrm.getType();
                                SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
                                Long uf_CustomFlow_formId = commonDevUtil.getObjId("auth_user_role");
                                logger_52370ec1.error("uf_CustomFlow_formId = " + uf_CustomFlow_formId);
                                Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId, currentEmployee);// 获取插入的空的建模id
                                String sql3 = "update e10_common.dbo.auth_user_role set roleid=" + dyjsid + ",resourceid=" + array[i] + ",rolelevel=" + level + ",resourcetype=1 where id  =  " + recodId + " and delete_type = 0 ";
                                boolean b1 = rs.executeSql(sql3, poolname);
                                logger_52370ec1.error("sql3 = " + sql3);
                                logger_52370ec1.error("添加 = " + b1);
                            }
                        }
                    }
                } else if ("1".equals(type)) {
                    // 变更
                    logger_52370ec1.error(String.valueOf("系统关键用户变更申请流程======取消用户[" + ygjyh + "]新增用户[" + xgjyh + "]"));
                    if (!"".equals(ygjyh)) {
                        String sql = "delete from e10_common.dbo.HrmRoleMembers where roleid = " + dyjsid + " and resourceid in (" + ygjyh + ")";
                        String poolname_6f = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql(sql, poolname_6f);
                        logger_52370ec1.error("b--"+b);
                    }
                    if (!"".equals(xgjyh)) {
                        String[] array = xgjyh.split(",");
                        if (array != null) {
                            for (int i = 0; i < array.length; i++) {
//                                String poolname_8i = CONN_TYPE.workflow.getType();
//                                // String cmd=array[i] + flag + dyjsid + flag + level;
//                                /*rs.executeProc("HrmRoleMembers_Insert", cmd);
// TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
// TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//                                long generate = IdGenerator.generate();
//                                rs.executeSql("insert into auth_user_role(roleid,resourceid,rolelevel,resourcetype) values(" + dyjsid + "," + array[i] + "," + level + ",1)", poolname_8i,generate);
                                String poolname = CONN_TYPE.hrm.getType();
                                SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
                                Long uf_CustomFlow_formId = commonDevUtil.getObjId("auth_user_role");
                                logger_52370ec1.error("uf_CustomFlow_formId = " + uf_CustomFlow_formId);
                                Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId, currentEmployee);
                                String sql3 = "update e10_common.dbo.auth_user_role set roleid=" + dyjsid + ",resourceid=" + array[i] + ",rolelevel=" + level + ",resourcetype=1 where id  =  " + recodId + " and delete_type = 0 ";
                                boolean b1 = rs.executeSql(sql3, poolname);
                                logger_52370ec1.error("sql3 = " + sql3);
                                logger_52370ec1.error("添加 = " + b1);
                            }
                        }
                    }
                } else if ("2".equals(type)) {
                    // 取消
                    logger_52370ec1.error(String.valueOf("系统关键用户变更申请流程======取消用户[" + ygjyh + "]"));
                    if (!"".equals(ygjyh)) {
                        String sql = "delete from dbo.HrmRoleMembers where roleid = " + dyjsid + " and resourceid in (" + ygjyh + ")";
                        String poolname = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql(sql, poolname);
                        logger_52370ec1.error("b--"+b);
                    }
                }
                logger_52370ec1.error(String.valueOf("系统关键用户变更申请成功。。。"));
            } catch (Exception e) {
                logger_52370ec1.error(String.valueOf(e.getMessage()));
                return  WeaResult.fail(500, "KeyUserAction err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), request.getRequestManager()));

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