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

import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.ebuilder.common.util.TenantContext;
import com.weaver.ebuilder.datasource.api.entity.ExecuteSqlEntity;
import com.weaver.ebuilder.datasource.api.enums.SourceType;
import com.weaver.ebuilder.datasource.api.service.DataSetService;
import com.weaver.framework.rpc.context.impl.TenantRpcContext;
import com.weaver.teams.api.tenant.Tenant;
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_UpdateTaskNumber")
public class UpdateTaskNumber implements Action, EsbServerlessRpcRemoteInterface {

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

    @Autowired
    private DataSetService dataSetService;

    private static final Logger logger_2c12a616 = LoggerFactory.getLogger(UpdateTaskNumber.class);

    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        logger_2c12a616.error("UpdateTaskNumber 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 paramRequestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        try {
            // 流程编号
            String rwbh = "";
            try {
                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("rwbh")) {
                        rwbh = value;
                    }
                }
                logger_2c12a616.error(String.valueOf("rwbh=" + rwbh));
                RecordSet rs = I18nContextUtil.getBean(RecordSet.class);
                String requestId = paramRequestInfo.getRequestid();
                String tablename = paramRequestInfo.getRequestManager().getBillTableName();
                String sql = "select t.id from e10_core_business.dbo." + tablename + "_dt1 t left join e10_core_business.dbo." + tablename + " a on a.form_data_id = t.form_data_id where a.id = " + requestId + " order by t.id";
                logger_2c12a616.error(String.valueOf("sql=" + sql));
                String poolname = CONN_TYPE.workflow.getType();
                // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
                boolean b = rs.executeQuery(sql, poolname);
                logger_2c12a616.error("b--"+b);
                int k = 0;
                while (rs.next()) {
                    String id = rs.getString("id");
                    logger_2c12a616.error(String.valueOf("id=" + id));
                    String seq = "";
                    if (k < 10) {
                        seq = "0" + (k + 1);
                    } else {
                        seq = (k + 1) + "";
                    }
                    String sql1 = "update e10_core_business.dbo." + tablename + "_dt1 set rwbh='" + rwbh + "_" + seq + "' where id=" + id;
//                    logger_2c12a616.error(String.valueOf("sql1=" + sql1));
//                    String poolname_dw = CONN_TYPE.workflow.getType();
//                    // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
//                    RecordSet rs1 = new RecordSet();
//                    boolean b1 = rs1.executeUpdate(sql1, poolname_dw);
                    executeForQuery(null2String(SourceType.LOGIC), "weaver-workflow-list-service", sql1);
                    k++;
                }
            } catch (Exception e) {
                logger_2c12a616.error("UpdateTaskNumber e: {}",e);
                paramRequestInfo.getRequestManager().setMessageid("ERROR");
                paramRequestInfo.getRequestManager().setMessagecontent(e.getMessage());
                return  WeaResult.fail(500, "UpdateTaskNumber err"+ e, getResultMapForAction(weaverResultMap, "result",e.getMessage(), paramRequestInfo.getRequestManager()));
            }
            return WeaResult.success(getResultMapForAction(weaverResultMap, "result", Action.SUCCESS, paramRequestInfo.getRequestManager()));
        } catch (Exception e) {
            e.printStackTrace();
            logger_2c12a616.error("UpdateTaskNumber e: {}", e);
            return  WeaResult.fail(500, "UpdateTaskNumber 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;
    }

    public Map<String, Object> executeForQuery(String sourceType, String groupId, String sql) {
//        log.error("executeForQuery sourceType-->" + sourceType + ",groupId-->" + groupId + ",sql-->" + sql);
        final Tenant currentTenant = TenantContext.getCurrentTenant();
        TenantRpcContext.setTargetTenantKey(String.valueOf(currentTenant));
        ExecuteSqlEntity executeSqlEntity = new ExecuteSqlEntity();
        executeSqlEntity.setSql(cn.hutool.core.codec.Base64.encode(sql));
        executeSqlEntity.setGroupId(groupId); //groupid,可以访问  E10地址/api/datasource/ds/group?sourceType=LOGIC 获取
        executeSqlEntity.setSourceType(SourceType.valueOf(sourceType));
//        log.error("executeForQuery executeSqlEntity-->"+executeSqlEntity.getSql()+"-->"+executeSqlEntity.getGroupId()+"-->"+executeSqlEntity.getSourceType());
        Map<String, Object> datas = dataSetService.executeSql(executeSqlEntity);
        logger_2c12a616.error("executeForQuery datas-->" + datas);
        TenantRpcContext.removeTargetTenantKey();
        return datas;
    }
    public static String null2String(String s){
        return s == null ? "" : s;
    }

    public static String null2String(Object o){
        return o == null ? "" : o.toString();
    }

    public static String null2String(String s1,String s2){
        return s1 == null ? (s2 == null ? "" : s2) : s1;
    }
}
