package com.hzya.frame.sys.flow.service.impl;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.hzya.frame.sys.flow.entity.SysFlowStepAccountEntity;
import com.hzya.frame.sys.flow.entity.SysFlowStepConfigEntity;
import com.hzya.frame.sys.flow.dao.ISysFlowStepConfigDao;
import com.hzya.frame.sys.flow.service.ISysFlowStepAccountService;
import com.hzya.frame.sys.flow.service.ISysFlowStepConfigService;
import com.hzya.frame.sysnew.application.database.entity.SysApplicationDatabaseEntity;
import com.hzya.frame.sysnew.application.database.service.ISysApplicationDatabaseService;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import com.hzya.frame.web.exception.BaseSystemException;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import com.hzya.frame.basedao.service.impl.BaseService;

import java.util.List;

/**
 * 映射信息主表(SysFlowStepConfig)表服务实现类
 *
 * @author xiang2lin
 * @since 2025-04-29 10:16:28
 */
@Service(value = "sysFlowStepConfigService")
public class SysFlowStepConfigServiceImpl extends BaseService<SysFlowStepConfigEntity, String> implements ISysFlowStepConfigService {

	Logger logger = LoggerFactory.getLogger(ISysFlowStepConfigService.class);
    private ISysFlowStepConfigDao sysFlowStepConfigDao;
    @Autowired
	private ISysFlowStepAccountService sysFlowStepAccountService;
	@Autowired
	private ISysApplicationDatabaseService sysApplicationDatabaseService;
    @Autowired
	public void setSysFlowStepConfigDao(ISysFlowStepConfigDao dao) {
		this.sysFlowStepConfigDao = dao;
		this.dao = dao;
	}

	/**
	 * 测试sql
	 *
	 * @param object
	 * @return
	 */
	@Override
	public JsonResultEntity testSql(JSONObject object) {
		SysFlowStepConfigEntity config = getData("jsonStr",object,SysFlowStepConfigEntity.class);
		try {
			checkParams(config,"type");
		}catch (Exception e){
			return BaseResult.getFailureMessageEntity(e.getMessage());
		}
		SysFlowStepAccountEntity accountEntity = sysFlowStepAccountService.get(config.getId());
		Assert.notNull(accountEntity,"没有找到对应账户");
		//查询数据源
		SysApplicationDatabaseEntity database = new SysApplicationDatabaseEntity();
		database.setSourceCode(accountEntity.getName()+"_flow");
		List<SysApplicationDatabaseEntity> databaseList = sysApplicationDatabaseService.query(database);
		if (CollectionUtils.isEmpty(databaseList)){
			throw new BaseSystemException("没有找到数据源");
		}
		return null;
	}

	/**
	 * 验证数据
	 * @param entity
	 * @param type
	 */
	private void checkParams(SysFlowStepConfigEntity entity, String type) {
		Assert.notNull(entity,"参数不能为空");
		Assert.notEmpty(entity.getTableName(),"tabName不能为空");
		Assert.notEmpty(entity.getStepAccountId(),"tabName不能为空");
	}
}
