package com.weaver.seconddev.cussso.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.ebuilder.datasource.api.enums.SourceType;
import com.weaver.ebuilder.datasource.api.service.DataSetService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class CusVarModule {

    private static final Logger log = LoggerFactory.getLogger(CusVarModule.class);

    @Autowired
    private DataSetService dataSetService;

    private String tenantKey;

    // 关于数据库查询
    // 1、eteams是公共库，可以与如E10_COMM,e10_core_business一起查询，但E10_COMM,e10_core_business不能合并在一起查询（单租户可以）
    // 2、对于E10里面的数据用户，可以指定sourcetype是SourceType.LOGIC,然后groupid是服务名查询
    // 具体可以查询weaver.properties，搜索weaver.service，知道哪个库，指定哪个服务去查询
    // 比如在avatr中，
    // E10_COMM可以用weaver-ebuilder-form-service
    // e10_core_business可以用weaver-data-search-service
    // e10_other_business可以用[weaver-inc-adapter-service等
    // 3、另外，也可以在数据加工中建立数据源（不管是连接e10自身的库，还是外部系统的库，都是外部数据源），可以指定sourcetype是SourceType.EXTERNAL
    // groupid可以在外部数据源F12看geconnection中id的值
    // 但此种方式，对于多租户，要先引用TenantRpcContext.setTargetTenantKey()先设置为对应的租户，不然执行sql会报没有权限

    /**
     * 获取主管理级团队租户ID
     * @return
     *        String
     * @throws Exception
     */
    public String getTenantkey() throws Exception {
        log.error("com.weaver.seconddev.bpm10.cons.VarModule.getTenantkey.tenantKey:" + tenantKey);
        if (StringUtils.isEmpty(tenantKey)) {
            String qrySql = "select tenantkey from tenant_info where delete_type = 0 and tenantmanager = 1";
            Map<String, Object> exeMap = dataSetService.executeSql(SourceType.LOGIC,"weaver-ebuilder-form-service",qrySql,"",new Object[]{});
            if (exeMap == null || !exeMap.containsKey("records")) {
                throw new Exception("seconddev.getTenantkey is empty,call by " + Thread.currentThread().getStackTrace()[2].getClassName() + "." + Thread.currentThread().getStackTrace()[2].getMethodName() );
            }
            Object records = exeMap.get("records");
            if (records != null) {
                JSONArray dataArr = JSONArray.parseArray(JSON.toJSONString(records));
                for (int i = 0; i < dataArr.size(); i++) {
                    if (i == 0) {
                        JSONObject dataObj = dataArr.getJSONObject(i);
                        for (String key : dataObj.keySet()) {
                            if ("tenantkey".equalsIgnoreCase(key)) {
                                tenantKey = dataObj.get(key) == null ? "" : String.valueOf(dataObj.get(key));
                            }
                        }
                    }
                }
            }
        }
        if (StringUtils.isEmpty(tenantKey)) {
            throw new Exception("com.weaver.seconddev.bpm10.cons.VarModule.getTenantkey is empty,call by " + Thread.currentThread().getStackTrace()[2].getClassName() + "." + Thread.currentThread().getStackTrace()[2].getMethodName() );
        }
        return tenantKey;
    }
}
