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

import com.weaver.common.distribution.genid.IdGenerator;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.ebuilder.form.client.ebform.data.EbFormDataDubboService;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.seconddev.interfaces.htjt.util.TransUtil;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
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.Cell;
import com.weaver.verupgrade.soa.workflow.request.DetailTable;
import com.weaver.verupgrade.soa.workflow.request.Row;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

@org.springframework.stereotype.Service("workflow_action_ChangeInformationExpertsAction")
public class ChangeInformationExpertsAction extends BaseBean implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_750b7a22 = LoggerFactory.getLogger(ChangeInformationExpertsAction.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 {
            String requestid = request.getRequestid();
//            String workflowid = request.getWorkflowid();
            String tablename = request.getRequestManager().getBillTableName();
            logger_750b7a22.error(String.valueOf("ChangeInformationExpertsAction--start--" + requestid));
            TransUtil tu = new TransUtil();
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
//            String tablename = tu.getTableName(workflowid);
            String roleid = "100502830000001498";
            String zjlx1 = "";
            String sqdw = "";
            String sql = "select * from e10_core_business.dbo." + tablename + " where id=" + requestid;
            String poolname = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean b2 = rs.executeSql(sql, poolname);
            logger_750b7a22.error("b2--" + b2);
            if (rs.next()) {
                zjlx1 = Util.null2String(rs.getString("zjlx1"));
                sqdw = Util.null2String(rs.getString("sqdw"));
            }
            if ("1".equals(zjlx1)) {
                roleid = "100502830000001564";
            }
            String xxhzj = "";
            String xxhzjrdgcl = "";
            sql = "SELECT xxhzj AS xxhzj, xxhzjrdgcl AS xxhzjrdgcl FROM (SELECT t1.*, t2.id AS subcomid FROM eteams.dbo.hrmsubcompanydefined t1 LEFT JOIN eteams.dbo.department t2 ON t1.FORM_DATA_ID = t2.formdata AND t2.delete_type = 0 AND t2.tenant_key = 't6kj9c07jr' WHERE t1.DELETE_TYPE = 0 AND t1.TENANT_KEY = 't6kj9c07jr') HrmSubcompanyDefinedWHERE HrmSubcompanyDefined.delete_type = 0 AND HrmSubcompanyDefined.tenant_key = 't6kj9c07jr' and subcomid = '" + sqdw +"'";
            String poolname_cq = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            logger_750b7a22.error("sql--" + sql);
            boolean b3 = rs.executeSql(sql, poolname_cq);
            logger_750b7a22.error("b3--" + b3);
            if (rs.next()) {
                xxhzj = Util.null2String(rs.getString("xxhzj"));
                xxhzjrdgcl = Util.null2String(rs.getString("xxhzjrdgcl"));
            }
            try {
                DetailTable[] detailtable = request.getDetailTableInfo().getDetailTable();
                DetailTable dtq = detailtable[0];
                Row[] sq = dtq.getRow();
                for (int j = 0; j < sq.length; ++j) {
                    Row rq = sq[j];
                    Cell[] cq = rq.getCell();
                    String bglx = "";
                    String xm = "";
                    for (int k = 0; k < cq.length; ++k) {
                        Cell cq1 = cq[k];
                        String nameq = cq1.getName().toLowerCase();
                        String valueq = Util.null2String(cq1.getValue());
                        if (nameq.equals("bglx")) {
                            bglx = valueq;
                        }
                        if (nameq.equals("xm")) {
                            xm = valueq;
                        }
                    }
                    String str = "";
                    if (bglx.equals("0")) {
                        str = "新增";
                        String poolname_jn = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql("select user_id from eteams.dbo.auth_user_role as  HrmRoleMembers where roleid=" + roleid + " and resourceid=" + xm, poolname_jn);
                        logger_750b7a22.error("b--" + b);
                        if (!rs.next()) {
                            String poolname_k7 = CONN_TYPE.workflow.getType();
                            /* *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 eteams.dbo.auth_user_role(roleid,resourceid,rolelevel,resourcetype) values(" + roleid + "," + xm + ",2,1)", poolname_k7,generate);
//                            SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
//                            Long uf_CustomFlow_formId = commonDevUtil.getObjId("auth_user_role");
//                            logger_750b7a22.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=" + roleid + ",resourceid=" + xm + ",rolelevel=2,resourcetype=1 where id  =  " + recodId + " and delete_type = 0 ";
//                            boolean b1 = rs.executeSql(sql3, poolname);
//                            logger_750b7a22.error("sql3 = " + sql3);
//                            logger_750b7a22.error("添加 = " + b1);
                        }
                        if ("0".equals(zjlx1)) {
                            if ("".equals(xxhzj)) {
                                xxhzj = xm;
                            } else if (("," + xxhzj + ",").indexOf("," + xm + ",") < 0) {
                                xxhzj = xxhzj + "," + xm;
                            }
                        } else if ("1".equals(zjlx1)) {
                            if ("".equals(xxhzjrdgcl)) {
                                xxhzjrdgcl = xm;
                            } else if (("," + xxhzjrdgcl + ",").indexOf("," + xm + ",") < 0) {
                                xxhzjrdgcl = xxhzjrdgcl + "," + xm;
                            }
                        }
                    } else if (bglx.equals("1")) {
                        str = "删除";
                        String poolname_8p = CONN_TYPE.workflow.getType();
                        // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                        boolean b = rs.executeSql("delete from eteams.dbo.HrmRoleMembers where roleid=" + roleid + " and resourceid=" + xm, poolname_8p);
                        logger_750b7a22.error("b = " + b);
                        if ("0".equals(zjlx1)) {
                            if (("," + xxhzj + ",").indexOf("," + xm + ",") >= 0) {
                                xxhzj = ("," + xxhzj + ",").replace(("," + xm + ","), ",");
                                if (",".equals(xxhzj)) {
                                    xxhzj = "";
                                } else {
                                    xxhzj = xxhzj.substring(1, xxhzj.length() - 1);
                                }
                            }
                        } else if ("1".equals(zjlx1)) {
                            if (("," + xxhzjrdgcl + ",").indexOf("," + xm + ",") >= 0) {
                                xxhzjrdgcl = ("," + xxhzjrdgcl + ",").replace(("," + xm + ","), ",");
                                if (",".equals(xxhzjrdgcl)) {
                                    xxhzjrdgcl = "";
                                } else {
                                    xxhzjrdgcl = xxhzjrdgcl.substring(1, xxhzjrdgcl.length() - 1);
                                }
                            }
                        }
                    }
                    logger_750b7a22.error(String.valueOf(requestid + "--ChangeInformationExpertsAction--info--" + str + "信息化专家【" + xm + "】"));
                }
//                sql = "update formdata_detail as  HrmSubcompanyDefined set xxhzj='" + xxhzj + "',xxhzjrdgcl='" + xxhzjrdgcl + "' where subcomid =" + sqdw;
//                logger_750b7a22.error(String.valueOf(requestid + " sql:" + sql));
//                String poolname_h6 = CONN_TYPE.workflow.getType();
//                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
//                rs.executeSql(sql, poolname_h6);
//                sql = "update Matrixtable_1 set xxhzj='" + xxhzj + "',xxhzjrdgcl='" + xxhzjrdgcl + "' where id =" + sqdw;
//                logger_750b7a22.error(String.valueOf(requestid + " sql:" + sql));
//                String poolname_3r = CONN_TYPE.workflow.getType();
//                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
//                rs.executeSql(sql, poolname_3r);
            } catch (Exception e) {
                logger_750b7a22.error(String.valueOf(e));
                logger_750b7a22.error(String.valueOf(requestid + "--ChangeInformationExpertsAction--error--" + e.toString()));
                return  WeaResult.fail(500, requestid + "--ChangeInformationExpertsAction--error--" + e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), request.getRequestManager()));
            }
            logger_750b7a22.error(String.valueOf("ChangeInformationExpertsAction--end--" + requestid));
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", SUCCESS, request.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_750b7a22.error("ChangeInformationExpertsAction e: {}", e.getMessage());
            return  WeaResult.fail(500, "ChangeInformationExpertsAction 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;
    }
}
