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

import java.util.HashMap;
import java.util.Map;

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.workflow.util.CommonDevUtil;
import com.weaver.teams.domain.user.SimpleEmployee;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
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 com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.general.Util;
import com.weaver.verupgrade.soa.workflow.request.MainTableInfo;
import com.weaver.verupgrade.soa.workflow.request.Property;
import com.weaver.verupgrade.interfaces.workflow.action.Action;

@org.springframework.stereotype.Service("workflow_action_BY_EnterToJhrwMx")
public class BY_EnterToJhrwMx implements Action, EsbServerlessRpcRemoteInterface {

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

    private static final Logger logger_b053f378 = LoggerFactory.getLogger(BY_EnterToJhrwMx.class);

    private Log log = LogFactory.getLog(BY_EnterToJhrwMx.class.getName());

    @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 paramRequestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        logger_b053f378.error("---------------- BY_EnterToJhrwMx start ---------------");
        logger_b053f378.error("requestIdTemp:" + requestIdTemp);
        logger_b053f378.error("userIdTemp:" + userIdTemp);
        try {
            String glid = "";
            String rwbh2 = "";
            Map mainMap = new HashMap();
            Property[] properties = paramRequestInfo.getMainTableInfo().getProperty();
            for (int i = 0; i < properties.length; i++) {
                String name = properties[i].getName();
                String value = Util.null2String(properties[i].getValue());
                if (name.equals("glid")) {
                    glid = value;
                }
                if (name.equals("rwbh")) {
                    rwbh2 = value;
                }
                mainMap.put(name, value);
            }

            logger_b053f378.error("glid:" + glid);
            logger_b053f378.error("rwbh2:" + rwbh2);
            RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
            RecordSet rs3 = I18nContextUtil.getBean(RecordSet.class);
            String sql = "insert into e10_common.dbo.JhrwMx(isdr,id,mainid,rwbh,lcbid,zkjh,gzrw,zrr,jxzb,ts,ksrq,jsrq,phr,ddr,qrr,csr,pid,glid,mxid,rwzt,requestid,rwbh2,lxsj,tdsj,rwlx,xmkp,yhry,rwjb,shr,jtyq,tbr,rbbm,ssgs,rwsm,fj,yfjd,xmbh)select T1.ISDR,T1.MXID,T1.GLID,'" + rwbh2 + "' + T1.RWBH,T1.lcbid,T1.zkjh,T1.GZRW,T1.ZRR,T1.JXZB,T1.TS," + "T1.KSRQ,T1.JSRQ,T1.PHR,T1.DDR,T1.QRR,T1.CSR,(CASE T1.PID WHEN 0 THEN isnull(T1.lcbid,0) ELSE T1.PID END) as PID,cast(T1.GLID as varchar) as glid,T1.MXID,'执行中'," + "'" + paramRequestInfo.getRequestid() + "'," + "'" + Util.null2String((String) mainMap.get("rwbh")) + "'," + "'" + Util.null2String((String) mainMap.get("lxsj")) + "'," + "'" + Util.null2String((String) mainMap.get("tdsj")) + "'," + "'" + Util.null2String((String) mainMap.get("rwlx")) + "'," + "'" + Util.null2String((String) mainMap.get("xmkp")) + "'," + "'" + Util.null2String((String) mainMap.get("yhry")) + "'," + "'" + Util.null2String((String) mainMap.get("rwjb")) + "'," + "'" + Util.null2String((String) mainMap.get("shr")) + "'," + "'" + Util.null2String((String) mainMap.get("jtyq")) + "'," + "'" + Util.null2String((String) mainMap.get("tbr")) + "'," + "'" + Util.null2String((String) mainMap.get("rbbm")) + "'," + "'" + Util.null2String((String) mainMap.get("ssgs")) + "'," + "'" + Util.null2String((String) mainMap.get("rwsm")).replace("'", "''") + "'," + "'" + Util.null2String((String) mainMap.get("fj")) + "'," + "'" + Util.null2String((String) mainMap.get("yfjd")) + "'," + "'" + Util.null2String((String) mainMap.get("xmbh")) + "'" + "from JhrwLcmx T1 where t1.mxid<>0 and T1.ISDR=0 AND glid = '" + glid + "' order by rwbh";
            logger_b053f378.error("sql:" + sql);
            String poolname = CONN_TYPE.ebuilder.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(sql, poolname,generate);

            // 写入流程提醒记录
            String sql4 = "insert into e10_common.dbo.jhrwmxlog(id,mainid,rwbh,lcbid,zkjh,gzrw,zrr,jxzb,ts,ksrq,jsrq,yqrq,phr,ddr,qrr,csr,pid,glid,mxid,isdr,rwzt,requestid,request,rwbh2,lxsj,tdsj,rwlx,xmkp,yhry,rwjb,shr,jtyq,tbr,rbbm,ssgs,rwsm,fj,yfjd,xmbh,FtriggerFlag) (select id,mainid,rwbh,lcbid,zkjh,gzrw,zrr,jxzb,ts,ksrq,jsrq,yqrq,phr,ddr,qrr,csr,pid,glid,mxid,isdr,rwzt,0 as requestid,requestid as request,rwbh2,lxsj,tdsj,rwlx,xmkp,yhry,rwjb,shr,jtyq,tbr,rbbm,ssgs,rwsm,fj,yfjd,xmbh,0 as FtriggerFlag from jhrwmx where mxid<>0 and ISDR=0 AND cast(glid as varchar) = '" + glid + "') order by rwbh ";
            logger_b053f378.error("sql4:" + sql4);
            String poolname_11 = CONN_TYPE.ebuilder.getType();
            /* *TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
 TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
            generate = IdGenerator.generate();
            rs.executeSql(sql4, poolname_11,generate);
            String poolname_ra = CONN_TYPE.ebuilder.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            rs3.executeSql("delete from  e10_common.dbo.mission_change where id=" + glid, poolname_ra);
//            String poolname_gh = CONN_TYPE.ebuilder.getType();
//            /* *TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
// TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//            generate = IdGenerator.generate();
//            rs3.executeSql("insert into  e10_common.dbo.mission_change (id,mmode,mtype) values(" + glid + ",1,2)", poolname_gh,generate);
            SimpleEmployee currentEmployee = HrmContextUtil.getCurrentUser();
            Long uf_CustomFlow_formId = commonDevUtil.getObjId("mission_change");
            logger_b053f378.error("uf_CustomFlow_formId = " + uf_CustomFlow_formId);
            Long recodId = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId, currentEmployee);// 获取插入的空的建模id
            String sql3 = "update e10_common.dbo.mission_change set id=" + glid + ",mmode=2,mtype=2 where id  =  " + recodId + " and delete_type = 0 ";
            boolean b1 = rs.executeSql(sql3, poolname);
            logger_b053f378.error("sql3 = " + sql3);
            logger_b053f378.error("添加 = " + b1);
            RecordSet rs1 = I18nContextUtil.getBean(RecordSet.class);
            /*
    String sql1 = " update JhrwMx set pid=(select top 1 t2.pid from jhrwlcmx t2 where t2.mxid=mxid and T2.ISDR<>0 AND T2.glid = '" + glid + "')," + 
      " glid=(cast(glid as varchar) + ',' + '" + glid + "')," + 
      " isdr=(select top 1 t3.isdr from jhrwlcmx t3 where t3.mxid=mxid and T3.ISDR<>0 AND T3.glid = '" + glid + "')" + 
      " where mxid in (select mxid from jhrwlcmx where ISDR<>0 AND glid = '" + glid + "')";
	*/
            String sql1 = " update e10_common.dbo.JhrwMx set pid=(select top 1 t2.pid from jhrwlcmx t2 where t2.mxid=mxid and T2.ISDR<>0 AND T2.glid = '" + glid + "')," + " glid=(cast(glid as varchar) + ',' + '" + glid + "')," + " isdr= '1' where mxid in (select mxid from jhrwlcmx where ISDR<>0 AND glid = '" + glid + "')";
            logger_b053f378.error("sql1:" + sql1);
            String poolname_m7 = CONN_TYPE.ebuilder.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean b2 = rs1.executeSql(sql1, poolname_m7);
            logger_b053f378.error("b2:" + b2);
            String poolname_p1 = CONN_TYPE.ebuilder.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            boolean b3 = rs3.executeSql("delete from  e10_common.dbo.mission_change where id=" + glid, poolname_p1);
            logger_b053f378.error("b3:" + b3);

//            String poolname_in = CONN_TYPE.ebuilder.getType();
//            /* *TODO  检测到insert语句 -> E9插入sql迁移到E10需要特殊处理请参考文档进行调整  https://www.e-cology.com.cn/sp/doc/docShare/1027709301045985331?tenantKey=t7akvdnf84
// TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源*/
//            rs3.executeSql("insert into  e10_common.dbo.mission_change (id,mmode,mtype) values(" + glid + ",2,2)", poolname_in);
            Long uf_CustomFlow_formId1 = commonDevUtil.getObjId("mission_change");
            logger_b053f378.error("uf_CustomFlow_formId1 = " + uf_CustomFlow_formId1);
            Long recodId1 = ebFormDataDubboService.addEmptyData(uf_CustomFlow_formId1, currentEmployee);// 获取插入的空的建模id
            String sql2 = "update e10_common.dbo.mission_change set id=" + glid + ",mmode=2,mtype=2 where id  =  " + recodId + " and delete_type = 0 ";
            boolean b = rs.executeSql(sql2, poolname);
            logger_b053f378.error("sql2 = " + sql2);
            logger_b053f378.error("添加 = " + b);
            logger_b053f378.error("---------------- BY_EnterToJhrwMx stop ---------------");
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", "1", paramRequestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_b053f378.error("BY_EnterToJhrwMx e: {}", e.getMessage());
            return  WeaResult.fail(500, "BY_EnterToJhrwMx e: {}"+ e, getResultMapForAction(weaverResultMap, "result", e.getMessage(), paramRequestInfo.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;
    }
}
